OrthancWebViewer-2.3/.hg_archival.txt0000644000000000000000000000027513133653001016007 0ustar 00000000000000repo: 02f7a0400a911dee22d2e761b21b6cab67ede076 node: daab267593577f078bc63d5b6ab62eb89286b6d2 branch: OrthancWebViewer-2.3 latesttag: null latesttagdistance: 161 changessincelatesttag: 165 OrthancWebViewer-2.3/AUTHORS0000644000000000000000000000051113133653001013762 0ustar 00000000000000Web Viewer plugin for Orthanc ============================= Authors ------- * Sebastien Jodogne Overall design and lead developer. * Department of Medical Physics University Hospital of Liege 4000 Liege Belgium * Osimis Rue des Chasseurs Ardennais 3 4031 Liege Belgium OrthancWebViewer-2.3/CMakeLists.txt0000644000000000000000000001671713133653001015471 0ustar 00000000000000# Orthanc - A Lightweight, RESTful DICOM Store # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics # Department, University Hospital of Liege, Belgium # Copyright (C) 2017 Osimis, Belgium # # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . cmake_minimum_required(VERSION 2.8) project(OrthancWebViewer) set(ORTHANC_WEBVIEWER_VERSION "2.3") # Parameters of the build set(STATIC_BUILD OFF CACHE BOOL "Static build of the third-party libraries (necessary for Windows)") SET(STANDALONE_BUILD ON CACHE BOOL "Standalone build (all the resources are embedded, necessary for releases)") set(ALLOW_DOWNLOADS OFF CACHE BOOL "Allow CMake to download packages") # Advanced parameters to fine-tune linking against system libraries set(USE_SYSTEM_BOOST ON CACHE BOOL "Use the system version of Boost") set(USE_SYSTEM_GDCM ON CACHE BOOL "Use the system version of Grassroot DICOM (GDCM)") set(USE_SYSTEM_GOOGLE_TEST ON CACHE BOOL "Use the system version of Google Test") set(USE_SYSTEM_JSONCPP ON CACHE BOOL "Use the system version of JsonCpp") set(USE_SYSTEM_SQLITE ON CACHE BOOL "Use the system version of SQLite") set(USE_SYSTEM_ORTHANC_SDK ON CACHE BOOL "Use the system version of the Orthanc plugin SDK") # Distribution-specific settings set(USE_GTEST_DEBIAN_SOURCE_PACKAGE OFF CACHE BOOL "Use the sources of Google Test shipped with libgtest-dev (Debian only)") mark_as_advanced(USE_GTEST_DEBIAN_SOURCE_PACKAGE) set(ORTHANC_ROOT ${CMAKE_SOURCE_DIR}/Orthanc) set(ORTHANC_DISABLE_PATCH ON) # No need for the "patch" command-line tool include(CheckIncludeFiles) include(CheckIncludeFileCXX) include(CheckLibraryExists) include(FindPythonInterp) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/Compiler.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/AutoGeneratedCode.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/DownloadPackage.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/BoostConfiguration.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/GoogleTestConfiguration.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/JsonCppConfiguration.cmake) include(${CMAKE_SOURCE_DIR}/Orthanc/Resources/CMake/SQLiteConfiguration.cmake) include(${CMAKE_SOURCE_DIR}/Resources/CMake/GdcmConfiguration.cmake) include(${CMAKE_SOURCE_DIR}/Resources/CMake/JavaScriptLibraries.cmake) # Check that the Orthanc SDK headers are available if (STATIC_BUILD OR NOT USE_SYSTEM_ORTHANC_SDK) include_directories(${ORTHANC_ROOT}/Sdk-0.9.5) else () CHECK_INCLUDE_FILE_CXX(orthanc/OrthancCPlugin.h HAVE_ORTHANC_H) if (NOT HAVE_ORTHANC_H) message(FATAL_ERROR "Please install the headers of the Orthanc plugins SDK") endif() endif() if (STANDALONE_BUILD) add_definitions( -DORTHANC_STANDALONE=1 ) set(EMBEDDED_RESOURCES WEB_VIEWER ${CMAKE_SOURCE_DIR}/WebApplication ) else() add_definitions( -DORTHANC_STANDALONE=0 -DWEB_VIEWER_PATH="${CMAKE_SOURCE_DIR}/WebApplication/" ) endif() EmbedResources( ORTHANC_EXPLORER ${CMAKE_SOURCE_DIR}/Resources/OrthancExplorer.js JAVASCRIPT_LIBS ${JAVASCRIPT_LIBS_DIR} ${EMBEDDED_RESOURCES} ) add_definitions( -DORTHANC_ENABLE_PUGIXML=0 -DORTHANC_SQLITE_STANDALONE=1 ) if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") link_libraries(rt) elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Windows") SET(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lws2_32") execute_process( COMMAND ${PYTHON_EXECUTABLE} ${ORTHANC_ROOT}/Resources/WindowsResources.py ${ORTHANC_WEBVIEWER_VERSION} "OrthancWebViewer" OrthancWebViewer.dll "Web viewer of medical images for Orthanc" ERROR_VARIABLE Failure OUTPUT_FILE ${AUTOGENERATED_DIR}/Version.rc ) if (Failure) message(FATAL_ERROR "Error while computing the version information: ${Failure}") endif() list(APPEND AUTOGENERATED_SOURCES ${AUTOGENERATED_DIR}/Version.rc) endif() if (APPLE) SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -framework CoreFoundation") SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -framework CoreFoundation") endif() add_definitions( -DORTHANC_ENABLE_MD5=0 -DORTHANC_ENABLE_BASE64=0 -DORTHANC_ENABLE_LOGGING=0 -DORTHANC_SANDBOXED=0 ) set(CORE_SOURCES ${BOOST_SOURCES} ${SQLITE_SOURCES} ${JSONCPP_SOURCES} # Sources inherited from Orthanc core ${CMAKE_SOURCE_DIR}/Orthanc/Core/ChunkedBuffer.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/Enumerations.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/FileStorage/FilesystemStorage.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/Images/ImageAccessor.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/Images/ImageBuffer.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/Images/ImageProcessing.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/MultiThreading/SharedMessageQueue.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/Connection.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/FunctionContext.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/Statement.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/StatementId.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/StatementReference.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SQLite/Transaction.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/SystemToolbox.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/Toolbox.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/DicomFormat/DicomMap.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/DicomFormat/DicomTag.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Core/DicomFormat/DicomValue.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Resources/ThirdParty/base64/base64.cpp ${CMAKE_SOURCE_DIR}/Plugin/Cache/CacheManager.cpp ${CMAKE_SOURCE_DIR}/Plugin/Cache/CacheScheduler.cpp ${CMAKE_SOURCE_DIR}/Plugin/ViewerToolbox.cpp ${CMAKE_SOURCE_DIR}/Plugin/ViewerPrefetchPolicy.cpp ${CMAKE_SOURCE_DIR}/Plugin/SeriesInformationAdapter.cpp ) add_library(OrthancWebViewer SHARED ${CORE_SOURCES} ${AUTOGENERATED_SOURCES} ${CMAKE_SOURCE_DIR}/Plugin/Plugin.cpp # The following files depend on GDCM ${CMAKE_SOURCE_DIR}/Plugin/DecodedImageAdapter.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Plugins/Samples/GdcmDecoder/GdcmImageDecoder.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Plugins/Samples/GdcmDecoder/GdcmDecoderCache.cpp ${CMAKE_SOURCE_DIR}/Orthanc/Plugins/Samples/GdcmDecoder/OrthancImageWrapper.cpp ) if (STATIC_BUILD OR NOT USE_SYSTEM_GDCM) add_dependencies(OrthancWebViewer GDCM) endif() target_link_libraries(OrthancWebViewer ${GDCM_LIBRARIES}) message("Setting the version of the library to ${ORTHANC_WEBVIEWER_VERSION}") add_definitions(-DORTHANC_WEBVIEWER_VERSION="${ORTHANC_WEBVIEWER_VERSION}") set_target_properties(OrthancWebViewer PROPERTIES VERSION ${ORTHANC_WEBVIEWER_VERSION} SOVERSION ${ORTHANC_WEBVIEWER_VERSION}) install( TARGETS OrthancWebViewer RUNTIME DESTINATION lib # Destination for Windows LIBRARY DESTINATION share/orthanc/plugins # Destination for Linux ) add_executable(UnitTests ${CORE_SOURCES} ${GTEST_SOURCES} ${JSONCPP_SOURCES} UnitTestsSources/UnitTestsMain.cpp ) OrthancWebViewer-2.3/COPYING0000644000000000000000000010333013133653001013750 0ustar 00000000000000 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . OrthancWebViewer-2.3/NEWS0000644000000000000000000000355613133653001013425 0ustar 00000000000000Pending changes in the mainline =============================== Version 2.3 (2017-07-19) ======================== * Upgrade to Cornerstone 0.11.0 * Performance warning if runtime debug assertions are turned on * Fix issue 44 (Bad interpretation of photometric interpretation MONOCHROME1) Version 2.2 (2016-06-28) ======================== * Option "EnableGdcm" to replace the built-in decoder of Orthanc with GDCM * Option "RestrictTransferSyntaxes" saying which transfer syntaxes should be decoded with GDCM * Fixed rendering of 16bpp images if values are < 0 or >= 32768 * Decoding of JPEG2000 lossless images with YBR_RCT photometric interpretation Version 2.1 (2015-12-10) ======================== * Automatic clearing of the cache if change in the version of Orthanc or of the plugin Version 2.0 (2015-12-02) ======================== => Minimum SDK version: 0.9.5 <= * The GDCM decoder replaces the built-in Orthanc decoder inside Orthanc Explorer * Support of multi-frame images * Upgrade to Cornerstone 0.8.4 Version 1.3 (2015-11-27) ======================== => Minimum SDK version: 0.9.4 <= * Support of images encoded using LUT (lookup tables) * Use Orthanc's primitives for PNG and JPEG * Fix for old versions of jQuery * Fix possible deadlock with other plugins in OnChangeCallback() * Upgrade to GDCM 2.6.0 for static builds * Upgrade to Boost 1.59.0 for static builds Version 1.2 (2015-08-02) ======================== => Minimum SDK version: 0.9.1 <= * Update to Boost 1.58.0 for static and Windows builds * Inject version information into Windows binaries * Support of OS X Version 1.1 (2015-07-03) ======================== * Support of Visual Studio 2008 * Support of FreeBSD * Fix issue 29 (support of photometric interpretation YBR_FULL_422) Version 1.0 (2015-02-27) ======================== * Configuration options 2015-02-25 ========== * Initial release OrthancWebViewer-2.3/Orthanc/Core/ChunkedBuffer.cpp0000644000000000000000000000542313133653001020426 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "PrecompiledHeaders.h" #include "ChunkedBuffer.h" #include #include namespace Orthanc { void ChunkedBuffer::Clear() { numBytes_ = 0; for (Chunks::iterator it = chunks_.begin(); it != chunks_.end(); ++it) { delete *it; } } void ChunkedBuffer::AddChunk(const void* chunkData, size_t chunkSize) { if (chunkSize == 0) { return; } else { assert(chunkData != NULL); chunks_.push_back(new std::string(reinterpret_cast(chunkData), chunkSize)); numBytes_ += chunkSize; } } void ChunkedBuffer::AddChunk(const std::string& chunk) { if (chunk.size() > 0) { AddChunk(&chunk[0], chunk.size()); } } void ChunkedBuffer::Flatten(std::string& result) { result.resize(numBytes_); size_t pos = 0; for (Chunks::iterator it = chunks_.begin(); it != chunks_.end(); ++it) { assert(*it != NULL); size_t s = (*it)->size(); if (s != 0) { memcpy(&result[pos], (*it)->c_str(), s); pos += s; } delete *it; } chunks_.clear(); numBytes_ = 0; } } OrthancWebViewer-2.3/Orthanc/Core/ChunkedBuffer.h0000644000000000000000000000420613133653001020071 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include namespace Orthanc { class ChunkedBuffer { private: typedef std::list Chunks; size_t numBytes_; Chunks chunks_; void Clear(); public: ChunkedBuffer() : numBytes_(0) { } ~ChunkedBuffer() { Clear(); } size_t GetNumBytes() const { return numBytes_; } void AddChunk(const void* chunkData, size_t chunkSize); void AddChunk(const std::string& chunk); void Flatten(std::string& result); }; } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomMap.cpp0000644000000000000000000005214113133653001021607 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "DicomMap.h" #include #include #include "../Endianness.h" #include "../OrthancException.h" namespace Orthanc { static DicomTag patientTags[] = { //DicomTag(0x0010, 0x1010), // PatientAge //DicomTag(0x0010, 0x1040) // PatientAddress DicomTag(0x0010, 0x0010), // PatientName DicomTag(0x0010, 0x0030), // PatientBirthDate DicomTag(0x0010, 0x0040), // PatientSex DicomTag(0x0010, 0x1000), // OtherPatientIDs DICOM_TAG_PATIENT_ID }; static DicomTag studyTags[] = { //DicomTag(0x0010, 0x1020), // PatientSize //DicomTag(0x0010, 0x1030) // PatientWeight DICOM_TAG_STUDY_DATE, DicomTag(0x0008, 0x0030), // StudyTime DicomTag(0x0020, 0x0010), // StudyID DICOM_TAG_STUDY_DESCRIPTION, DICOM_TAG_ACCESSION_NUMBER, DICOM_TAG_STUDY_INSTANCE_UID, DICOM_TAG_REQUESTED_PROCEDURE_DESCRIPTION, // New in db v6 DICOM_TAG_INSTITUTION_NAME, // New in db v6 DICOM_TAG_REQUESTING_PHYSICIAN, // New in db v6 DICOM_TAG_REFERRING_PHYSICIAN_NAME // New in db v6 }; static DicomTag seriesTags[] = { //DicomTag(0x0010, 0x1080), // MilitaryRank DicomTag(0x0008, 0x0021), // SeriesDate DicomTag(0x0008, 0x0031), // SeriesTime DICOM_TAG_MODALITY, DicomTag(0x0008, 0x0070), // Manufacturer DicomTag(0x0008, 0x1010), // StationName DICOM_TAG_SERIES_DESCRIPTION, DicomTag(0x0018, 0x0015), // BodyPartExamined DicomTag(0x0018, 0x0024), // SequenceName DicomTag(0x0018, 0x1030), // ProtocolName DicomTag(0x0020, 0x0011), // SeriesNumber DICOM_TAG_CARDIAC_NUMBER_OF_IMAGES, DICOM_TAG_IMAGES_IN_ACQUISITION, DICOM_TAG_NUMBER_OF_TEMPORAL_POSITIONS, DICOM_TAG_NUMBER_OF_SLICES, DICOM_TAG_NUMBER_OF_TIME_SLICES, DICOM_TAG_SERIES_INSTANCE_UID, DICOM_TAG_IMAGE_ORIENTATION_PATIENT, // New in db v6 DICOM_TAG_SERIES_TYPE, // New in db v6 DICOM_TAG_OPERATOR_NAME, // New in db v6 DICOM_TAG_PERFORMED_PROCEDURE_STEP_DESCRIPTION, // New in db v6 DICOM_TAG_ACQUISITION_DEVICE_PROCESSING_DESCRIPTION, // New in db v6 DICOM_TAG_CONTRAST_BOLUS_AGENT // New in db v6 }; static DicomTag instanceTags[] = { DicomTag(0x0008, 0x0012), // InstanceCreationDate DicomTag(0x0008, 0x0013), // InstanceCreationTime DicomTag(0x0020, 0x0012), // AcquisitionNumber DICOM_TAG_IMAGE_INDEX, DICOM_TAG_INSTANCE_NUMBER, DICOM_TAG_NUMBER_OF_FRAMES, DICOM_TAG_TEMPORAL_POSITION_IDENTIFIER, DICOM_TAG_SOP_INSTANCE_UID, DICOM_TAG_IMAGE_POSITION_PATIENT, // New in db v6 DICOM_TAG_IMAGE_COMMENTS // New in db v6 }; void DicomMap::LoadMainDicomTags(const DicomTag*& tags, size_t& size, ResourceType level) { switch (level) { case ResourceType_Patient: tags = patientTags; size = sizeof(patientTags) / sizeof(DicomTag); break; case ResourceType_Study: tags = studyTags; size = sizeof(studyTags) / sizeof(DicomTag); break; case ResourceType_Series: tags = seriesTags; size = sizeof(seriesTags) / sizeof(DicomTag); break; case ResourceType_Instance: tags = instanceTags; size = sizeof(instanceTags) / sizeof(DicomTag); break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } void DicomMap::SetValue(uint16_t group, uint16_t element, DicomValue* value) { DicomTag tag(group, element); Map::iterator it = map_.find(tag); if (it != map_.end()) { delete it->second; it->second = value; } else { map_.insert(std::make_pair(tag, value)); } } void DicomMap::SetValue(DicomTag tag, DicomValue* value) { SetValue(tag.GetGroup(), tag.GetElement(), value); } void DicomMap::Clear() { for (Map::iterator it = map_.begin(); it != map_.end(); ++it) { delete it->second; } map_.clear(); } void DicomMap::ExtractTags(DicomMap& result, const DicomTag* tags, size_t count) const { result.Clear(); for (unsigned int i = 0; i < count; i++) { Map::const_iterator it = map_.find(tags[i]); if (it != map_.end()) { result.SetValue(it->first, it->second->Clone()); } } } void DicomMap::ExtractPatientInformation(DicomMap& result) const { ExtractTags(result, patientTags, sizeof(patientTags) / sizeof(DicomTag)); } void DicomMap::ExtractStudyInformation(DicomMap& result) const { ExtractTags(result, studyTags, sizeof(studyTags) / sizeof(DicomTag)); } void DicomMap::ExtractSeriesInformation(DicomMap& result) const { ExtractTags(result, seriesTags, sizeof(seriesTags) / sizeof(DicomTag)); } void DicomMap::ExtractInstanceInformation(DicomMap& result) const { ExtractTags(result, instanceTags, sizeof(instanceTags) / sizeof(DicomTag)); } DicomMap* DicomMap::Clone() const { std::auto_ptr result(new DicomMap); for (Map::const_iterator it = map_.begin(); it != map_.end(); ++it) { result->map_.insert(std::make_pair(it->first, it->second->Clone())); } return result.release(); } void DicomMap::Assign(const DicomMap& other) { Clear(); for (Map::const_iterator it = other.map_.begin(); it != other.map_.end(); ++it) { map_.insert(std::make_pair(it->first, it->second->Clone())); } } const DicomValue& DicomMap::GetValue(const DicomTag& tag) const { const DicomValue* value = TestAndGetValue(tag); if (value) { return *value; } else { throw OrthancException(ErrorCode_InexistentTag); } } const DicomValue* DicomMap::TestAndGetValue(const DicomTag& tag) const { Map::const_iterator it = map_.find(tag); if (it == map_.end()) { return NULL; } else { return it->second; } } void DicomMap::Remove(const DicomTag& tag) { Map::iterator it = map_.find(tag); if (it != map_.end()) { delete it->second; map_.erase(it); } } static void SetupFindTemplate(DicomMap& result, const DicomTag* tags, size_t count) { result.Clear(); for (size_t i = 0; i < count; i++) { result.SetValue(tags[i], "", false); } } void DicomMap::SetupFindPatientTemplate(DicomMap& result) { SetupFindTemplate(result, patientTags, sizeof(patientTags) / sizeof(DicomTag)); } void DicomMap::SetupFindStudyTemplate(DicomMap& result) { SetupFindTemplate(result, studyTags, sizeof(studyTags) / sizeof(DicomTag)); result.SetValue(DICOM_TAG_ACCESSION_NUMBER, "", false); result.SetValue(DICOM_TAG_PATIENT_ID, "", false); // These main DICOM tags are only indirectly related to the // General Study Module, remove them result.Remove(DICOM_TAG_INSTITUTION_NAME); result.Remove(DICOM_TAG_REQUESTING_PHYSICIAN); result.Remove(DICOM_TAG_REQUESTED_PROCEDURE_DESCRIPTION); } void DicomMap::SetupFindSeriesTemplate(DicomMap& result) { SetupFindTemplate(result, seriesTags, sizeof(seriesTags) / sizeof(DicomTag)); result.SetValue(DICOM_TAG_ACCESSION_NUMBER, "", false); result.SetValue(DICOM_TAG_PATIENT_ID, "", false); result.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, "", false); // These tags are considered as "main" by Orthanc, but are not in the Series module result.Remove(DicomTag(0x0008, 0x0070)); // Manufacturer result.Remove(DicomTag(0x0008, 0x1010)); // Station name result.Remove(DicomTag(0x0018, 0x0024)); // Sequence name result.Remove(DICOM_TAG_CARDIAC_NUMBER_OF_IMAGES); result.Remove(DICOM_TAG_IMAGES_IN_ACQUISITION); result.Remove(DICOM_TAG_NUMBER_OF_SLICES); result.Remove(DICOM_TAG_NUMBER_OF_TEMPORAL_POSITIONS); result.Remove(DICOM_TAG_NUMBER_OF_TIME_SLICES); result.Remove(DICOM_TAG_IMAGE_ORIENTATION_PATIENT); result.Remove(DICOM_TAG_SERIES_TYPE); result.Remove(DICOM_TAG_ACQUISITION_DEVICE_PROCESSING_DESCRIPTION); result.Remove(DICOM_TAG_CONTRAST_BOLUS_AGENT); } void DicomMap::SetupFindInstanceTemplate(DicomMap& result) { SetupFindTemplate(result, instanceTags, sizeof(instanceTags) / sizeof(DicomTag)); result.SetValue(DICOM_TAG_ACCESSION_NUMBER, "", false); result.SetValue(DICOM_TAG_PATIENT_ID, "", false); result.SetValue(DICOM_TAG_STUDY_INSTANCE_UID, "", false); result.SetValue(DICOM_TAG_SERIES_INSTANCE_UID, "", false); } void DicomMap::CopyTagIfExists(const DicomMap& source, const DicomTag& tag) { if (source.HasTag(tag)) { SetValue(tag, source.GetValue(tag)); } } bool DicomMap::IsMainDicomTag(const DicomTag& tag, ResourceType level) { DicomTag *tags = NULL; size_t size; switch (level) { case ResourceType_Patient: tags = patientTags; size = sizeof(patientTags) / sizeof(DicomTag); break; case ResourceType_Study: tags = studyTags; size = sizeof(studyTags) / sizeof(DicomTag); break; case ResourceType_Series: tags = seriesTags; size = sizeof(seriesTags) / sizeof(DicomTag); break; case ResourceType_Instance: tags = instanceTags; size = sizeof(instanceTags) / sizeof(DicomTag); break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } for (size_t i = 0; i < size; i++) { if (tags[i] == tag) { return true; } } return false; } bool DicomMap::IsMainDicomTag(const DicomTag& tag) { return (IsMainDicomTag(tag, ResourceType_Patient) || IsMainDicomTag(tag, ResourceType_Study) || IsMainDicomTag(tag, ResourceType_Series) || IsMainDicomTag(tag, ResourceType_Instance)); } void DicomMap::GetMainDicomTagsInternal(std::set& result, ResourceType level) { DicomTag *tags = NULL; size_t size; switch (level) { case ResourceType_Patient: tags = patientTags; size = sizeof(patientTags) / sizeof(DicomTag); break; case ResourceType_Study: tags = studyTags; size = sizeof(studyTags) / sizeof(DicomTag); break; case ResourceType_Series: tags = seriesTags; size = sizeof(seriesTags) / sizeof(DicomTag); break; case ResourceType_Instance: tags = instanceTags; size = sizeof(instanceTags) / sizeof(DicomTag); break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } for (size_t i = 0; i < size; i++) { result.insert(tags[i]); } } void DicomMap::GetMainDicomTags(std::set& result, ResourceType level) { result.clear(); GetMainDicomTagsInternal(result, level); } void DicomMap::GetMainDicomTags(std::set& result) { result.clear(); GetMainDicomTagsInternal(result, ResourceType_Patient); GetMainDicomTagsInternal(result, ResourceType_Study); GetMainDicomTagsInternal(result, ResourceType_Series); GetMainDicomTagsInternal(result, ResourceType_Instance); } void DicomMap::GetTags(std::set& tags) const { tags.clear(); for (Map::const_iterator it = map_.begin(); it != map_.end(); ++it) { tags.insert(it->first); } } static uint16_t ReadUnsignedInteger16(const char* dicom) { return le16toh(*reinterpret_cast(dicom)); } static uint32_t ReadUnsignedInteger32(const char* dicom) { return le32toh(*reinterpret_cast(dicom)); } static bool ValidateTag(const ValueRepresentation& vr, const std::string& value) { switch (vr) { case ValueRepresentation_ApplicationEntity: return value.size() <= 16; case ValueRepresentation_AgeString: return (value.size() == 4 && isdigit(value[0]) && isdigit(value[1]) && isdigit(value[2]) && (value[3] == 'D' || value[3] == 'W' || value[3] == 'M' || value[3] == 'Y')); case ValueRepresentation_AttributeTag: return value.size() == 4; case ValueRepresentation_CodeString: return value.size() <= 16; case ValueRepresentation_Date: return value.size() <= 18; case ValueRepresentation_DecimalString: return value.size() <= 16; case ValueRepresentation_DateTime: return value.size() <= 54; case ValueRepresentation_FloatingPointSingle: return value.size() == 4; case ValueRepresentation_FloatingPointDouble: return value.size() == 8; case ValueRepresentation_IntegerString: return value.size() <= 12; case ValueRepresentation_LongString: return value.size() <= 64; case ValueRepresentation_LongText: return value.size() <= 10240; case ValueRepresentation_OtherByte: return true; case ValueRepresentation_OtherDouble: return value.size() <= (static_cast(1) << 32) - 8; case ValueRepresentation_OtherFloat: return value.size() <= (static_cast(1) << 32) - 4; case ValueRepresentation_OtherLong: return true; case ValueRepresentation_OtherWord: return true; case ValueRepresentation_PersonName: return true; case ValueRepresentation_ShortString: return value.size() <= 16; case ValueRepresentation_SignedLong: return value.size() == 4; case ValueRepresentation_Sequence: return true; case ValueRepresentation_SignedShort: return value.size() == 2; case ValueRepresentation_ShortText: return value.size() <= 1024; case ValueRepresentation_Time: return value.size() <= 28; case ValueRepresentation_UnlimitedCharacters: return value.size() <= (static_cast(1) << 32) - 2; case ValueRepresentation_UniqueIdentifier: return value.size() <= 64; case ValueRepresentation_UnsignedLong: return value.size() == 4; case ValueRepresentation_Unknown: return true; case ValueRepresentation_UniversalResource: return value.size() <= (static_cast(1) << 32) - 2; case ValueRepresentation_UnsignedShort: return value.size() == 2; case ValueRepresentation_UnlimitedText: return value.size() <= (static_cast(1) << 32) - 2; default: // Assume unsupported tags are OK return true; } } static void RemoveTagPadding(std::string& value, const ValueRepresentation& vr) { /** * Remove padding from character strings, if need be. For the time * being, only the UI VR is supported. * http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html **/ switch (vr) { case ValueRepresentation_UniqueIdentifier: { /** * "Values with a VR of UI shall be padded with a single * trailing NULL (00H) character when necessary to achieve even * length." **/ if (!value.empty() && value[value.size() - 1] == '\0') { value.resize(value.size() - 1); } break; } /** * TODO implement other VR **/ default: // No padding is applicable to this VR break; } } static bool ReadNextTag(DicomTag& tag, ValueRepresentation& vr, std::string& value, const char* dicom, size_t size, size_t& position) { /** * http://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2 * This function reads a data element with Explicit VR encoded using Little-Endian. **/ if (position + 6 > size) { return false; } tag = DicomTag(ReadUnsignedInteger16(dicom + position), ReadUnsignedInteger16(dicom + position + 2)); vr = StringToValueRepresentation(std::string(dicom + position + 4, 2), true); if (vr == ValueRepresentation_NotSupported) { return false; } if (vr == ValueRepresentation_OtherByte || vr == ValueRepresentation_OtherDouble || vr == ValueRepresentation_OtherFloat || vr == ValueRepresentation_OtherLong || vr == ValueRepresentation_OtherWord || vr == ValueRepresentation_Sequence || vr == ValueRepresentation_UnlimitedCharacters || vr == ValueRepresentation_UniversalResource || vr == ValueRepresentation_UnlimitedText || vr == ValueRepresentation_Unknown) // Note that "UN" should never appear in the Meta Information { if (position + 12 > size) { return false; } uint32_t length = ReadUnsignedInteger32(dicom + position + 8); if (position + 12 + length > size) { return false; } value.assign(dicom + position + 12, length); position += (12 + length); } else { if (position + 8 > size) { return false; } uint16_t length = ReadUnsignedInteger16(dicom + position + 6); if (position + 8 + length > size) { return false; } value.assign(dicom + position + 8, length); position += (8 + length); } if (!ValidateTag(vr, value)) { return false; } RemoveTagPadding(value, vr); return true; } bool DicomMap::ParseDicomMetaInformation(DicomMap& result, const char* dicom, size_t size) { /** * http://dicom.nema.org/medical/dicom/current/output/chtml/part10/chapter_7.html * According to Table 7.1-1, besides the "DICM" DICOM prefix, the * file preamble (i.e. dicom[0..127]) should not be taken into * account to determine whether the file is or is not a DICOM file. **/ if (size < 132 || dicom[128] != 'D' || dicom[129] != 'I' || dicom[130] != 'C' || dicom[131] != 'M') { return false; } /** * The DICOM File Meta Information must be encoded using the * Explicit VR Little Endian Transfer Syntax * (UID=1.2.840.10008.1.2.1). **/ result.Clear(); // First, we read the "File Meta Information Group Length" tag // (0002,0000) to know where to stop reading the meta header size_t position = 132; DicomTag tag(0x0000, 0x0000); // Dummy initialization ValueRepresentation vr; std::string value; if (!ReadNextTag(tag, vr, value, dicom, size, position) || tag.GetGroup() != 0x0002 || tag.GetElement() != 0x0000 || vr != ValueRepresentation_UnsignedLong || value.size() != 4) { return false; } size_t stopPosition = position + ReadUnsignedInteger32(value.c_str()); if (stopPosition > size) { return false; } while (position < stopPosition) { if (ReadNextTag(tag, vr, value, dicom, size, position)) { result.SetValue(tag, value, IsBinaryValueRepresentation(vr)); } else { return false; } } return true; } } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomMap.h0000644000000000000000000001244613133653001021260 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "DicomTag.h" #include "DicomValue.h" #include "../Enumerations.h" #include #include #include namespace Orthanc { class DicomMap : public boost::noncopyable { private: friend class DicomArray; friend class FromDcmtkBridge; friend class ParsedDicomFile; typedef std::map Map; Map map_; // Warning: This takes the ownership of "value" void SetValue(uint16_t group, uint16_t element, DicomValue* value); void SetValue(DicomTag tag, DicomValue* value); void ExtractTags(DicomMap& source, const DicomTag* tags, size_t count) const; static void GetMainDicomTagsInternal(std::set& result, ResourceType level); public: DicomMap() { } ~DicomMap() { Clear(); } size_t GetSize() const { return map_.size(); } DicomMap* Clone() const; void Assign(const DicomMap& other); void Clear(); void SetValue(uint16_t group, uint16_t element, const DicomValue& value) { SetValue(group, element, value.Clone()); } void SetValue(const DicomTag& tag, const DicomValue& value) { SetValue(tag, value.Clone()); } void SetValue(const DicomTag& tag, const std::string& str, bool isBinary) { SetValue(tag, new DicomValue(str, isBinary)); } void SetValue(uint16_t group, uint16_t element, const std::string& str, bool isBinary) { SetValue(group, element, new DicomValue(str, isBinary)); } bool HasTag(uint16_t group, uint16_t element) const { return HasTag(DicomTag(group, element)); } bool HasTag(const DicomTag& tag) const { return map_.find(tag) != map_.end(); } const DicomValue& GetValue(uint16_t group, uint16_t element) const { return GetValue(DicomTag(group, element)); } const DicomValue& GetValue(const DicomTag& tag) const; // DO NOT delete the returned value! const DicomValue* TestAndGetValue(uint16_t group, uint16_t element) const { return TestAndGetValue(DicomTag(group, element)); } // DO NOT delete the returned value! const DicomValue* TestAndGetValue(const DicomTag& tag) const; void Remove(const DicomTag& tag); void ExtractPatientInformation(DicomMap& result) const; void ExtractStudyInformation(DicomMap& result) const; void ExtractSeriesInformation(DicomMap& result) const; void ExtractInstanceInformation(DicomMap& result) const; static void SetupFindPatientTemplate(DicomMap& result); static void SetupFindStudyTemplate(DicomMap& result); static void SetupFindSeriesTemplate(DicomMap& result); static void SetupFindInstanceTemplate(DicomMap& result); void CopyTagIfExists(const DicomMap& source, const DicomTag& tag); static bool IsMainDicomTag(const DicomTag& tag, ResourceType level); static bool IsMainDicomTag(const DicomTag& tag); static void GetMainDicomTags(std::set& result, ResourceType level); static void GetMainDicomTags(std::set& result); void GetTags(std::set& tags) const; static void LoadMainDicomTags(const DicomTag*& tags, size_t& size, ResourceType level); static bool ParseDicomMetaInformation(DicomMap& result, const char* dicom, size_t size); }; } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomTag.cpp0000644000000000000000000002734313133653001021613 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "DicomTag.h" #include "../OrthancException.h" #include #include #include namespace Orthanc { bool DicomTag::operator< (const DicomTag& other) const { if (group_ < other.group_) return true; if (group_ > other.group_) return false; return element_ < other.element_; } std::ostream& operator<< (std::ostream& o, const DicomTag& tag) { using namespace std; ios_base::fmtflags state = o.flags(); o.flags(ios::right | ios::hex); o << "(" << setfill('0') << setw(4) << tag.GetGroup() << "," << setw(4) << tag.GetElement() << ")"; o.flags(state); return o; } std::string DicomTag::Format() const { char b[16]; sprintf(b, "%04x,%04x", group_, element_); return std::string(b); } const char* DicomTag::GetMainTagsName() const { if (*this == DICOM_TAG_ACCESSION_NUMBER) return "AccessionNumber"; if (*this == DICOM_TAG_SOP_INSTANCE_UID) return "SOPInstanceUID"; if (*this == DICOM_TAG_PATIENT_ID) return "PatientID"; if (*this == DICOM_TAG_SERIES_INSTANCE_UID) return "SeriesInstanceUID"; if (*this == DICOM_TAG_STUDY_INSTANCE_UID) return "StudyInstanceUID"; if (*this == DICOM_TAG_PIXEL_DATA) return "PixelData"; if (*this == DICOM_TAG_IMAGE_INDEX) return "ImageIndex"; if (*this == DICOM_TAG_INSTANCE_NUMBER) return "InstanceNumber"; if (*this == DICOM_TAG_NUMBER_OF_SLICES) return "NumberOfSlices"; if (*this == DICOM_TAG_NUMBER_OF_FRAMES) return "NumberOfFrames"; if (*this == DICOM_TAG_CARDIAC_NUMBER_OF_IMAGES) return "CardiacNumberOfImages"; if (*this == DICOM_TAG_IMAGES_IN_ACQUISITION) return "ImagesInAcquisition"; if (*this == DICOM_TAG_PATIENT_NAME) return "PatientName"; if (*this == DICOM_TAG_IMAGE_POSITION_PATIENT) return "ImagePositionPatient"; if (*this == DICOM_TAG_IMAGE_ORIENTATION_PATIENT) return "ImageOrientationPatient"; return ""; } void DicomTag::AddTagsForModule(std::set& target, DicomModule module) { // REFERENCE: 11_03pu.pdf, DICOM PS 3.3 2011 - Information Object Definitions switch (module) { case DicomModule_Patient: // This is Table C.7-1 "Patient Module Attributes" (p. 373) target.insert(DicomTag(0x0010, 0x0010)); // Patient's name target.insert(DicomTag(0x0010, 0x0020)); // Patient ID target.insert(DicomTag(0x0010, 0x0030)); // Patient's birth date target.insert(DicomTag(0x0010, 0x0040)); // Patient's sex target.insert(DicomTag(0x0008, 0x1120)); // Referenced patient sequence target.insert(DicomTag(0x0010, 0x0032)); // Patient's birth time target.insert(DicomTag(0x0010, 0x1000)); // Other patient IDs target.insert(DicomTag(0x0010, 0x1002)); // Other patient IDs sequence target.insert(DicomTag(0x0010, 0x1001)); // Other patient names target.insert(DicomTag(0x0010, 0x2160)); // Ethnic group target.insert(DicomTag(0x0010, 0x4000)); // Patient comments target.insert(DicomTag(0x0010, 0x2201)); // Patient species description target.insert(DicomTag(0x0010, 0x2202)); // Patient species code sequence target.insert(DicomTag(0x0010, 0x2292)); // Patient breed description target.insert(DicomTag(0x0010, 0x2293)); // Patient breed code sequence target.insert(DicomTag(0x0010, 0x2294)); // Breed registration sequence target.insert(DicomTag(0x0010, 0x2297)); // Responsible person target.insert(DicomTag(0x0010, 0x2298)); // Responsible person role target.insert(DicomTag(0x0010, 0x2299)); // Responsible organization target.insert(DicomTag(0x0012, 0x0062)); // Patient identity removed target.insert(DicomTag(0x0012, 0x0063)); // De-identification method target.insert(DicomTag(0x0012, 0x0064)); // De-identification method code sequence // Table 10-18 ISSUER OF PATIENT ID MACRO (p. 112) target.insert(DicomTag(0x0010, 0x0021)); // Issuer of Patient ID target.insert(DicomTag(0x0010, 0x0024)); // Issuer of Patient ID qualifiers sequence break; case DicomModule_Study: // This is Table C.7-3 "General Study Module Attributes" (p. 378) target.insert(DicomTag(0x0020, 0x000d)); // Study instance UID target.insert(DicomTag(0x0008, 0x0020)); // Study date target.insert(DicomTag(0x0008, 0x0030)); // Study time target.insert(DicomTag(0x0008, 0x0090)); // Referring physician's name target.insert(DicomTag(0x0008, 0x0096)); // Referring physician identification sequence target.insert(DicomTag(0x0020, 0x0010)); // Study ID target.insert(DicomTag(0x0008, 0x0050)); // Accession number target.insert(DicomTag(0x0008, 0x0051)); // Issuer of accession number sequence target.insert(DicomTag(0x0008, 0x1030)); // Study description target.insert(DicomTag(0x0008, 0x1048)); // Physician(s) of record target.insert(DicomTag(0x0008, 0x1049)); // Physician(s) of record identification sequence target.insert(DicomTag(0x0008, 0x1060)); // Name of physician(s) reading study target.insert(DicomTag(0x0008, 0x1062)); // Physician(s) reading study identification sequence target.insert(DicomTag(0x0032, 0x1034)); // Requesting service code sequence target.insert(DicomTag(0x0008, 0x1110)); // Referenced study sequence target.insert(DicomTag(0x0008, 0x1032)); // Procedure code sequence target.insert(DicomTag(0x0040, 0x1012)); // Reason for performed procedure code sequence break; case DicomModule_Series: // This is Table C.7-5 "General Series Module Attributes" (p. 385) target.insert(DicomTag(0x0008, 0x0060)); // Modality target.insert(DicomTag(0x0020, 0x000e)); // Series Instance UID target.insert(DicomTag(0x0020, 0x0011)); // Series Number target.insert(DicomTag(0x0020, 0x0060)); // Laterality target.insert(DicomTag(0x0008, 0x0021)); // Series Date target.insert(DicomTag(0x0008, 0x0031)); // Series Time target.insert(DicomTag(0x0008, 0x1050)); // Performing Physicians’ Name target.insert(DicomTag(0x0008, 0x1052)); // Performing Physician Identification Sequence target.insert(DicomTag(0x0018, 0x1030)); // Protocol Name target.insert(DicomTag(0x0008, 0x103e)); // Series Description target.insert(DicomTag(0x0008, 0x103f)); // Series Description Code Sequence target.insert(DicomTag(0x0008, 0x1070)); // Operators' Name target.insert(DicomTag(0x0008, 0x1072)); // Operator Identification Sequence target.insert(DicomTag(0x0008, 0x1111)); // Referenced Performed Procedure Step Sequence target.insert(DicomTag(0x0008, 0x1250)); // Related Series Sequence target.insert(DicomTag(0x0018, 0x0015)); // Body Part Examined target.insert(DicomTag(0x0018, 0x5100)); // Patient Position target.insert(DicomTag(0x0028, 0x0108)); // Smallest Pixel Value in Series target.insert(DicomTag(0x0029, 0x0109)); // Largest Pixel Value in Series target.insert(DicomTag(0x0040, 0x0275)); // Request Attributes Sequence target.insert(DicomTag(0x0010, 0x2210)); // Anatomical Orientation Type // Table 10-16 PERFORMED PROCEDURE STEP SUMMARY MACRO ATTRIBUTES target.insert(DicomTag(0x0040, 0x0253)); // Performed Procedure Step ID target.insert(DicomTag(0x0040, 0x0244)); // Performed Procedure Step Start Date target.insert(DicomTag(0x0040, 0x0245)); // Performed Procedure Step Start Time target.insert(DicomTag(0x0040, 0x0254)); // Performed Procedure Step Description target.insert(DicomTag(0x0040, 0x0260)); // Performed Protocol Code Sequence target.insert(DicomTag(0x0040, 0x0280)); // Comments on the Performed Procedure Step break; case DicomModule_Instance: // This is Table C.12-1 "SOP Common Module Attributes" (p. 1207) target.insert(DicomTag(0x0008, 0x0016)); // SOP Class UID target.insert(DicomTag(0x0008, 0x0018)); // SOP Instance UID target.insert(DicomTag(0x0008, 0x0005)); // Specific Character Set target.insert(DicomTag(0x0008, 0x0012)); // Instance Creation Date target.insert(DicomTag(0x0008, 0x0013)); // Instance Creation Time target.insert(DicomTag(0x0008, 0x0014)); // Instance Creator UID target.insert(DicomTag(0x0008, 0x001a)); // Related General SOP Class UID target.insert(DicomTag(0x0008, 0x001b)); // Original Specialized SOP Class UID target.insert(DicomTag(0x0008, 0x0110)); // Coding Scheme Identification Sequence target.insert(DicomTag(0x0008, 0x0201)); // Timezone Offset From UTC target.insert(DicomTag(0x0018, 0xa001)); // Contributing Equipment Sequence target.insert(DicomTag(0x0020, 0x0013)); // Instance Number target.insert(DicomTag(0x0100, 0x0410)); // SOP Instance Status target.insert(DicomTag(0x0100, 0x0420)); // SOP Authorization DateTime target.insert(DicomTag(0x0100, 0x0424)); // SOP Authorization Comment target.insert(DicomTag(0x0100, 0x0426)); // Authorization Equipment Certification Number target.insert(DicomTag(0x0400, 0x0500)); // Encrypted Attributes Sequence target.insert(DicomTag(0x0400, 0x0561)); // Original Attributes Sequence target.insert(DicomTag(0x0040, 0xa390)); // HL7 Structured Document Reference Sequence target.insert(DicomTag(0x0028, 0x0303)); // Longitudinal Temporal Information Modified // Table C.12-6 "DIGITAL SIGNATURES MACRO ATTRIBUTES" (p. 1216) target.insert(DicomTag(0x4ffe, 0x0001)); // MAC Parameters sequence target.insert(DicomTag(0xfffa, 0xfffa)); // Digital signatures sequence break; // TODO IMAGE MODULE? default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomTag.h0000644000000000000000000001761313133653001021257 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include #include #include "../Enumerations.h" namespace Orthanc { class DicomTag { // This must stay a POD (plain old data structure) private: uint16_t group_; uint16_t element_; public: DicomTag(uint16_t group, uint16_t element) : group_(group), element_(element) { } uint16_t GetGroup() const { return group_; } uint16_t GetElement() const { return element_; } bool IsPrivate() const { return group_ % 2 == 1; } const char* GetMainTagsName() const; bool operator< (const DicomTag& other) const; bool operator== (const DicomTag& other) const { return group_ == other.group_ && element_ == other.element_; } bool operator!= (const DicomTag& other) const { return !(*this == other); } std::string Format() const; friend std::ostream& operator<< (std::ostream& o, const DicomTag& tag); static void AddTagsForModule(std::set& target, DicomModule module); }; // Aliases for the most useful tags static const DicomTag DICOM_TAG_ACCESSION_NUMBER(0x0008, 0x0050); static const DicomTag DICOM_TAG_SOP_INSTANCE_UID(0x0008, 0x0018); static const DicomTag DICOM_TAG_PATIENT_ID(0x0010, 0x0020); static const DicomTag DICOM_TAG_SERIES_INSTANCE_UID(0x0020, 0x000e); static const DicomTag DICOM_TAG_STUDY_INSTANCE_UID(0x0020, 0x000d); static const DicomTag DICOM_TAG_PIXEL_DATA(0x7fe0, 0x0010); static const DicomTag DICOM_TAG_TRANSFER_SYNTAX_UID(0x0002, 0x0010); static const DicomTag DICOM_TAG_IMAGE_INDEX(0x0054, 0x1330); static const DicomTag DICOM_TAG_INSTANCE_NUMBER(0x0020, 0x0013); static const DicomTag DICOM_TAG_NUMBER_OF_SLICES(0x0054, 0x0081); static const DicomTag DICOM_TAG_NUMBER_OF_TIME_SLICES(0x0054, 0x0101); static const DicomTag DICOM_TAG_NUMBER_OF_FRAMES(0x0028, 0x0008); static const DicomTag DICOM_TAG_CARDIAC_NUMBER_OF_IMAGES(0x0018, 0x1090); static const DicomTag DICOM_TAG_IMAGES_IN_ACQUISITION(0x0020, 0x1002); static const DicomTag DICOM_TAG_PATIENT_NAME(0x0010, 0x0010); static const DicomTag DICOM_TAG_ENCAPSULATED_DOCUMENT(0x0042, 0x0011); static const DicomTag DICOM_TAG_STUDY_DESCRIPTION(0x0008, 0x1030); static const DicomTag DICOM_TAG_SERIES_DESCRIPTION(0x0008, 0x103e); static const DicomTag DICOM_TAG_MODALITY(0x0008, 0x0060); // The following is used for "modify/anonymize" operations static const DicomTag DICOM_TAG_SOP_CLASS_UID(0x0008, 0x0016); static const DicomTag DICOM_TAG_MEDIA_STORAGE_SOP_CLASS_UID(0x0002, 0x0002); static const DicomTag DICOM_TAG_MEDIA_STORAGE_SOP_INSTANCE_UID(0x0002, 0x0003); static const DicomTag DICOM_TAG_DEIDENTIFICATION_METHOD(0x0012, 0x0063); // DICOM tags used for fMRI (thanks to Will Ryder) static const DicomTag DICOM_TAG_NUMBER_OF_TEMPORAL_POSITIONS(0x0020, 0x0105); static const DicomTag DICOM_TAG_TEMPORAL_POSITION_IDENTIFIER(0x0020, 0x0100); // Tags for C-FIND and C-MOVE static const DicomTag DICOM_TAG_MESSAGE_ID(0x0000, 0x0110); static const DicomTag DICOM_TAG_SPECIFIC_CHARACTER_SET(0x0008, 0x0005); static const DicomTag DICOM_TAG_QUERY_RETRIEVE_LEVEL(0x0008, 0x0052); static const DicomTag DICOM_TAG_MODALITIES_IN_STUDY(0x0008, 0x0061); // Tags for images static const DicomTag DICOM_TAG_COLUMNS(0x0028, 0x0011); static const DicomTag DICOM_TAG_ROWS(0x0028, 0x0010); static const DicomTag DICOM_TAG_SAMPLES_PER_PIXEL(0x0028, 0x0002); static const DicomTag DICOM_TAG_BITS_ALLOCATED(0x0028, 0x0100); static const DicomTag DICOM_TAG_BITS_STORED(0x0028, 0x0101); static const DicomTag DICOM_TAG_HIGH_BIT(0x0028, 0x0102); static const DicomTag DICOM_TAG_PIXEL_REPRESENTATION(0x0028, 0x0103); static const DicomTag DICOM_TAG_PLANAR_CONFIGURATION(0x0028, 0x0006); static const DicomTag DICOM_TAG_PHOTOMETRIC_INTERPRETATION(0x0028, 0x0004); static const DicomTag DICOM_TAG_IMAGE_ORIENTATION_PATIENT(0x0020, 0x0037); static const DicomTag DICOM_TAG_IMAGE_POSITION_PATIENT(0x0020, 0x0032); // Tags related to date and time static const DicomTag DICOM_TAG_ACQUISITION_DATE(0x0008, 0x0022); static const DicomTag DICOM_TAG_ACQUISITION_TIME(0x0008, 0x0032); static const DicomTag DICOM_TAG_CONTENT_DATE(0x0008, 0x0023); static const DicomTag DICOM_TAG_CONTENT_TIME(0x0008, 0x0033); static const DicomTag DICOM_TAG_INSTANCE_CREATION_DATE(0x0008, 0x0012); static const DicomTag DICOM_TAG_INSTANCE_CREATION_TIME(0x0008, 0x0013); static const DicomTag DICOM_TAG_PATIENT_BIRTH_DATE(0x0010, 0x0030); static const DicomTag DICOM_TAG_PATIENT_BIRTH_TIME(0x0010, 0x0032); static const DicomTag DICOM_TAG_SERIES_DATE(0x0008, 0x0021); static const DicomTag DICOM_TAG_SERIES_TIME(0x0008, 0x0031); static const DicomTag DICOM_TAG_STUDY_DATE(0x0008, 0x0020); static const DicomTag DICOM_TAG_STUDY_TIME(0x0008, 0x0030); // Various tags static const DicomTag DICOM_TAG_SERIES_TYPE(0x0054, 0x1000); static const DicomTag DICOM_TAG_REQUESTED_PROCEDURE_DESCRIPTION(0x0032, 0x1060); static const DicomTag DICOM_TAG_INSTITUTION_NAME(0x0008, 0x0080); static const DicomTag DICOM_TAG_REQUESTING_PHYSICIAN(0x0032, 0x1032); static const DicomTag DICOM_TAG_REFERRING_PHYSICIAN_NAME(0x0008, 0x0090); static const DicomTag DICOM_TAG_OPERATOR_NAME(0x0008, 0x1070); static const DicomTag DICOM_TAG_PERFORMED_PROCEDURE_STEP_DESCRIPTION(0x0040, 0x0254); static const DicomTag DICOM_TAG_IMAGE_COMMENTS(0x0020, 0x4000); static const DicomTag DICOM_TAG_ACQUISITION_DEVICE_PROCESSING_DESCRIPTION(0x0018, 0x1400); static const DicomTag DICOM_TAG_CONTRAST_BOLUS_AGENT(0x0018, 0x0010); // Counting patients, studies and series // https://www.medicalconnections.co.uk/kb/Counting_Studies_Series_and_Instances static const DicomTag DICOM_TAG_NUMBER_OF_PATIENT_RELATED_STUDIES(0x0020, 0x1200); static const DicomTag DICOM_TAG_NUMBER_OF_PATIENT_RELATED_SERIES(0x0020, 0x1202); static const DicomTag DICOM_TAG_NUMBER_OF_PATIENT_RELATED_INSTANCES(0x0020, 0x1204); static const DicomTag DICOM_TAG_NUMBER_OF_STUDY_RELATED_SERIES(0x0020, 0x1206); static const DicomTag DICOM_TAG_NUMBER_OF_STUDY_RELATED_INSTANCES(0x0020, 0x1208); static const DicomTag DICOM_TAG_NUMBER_OF_SERIES_RELATED_INSTANCES(0x0020, 0x1209); static const DicomTag DICOM_TAG_SOP_CLASSES_IN_STUDY(0x0008, 0x0062); } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomValue.cpp0000644000000000000000000000543413133653001022151 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "DicomValue.h" #include "../OrthancException.h" #include "../Toolbox.h" namespace Orthanc { DicomValue::DicomValue(const DicomValue& other) : type_(other.type_), content_(other.content_) { } DicomValue::DicomValue(const std::string& content, bool isBinary) : type_(isBinary ? Type_Binary : Type_String), content_(content) { } DicomValue::DicomValue(const char* data, size_t size, bool isBinary) : type_(isBinary ? Type_Binary : Type_String) { content_.assign(data, size); } const std::string& DicomValue::GetContent() const { if (type_ == Type_Null) { throw OrthancException(ErrorCode_BadParameterType); } else { return content_; } } DicomValue* DicomValue::Clone() const { return new DicomValue(*this); } #if ORTHANC_ENABLE_BASE64 == 1 void DicomValue::FormatDataUriScheme(std::string& target, const std::string& mime) const { Toolbox::EncodeBase64(target, GetContent()); target.insert(0, "data:" + mime + ";base64,"); } #endif } OrthancWebViewer-2.3/Orthanc/Core/DicomFormat/DicomValue.h0000644000000000000000000000535613133653001021621 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include #if !defined(ORTHANC_ENABLE_BASE64) # error The macro ORTHANC_ENABLE_BASE64 must be defined #endif namespace Orthanc { class DicomValue : public boost::noncopyable { private: enum Type { Type_Null, Type_String, Type_Binary }; Type type_; std::string content_; DicomValue(const DicomValue& other); public: DicomValue() : type_(Type_Null) { } DicomValue(const std::string& content, bool isBinary); DicomValue(const char* data, size_t size, bool isBinary); const std::string& GetContent() const; bool IsNull() const { return type_ == Type_Null; } bool IsBinary() const { return type_ == Type_Binary; } DicomValue* Clone() const; #if ORTHANC_ENABLE_BASE64 == 1 void FormatDataUriScheme(std::string& target, const std::string& mime) const; void FormatDataUriScheme(std::string& target) const { FormatDataUriScheme(target, "application/octet-stream"); } #endif }; } OrthancWebViewer-2.3/Orthanc/Core/Endianness.h0000644000000000000000000001260413133653001017446 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once /******************************************************************** ** LINUX ARCHITECTURES ********************************************************************/ #if defined(__linux__) # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 1 # include #endif /******************************************************************** ** WINDOWS ARCHITECTURES ** ** On Windows x86, "host" will always be little-endian ("le"). ********************************************************************/ #if defined(_WIN32) # if defined(_MSC_VER) // Visual Studio - http://msdn.microsoft.com/en-us/library/a3140177.aspx # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 1 # define be16toh(x) _byteswap_ushort(x) # define be32toh(x) _byteswap_ulong(x) # define be64toh(x) _byteswap_uint64(x) # elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) // MinGW >= 4.3 - Use builtin intrinsic for byte swapping # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 1 # define be16toh(x) __builtin_bswap16(x) # define be32toh(x) __builtin_bswap32(x) # define be64toh(x) __builtin_bswap64(x) # else // MinGW <= 4.2, we must manually implement the byte swapping # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 0 # define be16toh(x) __orthanc_bswap16(x) # define be32toh(x) __orthanc_bswap32(x) # define be64toh(x) __orthanc_bswap64(x) # endif # define htobe16(x) be16toh(x) # define htobe32(x) be32toh(x) # define htobe64(x) be64toh(x) # define htole16(x) x # define htole32(x) x # define htole64(x) x # define le16toh(x) x # define le32toh(x) x # define le64toh(x) x #endif /******************************************************************** ** FREEBSD ARCHITECTURES ********************************************************************/ #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 1 # include #endif /******************************************************************** ** APPLE ARCHITECTURES (including OS X) ********************************************************************/ #if defined(__APPLE__) # define ORTHANC_HAS_BUILTIN_BYTE_SWAP 1 # include # define be16toh(x) OSSwapBigToHostInt16(x) # define be32toh(x) OSSwapBigToHostInt32(x) # define be64toh(x) OSSwapBigToHostInt64(x) # define htobe16(x) OSSwapHostToBigInt16(x) # define htobe32(x) OSSwapHostToBigInt32(x) # define htobe64(x) OSSwapHostToBigInt64(x) # define htole16(x) OSSwapHostToLittleInt16(x) # define htole32(x) OSSwapHostToLittleInt32(x) # define htole64(x) OSSwapHostToLittleInt64(x) # define le16toh(x) OSSwapLittleToHostInt16(x) # define le32toh(x) OSSwapLittleToHostInt32(x) # define le64toh(x) OSSwapLittleToHostInt64(x) #endif /******************************************************************** ** PORTABLE (BUT SLOW) IMPLEMENTATION OF BYTE-SWAPPING ********************************************************************/ #if ORTHANC_HAS_BUILTIN_BYTE_SWAP != 1 #include static inline uint16_t __orthanc_bswap16(uint16_t a) { return (a << 8) | (a >> 8); } static inline uint32_t __orthanc_bswap32(uint32_t a) { const uint8_t* p = reinterpret_cast(&a); return (static_cast(p[0]) << 24 | static_cast(p[1]) << 16 | static_cast(p[2]) << 8 | static_cast(p[3])); } static inline uint64_t __orthanc_bswap64(uint64_t a) { const uint8_t* p = reinterpret_cast(&a); return (static_cast(p[0]) << 56 | static_cast(p[1]) << 48 | static_cast(p[2]) << 40 | static_cast(p[3]) << 32 | static_cast(p[4]) << 24 | static_cast(p[5]) << 16 | static_cast(p[6]) << 8 | static_cast(p[7])); } #endif OrthancWebViewer-2.3/Orthanc/Core/Enumerations.cpp0000644000000000000000000010745513133653001020374 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "PrecompiledHeaders.h" #include "Enumerations.h" #include "OrthancException.h" #include "Toolbox.h" #include "Logging.h" #include #include namespace Orthanc { // This function is autogenerated by the script // "Resources/GenerateErrorCodes.py" const char* EnumerationToString(ErrorCode error) { switch (error) { case ErrorCode_InternalError: return "Internal error"; case ErrorCode_Success: return "Success"; case ErrorCode_Plugin: return "Error encountered within the plugin engine"; case ErrorCode_NotImplemented: return "Not implemented yet"; case ErrorCode_ParameterOutOfRange: return "Parameter out of range"; case ErrorCode_NotEnoughMemory: return "The server hosting Orthanc is running out of memory"; case ErrorCode_BadParameterType: return "Bad type for a parameter"; case ErrorCode_BadSequenceOfCalls: return "Bad sequence of calls"; case ErrorCode_InexistentItem: return "Accessing an inexistent item"; case ErrorCode_BadRequest: return "Bad request"; case ErrorCode_NetworkProtocol: return "Error in the network protocol"; case ErrorCode_SystemCommand: return "Error while calling a system command"; case ErrorCode_Database: return "Error with the database engine"; case ErrorCode_UriSyntax: return "Badly formatted URI"; case ErrorCode_InexistentFile: return "Inexistent file"; case ErrorCode_CannotWriteFile: return "Cannot write to file"; case ErrorCode_BadFileFormat: return "Bad file format"; case ErrorCode_Timeout: return "Timeout"; case ErrorCode_UnknownResource: return "Unknown resource"; case ErrorCode_IncompatibleDatabaseVersion: return "Incompatible version of the database"; case ErrorCode_FullStorage: return "The file storage is full"; case ErrorCode_CorruptedFile: return "Corrupted file (e.g. inconsistent MD5 hash)"; case ErrorCode_InexistentTag: return "Inexistent tag"; case ErrorCode_ReadOnly: return "Cannot modify a read-only data structure"; case ErrorCode_IncompatibleImageFormat: return "Incompatible format of the images"; case ErrorCode_IncompatibleImageSize: return "Incompatible size of the images"; case ErrorCode_SharedLibrary: return "Error while using a shared library (plugin)"; case ErrorCode_UnknownPluginService: return "Plugin invoking an unknown service"; case ErrorCode_UnknownDicomTag: return "Unknown DICOM tag"; case ErrorCode_BadJson: return "Cannot parse a JSON document"; case ErrorCode_Unauthorized: return "Bad credentials were provided to an HTTP request"; case ErrorCode_BadFont: return "Badly formatted font file"; case ErrorCode_DatabasePlugin: return "The plugin implementing a custom database back-end does not fulfill the proper interface"; case ErrorCode_StorageAreaPlugin: return "Error in the plugin implementing a custom storage area"; case ErrorCode_EmptyRequest: return "The request is empty"; case ErrorCode_NotAcceptable: return "Cannot send a response which is acceptable according to the Accept HTTP header"; case ErrorCode_NullPointer: return "Cannot handle a NULL pointer"; case ErrorCode_SQLiteNotOpened: return "SQLite: The database is not opened"; case ErrorCode_SQLiteAlreadyOpened: return "SQLite: Connection is already open"; case ErrorCode_SQLiteCannotOpen: return "SQLite: Unable to open the database"; case ErrorCode_SQLiteStatementAlreadyUsed: return "SQLite: This cached statement is already being referred to"; case ErrorCode_SQLiteExecute: return "SQLite: Cannot execute a command"; case ErrorCode_SQLiteRollbackWithoutTransaction: return "SQLite: Rolling back a nonexistent transaction (have you called Begin()?)"; case ErrorCode_SQLiteCommitWithoutTransaction: return "SQLite: Committing a nonexistent transaction"; case ErrorCode_SQLiteRegisterFunction: return "SQLite: Unable to register a function"; case ErrorCode_SQLiteFlush: return "SQLite: Unable to flush the database"; case ErrorCode_SQLiteCannotRun: return "SQLite: Cannot run a cached statement"; case ErrorCode_SQLiteCannotStep: return "SQLite: Cannot step over a cached statement"; case ErrorCode_SQLiteBindOutOfRange: return "SQLite: Bing a value while out of range (serious error)"; case ErrorCode_SQLitePrepareStatement: return "SQLite: Cannot prepare a cached statement"; case ErrorCode_SQLiteTransactionAlreadyStarted: return "SQLite: Beginning the same transaction twice"; case ErrorCode_SQLiteTransactionCommit: return "SQLite: Failure when committing the transaction"; case ErrorCode_SQLiteTransactionBegin: return "SQLite: Cannot start a transaction"; case ErrorCode_DirectoryOverFile: return "The directory to be created is already occupied by a regular file"; case ErrorCode_FileStorageCannotWrite: return "Unable to create a subdirectory or a file in the file storage"; case ErrorCode_DirectoryExpected: return "The specified path does not point to a directory"; case ErrorCode_HttpPortInUse: return "The TCP port of the HTTP server is privileged or already in use"; case ErrorCode_DicomPortInUse: return "The TCP port of the DICOM server is privileged or already in use"; case ErrorCode_BadHttpStatusInRest: return "This HTTP status is not allowed in a REST API"; case ErrorCode_RegularFileExpected: return "The specified path does not point to a regular file"; case ErrorCode_PathToExecutable: return "Unable to get the path to the executable"; case ErrorCode_MakeDirectory: return "Cannot create a directory"; case ErrorCode_BadApplicationEntityTitle: return "An application entity title (AET) cannot be empty or be longer than 16 characters"; case ErrorCode_NoCFindHandler: return "No request handler factory for DICOM C-FIND SCP"; case ErrorCode_NoCMoveHandler: return "No request handler factory for DICOM C-MOVE SCP"; case ErrorCode_NoCStoreHandler: return "No request handler factory for DICOM C-STORE SCP"; case ErrorCode_NoApplicationEntityFilter: return "No application entity filter"; case ErrorCode_NoSopClassOrInstance: return "DicomUserConnection: Unable to find the SOP class and instance"; case ErrorCode_NoPresentationContext: return "DicomUserConnection: No acceptable presentation context for modality"; case ErrorCode_DicomFindUnavailable: return "DicomUserConnection: The C-FIND command is not supported by the remote SCP"; case ErrorCode_DicomMoveUnavailable: return "DicomUserConnection: The C-MOVE command is not supported by the remote SCP"; case ErrorCode_CannotStoreInstance: return "Cannot store an instance"; case ErrorCode_CreateDicomNotString: return "Only string values are supported when creating DICOM instances"; case ErrorCode_CreateDicomOverrideTag: return "Trying to override a value inherited from a parent module"; case ErrorCode_CreateDicomUseContent: return "Use \"Content\" to inject an image into a new DICOM instance"; case ErrorCode_CreateDicomNoPayload: return "No payload is present for one instance in the series"; case ErrorCode_CreateDicomUseDataUriScheme: return "The payload of the DICOM instance must be specified according to Data URI scheme"; case ErrorCode_CreateDicomBadParent: return "Trying to attach a new DICOM instance to an inexistent resource"; case ErrorCode_CreateDicomParentIsInstance: return "Trying to attach a new DICOM instance to an instance (must be a series, study or patient)"; case ErrorCode_CreateDicomParentEncoding: return "Unable to get the encoding of the parent resource"; case ErrorCode_UnknownModality: return "Unknown modality"; case ErrorCode_BadJobOrdering: return "Bad ordering of filters in a job"; case ErrorCode_JsonToLuaTable: return "Cannot convert the given JSON object to a Lua table"; case ErrorCode_CannotCreateLua: return "Cannot create the Lua context"; case ErrorCode_CannotExecuteLua: return "Cannot execute a Lua command"; case ErrorCode_LuaAlreadyExecuted: return "Arguments cannot be pushed after the Lua function is executed"; case ErrorCode_LuaBadOutput: return "The Lua function does not give the expected number of outputs"; case ErrorCode_NotLuaPredicate: return "The Lua function is not a predicate (only true/false outputs allowed)"; case ErrorCode_LuaReturnsNoString: return "The Lua function does not return a string"; case ErrorCode_StorageAreaAlreadyRegistered: return "Another plugin has already registered a custom storage area"; case ErrorCode_DatabaseBackendAlreadyRegistered: return "Another plugin has already registered a custom database back-end"; case ErrorCode_DatabaseNotInitialized: return "Plugin trying to call the database during its initialization"; case ErrorCode_SslDisabled: return "Orthanc has been built without SSL support"; case ErrorCode_CannotOrderSlices: return "Unable to order the slices of the series"; case ErrorCode_NoWorklistHandler: return "No request handler factory for DICOM C-Find Modality SCP"; case ErrorCode_AlreadyExistingTag: return "Cannot override the value of a tag that already exists"; default: if (error >= ErrorCode_START_PLUGINS) { return "Error encountered within some plugin"; } else { return "Unknown error code"; } } } const char* EnumerationToString(HttpMethod method) { switch (method) { case HttpMethod_Get: return "GET"; case HttpMethod_Post: return "POST"; case HttpMethod_Delete: return "DELETE"; case HttpMethod_Put: return "PUT"; default: return "?"; } } const char* EnumerationToString(HttpStatus status) { switch (status) { case HttpStatus_100_Continue: return "Continue"; case HttpStatus_101_SwitchingProtocols: return "Switching Protocols"; case HttpStatus_102_Processing: return "Processing"; case HttpStatus_200_Ok: return "OK"; case HttpStatus_201_Created: return "Created"; case HttpStatus_202_Accepted: return "Accepted"; case HttpStatus_203_NonAuthoritativeInformation: return "Non-Authoritative Information"; case HttpStatus_204_NoContent: return "No Content"; case HttpStatus_205_ResetContent: return "Reset Content"; case HttpStatus_206_PartialContent: return "Partial Content"; case HttpStatus_207_MultiStatus: return "Multi-Status"; case HttpStatus_208_AlreadyReported: return "Already Reported"; case HttpStatus_226_IMUsed: return "IM Used"; case HttpStatus_300_MultipleChoices: return "Multiple Choices"; case HttpStatus_301_MovedPermanently: return "Moved Permanently"; case HttpStatus_302_Found: return "Found"; case HttpStatus_303_SeeOther: return "See Other"; case HttpStatus_304_NotModified: return "Not Modified"; case HttpStatus_305_UseProxy: return "Use Proxy"; case HttpStatus_307_TemporaryRedirect: return "Temporary Redirect"; case HttpStatus_400_BadRequest: return "Bad Request"; case HttpStatus_401_Unauthorized: return "Unauthorized"; case HttpStatus_402_PaymentRequired: return "Payment Required"; case HttpStatus_403_Forbidden: return "Forbidden"; case HttpStatus_404_NotFound: return "Not Found"; case HttpStatus_405_MethodNotAllowed: return "Method Not Allowed"; case HttpStatus_406_NotAcceptable: return "Not Acceptable"; case HttpStatus_407_ProxyAuthenticationRequired: return "Proxy Authentication Required"; case HttpStatus_408_RequestTimeout: return "Request Timeout"; case HttpStatus_409_Conflict: return "Conflict"; case HttpStatus_410_Gone: return "Gone"; case HttpStatus_411_LengthRequired: return "Length Required"; case HttpStatus_412_PreconditionFailed: return "Precondition Failed"; case HttpStatus_413_RequestEntityTooLarge: return "Request Entity Too Large"; case HttpStatus_414_RequestUriTooLong: return "Request-URI Too Long"; case HttpStatus_415_UnsupportedMediaType: return "Unsupported Media Type"; case HttpStatus_416_RequestedRangeNotSatisfiable: return "Requested Range Not Satisfiable"; case HttpStatus_417_ExpectationFailed: return "Expectation Failed"; case HttpStatus_422_UnprocessableEntity: return "Unprocessable Entity"; case HttpStatus_423_Locked: return "Locked"; case HttpStatus_424_FailedDependency: return "Failed Dependency"; case HttpStatus_426_UpgradeRequired: return "Upgrade Required"; case HttpStatus_500_InternalServerError: return "Internal Server Error"; case HttpStatus_501_NotImplemented: return "Not Implemented"; case HttpStatus_502_BadGateway: return "Bad Gateway"; case HttpStatus_503_ServiceUnavailable: return "Service Unavailable"; case HttpStatus_504_GatewayTimeout: return "Gateway Timeout"; case HttpStatus_505_HttpVersionNotSupported: return "HTTP Version Not Supported"; case HttpStatus_506_VariantAlsoNegotiates: return "Variant Also Negotiates"; case HttpStatus_507_InsufficientStorage: return "Insufficient Storage"; case HttpStatus_509_BandwidthLimitExceeded: return "Bandwidth Limit Exceeded"; case HttpStatus_510_NotExtended: return "Not Extended"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(ResourceType type) { switch (type) { case ResourceType_Patient: return "Patient"; case ResourceType_Study: return "Study"; case ResourceType_Series: return "Series"; case ResourceType_Instance: return "Instance"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(ImageFormat format) { switch (format) { case ImageFormat_Png: return "Png"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(Encoding encoding) { switch (encoding) { case Encoding_Ascii: return "Ascii"; case Encoding_Utf8: return "Utf8"; case Encoding_Latin1: return "Latin1"; case Encoding_Latin2: return "Latin2"; case Encoding_Latin3: return "Latin3"; case Encoding_Latin4: return "Latin4"; case Encoding_Latin5: return "Latin5"; case Encoding_Cyrillic: return "Cyrillic"; case Encoding_Windows1251: return "Windows1251"; case Encoding_Arabic: return "Arabic"; case Encoding_Greek: return "Greek"; case Encoding_Hebrew: return "Hebrew"; case Encoding_Thai: return "Thai"; case Encoding_Japanese: return "Japanese"; case Encoding_Chinese: return "Chinese"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(PhotometricInterpretation photometric) { switch (photometric) { case PhotometricInterpretation_RGB: return "RGB"; case PhotometricInterpretation_Monochrome1: return "MONOCHROME1"; case PhotometricInterpretation_Monochrome2: return "MONOCHROME2"; case PhotometricInterpretation_ARGB: return "ARGB"; case PhotometricInterpretation_CMYK: return "CMYK"; case PhotometricInterpretation_HSV: return "HSV"; case PhotometricInterpretation_Palette: return "PALETTE COLOR"; case PhotometricInterpretation_YBRFull: return "YBR_FULL"; case PhotometricInterpretation_YBRFull422: return "YBR_FULL_422"; case PhotometricInterpretation_YBRPartial420: return "YBR_PARTIAL_420"; case PhotometricInterpretation_YBRPartial422: return "YBR_PARTIAL_422"; case PhotometricInterpretation_YBR_ICT: return "YBR_ICT"; case PhotometricInterpretation_YBR_RCT: return "YBR_RCT"; case PhotometricInterpretation_Unknown: return "Unknown"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(RequestOrigin origin) { switch (origin) { case RequestOrigin_Unknown: return "Unknown"; case RequestOrigin_DicomProtocol: return "DicomProtocol"; case RequestOrigin_RestApi: return "RestApi"; case RequestOrigin_Plugins: return "Plugins"; case RequestOrigin_Lua: return "Lua"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(LogLevel level) { switch (level) { case LogLevel_Error: return "ERROR"; case LogLevel_Warning: return "WARNING"; case LogLevel_Info: return "INFO"; case LogLevel_Trace: return "TRACE"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* EnumerationToString(PixelFormat format) { switch (format) { case PixelFormat_RGB24: return "RGB24"; case PixelFormat_RGBA32: return "RGBA32"; case PixelFormat_BGRA32: return "BGRA32"; case PixelFormat_Grayscale8: return "Grayscale (unsigned 8bpp)"; case PixelFormat_Grayscale16: return "Grayscale (unsigned 16bpp)"; case PixelFormat_SignedGrayscale16: return "Grayscale (signed 16bpp)"; case PixelFormat_Float32: return "Grayscale (float 32bpp)"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } Encoding StringToEncoding(const char* encoding) { std::string s(encoding); Toolbox::ToUpperCase(s); if (s == "UTF8") { return Encoding_Utf8; } if (s == "ASCII") { return Encoding_Ascii; } if (s == "LATIN1") { return Encoding_Latin1; } if (s == "LATIN2") { return Encoding_Latin2; } if (s == "LATIN3") { return Encoding_Latin3; } if (s == "LATIN4") { return Encoding_Latin4; } if (s == "LATIN5") { return Encoding_Latin5; } if (s == "CYRILLIC") { return Encoding_Cyrillic; } if (s == "WINDOWS1251") { return Encoding_Windows1251; } if (s == "ARABIC") { return Encoding_Arabic; } if (s == "GREEK") { return Encoding_Greek; } if (s == "HEBREW") { return Encoding_Hebrew; } if (s == "THAI") { return Encoding_Thai; } if (s == "JAPANESE") { return Encoding_Japanese; } if (s == "CHINESE") { return Encoding_Chinese; } throw OrthancException(ErrorCode_ParameterOutOfRange); } ResourceType StringToResourceType(const char* type) { std::string s(type); Toolbox::ToUpperCase(s); if (s == "PATIENT" || s == "PATIENTS") { return ResourceType_Patient; } else if (s == "STUDY" || s == "STUDIES") { return ResourceType_Study; } else if (s == "SERIES") { return ResourceType_Series; } else if (s == "INSTANCE" || s == "IMAGE" || s == "INSTANCES" || s == "IMAGES") { return ResourceType_Instance; } throw OrthancException(ErrorCode_ParameterOutOfRange); } ImageFormat StringToImageFormat(const char* format) { std::string s(format); Toolbox::ToUpperCase(s); if (s == "PNG") { return ImageFormat_Png; } throw OrthancException(ErrorCode_ParameterOutOfRange); } LogLevel StringToLogLevel(const char *level) { if (strcmp(level, "ERROR") == 0) { return LogLevel_Error; } else if (strcmp(level, "WARNING") == 0) { return LogLevel_Warning; } else if (strcmp(level, "INFO") == 0) { return LogLevel_Info; } else if (strcmp(level, "TRACE") == 0) { return LogLevel_Trace; } else { throw OrthancException(ErrorCode_InternalError); } } ValueRepresentation StringToValueRepresentation(const std::string& vr, bool throwIfUnsupported) { if (vr == "AE") { return ValueRepresentation_ApplicationEntity; } else if (vr == "AS") { return ValueRepresentation_AgeString; } else if (vr == "AT") { return ValueRepresentation_AttributeTag; } else if (vr == "CS") { return ValueRepresentation_CodeString; } else if (vr == "DA") { return ValueRepresentation_Date; } else if (vr == "DS") { return ValueRepresentation_DecimalString; } else if (vr == "DT") { return ValueRepresentation_DateTime; } else if (vr == "FL") { return ValueRepresentation_FloatingPointSingle; } else if (vr == "FD") { return ValueRepresentation_FloatingPointDouble; } else if (vr == "IS") { return ValueRepresentation_IntegerString; } else if (vr == "LO") { return ValueRepresentation_LongString; } else if (vr == "LT") { return ValueRepresentation_LongText; } else if (vr == "OB") { return ValueRepresentation_OtherByte; } else if (vr == "OD") { return ValueRepresentation_OtherDouble; } else if (vr == "OF") { return ValueRepresentation_OtherFloat; } else if (vr == "OL") { return ValueRepresentation_OtherLong; } else if (vr == "OW") { return ValueRepresentation_OtherWord; } else if (vr == "PN") { return ValueRepresentation_PersonName; } else if (vr == "SH") { return ValueRepresentation_ShortString; } else if (vr == "SL") { return ValueRepresentation_SignedLong; } else if (vr == "SQ") { return ValueRepresentation_Sequence; } else if (vr == "SS") { return ValueRepresentation_SignedShort; } else if (vr == "ST") { return ValueRepresentation_ShortText; } else if (vr == "TM") { return ValueRepresentation_Time; } else if (vr == "UC") { return ValueRepresentation_UnlimitedCharacters; } else if (vr == "UI") { return ValueRepresentation_UniqueIdentifier; } else if (vr == "UL") { return ValueRepresentation_UnsignedLong; } else if (vr == "UN") { return ValueRepresentation_Unknown; } else if (vr == "UR") { return ValueRepresentation_UniversalResource; } else if (vr == "US") { return ValueRepresentation_UnsignedShort; } else if (vr == "UT") { return ValueRepresentation_UnlimitedText; } else { std::string s = "Unsupported value representation encountered: " + vr; if (throwIfUnsupported) { LOG(ERROR) << s; throw OrthancException(ErrorCode_ParameterOutOfRange); } else { LOG(INFO) << s; return ValueRepresentation_NotSupported; } } } PhotometricInterpretation StringToPhotometricInterpretation(const char* value) { // http://dicom.nema.org/medical/dicom/2017a/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.2 std::string s(value); if (s == "MONOCHROME1") { return PhotometricInterpretation_Monochrome1; } if (s == "MONOCHROME2") { return PhotometricInterpretation_Monochrome2; } if (s == "PALETTE COLOR") { return PhotometricInterpretation_Palette; } if (s == "RGB") { return PhotometricInterpretation_RGB; } if (s == "HSV") { return PhotometricInterpretation_HSV; } if (s == "ARGB") { return PhotometricInterpretation_ARGB; } if (s == "CMYK") { return PhotometricInterpretation_CMYK; } if (s == "YBR_FULL") { return PhotometricInterpretation_YBRFull; } if (s == "YBR_FULL_422") { return PhotometricInterpretation_YBRFull422; } if (s == "YBR_PARTIAL_422") { return PhotometricInterpretation_YBRPartial422; } if (s == "YBR_PARTIAL_420") { return PhotometricInterpretation_YBRPartial420; } if (s == "YBR_ICT") { return PhotometricInterpretation_YBR_ICT; } if (s == "YBR_RCT") { return PhotometricInterpretation_YBR_RCT; } throw OrthancException(ErrorCode_ParameterOutOfRange); } unsigned int GetBytesPerPixel(PixelFormat format) { switch (format) { case PixelFormat_Grayscale8: return 1; case PixelFormat_Grayscale16: case PixelFormat_SignedGrayscale16: return 2; case PixelFormat_RGB24: return 3; case PixelFormat_RGBA32: case PixelFormat_BGRA32: return 4; case PixelFormat_Float32: assert(sizeof(float) == 4); return 4; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } bool GetDicomEncoding(Encoding& encoding, const char* specificCharacterSet) { std::string s = Toolbox::StripSpaces(specificCharacterSet); Toolbox::ToUpperCase(s); // http://dicom.nema.org/medical/dicom/current/output/html/part03.html#sect_C.12.1.1.2 // https://github.com/dcm4che/dcm4che/blob/master/dcm4che-core/src/main/java/org/dcm4che3/data/SpecificCharacterSet.java if (s == "ISO_IR 6" || s == "ISO 2022 IR 6") { encoding = Encoding_Ascii; } else if (s == "ISO_IR 192") { encoding = Encoding_Utf8; } else if (s == "ISO_IR 100" || s == "ISO 2022 IR 100") { encoding = Encoding_Latin1; } else if (s == "ISO_IR 101" || s == "ISO 2022 IR 101") { encoding = Encoding_Latin2; } else if (s == "ISO_IR 109" || s == "ISO 2022 IR 109") { encoding = Encoding_Latin3; } else if (s == "ISO_IR 110" || s == "ISO 2022 IR 110") { encoding = Encoding_Latin4; } else if (s == "ISO_IR 148" || s == "ISO 2022 IR 148") { encoding = Encoding_Latin5; } else if (s == "ISO_IR 144" || s == "ISO 2022 IR 144") { encoding = Encoding_Cyrillic; } else if (s == "ISO_IR 127" || s == "ISO 2022 IR 127") { encoding = Encoding_Arabic; } else if (s == "ISO_IR 126" || s == "ISO 2022 IR 126") { encoding = Encoding_Greek; } else if (s == "ISO_IR 138" || s == "ISO 2022 IR 138") { encoding = Encoding_Hebrew; } else if (s == "ISO_IR 166" || s == "ISO 2022 IR 166") { encoding = Encoding_Thai; } else if (s == "ISO_IR 13" || s == "ISO 2022 IR 13") { encoding = Encoding_Japanese; } else if (s == "GB18030") { encoding = Encoding_Chinese; } /* else if (s == "ISO 2022 IR 149") { TODO } else if (s == "ISO 2022 IR 159") { TODO } else if (s == "ISO 2022 IR 87") { TODO } */ else { return false; } // The encoding was properly detected return true; } ResourceType GetChildResourceType(ResourceType type) { switch (type) { case ResourceType_Patient: return ResourceType_Study; case ResourceType_Study: return ResourceType_Series; case ResourceType_Series: return ResourceType_Instance; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } ResourceType GetParentResourceType(ResourceType type) { switch (type) { case ResourceType_Study: return ResourceType_Patient; case ResourceType_Series: return ResourceType_Study; case ResourceType_Instance: return ResourceType_Series; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } DicomModule GetModule(ResourceType type) { switch (type) { case ResourceType_Patient: return DicomModule_Patient; case ResourceType_Study: return DicomModule_Study; case ResourceType_Series: return DicomModule_Series; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } const char* GetDicomSpecificCharacterSet(Encoding encoding) { // http://dicom.nema.org/medical/dicom/current/output/html/part03.html#sect_C.12.1.1.2 switch (encoding) { case Encoding_Ascii: return "ISO_IR 6"; case Encoding_Utf8: return "ISO_IR 192"; case Encoding_Latin1: return "ISO_IR 100"; case Encoding_Latin2: return "ISO_IR 101"; case Encoding_Latin3: return "ISO_IR 109"; case Encoding_Latin4: return "ISO_IR 110"; case Encoding_Latin5: return "ISO_IR 148"; case Encoding_Cyrillic: return "ISO_IR 144"; case Encoding_Arabic: return "ISO_IR 127"; case Encoding_Greek: return "ISO_IR 126"; case Encoding_Hebrew: return "ISO_IR 138"; case Encoding_Japanese: return "ISO_IR 13"; case Encoding_Chinese: return "GB18030"; case Encoding_Thai: return "ISO_IR 166"; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } // This function is autogenerated by the script // "Resources/GenerateErrorCodes.py" HttpStatus ConvertErrorCodeToHttpStatus(ErrorCode error) { switch (error) { case ErrorCode_Success: return HttpStatus_200_Ok; case ErrorCode_ParameterOutOfRange: return HttpStatus_400_BadRequest; case ErrorCode_BadParameterType: return HttpStatus_400_BadRequest; case ErrorCode_InexistentItem: return HttpStatus_404_NotFound; case ErrorCode_BadRequest: return HttpStatus_400_BadRequest; case ErrorCode_UriSyntax: return HttpStatus_400_BadRequest; case ErrorCode_InexistentFile: return HttpStatus_404_NotFound; case ErrorCode_BadFileFormat: return HttpStatus_400_BadRequest; case ErrorCode_UnknownResource: return HttpStatus_404_NotFound; case ErrorCode_InexistentTag: return HttpStatus_404_NotFound; case ErrorCode_BadJson: return HttpStatus_400_BadRequest; case ErrorCode_Unauthorized: return HttpStatus_401_Unauthorized; case ErrorCode_NotAcceptable: return HttpStatus_406_NotAcceptable; default: return HttpStatus_500_InternalServerError; } } bool IsUserContentType(FileContentType type) { return (type >= FileContentType_StartUser && type <= FileContentType_EndUser); } bool IsBinaryValueRepresentation(ValueRepresentation vr) { // http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html switch (vr) { case ValueRepresentation_ApplicationEntity: // AE case ValueRepresentation_AgeString: // AS case ValueRepresentation_CodeString: // CS case ValueRepresentation_Date: // DA case ValueRepresentation_DecimalString: // DS case ValueRepresentation_DateTime: // DT case ValueRepresentation_IntegerString: // IS case ValueRepresentation_LongString: // LO case ValueRepresentation_LongText: // LT case ValueRepresentation_PersonName: // PN case ValueRepresentation_ShortString: // SH case ValueRepresentation_ShortText: // ST case ValueRepresentation_Time: // TM case ValueRepresentation_UnlimitedCharacters: // UC case ValueRepresentation_UniqueIdentifier: // UI (UID) case ValueRepresentation_UniversalResource: // UR (URI or URL) case ValueRepresentation_UnlimitedText: // UT { return false; } /** * Below are all the VR whose character repertoire is tagged as * "not applicable" **/ case ValueRepresentation_AttributeTag: // AT (2 x uint16_t) case ValueRepresentation_FloatingPointSingle: // FL (float) case ValueRepresentation_FloatingPointDouble: // FD (double) case ValueRepresentation_OtherByte: // OB case ValueRepresentation_OtherDouble: // OD case ValueRepresentation_OtherFloat: // OF case ValueRepresentation_OtherLong: // OL case ValueRepresentation_OtherWord: // OW case ValueRepresentation_SignedLong: // SL (int32_t) case ValueRepresentation_Sequence: // SQ case ValueRepresentation_SignedShort: // SS (int16_t) case ValueRepresentation_UnsignedLong: // UL (uint32_t) case ValueRepresentation_Unknown: // UN case ValueRepresentation_UnsignedShort: // US (uint16_t) { return true; } case ValueRepresentation_NotSupported: default: throw OrthancException(ErrorCode_ParameterOutOfRange); } } } OrthancWebViewer-2.3/Orthanc/Core/Enumerations.h0000644000000000000000000005561413133653001020040 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include namespace Orthanc { enum Endianness { Endianness_Unknown, Endianness_Big, Endianness_Little }; // This enumeration is autogenerated by the script // "Resources/GenerateErrorCodes.py" enum ErrorCode { ErrorCode_InternalError = -1 /*!< Internal error */, ErrorCode_Success = 0 /*!< Success */, ErrorCode_Plugin = 1 /*!< Error encountered within the plugin engine */, ErrorCode_NotImplemented = 2 /*!< Not implemented yet */, ErrorCode_ParameterOutOfRange = 3 /*!< Parameter out of range */, ErrorCode_NotEnoughMemory = 4 /*!< The server hosting Orthanc is running out of memory */, ErrorCode_BadParameterType = 5 /*!< Bad type for a parameter */, ErrorCode_BadSequenceOfCalls = 6 /*!< Bad sequence of calls */, ErrorCode_InexistentItem = 7 /*!< Accessing an inexistent item */, ErrorCode_BadRequest = 8 /*!< Bad request */, ErrorCode_NetworkProtocol = 9 /*!< Error in the network protocol */, ErrorCode_SystemCommand = 10 /*!< Error while calling a system command */, ErrorCode_Database = 11 /*!< Error with the database engine */, ErrorCode_UriSyntax = 12 /*!< Badly formatted URI */, ErrorCode_InexistentFile = 13 /*!< Inexistent file */, ErrorCode_CannotWriteFile = 14 /*!< Cannot write to file */, ErrorCode_BadFileFormat = 15 /*!< Bad file format */, ErrorCode_Timeout = 16 /*!< Timeout */, ErrorCode_UnknownResource = 17 /*!< Unknown resource */, ErrorCode_IncompatibleDatabaseVersion = 18 /*!< Incompatible version of the database */, ErrorCode_FullStorage = 19 /*!< The file storage is full */, ErrorCode_CorruptedFile = 20 /*!< Corrupted file (e.g. inconsistent MD5 hash) */, ErrorCode_InexistentTag = 21 /*!< Inexistent tag */, ErrorCode_ReadOnly = 22 /*!< Cannot modify a read-only data structure */, ErrorCode_IncompatibleImageFormat = 23 /*!< Incompatible format of the images */, ErrorCode_IncompatibleImageSize = 24 /*!< Incompatible size of the images */, ErrorCode_SharedLibrary = 25 /*!< Error while using a shared library (plugin) */, ErrorCode_UnknownPluginService = 26 /*!< Plugin invoking an unknown service */, ErrorCode_UnknownDicomTag = 27 /*!< Unknown DICOM tag */, ErrorCode_BadJson = 28 /*!< Cannot parse a JSON document */, ErrorCode_Unauthorized = 29 /*!< Bad credentials were provided to an HTTP request */, ErrorCode_BadFont = 30 /*!< Badly formatted font file */, ErrorCode_DatabasePlugin = 31 /*!< The plugin implementing a custom database back-end does not fulfill the proper interface */, ErrorCode_StorageAreaPlugin = 32 /*!< Error in the plugin implementing a custom storage area */, ErrorCode_EmptyRequest = 33 /*!< The request is empty */, ErrorCode_NotAcceptable = 34 /*!< Cannot send a response which is acceptable according to the Accept HTTP header */, ErrorCode_NullPointer = 35 /*!< Cannot handle a NULL pointer */, ErrorCode_SQLiteNotOpened = 1000 /*!< SQLite: The database is not opened */, ErrorCode_SQLiteAlreadyOpened = 1001 /*!< SQLite: Connection is already open */, ErrorCode_SQLiteCannotOpen = 1002 /*!< SQLite: Unable to open the database */, ErrorCode_SQLiteStatementAlreadyUsed = 1003 /*!< SQLite: This cached statement is already being referred to */, ErrorCode_SQLiteExecute = 1004 /*!< SQLite: Cannot execute a command */, ErrorCode_SQLiteRollbackWithoutTransaction = 1005 /*!< SQLite: Rolling back a nonexistent transaction (have you called Begin()?) */, ErrorCode_SQLiteCommitWithoutTransaction = 1006 /*!< SQLite: Committing a nonexistent transaction */, ErrorCode_SQLiteRegisterFunction = 1007 /*!< SQLite: Unable to register a function */, ErrorCode_SQLiteFlush = 1008 /*!< SQLite: Unable to flush the database */, ErrorCode_SQLiteCannotRun = 1009 /*!< SQLite: Cannot run a cached statement */, ErrorCode_SQLiteCannotStep = 1010 /*!< SQLite: Cannot step over a cached statement */, ErrorCode_SQLiteBindOutOfRange = 1011 /*!< SQLite: Bing a value while out of range (serious error) */, ErrorCode_SQLitePrepareStatement = 1012 /*!< SQLite: Cannot prepare a cached statement */, ErrorCode_SQLiteTransactionAlreadyStarted = 1013 /*!< SQLite: Beginning the same transaction twice */, ErrorCode_SQLiteTransactionCommit = 1014 /*!< SQLite: Failure when committing the transaction */, ErrorCode_SQLiteTransactionBegin = 1015 /*!< SQLite: Cannot start a transaction */, ErrorCode_DirectoryOverFile = 2000 /*!< The directory to be created is already occupied by a regular file */, ErrorCode_FileStorageCannotWrite = 2001 /*!< Unable to create a subdirectory or a file in the file storage */, ErrorCode_DirectoryExpected = 2002 /*!< The specified path does not point to a directory */, ErrorCode_HttpPortInUse = 2003 /*!< The TCP port of the HTTP server is privileged or already in use */, ErrorCode_DicomPortInUse = 2004 /*!< The TCP port of the DICOM server is privileged or already in use */, ErrorCode_BadHttpStatusInRest = 2005 /*!< This HTTP status is not allowed in a REST API */, ErrorCode_RegularFileExpected = 2006 /*!< The specified path does not point to a regular file */, ErrorCode_PathToExecutable = 2007 /*!< Unable to get the path to the executable */, ErrorCode_MakeDirectory = 2008 /*!< Cannot create a directory */, ErrorCode_BadApplicationEntityTitle = 2009 /*!< An application entity title (AET) cannot be empty or be longer than 16 characters */, ErrorCode_NoCFindHandler = 2010 /*!< No request handler factory for DICOM C-FIND SCP */, ErrorCode_NoCMoveHandler = 2011 /*!< No request handler factory for DICOM C-MOVE SCP */, ErrorCode_NoCStoreHandler = 2012 /*!< No request handler factory for DICOM C-STORE SCP */, ErrorCode_NoApplicationEntityFilter = 2013 /*!< No application entity filter */, ErrorCode_NoSopClassOrInstance = 2014 /*!< DicomUserConnection: Unable to find the SOP class and instance */, ErrorCode_NoPresentationContext = 2015 /*!< DicomUserConnection: No acceptable presentation context for modality */, ErrorCode_DicomFindUnavailable = 2016 /*!< DicomUserConnection: The C-FIND command is not supported by the remote SCP */, ErrorCode_DicomMoveUnavailable = 2017 /*!< DicomUserConnection: The C-MOVE command is not supported by the remote SCP */, ErrorCode_CannotStoreInstance = 2018 /*!< Cannot store an instance */, ErrorCode_CreateDicomNotString = 2019 /*!< Only string values are supported when creating DICOM instances */, ErrorCode_CreateDicomOverrideTag = 2020 /*!< Trying to override a value inherited from a parent module */, ErrorCode_CreateDicomUseContent = 2021 /*!< Use \"Content\" to inject an image into a new DICOM instance */, ErrorCode_CreateDicomNoPayload = 2022 /*!< No payload is present for one instance in the series */, ErrorCode_CreateDicomUseDataUriScheme = 2023 /*!< The payload of the DICOM instance must be specified according to Data URI scheme */, ErrorCode_CreateDicomBadParent = 2024 /*!< Trying to attach a new DICOM instance to an inexistent resource */, ErrorCode_CreateDicomParentIsInstance = 2025 /*!< Trying to attach a new DICOM instance to an instance (must be a series, study or patient) */, ErrorCode_CreateDicomParentEncoding = 2026 /*!< Unable to get the encoding of the parent resource */, ErrorCode_UnknownModality = 2027 /*!< Unknown modality */, ErrorCode_BadJobOrdering = 2028 /*!< Bad ordering of filters in a job */, ErrorCode_JsonToLuaTable = 2029 /*!< Cannot convert the given JSON object to a Lua table */, ErrorCode_CannotCreateLua = 2030 /*!< Cannot create the Lua context */, ErrorCode_CannotExecuteLua = 2031 /*!< Cannot execute a Lua command */, ErrorCode_LuaAlreadyExecuted = 2032 /*!< Arguments cannot be pushed after the Lua function is executed */, ErrorCode_LuaBadOutput = 2033 /*!< The Lua function does not give the expected number of outputs */, ErrorCode_NotLuaPredicate = 2034 /*!< The Lua function is not a predicate (only true/false outputs allowed) */, ErrorCode_LuaReturnsNoString = 2035 /*!< The Lua function does not return a string */, ErrorCode_StorageAreaAlreadyRegistered = 2036 /*!< Another plugin has already registered a custom storage area */, ErrorCode_DatabaseBackendAlreadyRegistered = 2037 /*!< Another plugin has already registered a custom database back-end */, ErrorCode_DatabaseNotInitialized = 2038 /*!< Plugin trying to call the database during its initialization */, ErrorCode_SslDisabled = 2039 /*!< Orthanc has been built without SSL support */, ErrorCode_CannotOrderSlices = 2040 /*!< Unable to order the slices of the series */, ErrorCode_NoWorklistHandler = 2041 /*!< No request handler factory for DICOM C-Find Modality SCP */, ErrorCode_AlreadyExistingTag = 2042 /*!< Cannot override the value of a tag that already exists */, ErrorCode_START_PLUGINS = 1000000 }; enum LogLevel { LogLevel_Error, LogLevel_Warning, LogLevel_Info, LogLevel_Trace }; /** * {summary}{The memory layout of the pixels (resp. voxels) of a 2D (resp. 3D) image.} **/ enum PixelFormat { /** * {summary}{Color image in RGB24 format.} * {description}{This format describes a color image. The pixels are stored in 3 * consecutive bytes. The memory layout is RGB.} **/ PixelFormat_RGB24 = 1, /** * {summary}{Color image in RGBA32 format.} * {description}{This format describes a color image. The pixels are stored in 4 * consecutive bytes. The memory layout is RGBA.} **/ PixelFormat_RGBA32 = 2, /** * {summary}{Graylevel 8bpp image.} * {description}{The image is graylevel. Each pixel is unsigned and stored in one byte.} **/ PixelFormat_Grayscale8 = 3, /** * {summary}{Graylevel, unsigned 16bpp image.} * {description}{The image is graylevel. Each pixel is unsigned and stored in two bytes.} **/ PixelFormat_Grayscale16 = 4, /** * {summary}{Graylevel, signed 16bpp image.} * {description}{The image is graylevel. Each pixel is signed and stored in two bytes.} **/ PixelFormat_SignedGrayscale16 = 5, /** * {summary}{Graylevel, floating-point image.} * {description}{The image is graylevel. Each pixel is floating-point and stored in 4 bytes.} **/ PixelFormat_Float32 = 6, // This is the memory layout for Cairo PixelFormat_BGRA32 = 7 }; /** * {summary}{The extraction mode specifies the way the values of the pixels are scaled when downloading a 2D image.} **/ enum ImageExtractionMode { /** * {summary}{Rescaled to 8bpp.} * {description}{The minimum value of the image is set to 0, and its maximum value is set to 255.} **/ ImageExtractionMode_Preview = 1, /** * {summary}{Truncation to the [0, 255] range.} **/ ImageExtractionMode_UInt8 = 2, /** * {summary}{Truncation to the [0, 65535] range.} **/ ImageExtractionMode_UInt16 = 3, /** * {summary}{Truncation to the [-32768, 32767] range.} **/ ImageExtractionMode_Int16 = 4 }; /** * Most common, non-joke and non-experimental HTTP status codes * http://en.wikipedia.org/wiki/List_of_HTTP_status_codes **/ enum HttpStatus { HttpStatus_None = -1, // 1xx Informational HttpStatus_100_Continue = 100, HttpStatus_101_SwitchingProtocols = 101, HttpStatus_102_Processing = 102, // 2xx Success HttpStatus_200_Ok = 200, HttpStatus_201_Created = 201, HttpStatus_202_Accepted = 202, HttpStatus_203_NonAuthoritativeInformation = 203, HttpStatus_204_NoContent = 204, HttpStatus_205_ResetContent = 205, HttpStatus_206_PartialContent = 206, HttpStatus_207_MultiStatus = 207, HttpStatus_208_AlreadyReported = 208, HttpStatus_226_IMUsed = 226, // 3xx Redirection HttpStatus_300_MultipleChoices = 300, HttpStatus_301_MovedPermanently = 301, HttpStatus_302_Found = 302, HttpStatus_303_SeeOther = 303, HttpStatus_304_NotModified = 304, HttpStatus_305_UseProxy = 305, HttpStatus_307_TemporaryRedirect = 307, // 4xx Client Error HttpStatus_400_BadRequest = 400, HttpStatus_401_Unauthorized = 401, HttpStatus_402_PaymentRequired = 402, HttpStatus_403_Forbidden = 403, HttpStatus_404_NotFound = 404, HttpStatus_405_MethodNotAllowed = 405, HttpStatus_406_NotAcceptable = 406, HttpStatus_407_ProxyAuthenticationRequired = 407, HttpStatus_408_RequestTimeout = 408, HttpStatus_409_Conflict = 409, HttpStatus_410_Gone = 410, HttpStatus_411_LengthRequired = 411, HttpStatus_412_PreconditionFailed = 412, HttpStatus_413_RequestEntityTooLarge = 413, HttpStatus_414_RequestUriTooLong = 414, HttpStatus_415_UnsupportedMediaType = 415, HttpStatus_416_RequestedRangeNotSatisfiable = 416, HttpStatus_417_ExpectationFailed = 417, HttpStatus_422_UnprocessableEntity = 422, HttpStatus_423_Locked = 423, HttpStatus_424_FailedDependency = 424, HttpStatus_426_UpgradeRequired = 426, // 5xx Server Error HttpStatus_500_InternalServerError = 500, HttpStatus_501_NotImplemented = 501, HttpStatus_502_BadGateway = 502, HttpStatus_503_ServiceUnavailable = 503, HttpStatus_504_GatewayTimeout = 504, HttpStatus_505_HttpVersionNotSupported = 505, HttpStatus_506_VariantAlsoNegotiates = 506, HttpStatus_507_InsufficientStorage = 507, HttpStatus_509_BandwidthLimitExceeded = 509, HttpStatus_510_NotExtended = 510 }; enum HttpMethod { HttpMethod_Get = 0, HttpMethod_Post = 1, HttpMethod_Delete = 2, HttpMethod_Put = 3 }; enum ImageFormat { ImageFormat_Png = 1 }; // https://en.wikipedia.org/wiki/HTTP_compression enum HttpCompression { HttpCompression_None, HttpCompression_Deflate, HttpCompression_Gzip }; // Specific Character Sets // http://dicom.nema.org/medical/dicom/current/output/html/part03.html#sect_C.12.1.1.2 enum Encoding { Encoding_Ascii, Encoding_Utf8, Encoding_Latin1, Encoding_Latin2, Encoding_Latin3, Encoding_Latin4, Encoding_Latin5, // Turkish Encoding_Cyrillic, Encoding_Windows1251, // Windows-1251 (commonly used for Cyrillic) Encoding_Arabic, Encoding_Greek, Encoding_Hebrew, Encoding_Thai, // TIS 620-2533 Encoding_Japanese, // JIS X 0201 (Shift JIS): Katakana Encoding_Chinese // GB18030 - Chinese simplified //Encoding_JapaneseKanji, // Multibyte - JIS X 0208: Kanji //Encoding_JapaneseSupplementaryKanji, // Multibyte - JIS X 0212: Supplementary Kanji set //Encoding_Korean, // Multibyte - KS X 1001: Hangul and Hanja }; // http://dicom.nema.org/medical/dicom/current/output/html/part03.html#sect_C.7.6.3.1.2 enum PhotometricInterpretation { PhotometricInterpretation_ARGB, // Retired PhotometricInterpretation_CMYK, // Retired PhotometricInterpretation_HSV, // Retired PhotometricInterpretation_Monochrome1, PhotometricInterpretation_Monochrome2, PhotometricInterpretation_Palette, PhotometricInterpretation_RGB, PhotometricInterpretation_YBRFull, PhotometricInterpretation_YBRFull422, PhotometricInterpretation_YBRPartial420, PhotometricInterpretation_YBRPartial422, PhotometricInterpretation_YBR_ICT, PhotometricInterpretation_YBR_RCT, PhotometricInterpretation_Unknown }; enum DicomModule { DicomModule_Patient, DicomModule_Study, DicomModule_Series, DicomModule_Instance, DicomModule_Image }; enum RequestOrigin { RequestOrigin_Unknown, RequestOrigin_DicomProtocol, RequestOrigin_RestApi, RequestOrigin_Plugins, RequestOrigin_Lua }; enum ServerBarrierEvent { ServerBarrierEvent_Stop, ServerBarrierEvent_Reload // SIGHUP signal: reload configuration file }; enum FileMode { FileMode_ReadBinary, FileMode_WriteBinary }; /** * The value representations Orthanc knows about. They correspond to * the DICOM 2016b version of the standard. * http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html **/ enum ValueRepresentation { ValueRepresentation_ApplicationEntity = 1, // AE ValueRepresentation_AgeString = 2, // AS ValueRepresentation_AttributeTag = 3, // AT (2 x uint16_t) ValueRepresentation_CodeString = 4, // CS ValueRepresentation_Date = 5, // DA ValueRepresentation_DecimalString = 6, // DS ValueRepresentation_DateTime = 7, // DT ValueRepresentation_FloatingPointSingle = 8, // FL (float) ValueRepresentation_FloatingPointDouble = 9, // FD (double) ValueRepresentation_IntegerString = 10, // IS ValueRepresentation_LongString = 11, // LO ValueRepresentation_LongText = 12, // LT ValueRepresentation_OtherByte = 13, // OB ValueRepresentation_OtherDouble = 14, // OD ValueRepresentation_OtherFloat = 15, // OF ValueRepresentation_OtherLong = 16, // OL ValueRepresentation_OtherWord = 17, // OW ValueRepresentation_PersonName = 18, // PN ValueRepresentation_ShortString = 19, // SH ValueRepresentation_SignedLong = 20, // SL (int32_t) ValueRepresentation_Sequence = 21, // SQ ValueRepresentation_SignedShort = 22, // SS (int16_t) ValueRepresentation_ShortText = 23, // ST ValueRepresentation_Time = 24, // TM ValueRepresentation_UnlimitedCharacters = 25, // UC ValueRepresentation_UniqueIdentifier = 26, // UI (UID) ValueRepresentation_UnsignedLong = 27, // UL (uint32_t) ValueRepresentation_Unknown = 28, // UN ValueRepresentation_UniversalResource = 29, // UR (URI or URL) ValueRepresentation_UnsignedShort = 30, // US (uint16_t) ValueRepresentation_UnlimitedText = 31, // UT ValueRepresentation_NotSupported // Not supported by Orthanc, or tag not in dictionary }; /** * WARNING: Do not change the explicit values in the enumerations * below this point. This would result in incompatible databases * between versions of Orthanc! **/ enum CompressionType { /** * Buffer/file that is stored as-is, in a raw fashion, without * compression. **/ CompressionType_None = 1, /** * Buffer that is compressed using the "deflate" algorithm (RFC * 1951), wrapped inside the zlib data format (RFC 1950), prefixed * with a "uint64_t" (8 bytes) that encodes the size of the * uncompressed buffer. If the compressed buffer is empty, its * represents an empty uncompressed buffer. This format is * internal to Orthanc. If the 8 first bytes are skipped AND the * buffer is non-empty, the buffer is compatible with the * "deflate" HTTP compression. **/ CompressionType_ZlibWithSize = 2 }; enum FileContentType { // If you add a value below, insert it in "PluginStorageArea" in // the file "Plugins/Engine/OrthancPlugins.cpp" FileContentType_Unknown = 0, FileContentType_Dicom = 1, FileContentType_DicomAsJson = 2, // Make sure that the value "65535" can be stored into this enumeration FileContentType_StartUser = 1024, FileContentType_EndUser = 65535 }; enum ResourceType { ResourceType_Patient = 1, ResourceType_Study = 2, ResourceType_Series = 3, ResourceType_Instance = 4 }; const char* EnumerationToString(ErrorCode code); const char* EnumerationToString(HttpMethod method); const char* EnumerationToString(HttpStatus status); const char* EnumerationToString(ResourceType type); const char* EnumerationToString(ImageFormat format); const char* EnumerationToString(Encoding encoding); const char* EnumerationToString(PhotometricInterpretation photometric); const char* EnumerationToString(LogLevel level); const char* EnumerationToString(RequestOrigin origin); const char* EnumerationToString(PixelFormat format); Encoding StringToEncoding(const char* encoding); ResourceType StringToResourceType(const char* type); ImageFormat StringToImageFormat(const char* format); LogLevel StringToLogLevel(const char* level); ValueRepresentation StringToValueRepresentation(const std::string& vr, bool throwIfUnsupported); PhotometricInterpretation StringToPhotometricInterpretation(const char* value); unsigned int GetBytesPerPixel(PixelFormat format); bool GetDicomEncoding(Encoding& encoding, const char* specificCharacterSet); ResourceType GetChildResourceType(ResourceType type); ResourceType GetParentResourceType(ResourceType type); DicomModule GetModule(ResourceType type); const char* GetDicomSpecificCharacterSet(Encoding encoding); HttpStatus ConvertErrorCodeToHttpStatus(ErrorCode error); bool IsUserContentType(FileContentType type); bool IsBinaryValueRepresentation(ValueRepresentation vr); } OrthancWebViewer-2.3/Orthanc/Core/FileStorage/FilesystemStorage.cpp0000644000000000000000000001655513133653001023600 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "FilesystemStorage.h" // http://stackoverflow.com/questions/1576272/storing-large-number-of-files-in-file-system // http://stackoverflow.com/questions/446358/storing-a-large-number-of-images #include "../Logging.h" #include "../OrthancException.h" #include "../Toolbox.h" #include "../SystemToolbox.h" #include static std::string ToString(const boost::filesystem::path& p) { #if BOOST_HAS_FILESYSTEM_V3 == 1 return p.filename().string(); #else return p.filename(); #endif } namespace Orthanc { boost::filesystem::path FilesystemStorage::GetPath(const std::string& uuid) const { namespace fs = boost::filesystem; if (!Toolbox::IsUuid(uuid)) { throw OrthancException(ErrorCode_ParameterOutOfRange); } fs::path path = root_; path /= std::string(&uuid[0], &uuid[2]); path /= std::string(&uuid[2], &uuid[4]); path /= uuid; #if BOOST_HAS_FILESYSTEM_V3 == 1 path.make_preferred(); #endif return path; } FilesystemStorage::FilesystemStorage(std::string root) { //root_ = boost::filesystem::absolute(root).string(); root_ = root; SystemToolbox::MakeDirectory(root); } static const char* GetDescriptionInternal(FileContentType content) { // This function is for logging only (internal use), a more // fully-featured version is available in ServerEnumerations.cpp switch (content) { case FileContentType_Unknown: return "Unknown"; case FileContentType_Dicom: return "DICOM"; case FileContentType_DicomAsJson: return "JSON summary of DICOM"; default: return "User-defined"; } } void FilesystemStorage::Create(const std::string& uuid, const void* content, size_t size, FileContentType type) { LOG(INFO) << "Creating attachment \"" << uuid << "\" of \"" << GetDescriptionInternal(type) << "\" type (size: " << (size / (1024 * 1024) + 1) << "MB)"; boost::filesystem::path path; path = GetPath(uuid); if (boost::filesystem::exists(path)) { // Extremely unlikely case: This Uuid has already been created // in the past. throw OrthancException(ErrorCode_InternalError); } if (boost::filesystem::exists(path.parent_path())) { if (!boost::filesystem::is_directory(path.parent_path())) { throw OrthancException(ErrorCode_DirectoryOverFile); } } else { if (!boost::filesystem::create_directories(path.parent_path())) { throw OrthancException(ErrorCode_FileStorageCannotWrite); } } SystemToolbox::WriteFile(content, size, path.string()); } void FilesystemStorage::Read(std::string& content, const std::string& uuid, FileContentType type) { LOG(INFO) << "Reading attachment \"" << uuid << "\" of \"" << GetDescriptionInternal(type) << "\" content type"; content.clear(); SystemToolbox::ReadFile(content, GetPath(uuid).string()); } uintmax_t FilesystemStorage::GetSize(const std::string& uuid) const { boost::filesystem::path path = GetPath(uuid); return boost::filesystem::file_size(path); } void FilesystemStorage::ListAllFiles(std::set& result) const { namespace fs = boost::filesystem; result.clear(); if (fs::exists(root_) && fs::is_directory(root_)) { for (fs::recursive_directory_iterator current(root_), end; current != end ; ++current) { if (SystemToolbox::IsRegularFile(current->path().string())) { try { fs::path d = current->path(); std::string uuid = ToString(d); if (Toolbox::IsUuid(uuid)) { fs::path p0 = d.parent_path().parent_path().parent_path(); std::string p1 = ToString(d.parent_path().parent_path()); std::string p2 = ToString(d.parent_path()); if (p1.length() == 2 && p2.length() == 2 && p1 == uuid.substr(0, 2) && p2 == uuid.substr(2, 2) && p0 == root_) { result.insert(uuid); } } } catch (fs::filesystem_error) { } } } } } void FilesystemStorage::Clear() { namespace fs = boost::filesystem; typedef std::set List; List result; ListAllFiles(result); for (List::const_iterator it = result.begin(); it != result.end(); ++it) { Remove(*it, FileContentType_Unknown /*ignored in this class*/); } } void FilesystemStorage::Remove(const std::string& uuid, FileContentType type) { LOG(INFO) << "Deleting attachment \"" << uuid << "\" of type " << static_cast(type); namespace fs = boost::filesystem; fs::path p = GetPath(uuid); try { fs::remove(p); } catch (...) { // Ignore the error } // Remove the two parent directories, ignoring the error code if // these directories are not empty try { #if BOOST_HAS_FILESYSTEM_V3 == 1 boost::system::error_code err; fs::remove(p.parent_path(), err); fs::remove(p.parent_path().parent_path(), err); #else fs::remove(p.parent_path()); fs::remove(p.parent_path().parent_path()); #endif } catch (...) { // Ignore the error } } uintmax_t FilesystemStorage::GetCapacity() const { return boost::filesystem::space(root_).capacity; } uintmax_t FilesystemStorage::GetAvailableSpace() const { return boost::filesystem::space(root_).available; } } OrthancWebViewer-2.3/Orthanc/Core/FileStorage/FilesystemStorage.h0000644000000000000000000000523213133653001023233 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "IStorageArea.h" #include #include #include namespace Orthanc { class FilesystemStorage : public IStorageArea { // TODO REMOVE THIS friend class FilesystemHttpSender; friend class FileStorageAccessor; private: boost::filesystem::path root_; boost::filesystem::path GetPath(const std::string& uuid) const; public: explicit FilesystemStorage(std::string root); virtual void Create(const std::string& uuid, const void* content, size_t size, FileContentType type); virtual void Read(std::string& content, const std::string& uuid, FileContentType type); virtual void Remove(const std::string& uuid, FileContentType type); void ListAllFiles(std::set& result) const; uintmax_t GetSize(const std::string& uuid) const; void Clear(); uintmax_t GetCapacity() const; uintmax_t GetAvailableSpace() const; }; } OrthancWebViewer-2.3/Orthanc/Core/FileStorage/IStorageArea.h0000644000000000000000000000434013133653001022067 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "../Enumerations.h" #include #include namespace Orthanc { class IStorageArea : public boost::noncopyable { public: virtual ~IStorageArea() { } virtual void Create(const std::string& uuid, const void* content, size_t size, FileContentType type) = 0; virtual void Read(std::string& content, const std::string& uuid, FileContentType type) = 0; virtual void Remove(const std::string& uuid, FileContentType type) = 0; }; } OrthancWebViewer-2.3/Orthanc/Core/IDynamicObject.h0000644000000000000000000000377713133653001020216 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include namespace Orthanc { /** * This class should be the ancestor to any class whose type is * determined at the runtime, and that can be dynamically allocated. * Being a child of IDynamicObject only implies the existence of a * virtual destructor. **/ class IDynamicObject : public boost::noncopyable { public: virtual ~IDynamicObject() { } }; } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageAccessor.cpp0000644000000000000000000001667413133653001021637 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "ImageAccessor.h" #include "../Logging.h" #include "../OrthancException.h" #include "../ChunkedBuffer.h" #include #include #include namespace Orthanc { template static void ToMatlabStringInternal(ChunkedBuffer& target, const ImageAccessor& source) { target.AddChunk("double([ "); for (unsigned int y = 0; y < source.GetHeight(); y++) { const PixelType* p = reinterpret_cast(source.GetConstRow(y)); std::string s; if (y > 0) { s = "; "; } s.reserve(source.GetWidth() * 8); for (unsigned int x = 0; x < source.GetWidth(); x++, p++) { s += boost::lexical_cast(static_cast(*p)) + " "; } target.AddChunk(s); } target.AddChunk("])"); } static void RGB24ToMatlabString(ChunkedBuffer& target, const ImageAccessor& source) { assert(source.GetFormat() == PixelFormat_RGB24); target.AddChunk("double(permute(reshape([ "); for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); std::string s; s.reserve(source.GetWidth() * 3 * 8); for (unsigned int x = 0; x < 3 * source.GetWidth(); x++, p++) { s += boost::lexical_cast(static_cast(*p)) + " "; } target.AddChunk(s); } target.AddChunk("], [ 3 " + boost::lexical_cast(source.GetHeight()) + " " + boost::lexical_cast(source.GetWidth()) + " ]), [ 3 2 1 ]))"); } void* ImageAccessor::GetBuffer() const { if (readOnly_) { #if ORTHANC_ENABLE_LOGGING == 1 LOG(ERROR) << "Trying to write on a read-only image"; #endif throw OrthancException(ErrorCode_ReadOnly); } return buffer_; } const void* ImageAccessor::GetConstRow(unsigned int y) const { if (buffer_ != NULL) { return buffer_ + y * pitch_; } else { return NULL; } } void* ImageAccessor::GetRow(unsigned int y) const { if (readOnly_) { #if ORTHANC_ENABLE_LOGGING == 1 LOG(ERROR) << "Trying to write on a read-only image"; #endif throw OrthancException(ErrorCode_ReadOnly); } if (buffer_ != NULL) { return buffer_ + y * pitch_; } else { return NULL; } } void ImageAccessor::AssignEmpty(PixelFormat format) { readOnly_ = false; format_ = format; width_ = 0; height_ = 0; pitch_ = 0; buffer_ = NULL; } void ImageAccessor::AssignReadOnly(PixelFormat format, unsigned int width, unsigned int height, unsigned int pitch, const void *buffer) { readOnly_ = true; format_ = format; width_ = width; height_ = height; pitch_ = pitch; buffer_ = reinterpret_cast(const_cast(buffer)); if (GetBytesPerPixel() * width_ > pitch_) { throw OrthancException(ErrorCode_ParameterOutOfRange); } } void ImageAccessor::AssignWritable(PixelFormat format, unsigned int width, unsigned int height, unsigned int pitch, void *buffer) { readOnly_ = false; format_ = format; width_ = width; height_ = height; pitch_ = pitch; buffer_ = reinterpret_cast(buffer); if (GetBytesPerPixel() * width_ > pitch_) { throw OrthancException(ErrorCode_ParameterOutOfRange); } } void ImageAccessor::ToMatlabString(std::string& target) const { ChunkedBuffer buffer; switch (GetFormat()) { case PixelFormat_Grayscale8: ToMatlabStringInternal(buffer, *this); break; case PixelFormat_Grayscale16: ToMatlabStringInternal(buffer, *this); break; case PixelFormat_SignedGrayscale16: ToMatlabStringInternal(buffer, *this); break; case PixelFormat_Float32: ToMatlabStringInternal(buffer, *this); break; case PixelFormat_RGB24: RGB24ToMatlabString(buffer, *this); break; default: throw OrthancException(ErrorCode_NotImplemented); } buffer.Flatten(target); } ImageAccessor ImageAccessor::GetRegion(unsigned int x, unsigned int y, unsigned int width, unsigned int height) const { if (x + width > width_ || y + height > height_) { throw OrthancException(ErrorCode_ParameterOutOfRange); } ImageAccessor result; if (width == 0 || height == 0) { result.AssignWritable(format_, 0, 0, 0, NULL); } else { uint8_t* p = (buffer_ + y * pitch_ + x * GetBytesPerPixel()); if (readOnly_) { result.AssignReadOnly(format_, width, height, pitch_, p); } else { result.AssignWritable(format_, width, height, pitch_, p); } } return result; } void ImageAccessor::SetFormat(PixelFormat format) { if (readOnly_) { #if ORTHANC_ENABLE_LOGGING == 1 LOG(ERROR) << "Trying to modify the format of a read-only image"; #endif throw OrthancException(ErrorCode_ReadOnly); } if (::Orthanc::GetBytesPerPixel(format) != ::Orthanc::GetBytesPerPixel(format_)) { throw OrthancException(ErrorCode_IncompatibleImageFormat); } format_ = format; } } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageAccessor.h0000644000000000000000000000672213133653001021275 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "../Enumerations.h" #include #include namespace Orthanc { class ImageAccessor { private: bool readOnly_; PixelFormat format_; unsigned int width_; unsigned int height_; unsigned int pitch_; uint8_t *buffer_; public: ImageAccessor() { AssignEmpty(PixelFormat_Grayscale8); } virtual ~ImageAccessor() { } bool IsReadOnly() const { return readOnly_; } PixelFormat GetFormat() const { return format_; } unsigned int GetBytesPerPixel() const { return ::Orthanc::GetBytesPerPixel(format_); } unsigned int GetWidth() const { return width_; } unsigned int GetHeight() const { return height_; } unsigned int GetPitch() const { return pitch_; } unsigned int GetSize() const { return GetHeight() * GetPitch(); } const void* GetConstBuffer() const { return buffer_; } void* GetBuffer() const; const void* GetConstRow(unsigned int y) const; void* GetRow(unsigned int y) const; void AssignEmpty(PixelFormat format); void AssignReadOnly(PixelFormat format, unsigned int width, unsigned int height, unsigned int pitch, const void *buffer); void AssignWritable(PixelFormat format, unsigned int width, unsigned int height, unsigned int pitch, void *buffer); void ToMatlabString(std::string& target) const; ImageAccessor GetRegion(unsigned int x, unsigned int y, unsigned int width, unsigned int height) const; void SetFormat(PixelFormat format); }; } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageBuffer.cpp0000644000000000000000000001052313133653001021271 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "ImageBuffer.h" #include "../OrthancException.h" #include #include namespace Orthanc { void ImageBuffer::Allocate() { if (changed_) { Deallocate(); /* if (forceMinimalPitch_) { TODO: Align pitch and memory buffer to optimal size for SIMD. } */ pitch_ = GetBytesPerPixel() * width_; size_t size = pitch_ * height_; if (size == 0) { buffer_ = NULL; } else { buffer_ = malloc(size); if (buffer_ == NULL) { throw OrthancException(ErrorCode_NotEnoughMemory); } } changed_ = false; } } void ImageBuffer::Deallocate() { if (buffer_ != NULL) { free(buffer_); buffer_ = NULL; changed_ = true; } } ImageBuffer::ImageBuffer(PixelFormat format, unsigned int width, unsigned int height, bool forceMinimalPitch) : forceMinimalPitch_(forceMinimalPitch) { Initialize(); SetWidth(width); SetHeight(height); SetFormat(format); } void ImageBuffer::Initialize() { changed_ = false; forceMinimalPitch_ = true; format_ = PixelFormat_Grayscale8; width_ = 0; height_ = 0; pitch_ = 0; buffer_ = NULL; } void ImageBuffer::SetFormat(PixelFormat format) { if (format != format_) { changed_ = true; format_ = format; } } void ImageBuffer::SetWidth(unsigned int width) { if (width != width_) { changed_ = true; width_ = width; } } void ImageBuffer::SetHeight(unsigned int height) { if (height != height_) { changed_ = true; height_ = height; } } ImageAccessor ImageBuffer::GetAccessor() { Allocate(); ImageAccessor accessor; accessor.AssignWritable(format_, width_, height_, pitch_, buffer_); return accessor; } ImageAccessor ImageBuffer::GetConstAccessor() { Allocate(); ImageAccessor accessor; accessor.AssignReadOnly(format_, width_, height_, pitch_, buffer_); return accessor; } void ImageBuffer::AcquireOwnership(ImageBuffer& other) { // Remove the content of the current image Deallocate(); // Force the allocation of the other image (if not already // allocated) other.Allocate(); // Transfer the content of the other image changed_ = false; forceMinimalPitch_ = other.forceMinimalPitch_; format_ = other.format_; width_ = other.width_; height_ = other.height_; pitch_ = other.pitch_; buffer_ = other.buffer_; // Force the reinitialization of the other image other.Initialize(); } } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageBuffer.h0000644000000000000000000000566213133653001020746 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "ImageAccessor.h" #include #include #include namespace Orthanc { class ImageBuffer : public boost::noncopyable { private: bool changed_; bool forceMinimalPitch_; // Currently unused PixelFormat format_; unsigned int width_; unsigned int height_; unsigned int pitch_; void *buffer_; void Initialize(); void Allocate(); void Deallocate(); public: ImageBuffer(PixelFormat format, unsigned int width, unsigned int height, bool forceMinimalPitch); ImageBuffer() { Initialize(); } ~ImageBuffer() { Deallocate(); } PixelFormat GetFormat() const { return format_; } void SetFormat(PixelFormat format); unsigned int GetWidth() const { return width_; } void SetWidth(unsigned int width); unsigned int GetHeight() const { return height_; } void SetHeight(unsigned int height); unsigned int GetBytesPerPixel() const { return ::Orthanc::GetBytesPerPixel(format_); } ImageAccessor GetAccessor(); ImageAccessor GetConstAccessor(); bool IsMinimalPitchForced() const { return forceMinimalPitch_; } void AcquireOwnership(ImageBuffer& other); }; } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageProcessing.cpp0000644000000000000000000005202413133653001022176 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "ImageProcessing.h" #include "../OrthancException.h" #include #include #include #include #include namespace Orthanc { template static void ConvertInternal(ImageAccessor& target, const ImageAccessor& source) { const TargetType minValue = std::numeric_limits::min(); const TargetType maxValue = std::numeric_limits::max(); for (unsigned int y = 0; y < source.GetHeight(); y++) { TargetType* t = reinterpret_cast(target.GetRow(y)); const SourceType* s = reinterpret_cast(source.GetConstRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, t++, s++) { if (static_cast(*s) < static_cast(minValue)) { *t = minValue; } else if (static_cast(*s) > static_cast(maxValue)) { *t = maxValue; } else { *t = static_cast(*s); } } } } template static void ConvertGrayscaleToFloat(ImageAccessor& target, const ImageAccessor& source) { assert(sizeof(float) == 4); for (unsigned int y = 0; y < source.GetHeight(); y++) { float* t = reinterpret_cast(target.GetRow(y)); const SourceType* s = reinterpret_cast(source.GetConstRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, t++, s++) { *t = static_cast(*s); } } } template static void ConvertColorToGrayscale(ImageAccessor& target, const ImageAccessor& source) { assert(source.GetFormat() == PixelFormat_RGB24); const TargetType minValue = std::numeric_limits::min(); const TargetType maxValue = std::numeric_limits::max(); for (unsigned int y = 0; y < source.GetHeight(); y++) { TargetType* t = reinterpret_cast(target.GetRow(y)); const uint8_t* s = reinterpret_cast(source.GetConstRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, t++, s += 3) { // Y = 0.2126 R + 0.7152 G + 0.0722 B int32_t v = (2126 * static_cast(s[0]) + 7152 * static_cast(s[1]) + 0722 * static_cast(s[2])) / 1000; if (static_cast(v) < static_cast(minValue)) { *t = minValue; } else if (static_cast(v) > static_cast(maxValue)) { *t = maxValue; } else { *t = static_cast(v); } } } } template static void SetInternal(ImageAccessor& image, int64_t constant) { for (unsigned int y = 0; y < image.GetHeight(); y++) { PixelType* p = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++, p++) { *p = static_cast(constant); } } } template static void GetMinMaxValueInternal(PixelType& minValue, PixelType& maxValue, const ImageAccessor& source) { // Deal with the special case of empty image if (source.GetWidth() == 0 || source.GetHeight() == 0) { minValue = 0; maxValue = 0; return; } minValue = std::numeric_limits::max(); maxValue = std::numeric_limits::min(); for (unsigned int y = 0; y < source.GetHeight(); y++) { const PixelType* p = reinterpret_cast(source.GetConstRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, p++) { if (*p < minValue) { minValue = *p; } if (*p > maxValue) { maxValue = *p; } } } } template static void AddConstantInternal(ImageAccessor& image, int64_t constant) { if (constant == 0) { return; } const int64_t minValue = std::numeric_limits::min(); const int64_t maxValue = std::numeric_limits::max(); for (unsigned int y = 0; y < image.GetHeight(); y++) { PixelType* p = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++, p++) { int64_t v = static_cast(*p) + constant; if (v > maxValue) { *p = std::numeric_limits::max(); } else if (v < minValue) { *p = std::numeric_limits::min(); } else { *p = static_cast(v); } } } } template void MultiplyConstantInternal(ImageAccessor& image, float factor) { if (std::abs(factor - 1.0f) <= std::numeric_limits::epsilon()) { return; } const int64_t minValue = std::numeric_limits::min(); const int64_t maxValue = std::numeric_limits::max(); for (unsigned int y = 0; y < image.GetHeight(); y++) { PixelType* p = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++, p++) { int64_t v = boost::math::llround(static_cast(*p) * factor); if (v > maxValue) { *p = std::numeric_limits::max(); } else if (v < minValue) { *p = std::numeric_limits::min(); } else { *p = static_cast(v); } } } } template void ShiftScaleInternal(ImageAccessor& image, float offset, float scaling) { const float minValue = static_cast(std::numeric_limits::min()); const float maxValue = static_cast(std::numeric_limits::max()); for (unsigned int y = 0; y < image.GetHeight(); y++) { PixelType* p = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++, p++) { float v = (static_cast(*p) + offset) * scaling; if (v > maxValue) { *p = std::numeric_limits::max(); } else if (v < minValue) { *p = std::numeric_limits::min(); } else { *p = static_cast(boost::math::iround(v)); } } } } void ImageProcessing::Copy(ImageAccessor& target, const ImageAccessor& source) { if (target.GetWidth() != source.GetWidth() || target.GetHeight() != source.GetHeight()) { throw OrthancException(ErrorCode_IncompatibleImageSize); } if (target.GetFormat() != source.GetFormat()) { throw OrthancException(ErrorCode_IncompatibleImageFormat); } unsigned int lineSize = GetBytesPerPixel(source.GetFormat()) * source.GetWidth(); assert(source.GetPitch() >= lineSize && target.GetPitch() >= lineSize); for (unsigned int y = 0; y < source.GetHeight(); y++) { memcpy(target.GetRow(y), source.GetConstRow(y), lineSize); } } void ImageProcessing::Convert(ImageAccessor& target, const ImageAccessor& source) { if (target.GetWidth() != source.GetWidth() || target.GetHeight() != source.GetHeight()) { throw OrthancException(ErrorCode_IncompatibleImageSize); } if (source.GetFormat() == target.GetFormat()) { Copy(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale16 && source.GetFormat() == PixelFormat_Grayscale8) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_SignedGrayscale16 && source.GetFormat() == PixelFormat_Grayscale8) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale8 && source.GetFormat() == PixelFormat_Grayscale16) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_SignedGrayscale16 && source.GetFormat() == PixelFormat_Grayscale16) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale8 && source.GetFormat() == PixelFormat_SignedGrayscale16) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale16 && source.GetFormat() == PixelFormat_SignedGrayscale16) { ConvertInternal(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale8 && source.GetFormat() == PixelFormat_RGB24) { ConvertColorToGrayscale(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale16 && source.GetFormat() == PixelFormat_RGB24) { ConvertColorToGrayscale(target, source); return; } if (target.GetFormat() == PixelFormat_SignedGrayscale16 && source.GetFormat() == PixelFormat_RGB24) { ConvertColorToGrayscale(target, source); return; } if (target.GetFormat() == PixelFormat_Float32 && source.GetFormat() == PixelFormat_Grayscale8) { ConvertGrayscaleToFloat(target, source); return; } if (target.GetFormat() == PixelFormat_Float32 && source.GetFormat() == PixelFormat_Grayscale16) { ConvertGrayscaleToFloat(target, source); return; } if (target.GetFormat() == PixelFormat_Float32 && source.GetFormat() == PixelFormat_SignedGrayscale16) { ConvertGrayscaleToFloat(target, source); return; } if (target.GetFormat() == PixelFormat_Grayscale8 && source.GetFormat() == PixelFormat_RGBA32) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, q++) { *q = static_cast((2126 * static_cast(p[0]) + 7152 * static_cast(p[1]) + 0722 * static_cast(p[2])) / 10000); p += 4; } } return; } if (target.GetFormat() == PixelFormat_RGB24 && source.GetFormat() == PixelFormat_RGBA32) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = p[0]; q[1] = p[1]; q[2] = p[2]; p += 4; q += 3; } } return; } if (target.GetFormat() == PixelFormat_RGB24 && source.GetFormat() == PixelFormat_BGRA32) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = p[2]; q[1] = p[1]; q[2] = p[0]; p += 4; q += 3; } } return; } if (target.GetFormat() == PixelFormat_RGBA32 && source.GetFormat() == PixelFormat_RGB24) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = p[0]; q[1] = p[1]; q[2] = p[2]; q[3] = 255; // Set the alpha channel to full opacity p += 3; q += 4; } } return; } if (target.GetFormat() == PixelFormat_RGB24 && source.GetFormat() == PixelFormat_Grayscale8) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = *p; q[1] = *p; q[2] = *p; p += 1; q += 3; } } return; } if (target.GetFormat() == PixelFormat_RGBA32 && source.GetFormat() == PixelFormat_Grayscale8) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = *p; q[1] = *p; q[2] = *p; q[3] = 255; p += 1; q += 4; } } return; } if (target.GetFormat() == PixelFormat_BGRA32 && source.GetFormat() == PixelFormat_RGB24) { for (unsigned int y = 0; y < source.GetHeight(); y++) { const uint8_t* p = reinterpret_cast(source.GetConstRow(y)); uint8_t* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++) { q[0] = p[2]; q[1] = p[1]; q[2] = p[0]; q[3] = 255; p += 3; q += 4; } } return; } throw OrthancException(ErrorCode_NotImplemented); } void ImageProcessing::Set(ImageAccessor& image, int64_t value) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: SetInternal(image, value); return; case PixelFormat_Grayscale16: SetInternal(image, value); return; case PixelFormat_SignedGrayscale16: SetInternal(image, value); return; case PixelFormat_Float32: assert(sizeof(float) == 4); SetInternal(image, value); return; default: throw OrthancException(ErrorCode_NotImplemented); } } void ImageProcessing::Set(ImageAccessor& image, uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { uint8_t p[4]; unsigned int size; switch (image.GetFormat()) { case PixelFormat_RGBA32: p[0] = red; p[1] = green; p[2] = blue; p[3] = alpha; size = 4; break; case PixelFormat_BGRA32: p[0] = blue; p[1] = green; p[2] = red; p[3] = alpha; size = 4; break; case PixelFormat_RGB24: p[0] = red; p[1] = green; p[2] = blue; size = 3; break; default: throw OrthancException(ErrorCode_NotImplemented); } for (unsigned int y = 0; y < image.GetHeight(); y++) { uint8_t* q = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++) { for (unsigned int i = 0; i < size; i++) { q[i] = p[i]; } q += size; } } } void ImageProcessing::ShiftRight(ImageAccessor& image, unsigned int shift) { if (image.GetWidth() == 0 || image.GetHeight() == 0 || shift == 0) { // Nothing to do return; } throw OrthancException(ErrorCode_NotImplemented); } void ImageProcessing::GetMinMaxValue(int64_t& minValue, int64_t& maxValue, const ImageAccessor& image) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: { uint8_t a, b; GetMinMaxValueInternal(a, b, image); minValue = a; maxValue = b; break; } case PixelFormat_Grayscale16: { uint16_t a, b; GetMinMaxValueInternal(a, b, image); minValue = a; maxValue = b; break; } case PixelFormat_SignedGrayscale16: { int16_t a, b; GetMinMaxValueInternal(a, b, image); minValue = a; maxValue = b; break; } default: throw OrthancException(ErrorCode_NotImplemented); } } void ImageProcessing::AddConstant(ImageAccessor& image, int64_t value) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: AddConstantInternal(image, value); return; case PixelFormat_Grayscale16: AddConstantInternal(image, value); return; case PixelFormat_SignedGrayscale16: AddConstantInternal(image, value); return; default: throw OrthancException(ErrorCode_NotImplemented); } } void ImageProcessing::MultiplyConstant(ImageAccessor& image, float factor) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: MultiplyConstantInternal(image, factor); return; case PixelFormat_Grayscale16: MultiplyConstantInternal(image, factor); return; case PixelFormat_SignedGrayscale16: MultiplyConstantInternal(image, factor); return; default: throw OrthancException(ErrorCode_NotImplemented); } } void ImageProcessing::ShiftScale(ImageAccessor& image, float offset, float scaling) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: ShiftScaleInternal(image, offset, scaling); return; case PixelFormat_Grayscale16: ShiftScaleInternal(image, offset, scaling); return; case PixelFormat_SignedGrayscale16: ShiftScaleInternal(image, offset, scaling); return; default: throw OrthancException(ErrorCode_NotImplemented); } } void ImageProcessing::Invert(ImageAccessor& image) { switch (image.GetFormat()) { case PixelFormat_Grayscale8: { for (unsigned int y = 0; y < image.GetHeight(); y++) { uint8_t* p = reinterpret_cast(image.GetRow(y)); for (unsigned int x = 0; x < image.GetWidth(); x++, p++) { *p = 255 - (*p); } } return; } default: throw OrthancException(ErrorCode_NotImplemented); } } } OrthancWebViewer-2.3/Orthanc/Core/Images/ImageProcessing.h0000644000000000000000000000543613133653001021650 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "ImageAccessor.h" #include namespace Orthanc { class ImageProcessing { public: static void Copy(ImageAccessor& target, const ImageAccessor& source); static void Convert(ImageAccessor& target, const ImageAccessor& source); static void Set(ImageAccessor& image, int64_t value); static void Set(ImageAccessor& image, uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha); static void ShiftRight(ImageAccessor& target, unsigned int shift); static void GetMinMaxValue(int64_t& minValue, int64_t& maxValue, const ImageAccessor& image); static void AddConstant(ImageAccessor& image, int64_t value); static void MultiplyConstant(ImageAccessor& image, float factor); static void ShiftScale(ImageAccessor& image, float offset, float scaling); static void Invert(ImageAccessor& image); }; } OrthancWebViewer-2.3/Orthanc/Core/Logging.h0000644000000000000000000001126513133653001016747 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #if !defined(ORTHANC_ENABLE_LOGGING) # error The macro ORTHANC_ENABLE_LOGGING must be defined #endif #if !defined(ORTHANC_ENABLE_LOGGING_PLUGIN) # if ORTHANC_ENABLE_LOGGING == 1 # error The macro ORTHANC_ENABLE_LOGGING_PLUGIN must be defined # else # define ORTHANC_ENABLE_LOGGING_PLUGIN 0 # endif #endif #if ORTHANC_ENABLE_LOGGING_PLUGIN == 1 # include #endif namespace Orthanc { namespace Logging { #if ORTHANC_ENABLE_LOGGING_PLUGIN == 1 void Initialize(OrthancPluginContext* context); #else void Initialize(); #endif void Finalize(); void Reset(); void Flush(); void EnableInfoLevel(bool enabled); void EnableTraceLevel(bool enabled); void SetTargetFile(const std::string& path); void SetTargetFolder(const std::string& path); struct NullStream : public std::ostream { NullStream() : std::ios(0), std::ostream(0) { } std::ostream& operator<< (const std::string& message) { return *this; } // This overload fixes build problems with Visual Studio 2015 std::ostream& operator<< (const char* message) { return *this; } }; } } #if ORTHANC_ENABLE_LOGGING != 1 # define LOG(level) ::Orthanc::Logging::NullStream() # define VLOG(level) ::Orthanc::Logging::NullStream() #elif ORTHANC_ENABLE_LOGGING_PLUGIN == 1 # include # define LOG(level) ::Orthanc::Logging::InternalLogger(#level, __FILE__, __LINE__) # define VLOG(level) ::Orthanc::Logging::InternalLogger("TRACE", __FILE__, __LINE__) namespace Orthanc { namespace Logging { class InternalLogger : public boost::noncopyable { private: std::string level_; std::string message_; public: InternalLogger(const char* level, const char* file, int line); ~InternalLogger(); InternalLogger& operator<< (const std::string& message); InternalLogger& operator<< (const char* message); InternalLogger& operator<< (int message); }; } } #else /* ORTHANC_ENABLE_LOGGING_PLUGIN == 0 && ORTHANC_ENABLE_LOGGING == 1 */ # include # define LOG(level) ::Orthanc::Logging::InternalLogger(#level, __FILE__, __LINE__) # define VLOG(level) ::Orthanc::Logging::InternalLogger("TRACE", __FILE__, __LINE__) namespace Orthanc { namespace Logging { class InternalLogger { private: boost::mutex::scoped_lock lock_; NullStream null_; std::ostream* stream_; public: InternalLogger(const char* level, const char* file, int line); ~InternalLogger(); std::ostream& operator<< (const std::string& message) { return (*stream_) << message; } // This overload fixes build problems with Visual Studio 2015 std::ostream& operator<< (const char* message) { return (*stream_) << message; } }; } } #endif // ORTHANC_ENABLE_LOGGING OrthancWebViewer-2.3/Orthanc/Core/MultiThreading/SharedMessageQueue.cpp0000644000000000000000000001213013133653001024344 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "../PrecompiledHeaders.h" #include "SharedMessageQueue.h" /** * FIFO (queue): * * back front * +--+--+--+--+--+--+--+--+--+--+--+ * Enqueue -> | | | | | | | | | | | | * | | | | | | | | | | | | -> Dequeue * +--+--+--+--+--+--+--+--+--+--+--+ * ^ * | * Make room here * * * LIFO (stack): * * back front * +--+--+--+--+--+--+--+--+--+--+--+ * | | | | | | | | | | | | <- Enqueue * | | | | | | | | | | | | -> Dequeue * +--+--+--+--+--+--+--+--+--+--+--+ * ^ * | * Make room here **/ namespace Orthanc { SharedMessageQueue::SharedMessageQueue(unsigned int maxSize) : isFifo_(true), maxSize_(maxSize) { } SharedMessageQueue::~SharedMessageQueue() { for (Queue::iterator it = queue_.begin(); it != queue_.end(); ++it) { delete *it; } } void SharedMessageQueue::Enqueue(IDynamicObject* message) { boost::mutex::scoped_lock lock(mutex_); if (maxSize_ != 0 && queue_.size() > maxSize_) { if (isFifo_) { // Too many elements in the queue: Make room delete queue_.front(); queue_.pop_front(); } else { // Too many elements in the stack: Make room delete queue_.back(); queue_.pop_back(); } } if (isFifo_) { // Queue policy (FIFO) queue_.push_back(message); } else { // Stack policy (LIFO) queue_.push_front(message); } elementAvailable_.notify_one(); } IDynamicObject* SharedMessageQueue::Dequeue(int32_t millisecondsTimeout) { boost::mutex::scoped_lock lock(mutex_); // Wait for a message to arrive in the FIFO queue while (queue_.empty()) { if (millisecondsTimeout == 0) { elementAvailable_.wait(lock); } else { bool success = elementAvailable_.timed_wait (lock, boost::posix_time::milliseconds(millisecondsTimeout)); if (!success) { return NULL; } } } std::auto_ptr message(queue_.front()); queue_.pop_front(); if (queue_.empty()) { emptied_.notify_all(); } return message.release(); } bool SharedMessageQueue::WaitEmpty(int32_t millisecondsTimeout) { boost::mutex::scoped_lock lock(mutex_); // Wait for the queue to become empty while (!queue_.empty()) { if (millisecondsTimeout == 0) { emptied_.wait(lock); } else { if (!emptied_.timed_wait (lock, boost::posix_time::milliseconds(millisecondsTimeout))) { return false; } } } return true; } void SharedMessageQueue::SetFifoPolicy() { boost::mutex::scoped_lock lock(mutex_); isFifo_ = true; } void SharedMessageQueue::SetLifoPolicy() { boost::mutex::scoped_lock lock(mutex_); isFifo_ = false; } void SharedMessageQueue::Clear() { boost::mutex::scoped_lock lock(mutex_); if (queue_.empty()) { return; } else { while (!queue_.empty()) { std::auto_ptr message(queue_.front()); queue_.pop_front(); } emptied_.notify_all(); } } } OrthancWebViewer-2.3/Orthanc/Core/MultiThreading/SharedMessageQueue.h0000644000000000000000000000510413133653001024014 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "../IDynamicObject.h" #include #include #include namespace Orthanc { class SharedMessageQueue : public boost::noncopyable { private: typedef std::list Queue; bool isFifo_; unsigned int maxSize_; Queue queue_; boost::mutex mutex_; boost::condition_variable elementAvailable_; boost::condition_variable emptied_; public: explicit SharedMessageQueue(unsigned int maxSize = 0); ~SharedMessageQueue(); // This transfers the ownership of the message void Enqueue(IDynamicObject* message); // The caller is responsible to delete the dequeud message! IDynamicObject* Dequeue(int32_t millisecondsTimeout); bool WaitEmpty(int32_t millisecondsTimeout); bool IsFifoPolicy() const { return isFifo_; } bool IsLifoPolicy() const { return !isFifo_; } void SetFifoPolicy(); void SetLifoPolicy(); void Clear(); }; } OrthancWebViewer-2.3/Orthanc/Core/OrthancException.h0000644000000000000000000000452213133653001020634 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include #include "Enumerations.h" namespace Orthanc { class OrthancException { protected: ErrorCode errorCode_; HttpStatus httpStatus_; public: explicit OrthancException(ErrorCode errorCode) : errorCode_(errorCode), httpStatus_(ConvertErrorCodeToHttpStatus(errorCode)) { } OrthancException(ErrorCode errorCode, HttpStatus httpStatus) : errorCode_(errorCode), httpStatus_(httpStatus) { } ErrorCode GetErrorCode() const { return errorCode_; } HttpStatus GetHttpStatus() const { return httpStatus_; } const char* What() const { return EnumerationToString(errorCode_); } }; } OrthancWebViewer-2.3/Orthanc/Core/PrecompiledHeaders.cpp0000644000000000000000000000316513133653001021453 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "PrecompiledHeaders.h" OrthancWebViewer-2.3/Orthanc/Core/PrecompiledHeaders.h0000644000000000000000000000420613133653001021115 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #if defined(_WIN32) && !defined(NOMINMAX) #define NOMINMAX #endif #if ORTHANC_USE_PRECOMPILED_HEADERS == 1 #include #include #include #include #include #include #include #include #if ORTHANC_ENABLE_PUGIXML == 1 #include #endif #include "Enumerations.h" #include "Logging.h" #include "OrthancException.h" #include "Toolbox.h" #endif OrthancWebViewer-2.3/Orthanc/Core/SQLite/Connection.cpp0000644000000000000000000002412113133653001021147 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "Connection.h" #include "OrthancSQLiteException.h" #include #include #include #if ORTHANC_SQLITE_STANDALONE != 1 #include "../Logging.h" #endif #include "sqlite3.h" namespace Orthanc { namespace SQLite { Connection::Connection() : db_(NULL), transactionNesting_(0), needsRollback_(false) { } Connection::~Connection() { Close(); } void Connection::CheckIsOpen() const { if (!db_) { throw OrthancSQLiteException(ErrorCode_SQLiteNotOpened); } } void Connection::Open(const std::string& path) { if (db_) { throw OrthancSQLiteException(ErrorCode_SQLiteAlreadyOpened); } int err = sqlite3_open(path.c_str(), &db_); if (err != SQLITE_OK) { Close(); db_ = NULL; throw OrthancSQLiteException(ErrorCode_SQLiteCannotOpen); } // Execute PRAGMAs at this point // http://www.sqlite.org/pragma.html Execute("PRAGMA FOREIGN_KEYS=ON;"); Execute("PRAGMA RECURSIVE_TRIGGERS=ON;"); } void Connection::OpenInMemory() { Open(":memory:"); } void Connection::Close() { ClearCache(); if (db_) { sqlite3_close(db_); db_ = NULL; } } void Connection::ClearCache() { for (CachedStatements::iterator it = cachedStatements_.begin(); it != cachedStatements_.end(); ++it) { delete it->second; } cachedStatements_.clear(); } StatementReference& Connection::GetCachedStatement(const StatementId& id, const char* sql) { CachedStatements::iterator i = cachedStatements_.find(id); if (i != cachedStatements_.end()) { if (i->second->GetReferenceCount() >= 1) { throw OrthancSQLiteException(ErrorCode_SQLiteStatementAlreadyUsed); } return *i->second; } else { StatementReference* statement = new StatementReference(db_, sql); cachedStatements_[id] = statement; return *statement; } } bool Connection::Execute(const char* sql) { #if ORTHANC_SQLITE_STANDALONE != 1 VLOG(1) << "SQLite::Connection::Execute " << sql; #endif CheckIsOpen(); int error = sqlite3_exec(db_, sql, NULL, NULL, NULL); if (error == SQLITE_ERROR) { #if ORTHANC_SQLITE_STANDALONE != 1 LOG(ERROR) << "SQLite execute error: " << sqlite3_errmsg(db_) << " (" << sqlite3_extended_errcode(db_) << ")"; #endif throw OrthancSQLiteException(ErrorCode_SQLiteExecute); } else { return error == SQLITE_OK; } } int Connection::ExecuteAndReturnErrorCode(const char* sql) { CheckIsOpen(); return sqlite3_exec(db_, sql, NULL, NULL, NULL); } // Info querying ------------------------------------------------------------- bool Connection::IsSQLValid(const char* sql) { sqlite3_stmt* stmt = NULL; if (sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL) != SQLITE_OK) return false; sqlite3_finalize(stmt); return true; } bool Connection::DoesTableOrIndexExist(const char* name, const char* type) const { // Our SQL is non-mutating, so this cast is OK. Statement statement(const_cast(*this), "SELECT name FROM sqlite_master WHERE type=? AND name=?"); statement.BindString(0, type); statement.BindString(1, name); return statement.Step(); // Table exists if any row was returned. } bool Connection::DoesTableExist(const char* table_name) const { return DoesTableOrIndexExist(table_name, "table"); } bool Connection::DoesIndexExist(const char* index_name) const { return DoesTableOrIndexExist(index_name, "index"); } bool Connection::DoesColumnExist(const char* table_name, const char* column_name) const { std::string sql("PRAGMA TABLE_INFO("); sql.append(table_name); sql.append(")"); // Our SQL is non-mutating, so this cast is OK. Statement statement(const_cast(*this), sql.c_str()); while (statement.Step()) { if (!statement.ColumnString(1).compare(column_name)) return true; } return false; } int64_t Connection::GetLastInsertRowId() const { return sqlite3_last_insert_rowid(db_); } int Connection::GetLastChangeCount() const { return sqlite3_changes(db_); } int Connection::GetErrorCode() const { return sqlite3_errcode(db_); } int Connection::GetLastErrno() const { int err = 0; if (SQLITE_OK != sqlite3_file_control(db_, NULL, SQLITE_LAST_ERRNO, &err)) return -2; return err; } const char* Connection::GetErrorMessage() const { return sqlite3_errmsg(db_); } bool Connection::BeginTransaction() { if (needsRollback_) { assert(transactionNesting_ > 0); // When we're going to rollback, fail on this begin and don't actually // mark us as entering the nested transaction. return false; } bool success = true; if (!transactionNesting_) { needsRollback_ = false; Statement begin(*this, SQLITE_FROM_HERE, "BEGIN TRANSACTION"); if (!begin.Run()) return false; } transactionNesting_++; return success; } void Connection::RollbackTransaction() { if (!transactionNesting_) { throw OrthancSQLiteException(ErrorCode_SQLiteRollbackWithoutTransaction); } transactionNesting_--; if (transactionNesting_ > 0) { // Mark the outermost transaction as needing rollback. needsRollback_ = true; return; } DoRollback(); } bool Connection::CommitTransaction() { if (!transactionNesting_) { throw OrthancSQLiteException(ErrorCode_SQLiteCommitWithoutTransaction); } transactionNesting_--; if (transactionNesting_ > 0) { // Mark any nested transactions as failing after we've already got one. return !needsRollback_; } if (needsRollback_) { DoRollback(); return false; } Statement commit(*this, SQLITE_FROM_HERE, "COMMIT"); return commit.Run(); } void Connection::DoRollback() { Statement rollback(*this, SQLITE_FROM_HERE, "ROLLBACK"); rollback.Run(); needsRollback_ = false; } static void ScalarFunctionCaller(sqlite3_context* rawContext, int argc, sqlite3_value** argv) { FunctionContext context(rawContext, argc, argv); void* payload = sqlite3_user_data(rawContext); assert(payload != NULL); IScalarFunction& func = *reinterpret_cast(payload); func.Compute(context); } static void ScalarFunctionDestroyer(void* payload) { assert(payload != NULL); delete reinterpret_cast(payload); } IScalarFunction* Connection::Register(IScalarFunction* func) { int err = sqlite3_create_function_v2(db_, func->GetName(), func->GetCardinality(), SQLITE_UTF8, func, ScalarFunctionCaller, NULL, NULL, ScalarFunctionDestroyer); if (err != SQLITE_OK) { delete func; throw OrthancSQLiteException(ErrorCode_SQLiteRegisterFunction); } return func; } void Connection::FlushToDisk() { #if ORTHANC_SQLITE_STANDALONE != 1 VLOG(1) << "SQLite::Connection::FlushToDisk"; #endif int err = sqlite3_wal_checkpoint(db_, NULL); if (err != SQLITE_OK) { throw OrthancSQLiteException(ErrorCode_SQLiteFlush); } } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/Connection.h0000644000000000000000000001336313133653001020622 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "Statement.h" #include "IScalarFunction.h" #include "SQLiteTypes.h" #include #include #define SQLITE_FROM_HERE ::Orthanc::SQLite::StatementId(__FILE__, __LINE__) namespace Orthanc { namespace SQLite { class Connection : NonCopyable { friend class Statement; friend class Transaction; private: // All cached statements. Keeping a reference to these statements means that // they'll remain active. typedef std::map CachedStatements; CachedStatements cachedStatements_; // The actual sqlite database. Will be NULL before Init has been called or if // Init resulted in an error. sqlite3* db_; // Number of currently-nested transactions. int transactionNesting_; // True if any of the currently nested transactions have been rolled back. // When we get to the outermost transaction, this will determine if we do // a rollback instead of a commit. bool needsRollback_; void ClearCache(); void CheckIsOpen() const; sqlite3* GetWrappedObject() { return db_; } StatementReference& GetCachedStatement(const StatementId& id, const char* sql); bool DoesTableOrIndexExist(const char* name, const char* type) const; void DoRollback(); public: // The database is opened by calling Open[InMemory](). Any uncommitted // transactions will be rolled back when this object is deleted. Connection(); ~Connection(); void Open(const std::string& path); void OpenInMemory(); void Close(); bool Execute(const char* sql); bool Execute(const std::string& sql) { return Execute(sql.c_str()); } void FlushToDisk(); IScalarFunction* Register(IScalarFunction* func); // Takes the ownership of the function // Info querying ------------------------------------------------------------- // Used to check a |sql| statement for syntactic validity. If the // statement is valid SQL, returns true. bool IsSQLValid(const char* sql); // Returns true if the given table exists. bool DoesTableExist(const char* table_name) const; // Returns true if the given index exists. bool DoesIndexExist(const char* index_name) const; // Returns true if a column with the given name exists in the given table. bool DoesColumnExist(const char* table_name, const char* column_name) const; // Returns sqlite's internal ID for the last inserted row. Valid only // immediately after an insert. int64_t GetLastInsertRowId() const; // Returns sqlite's count of the number of rows modified by the last // statement executed. Will be 0 if no statement has executed or the database // is closed. int GetLastChangeCount() const; // Errors -------------------------------------------------------------------- // Returns the error code associated with the last sqlite operation. int GetErrorCode() const; // Returns the errno associated with GetErrorCode(). See // SQLITE_LAST_ERRNO in SQLite documentation. int GetLastErrno() const; // Returns a pointer to a statically allocated string associated with the // last sqlite operation. const char* GetErrorMessage() const; // Diagnostics (for unit tests) ---------------------------------------------- int ExecuteAndReturnErrorCode(const char* sql); bool HasCachedStatement(const StatementId& id) const { return cachedStatements_.find(id) != cachedStatements_.end(); } int GetTransactionNesting() const { return transactionNesting_; } // Transactions -------------------------------------------------------------- bool BeginTransaction(); void RollbackTransaction(); bool CommitTransaction(); }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/FunctionContext.cpp0000644000000000000000000000760313133653001022210 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of the CHU of Liege, nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "FunctionContext.h" #include "OrthancSQLiteException.h" #include #include "sqlite3.h" namespace Orthanc { namespace SQLite { FunctionContext::FunctionContext(struct sqlite3_context* context, int argc, Internals::SQLiteValue** argv) { assert(context != NULL); assert(argc >= 0); assert(argv != NULL); context_ = context; argc_ = static_cast(argc); argv_ = argv; } void FunctionContext::CheckIndex(unsigned int index) const { if (index >= argc_) { throw OrthancSQLiteException(ErrorCode_ParameterOutOfRange); } } ColumnType FunctionContext::GetColumnType(unsigned int index) const { CheckIndex(index); return static_cast(sqlite3_value_type(argv_[index])); } int FunctionContext::GetIntValue(unsigned int index) const { CheckIndex(index); return sqlite3_value_int(argv_[index]); } int64_t FunctionContext::GetInt64Value(unsigned int index) const { CheckIndex(index); return sqlite3_value_int64(argv_[index]); } double FunctionContext::GetDoubleValue(unsigned int index) const { CheckIndex(index); return sqlite3_value_double(argv_[index]); } std::string FunctionContext::GetStringValue(unsigned int index) const { CheckIndex(index); return std::string(reinterpret_cast(sqlite3_value_text(argv_[index]))); } bool FunctionContext::IsNullValue(unsigned int index) const { CheckIndex(index); return sqlite3_value_type(argv_[index]) == SQLITE_NULL; } void FunctionContext::SetNullResult() { sqlite3_result_null(context_); } void FunctionContext::SetIntResult(int value) { sqlite3_result_int(context_, value); } void FunctionContext::SetDoubleResult(double value) { sqlite3_result_double(context_, value); } void FunctionContext::SetStringResult(const std::string& str) { sqlite3_result_text(context_, str.data(), str.size(), SQLITE_TRANSIENT); } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/FunctionContext.h0000644000000000000000000000532113133653001021650 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of the CHU of Liege, nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "Statement.h" namespace Orthanc { namespace SQLite { class FunctionContext : public NonCopyable { friend class Connection; private: struct sqlite3_context* context_; unsigned int argc_; Internals::SQLiteValue** argv_; void CheckIndex(unsigned int index) const; public: FunctionContext(struct sqlite3_context* context, int argc, Internals::SQLiteValue** argv); ColumnType GetColumnType(unsigned int index) const; unsigned int GetParameterCount() const { return argc_; } int GetIntValue(unsigned int index) const; int64_t GetInt64Value(unsigned int index) const; double GetDoubleValue(unsigned int index) const; std::string GetStringValue(unsigned int index) const; bool IsNullValue(unsigned int index) const; void SetNullResult(); void SetIntResult(int value); void SetDoubleResult(double value); void SetStringResult(const std::string& str); }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/IScalarFunction.h0000644000000000000000000000405113133653001021541 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of the CHU of Liege, nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "NonCopyable.h" #include "FunctionContext.h" namespace Orthanc { namespace SQLite { class IScalarFunction : public NonCopyable { public: virtual ~IScalarFunction() { } virtual const char* GetName() const = 0; virtual unsigned int GetCardinality() const = 0; virtual void Compute(FunctionContext& context) = 0; }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/ITransaction.h0000644000000000000000000000473113133653001021120 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "NonCopyable.h" namespace Orthanc { namespace SQLite { class ITransaction : public NonCopyable { public: virtual ~ITransaction() { } // Begins the transaction. This uses the default sqlite "deferred" transaction // type, which means that the DB lock is lazily acquired the next time the // database is accessed, not in the begin transaction command. virtual void Begin() = 0; // Rolls back the transaction. This will happen automatically if you do // nothing when the transaction goes out of scope. virtual void Rollback() = 0; // Commits the transaction, returning true on success. virtual void Commit() = 0; }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/NonCopyable.h0000644000000000000000000000400513133653001020725 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once namespace Orthanc { namespace SQLite { // This class mimics "boost::noncopyable" class NonCopyable { private: NonCopyable(const NonCopyable&); NonCopyable& operator= (const NonCopyable&); protected: NonCopyable() { } ~NonCopyable() { } }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/OrthancSQLiteException.h0000644000000000000000000001221713133653001023057 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #if ORTHANC_SQLITE_STANDALONE == 1 #include namespace Orthanc { namespace SQLite { // Auto-generated by "Resources/GenerateErrorCodes.py" enum ErrorCode { ErrorCode_ParameterOutOfRange, ErrorCode_BadParameterType, ErrorCode_SQLiteNotOpened, ErrorCode_SQLiteAlreadyOpened, ErrorCode_SQLiteCannotOpen, ErrorCode_SQLiteStatementAlreadyUsed, ErrorCode_SQLiteExecute, ErrorCode_SQLiteRollbackWithoutTransaction, ErrorCode_SQLiteCommitWithoutTransaction, ErrorCode_SQLiteRegisterFunction, ErrorCode_SQLiteFlush, ErrorCode_SQLiteCannotRun, ErrorCode_SQLiteCannotStep, ErrorCode_SQLiteBindOutOfRange, ErrorCode_SQLitePrepareStatement, ErrorCode_SQLiteTransactionAlreadyStarted, ErrorCode_SQLiteTransactionCommit, ErrorCode_SQLiteTransactionBegin }; class OrthancSQLiteException : public ::std::runtime_error { public: OrthancSQLiteException(ErrorCode error) : ::std::runtime_error(EnumerationToString(error)) { } // Auto-generated by "Resources/GenerateErrorCodes.py" static const char* EnumerationToString(ErrorCode code) { switch (code) { case ErrorCode_ParameterOutOfRange: return "Parameter out of range"; case ErrorCode_BadParameterType: return "Bad type for a parameter"; case ErrorCode_SQLiteNotOpened: return "SQLite: The database is not opened"; case ErrorCode_SQLiteAlreadyOpened: return "SQLite: Connection is already open"; case ErrorCode_SQLiteCannotOpen: return "SQLite: Unable to open the database"; case ErrorCode_SQLiteStatementAlreadyUsed: return "SQLite: This cached statement is already being referred to"; case ErrorCode_SQLiteExecute: return "SQLite: Cannot execute a command"; case ErrorCode_SQLiteRollbackWithoutTransaction: return "SQLite: Rolling back a nonexistent transaction (have you called Begin()?)"; case ErrorCode_SQLiteCommitWithoutTransaction: return "SQLite: Committing a nonexistent transaction"; case ErrorCode_SQLiteRegisterFunction: return "SQLite: Unable to register a function"; case ErrorCode_SQLiteFlush: return "SQLite: Unable to flush the database"; case ErrorCode_SQLiteCannotRun: return "SQLite: Cannot run a cached statement"; case ErrorCode_SQLiteCannotStep: return "SQLite: Cannot step over a cached statement"; case ErrorCode_SQLiteBindOutOfRange: return "SQLite: Bing a value while out of range (serious error)"; case ErrorCode_SQLitePrepareStatement: return "SQLite: Cannot prepare a cached statement"; case ErrorCode_SQLiteTransactionAlreadyStarted: return "SQLite: Beginning the same transaction twice"; case ErrorCode_SQLiteTransactionCommit: return "SQLite: Failure when committing the transaction"; case ErrorCode_SQLiteTransactionBegin: return "SQLite: Cannot start a transaction"; default: return "Unknown error code"; } } }; } } #else # include "../OrthancException.h" # define OrthancSQLiteException ::Orthanc::OrthancException #endif OrthancWebViewer-2.3/Orthanc/Core/SQLite/SQLiteTypes.h0000644000000000000000000000474013133653001020710 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of the CHU of Liege, nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once struct sqlite3; struct sqlite3_context; struct sqlite3_stmt; #if !defined(ORTHANC_SQLITE_VERSION) #error Please define macro ORTHANC_SQLITE_VERSION #endif /** * "sqlite3_value" is defined as: * - "typedef struct Mem sqlite3_value;" up to SQLite <= 3.18.2 * - "typedef struct sqlite3_value sqlite3_value;" since SQLite >= 3.19.0. * We create our own copy of this typedef to get around this API incompatibility. * https://github.com/mackyle/sqlite/commit/db1d90df06a78264775a14d22c3361eb5b42be17 **/ #if ORTHANC_SQLITE_VERSION < 3019000 struct Mem; #else struct sqlite3_value; #endif namespace Orthanc { namespace SQLite { namespace Internals { #if ORTHANC_SQLITE_VERSION < 3019000 typedef struct ::Mem SQLiteValue; #else typedef struct ::sqlite3_value SQLiteValue; #endif } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/Statement.cpp0000644000000000000000000002411713133653001021021 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "Statement.h" #include "Connection.h" #include #include #include #if ORTHANC_SQLITE_STANDALONE != 1 #include "../Logging.h" #endif #include "sqlite3.h" #if defined(_MSC_VER) #define snprintf _snprintf #endif namespace Orthanc { namespace SQLite { int Statement::CheckError(int err, ErrorCode code) const { bool succeeded = (err == SQLITE_OK || err == SQLITE_ROW || err == SQLITE_DONE); if (!succeeded) { #if ORTHANC_SQLITE_STANDALONE != 1 char buffer[128]; snprintf(buffer, sizeof(buffer) - 1, "SQLite error code %d", err); LOG(ERROR) << buffer; #endif throw OrthancSQLiteException(code); } return err; } void Statement::CheckOk(int err, ErrorCode code) const { if (err == SQLITE_RANGE) { // Binding to a non-existent variable is evidence of a serious error. throw OrthancSQLiteException(ErrorCode_SQLiteBindOutOfRange); } else if (err != SQLITE_OK) { #if ORTHANC_SQLITE_STANDALONE != 1 char buffer[128]; snprintf(buffer, sizeof(buffer) - 1, "SQLite error code %d", err); LOG(ERROR) << buffer; #endif throw OrthancSQLiteException(code); } } Statement::Statement(Connection& database, const StatementId& id, const std::string& sql) : reference_(database.GetCachedStatement(id, sql.c_str())) { Reset(true); } Statement::Statement(Connection& database, const StatementId& id, const char* sql) : reference_(database.GetCachedStatement(id, sql)) { Reset(true); } Statement::Statement(Connection& database, const std::string& sql) : reference_(database.GetWrappedObject(), sql.c_str()) { } Statement::Statement(Connection& database, const char* sql) : reference_(database.GetWrappedObject(), sql) { } bool Statement::Run() { #if ORTHANC_SQLITE_STANDALONE != 1 VLOG(1) << "SQLite::Statement::Run " << sqlite3_sql(GetStatement()); #endif return CheckError(sqlite3_step(GetStatement()), ErrorCode_SQLiteCannotRun) == SQLITE_DONE; } bool Statement::Step() { #if ORTHANC_SQLITE_STANDALONE != 1 VLOG(1) << "SQLite::Statement::Step " << sqlite3_sql(GetStatement()); #endif return CheckError(sqlite3_step(GetStatement()), ErrorCode_SQLiteCannotStep) == SQLITE_ROW; } void Statement::Reset(bool clear_bound_vars) { // We don't call CheckError() here because sqlite3_reset() returns // the last error that Step() caused thereby generating a second // spurious error callback. if (clear_bound_vars) sqlite3_clear_bindings(GetStatement()); //VLOG(1) << "SQLite::Statement::Reset"; sqlite3_reset(GetStatement()); } std::string Statement::GetOriginalSQLStatement() { return std::string(sqlite3_sql(GetStatement())); } void Statement::BindNull(int col) { CheckOk(sqlite3_bind_null(GetStatement(), col + 1), ErrorCode_BadParameterType); } void Statement::BindBool(int col, bool val) { BindInt(col, val ? 1 : 0); } void Statement::BindInt(int col, int val) { CheckOk(sqlite3_bind_int(GetStatement(), col + 1, val), ErrorCode_BadParameterType); } void Statement::BindInt64(int col, int64_t val) { CheckOk(sqlite3_bind_int64(GetStatement(), col + 1, val), ErrorCode_BadParameterType); } void Statement::BindDouble(int col, double val) { CheckOk(sqlite3_bind_double(GetStatement(), col + 1, val), ErrorCode_BadParameterType); } void Statement::BindCString(int col, const char* val) { CheckOk(sqlite3_bind_text(GetStatement(), col + 1, val, -1, SQLITE_TRANSIENT), ErrorCode_BadParameterType); } void Statement::BindString(int col, const std::string& val) { CheckOk(sqlite3_bind_text(GetStatement(), col + 1, val.data(), val.size(), SQLITE_TRANSIENT), ErrorCode_BadParameterType); } /*void Statement::BindString16(int col, const string16& value) { BindString(col, UTF16ToUTF8(value)); }*/ void Statement::BindBlob(int col, const void* val, int val_len) { CheckOk(sqlite3_bind_blob(GetStatement(), col + 1, val, val_len, SQLITE_TRANSIENT), ErrorCode_BadParameterType); } int Statement::ColumnCount() const { return sqlite3_column_count(GetStatement()); } ColumnType Statement::GetColumnType(int col) const { // Verify that our enum matches sqlite's values. assert(COLUMN_TYPE_INTEGER == SQLITE_INTEGER); assert(COLUMN_TYPE_FLOAT == SQLITE_FLOAT); assert(COLUMN_TYPE_TEXT == SQLITE_TEXT); assert(COLUMN_TYPE_BLOB == SQLITE_BLOB); assert(COLUMN_TYPE_NULL == SQLITE_NULL); return static_cast(sqlite3_column_type(GetStatement(), col)); } ColumnType Statement::GetDeclaredColumnType(int col) const { std::string column_type(sqlite3_column_decltype(GetStatement(), col)); std::transform(column_type.begin(), column_type.end(), column_type.begin(), tolower); if (column_type == "integer") return COLUMN_TYPE_INTEGER; else if (column_type == "float") return COLUMN_TYPE_FLOAT; else if (column_type == "text") return COLUMN_TYPE_TEXT; else if (column_type == "blob") return COLUMN_TYPE_BLOB; return COLUMN_TYPE_NULL; } bool Statement::ColumnIsNull(int col) const { return sqlite3_column_type(GetStatement(), col) == SQLITE_NULL; } bool Statement::ColumnBool(int col) const { return !!ColumnInt(col); } int Statement::ColumnInt(int col) const { return sqlite3_column_int(GetStatement(), col); } int64_t Statement::ColumnInt64(int col) const { return sqlite3_column_int64(GetStatement(), col); } double Statement::ColumnDouble(int col) const { return sqlite3_column_double(GetStatement(), col); } std::string Statement::ColumnString(int col) const { const char* str = reinterpret_cast( sqlite3_column_text(GetStatement(), col)); int len = sqlite3_column_bytes(GetStatement(), col); std::string result; if (str && len > 0) result.assign(str, len); return result; } /*string16 Statement::ColumnString16(int col) const { std::string s = ColumnString(col); return !s.empty() ? UTF8ToUTF16(s) : string16(); }*/ int Statement::ColumnByteLength(int col) const { return sqlite3_column_bytes(GetStatement(), col); } const void* Statement::ColumnBlob(int col) const { return sqlite3_column_blob(GetStatement(), col); } bool Statement::ColumnBlobAsString(int col, std::string* blob) { const void* p = ColumnBlob(col); size_t len = ColumnByteLength(col); blob->resize(len); if (blob->size() != len) { return false; } blob->assign(reinterpret_cast(p), len); return true; } /*bool Statement::ColumnBlobAsString16(int col, string16* val) const { const void* data = ColumnBlob(col); size_t len = ColumnByteLength(col) / sizeof(char16); val->resize(len); if (val->size() != len) return false; val->assign(reinterpret_cast(data), len); return true; }*/ /*bool Statement::ColumnBlobAsVector(int col, std::vector* val) const { val->clear(); const void* data = sqlite3_column_blob(GetStatement(), col); int len = sqlite3_column_bytes(GetStatement(), col); if (data && len > 0) { val->resize(len); memcpy(&(*val)[0], data, len); } return true; }*/ /*bool Statement::ColumnBlobAsVector( int col, std::vector* val) const { return ColumnBlobAsVector(col, reinterpret_cast< std::vector* >(val)); }*/ } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/Statement.h0000644000000000000000000001343313133653001020465 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "NonCopyable.h" #include "OrthancSQLiteException.h" #include "StatementId.h" #include "StatementReference.h" #include #include #if ORTHANC_BUILD_UNIT_TESTS == 1 #include #endif namespace Orthanc { namespace SQLite { class Connection; // Possible return values from ColumnType in a statement. These // should match the values in sqlite3.h. enum ColumnType { COLUMN_TYPE_INTEGER = 1, COLUMN_TYPE_FLOAT = 2, COLUMN_TYPE_TEXT = 3, COLUMN_TYPE_BLOB = 4, COLUMN_TYPE_NULL = 5 }; class Statement : public NonCopyable { friend class Connection; #if ORTHANC_BUILD_UNIT_TESTS == 1 FRIEND_TEST(SQLStatementTest, Run); FRIEND_TEST(SQLStatementTest, Reset); #endif private: StatementReference reference_; int CheckError(int err, ErrorCode code) const; void CheckOk(int err, ErrorCode code) const; struct sqlite3_stmt* GetStatement() const { return reference_.GetWrappedObject(); } public: Statement(Connection& database, const std::string& sql); Statement(Connection& database, const StatementId& id, const std::string& sql); Statement(Connection& database, const char* sql); Statement(Connection& database, const StatementId& id, const char* sql); ~Statement() { Reset(); } bool Run(); bool Step(); // Diagnostics -------------------------------------------------------------- std::string GetOriginalSQLStatement(); // Binding ------------------------------------------------------------------- // These all take a 0-based argument index void BindNull(int col); void BindBool(int col, bool val); void BindInt(int col, int val); void BindInt64(int col, int64_t val); void BindDouble(int col, double val); void BindCString(int col, const char* val); void BindString(int col, const std::string& val); //void BindString16(int col, const string16& value); void BindBlob(int col, const void* value, int value_len); // Retrieving ---------------------------------------------------------------- // Returns the number of output columns in the result. int ColumnCount() const; // Returns the type associated with the given column. // // Watch out: the type may be undefined if you've done something to cause a // "type conversion." This means requesting the value of a column of a type // where that type is not the native type. For safety, call ColumnType only // on a column before getting the value out in any way. ColumnType GetColumnType(int col) const; ColumnType GetDeclaredColumnType(int col) const; // These all take a 0-based argument index. bool ColumnIsNull(int col) const ; bool ColumnBool(int col) const; int ColumnInt(int col) const; int64_t ColumnInt64(int col) const; double ColumnDouble(int col) const; std::string ColumnString(int col) const; //string16 ColumnString16(int col) const; // When reading a blob, you can get a raw pointer to the underlying data, // along with the length, or you can just ask us to copy the blob into a // vector. Danger! ColumnBlob may return NULL if there is no data! int ColumnByteLength(int col) const; const void* ColumnBlob(int col) const; bool ColumnBlobAsString(int col, std::string* blob); //bool ColumnBlobAsString16(int col, string16* val) const; //bool ColumnBlobAsVector(int col, std::vector* val) const; //bool ColumnBlobAsVector(int col, std::vector* val) const; // Resets the statement to its initial condition. This includes any current // result row, and also the bound variables if the |clear_bound_vars| is true. void Reset(bool clear_bound_vars = true); }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/StatementId.cpp0000644000000000000000000000414413133653001021274 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "StatementId.h" #include namespace Orthanc { namespace SQLite { bool StatementId::operator< (const StatementId& other) const { if (line_ != other.line_) return line_ < other.line_; return strcmp(file_, other.file_) < 0; } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/StatementId.h0000644000000000000000000000412113133653001020734 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once namespace Orthanc { namespace SQLite { class StatementId { private: const char* file_; int line_; StatementId(); // Forbidden public: StatementId(const char* file, int line) : file_(file), line_(line) { } bool operator< (const StatementId& other) const; }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/StatementReference.cpp0000644000000000000000000001046013133653001022634 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "StatementReference.h" #include "OrthancSQLiteException.h" #if ORTHANC_SQLITE_STANDALONE != 1 #include "../Logging.h" #endif #include #include #include "sqlite3.h" namespace Orthanc { namespace SQLite { bool StatementReference::IsRoot() const { return root_ == NULL; } StatementReference::StatementReference() { root_ = NULL; refCount_ = 0; statement_ = NULL; assert(IsRoot()); } StatementReference::StatementReference(sqlite3* database, const char* sql) { if (database == NULL || sql == NULL) { throw OrthancSQLiteException(ErrorCode_ParameterOutOfRange); } root_ = NULL; refCount_ = 0; int error = sqlite3_prepare_v2(database, sql, -1, &statement_, NULL); if (error != SQLITE_OK) { #if ORTHANC_SQLITE_STANDALONE != 1 LOG(ERROR) << "SQLite: " << sqlite3_errmsg(database) << " (" << sqlite3_extended_errcode(database) << ")"; #endif throw OrthancSQLiteException(ErrorCode_SQLitePrepareStatement); } assert(IsRoot()); } StatementReference::StatementReference(StatementReference& other) { refCount_ = 0; if (other.IsRoot()) { root_ = &other; } else { root_ = other.root_; } root_->refCount_++; statement_ = root_->statement_; assert(!IsRoot()); } StatementReference::~StatementReference() { if (IsRoot()) { if (refCount_ != 0) { // There remain references to this object. We cannot throw // an exception because: // http://www.parashift.com/c++-faq/dtors-shouldnt-throw.html #if ORTHANC_SQLITE_STANDALONE != 1 LOG(ERROR) << "Bad value of the reference counter"; #endif } else if (statement_ != NULL) { sqlite3_finalize(statement_); } } else { if (root_->refCount_ == 0) { // There remain references to this object. We cannot throw // an exception because: // http://www.parashift.com/c++-faq/dtors-shouldnt-throw.html #if ORTHANC_SQLITE_STANDALONE != 1 LOG(ERROR) << "Bad value of the reference counter"; #endif } else { root_->refCount_--; } } } uint32_t StatementReference::GetReferenceCount() const { return refCount_; } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/StatementReference.h0000644000000000000000000000506213133653001022303 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "NonCopyable.h" #include "SQLiteTypes.h" #include #include #include namespace Orthanc { namespace SQLite { class StatementReference : NonCopyable { private: StatementReference* root_; // Only used for non-root nodes uint32_t refCount_; // Only used for root node struct sqlite3_stmt* statement_; bool IsRoot() const; public: StatementReference(); StatementReference(sqlite3* database, const char* sql); StatementReference(StatementReference& other); ~StatementReference(); uint32_t GetReferenceCount() const; struct sqlite3_stmt* GetWrappedObject() const { assert(statement_ != NULL); return statement_; } }; } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/Transaction.cpp0000644000000000000000000000601513133653001021337 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #if ORTHANC_SQLITE_STANDALONE != 1 #include "../PrecompiledHeaders.h" #endif #include "Transaction.h" #include "OrthancSQLiteException.h" namespace Orthanc { namespace SQLite { Transaction::Transaction(Connection& connection) : connection_(connection), isOpen_(false) { } Transaction::~Transaction() { if (isOpen_) { connection_.RollbackTransaction(); } } void Transaction::Begin() { if (isOpen_) { throw OrthancSQLiteException(ErrorCode_SQLiteTransactionAlreadyStarted); } isOpen_ = connection_.BeginTransaction(); if (!isOpen_) { throw OrthancSQLiteException(ErrorCode_SQLiteTransactionBegin); } } void Transaction::Rollback() { if (!isOpen_) { throw OrthancSQLiteException(ErrorCode_SQLiteRollbackWithoutTransaction); } isOpen_ = false; connection_.RollbackTransaction(); } void Transaction::Commit() { if (!isOpen_) { throw OrthancSQLiteException(ErrorCode_SQLiteRollbackWithoutTransaction); } isOpen_ = false; if (!connection_.CommitTransaction()) { throw OrthancSQLiteException(ErrorCode_SQLiteTransactionCommit); } } } } OrthancWebViewer-2.3/Orthanc/Core/SQLite/Transaction.h0000644000000000000000000000461513133653001021010 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * * Copyright (C) 2012-2016 Sebastien Jodogne , * Medical Physics Department, CHU of Liege, Belgium * * Copyright (c) 2012 The Chromium Authors. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc., the name of the CHU of Liege, * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #pragma once #include "Connection.h" #include "ITransaction.h" namespace Orthanc { namespace SQLite { class Transaction : public ITransaction { private: Connection& connection_; // True when the transaction is open, false when it's already been committed // or rolled back. bool isOpen_; public: explicit Transaction(Connection& connection); virtual ~Transaction(); // Returns true when there is a transaction that has been successfully begun. bool IsOpen() const { return isOpen_; } virtual void Begin(); virtual void Rollback(); virtual void Commit(); }; } } OrthancWebViewer-2.3/Orthanc/Core/SystemToolbox.cpp0000644000000000000000000003176513133653001020556 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "PrecompiledHeaders.h" #include "SystemToolbox.h" #if BOOST_HAS_DATE_TIME == 1 # include #endif #if defined(_WIN32) # include # include // For "_spawnvp()" and "_getpid()" #else # include // For "execvp()" # include // For "waitpid()" #endif #if defined(__APPLE__) && defined(__MACH__) # include /* _NSGetExecutablePath */ # include /* PATH_MAX */ #endif #if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) # include /* PATH_MAX */ # include # include #endif // Inclusions for UUID // http://stackoverflow.com/a/1626302 extern "C" { #ifdef WIN32 # include #else # include #endif } #include "Logging.h" #include "OrthancException.h" #include "Toolbox.h" #include #include namespace Orthanc { static bool finish_; static ServerBarrierEvent barrierEvent_; #if defined(_WIN32) static BOOL WINAPI ConsoleControlHandler(DWORD dwCtrlType) { // http://msdn.microsoft.com/en-us/library/ms683242(v=vs.85).aspx finish_ = true; return true; } #else static void SignalHandler(int signal) { if (signal == SIGHUP) { barrierEvent_ = ServerBarrierEvent_Reload; } finish_ = true; } #endif static ServerBarrierEvent ServerBarrierInternal(const bool* stopFlag) { #if defined(_WIN32) SetConsoleCtrlHandler(ConsoleControlHandler, true); #else signal(SIGINT, SignalHandler); signal(SIGQUIT, SignalHandler); signal(SIGTERM, SignalHandler); signal(SIGHUP, SignalHandler); #endif // Active loop that awakens every 100ms finish_ = false; barrierEvent_ = ServerBarrierEvent_Stop; while (!(*stopFlag || finish_)) { SystemToolbox::USleep(100 * 1000); } #if defined(_WIN32) SetConsoleCtrlHandler(ConsoleControlHandler, false); #else signal(SIGINT, NULL); signal(SIGQUIT, NULL); signal(SIGTERM, NULL); signal(SIGHUP, NULL); #endif return barrierEvent_; } ServerBarrierEvent SystemToolbox::ServerBarrier(const bool& stopFlag) { return ServerBarrierInternal(&stopFlag); } ServerBarrierEvent SystemToolbox::ServerBarrier() { const bool stopFlag = false; return ServerBarrierInternal(&stopFlag); } void SystemToolbox::USleep(uint64_t microSeconds) { #if defined(_WIN32) ::Sleep(static_cast(microSeconds / static_cast(1000))); #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) || defined(__native_client__) usleep(microSeconds); #else #error Support your platform here #endif } static std::streamsize GetStreamSize(std::istream& f) { // http://www.cplusplus.com/reference/iostream/istream/tellg/ f.seekg(0, std::ios::end); std::streamsize size = f.tellg(); f.seekg(0, std::ios::beg); return size; } void SystemToolbox::ReadFile(std::string& content, const std::string& path) { if (!IsRegularFile(path)) { LOG(ERROR) << std::string("The path does not point to a regular file: ") << path; throw OrthancException(ErrorCode_RegularFileExpected); } boost::filesystem::ifstream f; f.open(path, std::ifstream::in | std::ifstream::binary); if (!f.good()) { throw OrthancException(ErrorCode_InexistentFile); } std::streamsize size = GetStreamSize(f); content.resize(size); if (size != 0) { f.read(reinterpret_cast(&content[0]), size); } f.close(); } bool SystemToolbox::ReadHeader(std::string& header, const std::string& path, size_t headerSize) { if (!IsRegularFile(path)) { LOG(ERROR) << std::string("The path does not point to a regular file: ") << path; throw OrthancException(ErrorCode_RegularFileExpected); } boost::filesystem::ifstream f; f.open(path, std::ifstream::in | std::ifstream::binary); if (!f.good()) { throw OrthancException(ErrorCode_InexistentFile); } bool full = true; { std::streamsize size = GetStreamSize(f); if (size <= 0) { headerSize = 0; full = false; } else if (static_cast(size) < headerSize) { headerSize = size; // Truncate to the size of the file full = false; } } header.resize(headerSize); if (headerSize != 0) { f.read(reinterpret_cast(&header[0]), headerSize); } f.close(); return full; } void SystemToolbox::WriteFile(const void* content, size_t size, const std::string& path) { boost::filesystem::ofstream f; f.open(path, std::ofstream::out | std::ofstream::binary); if (!f.good()) { throw OrthancException(ErrorCode_CannotWriteFile); } if (size != 0) { f.write(reinterpret_cast(content), size); if (!f.good()) { f.close(); throw OrthancException(ErrorCode_FileStorageCannotWrite); } } f.close(); } void SystemToolbox::WriteFile(const std::string& content, const std::string& path) { WriteFile(content.size() > 0 ? content.c_str() : NULL, content.size(), path); } void SystemToolbox::RemoveFile(const std::string& path) { if (boost::filesystem::exists(path)) { if (IsRegularFile(path)) { boost::filesystem::remove(path); } else { throw OrthancException(ErrorCode_RegularFileExpected); } } } uint64_t SystemToolbox::GetFileSize(const std::string& path) { try { return static_cast(boost::filesystem::file_size(path)); } catch (boost::filesystem::filesystem_error&) { throw OrthancException(ErrorCode_InexistentFile); } } void SystemToolbox::MakeDirectory(const std::string& path) { if (boost::filesystem::exists(path)) { if (!boost::filesystem::is_directory(path)) { throw OrthancException(ErrorCode_DirectoryOverFile); } } else { if (!boost::filesystem::create_directories(path)) { throw OrthancException(ErrorCode_MakeDirectory); } } } bool SystemToolbox::IsExistingFile(const std::string& path) { return boost::filesystem::exists(path); } #if defined(_WIN32) static std::string GetPathToExecutableInternal() { // Yes, this is ugly, but there is no simple way to get the // required buffer size, so we use a big constant std::vector buffer(32768); /*int bytes =*/ GetModuleFileNameA(NULL, &buffer[0], static_cast(buffer.size() - 1)); return std::string(&buffer[0]); } #elif defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__FreeBSD__) static std::string GetPathToExecutableInternal() { std::vector buffer(PATH_MAX + 1); ssize_t bytes = readlink("/proc/self/exe", &buffer[0], buffer.size() - 1); if (bytes == 0) { throw OrthancException(ErrorCode_PathToExecutable); } return std::string(&buffer[0]); } #elif defined(__APPLE__) && defined(__MACH__) static std::string GetPathToExecutableInternal() { char pathbuf[PATH_MAX + 1]; unsigned int bufsize = static_cast(sizeof(pathbuf)); _NSGetExecutablePath( pathbuf, &bufsize); return std::string(pathbuf); } #else #error Support your platform here #endif std::string SystemToolbox::GetPathToExecutable() { boost::filesystem::path p(GetPathToExecutableInternal()); return boost::filesystem::absolute(p).string(); } std::string SystemToolbox::GetDirectoryOfExecutable() { boost::filesystem::path p(GetPathToExecutableInternal()); return boost::filesystem::absolute(p.parent_path()).string(); } void SystemToolbox::ExecuteSystemCommand(const std::string& command, const std::vector& arguments) { // Convert the arguments as a C array std::vector args(arguments.size() + 2); args.front() = const_cast(command.c_str()); for (size_t i = 0; i < arguments.size(); i++) { args[i + 1] = const_cast(arguments[i].c_str()); } args.back() = NULL; int status; #if defined(_WIN32) // http://msdn.microsoft.com/en-us/library/275khfab.aspx status = static_cast(_spawnvp(_P_OVERLAY, command.c_str(), &args[0])); #else int pid = fork(); if (pid == -1) { // Error in fork() #if ORTHANC_ENABLE_LOGGING == 1 LOG(ERROR) << "Cannot fork a child process"; #endif throw OrthancException(ErrorCode_SystemCommand); } else if (pid == 0) { // Execute the system command in the child process execvp(command.c_str(), &args[0]); // We should never get here _exit(1); } else { // Wait for the system command to exit waitpid(pid, &status, 0); } #endif if (status != 0) { #if ORTHANC_ENABLE_LOGGING == 1 LOG(ERROR) << "System command failed with status code " << status; #endif throw OrthancException(ErrorCode_SystemCommand); } } int SystemToolbox::GetProcessId() { #if defined(_WIN32) return static_cast(_getpid()); #else return static_cast(getpid()); #endif } bool SystemToolbox::IsRegularFile(const std::string& path) { namespace fs = boost::filesystem; try { if (fs::exists(path)) { fs::file_status status = fs::status(path); return (status.type() == boost::filesystem::regular_file || status.type() == boost::filesystem::reparse_file); // Fix BitBucket issue #11 } } catch (fs::filesystem_error&) { } return false; } FILE* SystemToolbox::OpenFile(const std::string& path, FileMode mode) { #if defined(_WIN32) // TODO Deal with special characters by converting to the current locale #endif const char* m; switch (mode) { case FileMode_ReadBinary: m = "rb"; break; case FileMode_WriteBinary: m = "wb"; break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } return fopen(path.c_str(), m); } std::string SystemToolbox::GenerateUuid() { #ifdef WIN32 UUID uuid; UuidCreate ( &uuid ); unsigned char * str; UuidToStringA ( &uuid, &str ); std::string s( ( char* ) str ); RpcStringFreeA ( &str ); #else uuid_t uuid; uuid_generate_random ( uuid ); char s[37]; uuid_unparse ( uuid, s ); #endif return s; } #if BOOST_HAS_DATE_TIME == 1 std::string SystemToolbox::GetNowIsoString() { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); return boost::posix_time::to_iso_string(now); } void SystemToolbox::GetNowDicom(std::string& date, std::string& time) { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); tm tm = boost::posix_time::to_tm(now); char s[32]; sprintf(s, "%04d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); date.assign(s); // TODO milliseconds sprintf(s, "%02d%02d%02d.%06d", tm.tm_hour, tm.tm_min, tm.tm_sec, 0); time.assign(s); } #endif } OrthancWebViewer-2.3/Orthanc/Core/SystemToolbox.h0000644000000000000000000000635213133653001020215 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #if !defined(ORTHANC_SANDBOXED) # error The macro ORTHANC_SANDBOXED must be defined #endif #if ORTHANC_SANDBOXED == 1 # error The namespace SystemToolbox cannot be used in sandboxed environments #endif #include "Enumerations.h" #include #include #include namespace Orthanc { namespace SystemToolbox { void USleep(uint64_t microSeconds); ServerBarrierEvent ServerBarrier(const bool& stopFlag); ServerBarrierEvent ServerBarrier(); void ReadFile(std::string& content, const std::string& path); bool ReadHeader(std::string& header, const std::string& path, size_t headerSize); void WriteFile(const void* content, size_t size, const std::string& path); void WriteFile(const std::string& content, const std::string& path); void RemoveFile(const std::string& path); uint64_t GetFileSize(const std::string& path); void MakeDirectory(const std::string& path); bool IsExistingFile(const std::string& path); std::string GetPathToExecutable(); std::string GetDirectoryOfExecutable(); void ExecuteSystemCommand(const std::string& command, const std::vector& arguments); int GetProcessId(); bool IsRegularFile(const std::string& path); FILE* OpenFile(const std::string& path, FileMode mode); std::string GenerateUuid(); #if BOOST_HAS_DATE_TIME == 1 std::string GetNowIsoString(); void GetNowDicom(std::string& date, std::string& time); #endif } } OrthancWebViewer-2.3/Orthanc/Core/Toolbox.cpp0000644000000000000000000006640613133653001017351 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "PrecompiledHeaders.h" #include "Toolbox.h" #include "OrthancException.h" #include "Logging.h" #include #include #include #include #include #include #include #include #include #if BOOST_HAS_REGEX == 1 # include #endif #if BOOST_HAS_LOCALE != 1 # error Since version 0.7.6, Orthanc entirely relies on boost::locale #endif #if ORTHANC_ENABLE_MD5 == 1 # include "../Resources/ThirdParty/md5/md5.h" #endif #if ORTHANC_ENABLE_BASE64 == 1 # include "../Resources/ThirdParty/base64/base64.h" #endif #if defined(_MSC_VER) && (_MSC_VER < 1800) // Patch for the missing "_strtoll" symbol when compiling with Visual Studio < 2013 extern "C" { int64_t _strtoi64(const char *nptr, char **endptr, int base); int64_t strtoll(const char *nptr, char **endptr, int base) { return _strtoi64(nptr, endptr, base); } } #endif #if defined(_WIN32) # include // For ::Sleep #endif #if ORTHANC_ENABLE_PUGIXML == 1 # include "ChunkedBuffer.h" # include #endif namespace Orthanc { void Toolbox::ToUpperCase(std::string& s) { std::transform(s.begin(), s.end(), s.begin(), toupper); } void Toolbox::ToLowerCase(std::string& s) { std::transform(s.begin(), s.end(), s.begin(), tolower); } void Toolbox::ToUpperCase(std::string& result, const std::string& source) { result = source; ToUpperCase(result); } void Toolbox::ToLowerCase(std::string& result, const std::string& source) { result = source; ToLowerCase(result); } void Toolbox::SplitUriComponents(UriComponents& components, const std::string& uri) { static const char URI_SEPARATOR = '/'; components.clear(); if (uri.size() == 0 || uri[0] != URI_SEPARATOR) { throw OrthancException(ErrorCode_UriSyntax); } // Count the number of slashes in the URI to make an assumption // about the number of components in the URI unsigned int estimatedSize = 0; for (unsigned int i = 0; i < uri.size(); i++) { if (uri[i] == URI_SEPARATOR) estimatedSize++; } components.reserve(estimatedSize - 1); unsigned int start = 1; unsigned int end = 1; while (end < uri.size()) { // This is the loop invariant assert(uri[start - 1] == '/' && (end >= start)); if (uri[end] == '/') { components.push_back(std::string(&uri[start], end - start)); end++; start = end; } else { end++; } } if (start < uri.size()) { components.push_back(std::string(&uri[start], end - start)); } for (size_t i = 0; i < components.size(); i++) { if (components[i].size() == 0) { // Empty component, as in: "/coucou//e" throw OrthancException(ErrorCode_UriSyntax); } } } void Toolbox::TruncateUri(UriComponents& target, const UriComponents& source, size_t fromLevel) { target.clear(); if (source.size() > fromLevel) { target.resize(source.size() - fromLevel); size_t j = 0; for (size_t i = fromLevel; i < source.size(); i++, j++) { target[j] = source[i]; } assert(j == target.size()); } } bool Toolbox::IsChildUri(const UriComponents& baseUri, const UriComponents& testedUri) { if (testedUri.size() < baseUri.size()) { return false; } for (size_t i = 0; i < baseUri.size(); i++) { if (baseUri[i] != testedUri[i]) return false; } return true; } std::string Toolbox::AutodetectMimeType(const std::string& path) { std::string contentType; size_t lastDot = path.rfind('.'); size_t lastSlash = path.rfind('/'); if (lastDot == std::string::npos || (lastSlash != std::string::npos && lastDot < lastSlash)) { // No trailing dot, unable to detect the content type } else { const char* extension = &path[lastDot + 1]; // http://en.wikipedia.org/wiki/Mime_types // Text types if (!strcmp(extension, "txt")) contentType = "text/plain"; else if (!strcmp(extension, "html")) contentType = "text/html"; else if (!strcmp(extension, "xml")) contentType = "text/xml"; else if (!strcmp(extension, "css")) contentType = "text/css"; // Application types else if (!strcmp(extension, "js")) contentType = "application/javascript"; else if (!strcmp(extension, "json")) contentType = "application/json"; else if (!strcmp(extension, "pdf")) contentType = "application/pdf"; // Images types else if (!strcmp(extension, "jpg") || !strcmp(extension, "jpeg")) contentType = "image/jpeg"; else if (!strcmp(extension, "gif")) contentType = "image/gif"; else if (!strcmp(extension, "png")) contentType = "image/png"; } return contentType; } std::string Toolbox::FlattenUri(const UriComponents& components, size_t fromLevel) { if (components.size() <= fromLevel) { return "/"; } else { std::string r; for (size_t i = fromLevel; i < components.size(); i++) { r += "/" + components[i]; } return r; } } #if ORTHANC_ENABLE_MD5 == 1 static char GetHexadecimalCharacter(uint8_t value) { assert(value < 16); if (value < 10) { return value + '0'; } else { return (value - 10) + 'a'; } } void Toolbox::ComputeMD5(std::string& result, const std::string& data) { if (data.size() > 0) { ComputeMD5(result, &data[0], data.size()); } else { ComputeMD5(result, NULL, 0); } } void Toolbox::ComputeMD5(std::string& result, const void* data, size_t size) { md5_state_s state; md5_init(&state); if (size > 0) { md5_append(&state, reinterpret_cast(data), static_cast(size)); } md5_byte_t actualHash[16]; md5_finish(&state, actualHash); result.resize(32); for (unsigned int i = 0; i < 16; i++) { result[2 * i] = GetHexadecimalCharacter(static_cast(actualHash[i] / 16)); result[2 * i + 1] = GetHexadecimalCharacter(static_cast(actualHash[i] % 16)); } } #endif #if ORTHANC_ENABLE_BASE64 == 1 void Toolbox::EncodeBase64(std::string& result, const std::string& data) { result = base64_encode(data); } void Toolbox::DecodeBase64(std::string& result, const std::string& data) { for (size_t i = 0; i < data.length(); i++) { if (!isalnum(data[i]) && data[i] != '+' && data[i] != '/' && data[i] != '=') { // This is not a valid character for a Base64 string throw OrthancException(ErrorCode_BadFileFormat); } } result = base64_decode(data); } # if BOOST_HAS_REGEX == 1 bool Toolbox::DecodeDataUriScheme(std::string& mime, std::string& content, const std::string& source) { boost::regex pattern("data:([^;]+);base64,([a-zA-Z0-9=+/]*)", boost::regex::icase /* case insensitive search */); boost::cmatch what; if (regex_match(source.c_str(), what, pattern)) { mime = what[1]; DecodeBase64(content, what[2]); return true; } else { return false; } } # endif void Toolbox::EncodeDataUriScheme(std::string& result, const std::string& mime, const std::string& content) { result = "data:" + mime + ";base64," + base64_encode(content); } #endif static const char* GetBoostLocaleEncoding(const Encoding sourceEncoding) { switch (sourceEncoding) { case Encoding_Utf8: return "UTF-8"; case Encoding_Ascii: return "ASCII"; case Encoding_Latin1: return "ISO-8859-1"; break; case Encoding_Latin2: return "ISO-8859-2"; break; case Encoding_Latin3: return "ISO-8859-3"; break; case Encoding_Latin4: return "ISO-8859-4"; break; case Encoding_Latin5: return "ISO-8859-9"; break; case Encoding_Cyrillic: return "ISO-8859-5"; break; case Encoding_Windows1251: return "WINDOWS-1251"; break; case Encoding_Arabic: return "ISO-8859-6"; break; case Encoding_Greek: return "ISO-8859-7"; break; case Encoding_Hebrew: return "ISO-8859-8"; break; case Encoding_Japanese: return "SHIFT-JIS"; break; case Encoding_Chinese: return "GB18030"; break; case Encoding_Thai: return "TIS620.2533-0"; break; default: throw OrthancException(ErrorCode_NotImplemented); } } std::string Toolbox::ConvertToUtf8(const std::string& source, Encoding sourceEncoding) { if (sourceEncoding == Encoding_Utf8) { // Already in UTF-8: No conversion is required return source; } if (sourceEncoding == Encoding_Ascii) { return ConvertToAscii(source); } const char* encoding = GetBoostLocaleEncoding(sourceEncoding); try { return boost::locale::conv::to_utf(source, encoding); } catch (std::runtime_error&) { // Bad input string or bad encoding return ConvertToAscii(source); } } std::string Toolbox::ConvertFromUtf8(const std::string& source, Encoding targetEncoding) { if (targetEncoding == Encoding_Utf8) { // Already in UTF-8: No conversion is required return source; } if (targetEncoding == Encoding_Ascii) { return ConvertToAscii(source); } const char* encoding = GetBoostLocaleEncoding(targetEncoding); try { return boost::locale::conv::from_utf(source, encoding); } catch (std::runtime_error&) { // Bad input string or bad encoding return ConvertToAscii(source); } } bool Toolbox::IsAsciiString(const void* data, size_t size) { const uint8_t* p = reinterpret_cast(data); for (size_t i = 0; i < size; i++, p++) { if (*p > 127 || (*p != 0 && iscntrl(*p))) { return false; } } return true; } std::string Toolbox::ConvertToAscii(const std::string& source) { std::string result; result.reserve(source.size() + 1); for (size_t i = 0; i < source.size(); i++) { if (source[i] <= 127 && source[i] >= 0 && !iscntrl(source[i])) { result.push_back(source[i]); } } return result; } void Toolbox::ComputeSHA1(std::string& result, const void* data, size_t size) { boost::uuids::detail::sha1 sha1; if (size > 0) { sha1.process_bytes(data, size); } unsigned int digest[5]; // Sanity check for the memory layout: A SHA-1 digest is 160 bits wide assert(sizeof(unsigned int) == 4 && sizeof(digest) == (160 / 8)); sha1.get_digest(digest); result.resize(8 * 5 + 4); sprintf(&result[0], "%08x-%08x-%08x-%08x-%08x", digest[0], digest[1], digest[2], digest[3], digest[4]); } void Toolbox::ComputeSHA1(std::string& result, const std::string& data) { if (data.size() > 0) { ComputeSHA1(result, data.c_str(), data.size()); } else { ComputeSHA1(result, NULL, 0); } } bool Toolbox::IsSHA1(const char* str, size_t size) { if (size == 0) { return false; } const char* start = str; const char* end = str + size; // Trim the beginning of the string while (start < end) { if (*start == '\0' || isspace(*start)) { start++; } else { break; } } // Trim the trailing of the string while (start < end) { if (*(end - 1) == '\0' || isspace(*(end - 1))) { end--; } else { break; } } if (end - start != 44) { return false; } for (unsigned int i = 0; i < 44; i++) { if (i == 8 || i == 17 || i == 26 || i == 35) { if (start[i] != '-') return false; } else { if (!isalnum(start[i])) return false; } } return true; } bool Toolbox::IsSHA1(const std::string& s) { if (s.size() == 0) { return false; } else { return IsSHA1(s.c_str(), s.size()); } } std::string Toolbox::StripSpaces(const std::string& source) { size_t first = 0; while (first < source.length() && isspace(source[first])) { first++; } if (first == source.length()) { // String containing only spaces return ""; } size_t last = source.length(); while (last > first && isspace(source[last - 1])) { last--; } assert(first <= last); return source.substr(first, last - first); } static char Hex2Dec(char c) { return ((c >= '0' && c <= '9') ? c - '0' : ((c >= 'a' && c <= 'f') ? c - 'a' + 10 : c - 'A' + 10)); } void Toolbox::UrlDecode(std::string& s) { // http://en.wikipedia.org/wiki/Percent-encoding // http://www.w3schools.com/tags/ref_urlencode.asp // http://stackoverflow.com/questions/154536/encode-decode-urls-in-c if (s.size() == 0) { return; } size_t source = 0; size_t target = 0; while (source < s.size()) { if (s[source] == '%' && source + 2 < s.size() && isalnum(s[source + 1]) && isalnum(s[source + 2])) { s[target] = (Hex2Dec(s[source + 1]) << 4) | Hex2Dec(s[source + 2]); source += 3; target += 1; } else { if (s[source] == '+') s[target] = ' '; else s[target] = s[source]; source++; target++; } } s.resize(target); } Endianness Toolbox::DetectEndianness() { // http://sourceforge.net/p/predef/wiki/Endianness/ uint8_t buffer[4]; buffer[0] = 0x00; buffer[1] = 0x01; buffer[2] = 0x02; buffer[3] = 0x03; switch (*((uint32_t *)buffer)) { case 0x00010203: return Endianness_Big; case 0x03020100: return Endianness_Little; default: throw OrthancException(ErrorCode_NotImplemented); } } #if BOOST_HAS_REGEX == 1 std::string Toolbox::WildcardToRegularExpression(const std::string& source) { // TODO - Speed up this with a regular expression std::string result = source; // Escape all special characters boost::replace_all(result, "\\", "\\\\"); boost::replace_all(result, "^", "\\^"); boost::replace_all(result, ".", "\\."); boost::replace_all(result, "$", "\\$"); boost::replace_all(result, "|", "\\|"); boost::replace_all(result, "(", "\\("); boost::replace_all(result, ")", "\\)"); boost::replace_all(result, "[", "\\["); boost::replace_all(result, "]", "\\]"); boost::replace_all(result, "+", "\\+"); boost::replace_all(result, "/", "\\/"); boost::replace_all(result, "{", "\\{"); boost::replace_all(result, "}", "\\}"); // Convert wildcards '*' and '?' to their regex equivalents boost::replace_all(result, "?", "."); boost::replace_all(result, "*", ".*"); return result; } #endif void Toolbox::TokenizeString(std::vector& result, const std::string& value, char separator) { result.clear(); std::string currentItem; for (size_t i = 0; i < value.size(); i++) { if (value[i] == separator) { result.push_back(currentItem); currentItem.clear(); } else { currentItem.push_back(value[i]); } } result.push_back(currentItem); } #if ORTHANC_ENABLE_PUGIXML == 1 class ChunkedBufferWriter : public pugi::xml_writer { private: ChunkedBuffer buffer_; public: virtual void write(const void *data, size_t size) { if (size > 0) { buffer_.AddChunk(reinterpret_cast(data), size); } } void Flatten(std::string& s) { buffer_.Flatten(s); } }; static void JsonToXmlInternal(pugi::xml_node& target, const Json::Value& source, const std::string& arrayElement) { // http://jsoncpp.sourceforge.net/value_8h_source.html#l00030 switch (source.type()) { case Json::nullValue: { target.append_child(pugi::node_pcdata).set_value("null"); break; } case Json::intValue: { std::string s = boost::lexical_cast(source.asInt()); target.append_child(pugi::node_pcdata).set_value(s.c_str()); break; } case Json::uintValue: { std::string s = boost::lexical_cast(source.asUInt()); target.append_child(pugi::node_pcdata).set_value(s.c_str()); break; } case Json::realValue: { std::string s = boost::lexical_cast(source.asFloat()); target.append_child(pugi::node_pcdata).set_value(s.c_str()); break; } case Json::stringValue: { target.append_child(pugi::node_pcdata).set_value(source.asString().c_str()); break; } case Json::booleanValue: { target.append_child(pugi::node_pcdata).set_value(source.asBool() ? "true" : "false"); break; } case Json::arrayValue: { for (Json::Value::ArrayIndex i = 0; i < source.size(); i++) { pugi::xml_node node = target.append_child(); node.set_name(arrayElement.c_str()); JsonToXmlInternal(node, source[i], arrayElement); } break; } case Json::objectValue: { Json::Value::Members members = source.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { pugi::xml_node node = target.append_child(); node.set_name(members[i].c_str()); JsonToXmlInternal(node, source[members[i]], arrayElement); } break; } default: throw OrthancException(ErrorCode_NotImplemented); } } void Toolbox::JsonToXml(std::string& target, const Json::Value& source, const std::string& rootElement, const std::string& arrayElement) { pugi::xml_document doc; pugi::xml_node n = doc.append_child(rootElement.c_str()); JsonToXmlInternal(n, source, arrayElement); pugi::xml_node decl = doc.prepend_child(pugi::node_declaration); decl.append_attribute("version").set_value("1.0"); decl.append_attribute("encoding").set_value("utf-8"); ChunkedBufferWriter writer; doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8); writer.Flatten(target); } #endif bool Toolbox::IsInteger(const std::string& str) { std::string s = StripSpaces(str); if (s.size() == 0) { return false; } size_t pos = 0; if (s[0] == '-') { if (s.size() == 1) { return false; } pos = 1; } while (pos < s.size()) { if (!isdigit(s[pos])) { return false; } pos++; } return true; } void Toolbox::CopyJsonWithoutComments(Json::Value& target, const Json::Value& source) { switch (source.type()) { case Json::nullValue: target = Json::nullValue; break; case Json::intValue: target = source.asInt64(); break; case Json::uintValue: target = source.asUInt64(); break; case Json::realValue: target = source.asDouble(); break; case Json::stringValue: target = source.asString(); break; case Json::booleanValue: target = source.asBool(); break; case Json::arrayValue: { target = Json::arrayValue; for (Json::Value::ArrayIndex i = 0; i < source.size(); i++) { Json::Value& item = target.append(Json::nullValue); CopyJsonWithoutComments(item, source[i]); } break; } case Json::objectValue: { target = Json::objectValue; Json::Value::Members members = source.getMemberNames(); for (Json::Value::ArrayIndex i = 0; i < members.size(); i++) { const std::string item = members[i]; CopyJsonWithoutComments(target[item], source[item]); } break; } default: break; } } bool Toolbox::StartsWith(const std::string& str, const std::string& prefix) { if (str.size() < prefix.size()) { return false; } else { return str.compare(0, prefix.size(), prefix) == 0; } } static bool IsUnreservedCharacter(char c) { // This function checks whether "c" is an unserved character // wrt. an URI percent-encoding // https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding%5Fin%5Fa%5FURI return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~'); } void Toolbox::UriEncode(std::string& target, const std::string& source) { // Estimate the length of the percent-encoded URI size_t length = 0; for (size_t i = 0; i < source.size(); i++) { if (IsUnreservedCharacter(source[i])) { length += 1; } else { // This character must be percent-encoded length += 3; } } target.clear(); target.reserve(length); for (size_t i = 0; i < source.size(); i++) { if (IsUnreservedCharacter(source[i])) { target.push_back(source[i]); } else { // This character must be percent-encoded uint8_t byte = static_cast(source[i]); uint8_t a = byte >> 4; uint8_t b = byte & 0x0f; target.push_back('%'); target.push_back(a < 10 ? a + '0' : a - 10 + 'A'); target.push_back(b < 10 ? b + '0' : b - 10 + 'A'); } } } static bool HasField(const Json::Value& json, const std::string& key, Json::ValueType expectedType) { if (json.type() != Json::objectValue || !json.isMember(key)) { return false; } else if (json[key].type() == expectedType) { return true; } else { throw OrthancException(ErrorCode_BadParameterType); } } std::string Toolbox::GetJsonStringField(const Json::Value& json, const std::string& key, const std::string& defaultValue) { if (HasField(json, key, Json::stringValue)) { return json[key].asString(); } else { return defaultValue; } } bool Toolbox::GetJsonBooleanField(const ::Json::Value& json, const std::string& key, bool defaultValue) { if (HasField(json, key, Json::booleanValue)) { return json[key].asBool(); } else { return defaultValue; } } int Toolbox::GetJsonIntegerField(const ::Json::Value& json, const std::string& key, int defaultValue) { if (HasField(json, key, Json::intValue)) { return json[key].asInt(); } else { return defaultValue; } } unsigned int Toolbox::GetJsonUnsignedIntegerField(const ::Json::Value& json, const std::string& key, unsigned int defaultValue) { int v = GetJsonIntegerField(json, key, defaultValue); if (v < 0) { throw OrthancException(ErrorCode_ParameterOutOfRange); } else { return static_cast(v); } } bool Toolbox::IsUuid(const std::string& str) { if (str.size() != 36) { return false; } for (size_t i = 0; i < str.length(); i++) { if (i == 8 || i == 13 || i == 18 || i == 23) { if (str[i] != '-') return false; } else { if (!isalnum(str[i])) return false; } } return true; } bool Toolbox::StartsWithUuid(const std::string& str) { if (str.size() < 36) { return false; } if (str.size() == 36) { return IsUuid(str); } assert(str.size() > 36); if (!isspace(str[36])) { return false; } return IsUuid(str.substr(0, 36)); } } OrthancWebViewer-2.3/Orthanc/Core/Toolbox.h0000644000000000000000000001517413133653001017012 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "Enumerations.h" #include #include #include #include #if !defined(ORTHANC_ENABLE_BASE64) # error The macro ORTHANC_ENABLE_BASE64 must be defined #endif #if !defined(ORTHANC_ENABLE_MD5) # error The macro ORTHANC_ENABLE_MD5 must be defined #endif #if !defined(ORTHANC_ENABLE_PUGIXML) # error The macro ORTHANC_ENABLE_PUGIXML must be defined #endif #if !defined(BOOST_HAS_REGEX) # error The macro BOOST_HAS_REGEX must be defined #endif /** * NOTE: GUID vs. UUID * The simple answer is: no difference, they are the same thing. Treat * them as a 16 byte (128 bits) value that is used as a unique * value. In Microsoft-speak they are called GUIDs, but call them * UUIDs when not using Microsoft-speak. * http://stackoverflow.com/questions/246930/is-there-any-difference-between-a-guid-and-a-uuid **/ namespace Orthanc { typedef std::vector UriComponents; class NullType { }; namespace Toolbox { void ToUpperCase(std::string& s); // Inplace version void ToLowerCase(std::string& s); // Inplace version void ToUpperCase(std::string& result, const std::string& source); void ToLowerCase(std::string& result, const std::string& source); void SplitUriComponents(UriComponents& components, const std::string& uri); void TruncateUri(UriComponents& target, const UriComponents& source, size_t fromLevel); bool IsChildUri(const UriComponents& baseUri, const UriComponents& testedUri); std::string AutodetectMimeType(const std::string& path); std::string FlattenUri(const UriComponents& components, size_t fromLevel = 0); #if ORTHANC_ENABLE_MD5 == 1 void ComputeMD5(std::string& result, const std::string& data); void ComputeMD5(std::string& result, const void* data, size_t size); #endif void ComputeSHA1(std::string& result, const std::string& data); void ComputeSHA1(std::string& result, const void* data, size_t size); bool IsSHA1(const char* str, size_t size); bool IsSHA1(const std::string& s); #if ORTHANC_ENABLE_BASE64 == 1 void DecodeBase64(std::string& result, const std::string& data); void EncodeBase64(std::string& result, const std::string& data); # if BOOST_HAS_REGEX == 1 bool DecodeDataUriScheme(std::string& mime, std::string& content, const std::string& source); # endif void EncodeDataUriScheme(std::string& result, const std::string& mime, const std::string& content); #endif std::string ConvertToUtf8(const std::string& source, Encoding sourceEncoding); std::string ConvertFromUtf8(const std::string& source, Encoding targetEncoding); bool IsAsciiString(const void* data, size_t size); std::string ConvertToAscii(const std::string& source); std::string StripSpaces(const std::string& source); // In-place percent-decoding for URL void UrlDecode(std::string& s); Endianness DetectEndianness(); #if BOOST_HAS_REGEX == 1 std::string WildcardToRegularExpression(const std::string& s); #endif void TokenizeString(std::vector& result, const std::string& source, char separator); #if ORTHANC_ENABLE_PUGIXML == 1 void JsonToXml(std::string& target, const Json::Value& source, const std::string& rootElement = "root", const std::string& arrayElement = "item"); #endif bool IsInteger(const std::string& str); void CopyJsonWithoutComments(Json::Value& target, const Json::Value& source); bool StartsWith(const std::string& str, const std::string& prefix); void UriEncode(std::string& target, const std::string& source); std::string GetJsonStringField(const ::Json::Value& json, const std::string& key, const std::string& defaultValue); bool GetJsonBooleanField(const ::Json::Value& json, const std::string& key, bool defaultValue); int GetJsonIntegerField(const ::Json::Value& json, const std::string& key, int defaultValue); unsigned int GetJsonUnsignedIntegerField(const ::Json::Value& json, const std::string& key, unsigned int defaultValue); bool IsUuid(const std::string& str); bool StartsWithUuid(const std::string& str); } } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/Common/ExportedSymbols.list0000644000000000000000000000030013133653001024621 0ustar 00000000000000# This is the list of the symbols that must be exported by Orthanc # plugins, if targeting OS X _OrthancPluginInitialize _OrthancPluginFinalize _OrthancPluginGetName _OrthancPluginGetVersion OrthancWebViewer-2.3/Orthanc/Plugins/Samples/Common/VersionScript.map0000644000000000000000000000026113133653001024100 0ustar 00000000000000# This is a version-script for Orthanc plugins { global: OrthancPluginInitialize; OrthancPluginFinalize; OrthancPluginGetName; OrthancPluginGetVersion; local: *; }; OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/GdcmDecoderCache.cpp0000644000000000000000000000537113133653001025276 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "GdcmDecoderCache.h" #include "OrthancImageWrapper.h" namespace OrthancPlugins { std::string GdcmDecoderCache::ComputeMd5(OrthancPluginContext* context, const void* dicom, size_t size) { std::string result; char* md5 = OrthancPluginComputeMd5(context, dicom, size); if (md5 == NULL) { throw std::runtime_error("Cannot compute MD5 hash"); } bool ok = false; try { result.assign(md5); ok = true; } catch (...) { } OrthancPluginFreeString(context, md5); if (!ok) { throw std::runtime_error("Not enough memory"); } else { return result; } } OrthancImageWrapper* GdcmDecoderCache::Decode(OrthancPluginContext* context, const void* dicom, const uint32_t size, uint32_t frameIndex) { std::string md5 = ComputeMd5(context, dicom, size); // First check whether the previously decoded image is the same // as this one { boost::mutex::scoped_lock lock(mutex_); if (decoder_.get() != NULL && size_ == size && md5_ == md5) { // This is the same image: Reuse the previous decoding return new OrthancImageWrapper(context, decoder_->Decode(context, frameIndex)); } } // This is not the same image std::auto_ptr decoder(new GdcmImageDecoder(dicom, size)); std::auto_ptr image(new OrthancImageWrapper(context, decoder->Decode(context, frameIndex))); { // Cache the newly created decoder for further use boost::mutex::scoped_lock lock(mutex_); decoder_ = decoder; size_ = size; md5_ = md5; } return image.release(); } } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/GdcmDecoderCache.h0000644000000000000000000000316513133653001024742 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include "GdcmImageDecoder.h" #include "OrthancImageWrapper.h" #include namespace OrthancPlugins { class GdcmDecoderCache : public boost::noncopyable { private: boost::mutex mutex_; std::auto_ptr decoder_; size_t size_; std::string md5_; static std::string ComputeMd5(OrthancPluginContext* context, const void* dicom, size_t size); public: GdcmDecoderCache() : size_(0) { } OrthancImageWrapper* Decode(OrthancPluginContext* context, const void* dicom, const uint32_t size, uint32_t frameIndex); }; } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/GdcmImageDecoder.cpp0000644000000000000000000002172713133653001025320 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "GdcmImageDecoder.h" #include "OrthancImageWrapper.h" #include #include #include #include #include #include #include namespace OrthancPlugins { struct GdcmImageDecoder::PImpl { const void* dicom_; size_t size_; gdcm::ImageReader reader_; std::auto_ptr lut_; std::auto_ptr photometric_; std::auto_ptr interleaved_; std::string decoded_; PImpl(const void* dicom, size_t size) : dicom_(dicom), size_(size) { } const gdcm::DataSet& GetDataSet() const { return reader_.GetFile().GetDataSet(); } const gdcm::Image& GetImage() const { if (interleaved_.get() != NULL) { return interleaved_->GetOutput(); } if (lut_.get() != NULL) { return lut_->GetOutput(); } if (photometric_.get() != NULL) { return photometric_->GetOutput(); } return reader_.GetImage(); } void Decode() { // Change photometric interpretation or apply LUT, if required { const gdcm::Image& image = GetImage(); if (image.GetPixelFormat().GetSamplesPerPixel() == 1 && image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::PALETTE_COLOR) { lut_.reset(new gdcm::ImageApplyLookupTable()); lut_->SetInput(image); if (!lut_->Apply()) { throw std::runtime_error( "GDCM cannot apply the lookup table"); } } else if (image.GetPixelFormat().GetSamplesPerPixel() == 1) { if (image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::MONOCHROME1 && image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::MONOCHROME2) { photometric_.reset(new gdcm::ImageChangePhotometricInterpretation()); photometric_->SetInput(image); photometric_->SetPhotometricInterpretation(gdcm::PhotometricInterpretation::MONOCHROME2); if (!photometric_->Change() || GetImage().GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::MONOCHROME2) { throw std::runtime_error("GDCM cannot change the photometric interpretation"); } } } else { if (image.GetPixelFormat().GetSamplesPerPixel() == 3 && image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::RGB && (image.GetTransferSyntax() != gdcm::TransferSyntax::JPEG2000Lossless || image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::YBR_RCT)) { photometric_.reset(new gdcm::ImageChangePhotometricInterpretation()); photometric_->SetInput(image); photometric_->SetPhotometricInterpretation(gdcm::PhotometricInterpretation::RGB); if (!photometric_->Change() || GetImage().GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::RGB) { throw std::runtime_error("GDCM cannot change the photometric interpretation"); } } } } // Possibly convert planar configuration to interleaved { const gdcm::Image& image = GetImage(); if (image.GetPlanarConfiguration() != 0 && image.GetPixelFormat().GetSamplesPerPixel() != 1) { interleaved_.reset(new gdcm::ImageChangePlanarConfiguration()); interleaved_->SetInput(image); if (!interleaved_->Change() || GetImage().GetPlanarConfiguration() != 0) { throw std::runtime_error("GDCM cannot change the planar configuration to interleaved"); } } } } }; GdcmImageDecoder::GdcmImageDecoder(const void* dicom, size_t size) : pimpl_(new PImpl(dicom, size)) { // Setup a stream to the memory buffer using namespace boost::iostreams; basic_array_source source(reinterpret_cast(dicom), size); stream > stream(source); // Parse the DICOM instance using GDCM pimpl_->reader_.SetStream(stream); if (!pimpl_->reader_.Read()) { throw std::runtime_error("Bad file format"); } pimpl_->Decode(); } OrthancPluginPixelFormat GdcmImageDecoder::GetFormat() const { const gdcm::Image& image = pimpl_->GetImage(); if (image.GetPixelFormat().GetSamplesPerPixel() == 1 && (image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::MONOCHROME1 || image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::MONOCHROME2)) { switch (image.GetPixelFormat()) { case gdcm::PixelFormat::UINT16: return OrthancPluginPixelFormat_Grayscale16; case gdcm::PixelFormat::INT16: return OrthancPluginPixelFormat_SignedGrayscale16; case gdcm::PixelFormat::UINT8: return OrthancPluginPixelFormat_Grayscale8; default: throw std::runtime_error("Unsupported pixel format"); } } else if (image.GetPixelFormat().GetSamplesPerPixel() == 3 && (image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::RGB || image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::YBR_RCT)) { switch (image.GetPixelFormat()) { case gdcm::PixelFormat::UINT8: return OrthancPluginPixelFormat_RGB24; default: break; } } throw std::runtime_error("Unsupported pixel format"); } unsigned int GdcmImageDecoder::GetWidth() const { return pimpl_->GetImage().GetColumns(); } unsigned int GdcmImageDecoder::GetHeight() const { return pimpl_->GetImage().GetRows(); } unsigned int GdcmImageDecoder::GetFramesCount() const { return pimpl_->GetImage().GetDimension(2); } size_t GdcmImageDecoder::GetBytesPerPixel(OrthancPluginPixelFormat format) { switch (format) { case OrthancPluginPixelFormat_Grayscale8: return 1; case OrthancPluginPixelFormat_Grayscale16: case OrthancPluginPixelFormat_SignedGrayscale16: return 2; case OrthancPluginPixelFormat_RGB24: return 3; default: throw std::runtime_error("Unsupport pixel format"); } } OrthancPluginImage* GdcmImageDecoder::Decode(OrthancPluginContext* context, unsigned int frameIndex) const { unsigned int frames = GetFramesCount(); unsigned int width = GetWidth(); unsigned int height = GetHeight(); OrthancPluginPixelFormat format = GetFormat(); size_t bpp = GetBytesPerPixel(format); if (frameIndex >= frames) { throw std::runtime_error("Inexistent frame index"); } std::string& decoded = pimpl_->decoded_; OrthancImageWrapper target(context, format, width, height); if (width == 0 || height == 0) { return target.Release(); } if (decoded.empty()) { decoded.resize(pimpl_->GetImage().GetBufferLength()); pimpl_->GetImage().GetBuffer(&decoded[0]); } const void* sourceBuffer = &decoded[0]; if (target.GetPitch() == bpp * width && frames == 1) { assert(decoded.size() == target.GetPitch() * target.GetHeight()); memcpy(target.GetBuffer(), sourceBuffer, decoded.size()); } else { size_t targetPitch = target.GetPitch(); size_t sourcePitch = width * bpp; const char* a = &decoded[sourcePitch * height * frameIndex]; char* b = target.GetBuffer(); for (uint32_t y = 0; y < height; y++) { memcpy(b, a, sourcePitch); a += sourcePitch; b += targetPitch; } } return target.Release(); } } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/GdcmImageDecoder.h0000644000000000000000000000310113133653001024747 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include #include #include namespace OrthancPlugins { class GdcmImageDecoder : public boost::noncopyable { private: struct PImpl; boost::shared_ptr pimpl_; public: GdcmImageDecoder(const void* dicom, size_t size); OrthancPluginPixelFormat GetFormat() const; unsigned int GetWidth() const; unsigned int GetHeight() const; unsigned int GetFramesCount() const; static size_t GetBytesPerPixel(OrthancPluginPixelFormat format); OrthancPluginImage* Decode(OrthancPluginContext* context, unsigned int frameIndex) const; }; } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/OrthancImageWrapper.cpp0000644000000000000000000000505213133653001026110 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #include "OrthancImageWrapper.h" #include namespace OrthancPlugins { OrthancImageWrapper::OrthancImageWrapper(OrthancPluginContext* context, OrthancPluginPixelFormat format, uint32_t width, uint32_t height) : context_(context) { image_ = OrthancPluginCreateImage(context_, format, width, height); if (image_ == NULL) { throw std::runtime_error("Cannot create an image"); } } OrthancImageWrapper::OrthancImageWrapper(OrthancPluginContext* context, OrthancPluginImage* image) : context_(context), image_(image) { if (image_ == NULL) { throw std::runtime_error("Invalid image returned by the core of Orthanc"); } } OrthancImageWrapper::~OrthancImageWrapper() { if (image_ != NULL) { OrthancPluginFreeImage(context_, image_); } } OrthancPluginImage* OrthancImageWrapper::Release() { OrthancPluginImage* tmp = image_; image_ = NULL; return tmp; } uint32_t OrthancImageWrapper::GetWidth() { return OrthancPluginGetImageWidth(context_, image_); } uint32_t OrthancImageWrapper::GetHeight() { return OrthancPluginGetImageHeight(context_, image_); } uint32_t OrthancImageWrapper::GetPitch() { return OrthancPluginGetImagePitch(context_, image_); } OrthancPluginPixelFormat OrthancImageWrapper::GetFormat() { return OrthancPluginGetImagePixelFormat(context_, image_); } char* OrthancImageWrapper::GetBuffer() { return reinterpret_cast(OrthancPluginGetImageBuffer(context_, image_)); } } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/OrthancImageWrapper.h0000644000000000000000000000325613133653001025561 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include "GdcmImageDecoder.h" namespace OrthancPlugins { class OrthancImageWrapper { private: OrthancPluginContext* context_; OrthancPluginImage* image_; public: OrthancImageWrapper(OrthancPluginContext* context, OrthancPluginPixelFormat format, uint32_t width, uint32_t height); OrthancImageWrapper(OrthancPluginContext* context, OrthancPluginImage* image); // Takes ownership ~OrthancImageWrapper(); OrthancPluginContext* GetContext() { return context_; } OrthancPluginImage* Release(); uint32_t GetWidth(); uint32_t GetHeight(); uint32_t GetPitch(); OrthancPluginPixelFormat GetFormat(); char* GetBuffer(); }; } OrthancWebViewer-2.3/Orthanc/Plugins/Samples/GdcmDecoder/README0000644000000000000000000000040013133653001022352 0ustar 00000000000000This sample shows how to replace the decoder of DICOM images that is built in Orthanc, by the GDCM library. A production-ready version of this sample, is available in the offical Web viewer plugin: http://www.orthanc-server.com/static.php?page=web-viewer OrthancWebViewer-2.3/Orthanc/README.txt0000644000000000000000000000022313133653001016006 0ustar 00000000000000This folder contains an excerpt of the source code of Orthanc. It is automatically generated using the "../Resources/SyncOrthancFolder.py" script. OrthancWebViewer-2.3/Orthanc/Resources/CMake/AutoGeneratedCode.cmake0000644000000000000000000000274313133653001023577 0ustar 00000000000000set(AUTOGENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/AUTOGENERATED") set(AUTOGENERATED_SOURCES) file(MAKE_DIRECTORY ${AUTOGENERATED_DIR}) include_directories(${AUTOGENERATED_DIR}) macro(EmbedResources) # Convert a semicolon separated list to a whitespace separated string set(SCRIPT_OPTIONS) set(SCRIPT_ARGUMENTS) set(DEPENDENCIES) set(IS_PATH_NAME false) # Loop over the arguments of the function foreach(arg ${ARGN}) # Extract the first character of the argument string(SUBSTRING "${arg}" 0 1 FIRST_CHAR) if (${FIRST_CHAR} STREQUAL "-") # If the argument starts with a dash "-", this is an option to # EmbedResources.py list(APPEND SCRIPT_OPTIONS ${arg}) else() if (${IS_PATH_NAME}) list(APPEND SCRIPT_ARGUMENTS "${arg}") list(APPEND DEPENDENCIES "${arg}") set(IS_PATH_NAME false) else() list(APPEND SCRIPT_ARGUMENTS "${arg}") set(IS_PATH_NAME true) endif() endif() endforeach() set(TARGET_BASE "${AUTOGENERATED_DIR}/EmbeddedResources") add_custom_command( OUTPUT "${TARGET_BASE}.h" "${TARGET_BASE}.cpp" COMMAND ${PYTHON_EXECUTABLE} "${ORTHANC_ROOT}/Resources/EmbedResources.py" ${SCRIPT_OPTIONS} "${AUTOGENERATED_DIR}/EmbeddedResources" ${SCRIPT_ARGUMENTS} DEPENDS "${ORTHANC_ROOT}/Resources/EmbedResources.py" ${DEPENDENCIES} ) list(APPEND AUTOGENERATED_SOURCES "${AUTOGENERATED_DIR}/EmbeddedResources.cpp" ) endmacro() OrthancWebViewer-2.3/Orthanc/Resources/CMake/BoostConfiguration.cmake0000644000000000000000000001742113133653001024072 0ustar 00000000000000if (STATIC_BUILD OR NOT USE_SYSTEM_BOOST) set(BOOST_STATIC 1) else() include(FindBoost) set(BOOST_STATIC 0) #set(Boost_DEBUG 1) #set(Boost_USE_STATIC_LIBS ON) find_package(Boost COMPONENTS filesystem thread system date_time regex locale ${ORTHANC_BOOST_COMPONENTS}) if (NOT Boost_FOUND) message(FATAL_ERROR "Unable to locate Boost on this system") endif() # Boost releases 1.44 through 1.47 supply both V2 and V3 filesystem # http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/index.htm if (${Boost_VERSION} LESS 104400) add_definitions( -DBOOST_HAS_FILESYSTEM_V3=0 ) else() add_definitions( -DBOOST_HAS_FILESYSTEM_V3=1 -DBOOST_FILESYSTEM_VERSION=3 ) endif() #if (${Boost_VERSION} LESS 104800) # boost::locale is only available from 1.48.00 #message("Too old version of Boost (${Boost_LIB_VERSION}): Building the static version") # set(BOOST_STATIC 1) #endif() include_directories(${Boost_INCLUDE_DIRS}) link_libraries(${Boost_LIBRARIES}) endif() if (BOOST_STATIC) # Parameters for Boost 1.60.0 set(BOOST_NAME boost_1_60_0) set(BOOST_BCP_SUFFIX bcpdigest-1.0.1) set(BOOST_MD5 "a789f8ec2056ad1c2d5f0cb64687cc7b") set(BOOST_URL "http://www.orthanc-server.com/downloads/third-party/${BOOST_NAME}_${BOOST_BCP_SUFFIX}.tar.gz") set(BOOST_FILESYSTEM_SOURCES_DIR "${BOOST_NAME}/libs/filesystem/src") set(BOOST_SOURCES_DIR ${CMAKE_BINARY_DIR}/${BOOST_NAME}) DownloadPackage(${BOOST_MD5} ${BOOST_URL} "${BOOST_SOURCES_DIR}") set(BOOST_SOURCES) if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR ${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" OR ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "PNaCl" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl32" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl64") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/atomic/src/lockpool.cpp ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/once.cpp ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/thread.cpp ) add_definitions( -DBOOST_LOCALE_WITH_ICONV=1 -DBOOST_LOCALE_NO_WINAPI_BACKEND=1 -DBOOST_LOCALE_NO_STD_BACKEND=1 ) if ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase" OR ${CMAKE_SYSTEM_NAME} STREQUAL "PNaCl" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl32" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl64") add_definitions(-DBOOST_HAS_SCHED_YIELD=1) endif() elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_dll.cpp ${BOOST_SOURCES_DIR}/libs/thread/src/win32/thread.cpp ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_pe.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/windows_file_codecvt.cpp ) # Starting with release 0.8.2, Orthanc statically links against # libiconv, even on Windows. Indeed, the "WCONV" library of # Windows XP seems not to support properly several codepages # (notably "Latin3", "Hebrew", and "Arabic"). if (USE_BOOST_ICONV) include(${ORTHANC_ROOT}/Resources/CMake/LibIconvConfiguration.cmake) else() add_definitions(-DBOOST_LOCALE_WITH_WCONV=1) endif() add_definitions( -DBOOST_LOCALE_NO_POSIX_BACKEND=1 -DBOOST_LOCALE_NO_STD_BACKEND=1 ) elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Emscripten") add_definitions( -DBOOST_LOCALE_NO_POSIX_BACKEND=1 -DBOOST_LOCALE_NO_STD_BACKEND=1 ) else() message(FATAL_ERROR "Support your platform here") endif() if (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/filesystem/src/utf8_codecvt_facet.cpp ) endif() aux_source_directory(${BOOST_SOURCES_DIR}/libs/regex/src BOOST_REGEX_SOURCES) list(APPEND BOOST_SOURCES ${BOOST_REGEX_SOURCES} ${BOOST_SOURCES_DIR}/libs/date_time/src/gregorian/greg_month.cpp ${BOOST_SOURCES_DIR}/libs/system/src/error_code.cpp ) if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Emscripten") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/locale/src/encoding/codepage.cpp ) endif() if (${CMAKE_SYSTEM_NAME} STREQUAL "PNaCl" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl32" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl64") # boost::filesystem is not available on PNaCl add_definitions( -DBOOST_HAS_FILESYSTEM_V3=0 -D__INTEGRITY=1 ) else() add_definitions( -DBOOST_HAS_FILESYSTEM_V3=1 ) list(APPEND BOOST_SOURCES ${BOOST_FILESYSTEM_SOURCES_DIR}/codecvt_error_category.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/operations.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/path.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/path_traits.cpp ) endif() if (USE_BOOST_LOCALE_BACKENDS) if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR ${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" OR ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "PNaCl" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl32" OR ${CMAKE_SYSTEM_NAME} STREQUAL "NaCl64") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/locale/src/posix/codecvt.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/posix/collate.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/posix/converter.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/posix/numeric.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/posix/posix_backend.cpp ) elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") list(APPEND BOOST_SOURCES ${BOOST_SOURCES_DIR}/libs/locale/src/win32/collate.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/win32/converter.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/win32/lcid.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/win32/numeric.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/win32/win_backend.cpp ) else() message(FATAL_ERROR "Support your platform here") endif() list(APPEND BOOST_SOURCES ${BOOST_REGEX_SOURCES} ${BOOST_SOURCES_DIR}/libs/date_time/src/gregorian/greg_month.cpp ${BOOST_SOURCES_DIR}/libs/system/src/error_code.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/codecvt_error_category.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/operations.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/path.cpp ${BOOST_FILESYSTEM_SOURCES_DIR}/path_traits.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/generator.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/date_time.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/formatting.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/ids.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/localization_backend.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/message.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/shared/mo_lambda.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/util/codecvt_converter.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/util/default_locale.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/util/gregorian.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/util/info.cpp ${BOOST_SOURCES_DIR}/libs/locale/src/util/locale_data.cpp ) endif() add_definitions( # Static build of Boost -DBOOST_ALL_NO_LIB -DBOOST_ALL_NOLIB -DBOOST_DATE_TIME_NO_LIB -DBOOST_THREAD_BUILD_LIB -DBOOST_PROGRAM_OPTIONS_NO_LIB -DBOOST_REGEX_NO_LIB -DBOOST_SYSTEM_NO_LIB -DBOOST_LOCALE_NO_LIB -DBOOST_HAS_LOCALE=1 ) if (CMAKE_COMPILER_IS_GNUCXX) add_definitions(-isystem ${BOOST_SOURCES_DIR}) endif() include_directories( ${BOOST_SOURCES_DIR} ) source_group(ThirdParty\\boost REGULAR_EXPRESSION ${BOOST_SOURCES_DIR}/.*) else() add_definitions( -DBOOST_HAS_LOCALE=1 ) endif() add_definitions( -DBOOST_HAS_DATE_TIME=1 -DBOOST_HAS_REGEX=1 ) OrthancWebViewer-2.3/Orthanc/Resources/CMake/Compiler.cmake0000644000000000000000000001556513133653001022035 0ustar 00000000000000# This file sets all the compiler-related flags if (CMAKE_CROSSCOMPILING) # Cross-compilation necessarily implies standalone and static build SET(STATIC_BUILD ON) SET(STANDALONE_BUILD ON) endif() if (CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-long-long -Wno-implicit-function-declaration") # --std=c99 makes libcurl not to compile # -pedantic gives a lot of warnings on OpenSSL set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -Wno-variadic-macros") if (CMAKE_CROSSCOMPILING) # http://stackoverflow.com/a/3543845/881731 set(CMAKE_RC_COMPILE_OBJECT " -O coff -I ") endif() elseif (MSVC) # Use static runtime under Visual Studio # http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace # http://stackoverflow.com/a/6510446 foreach(flag_var CMAKE_C_FLAGS_DEBUG CMAKE_CXX_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELEASE CMAKE_C_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_RELWITHDEBINFO) string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") string(REGEX REPLACE "/MDd" "/MTd" ${flag_var} "${${flag_var}}") endforeach(flag_var) # Add /Zm256 compiler option to Visual Studio to fix PCH errors set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zm256") add_definitions( -D_CRT_SECURE_NO_WARNINGS=1 -D_CRT_SECURE_NO_DEPRECATE=1 ) if (MSVC_VERSION LESS 1600) # Starting with Visual Studio >= 2010 (i.e. macro _MSC_VER >= # 1600), Microsoft ships a standard-compliant # header. For earlier versions of Visual Studio, give access to a # compatibility header. # http://stackoverflow.com/a/70630/881731 # https://en.wikibooks.org/wiki/C_Programming/C_Reference/stdint.h#External_links include_directories(${ORTHANC_ROOT}/Resources/ThirdParty/VisualStudio) endif() link_libraries(netapi32) endif() if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,--no-undefined") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined") if (NOT DEFINED ENABLE_PLUGINS_VERSION_SCRIPT OR ENABLE_PLUGINS_VERSION_SCRIPT) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--version-script=${ORTHANC_ROOT}/Plugins/Samples/Common/VersionScript.map") endif() # Remove the "-rdynamic" option # http://www.mail-archive.com/cmake@cmake.org/msg08837.html set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") link_libraries(uuid pthread rt) if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--as-needed") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,--as-needed") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--as-needed") add_definitions( -D_LARGEFILE64_SOURCE=1 -D_FILE_OFFSET_BITS=64 ) link_libraries(dl) endif() CHECK_INCLUDE_FILES(uuid/uuid.h HAVE_UUID_H) if (NOT HAVE_UUID_H) message(FATAL_ERROR "Please install the uuid-dev package") endif() elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") if (MSVC) message("MSVC compiler version = " ${MSVC_VERSION} "\n") # Starting Visual Studio 2013 (version 1800), it is not possible # to target Windows XP anymore if (MSVC_VERSION LESS 1800) add_definitions( -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 ) endif() else() add_definitions( -DWINVER=0x0501 -D_WIN32_WINNT=0x0501 ) endif() add_definitions( -D_CRT_SECURE_NO_WARNINGS=1 ) link_libraries(rpcrt4 ws2_32) if (CMAKE_COMPILER_IS_GNUCXX) # Some additional C/C++ compiler flags for MinGW SET(MINGW_NO_WARNINGS "-Wno-unused-function -Wno-unused-variable") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MINGW_NO_WARNINGS} -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MINGW_NO_WARNINGS}") # This is a patch for MinGW64 SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--allow-multiple-definition -static-libgcc -static-libstdc++") SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--allow-multiple-definition -static-libgcc -static-libstdc++") CHECK_LIBRARY_EXISTS(winpthread pthread_create "" HAVE_WIN_PTHREAD) if (HAVE_WIN_PTHREAD) # This line is necessary to compile with recent versions of MinGW, # otherwise "libwinpthread-1.dll" is not statically linked. SET(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -Wl,-Bstatic -lstdc++ -lpthread -Wl,-Bdynamic") add_definitions(-DHAVE_WIN_PTHREAD=1) else() add_definitions(-DHAVE_WIN_PTHREAD=0) endif() endif() elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin") SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -exported_symbols_list ${ORTHANC_ROOT}/Plugins/Samples/Common/ExportedSymbols.list") add_definitions( -D_XOPEN_SOURCE=1 ) link_libraries(iconv) CHECK_INCLUDE_FILES(uuid/uuid.h HAVE_UUID_H) if (NOT HAVE_UUID_H) message(FATAL_ERROR "Please install the uuid-dev package") endif() endif() if ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -I${LSB_PATH}/include") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -nostdinc++ -I${LSB_PATH}/include -I${LSB_PATH}/include/c++ -I${LSB_PATH}/include/c++/backward -fpermissive") SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --lsb-target-version=${LSB_TARGET_VERSION} -L${LSB_LIBPATH}") endif() if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") # In FreeBSD, the "/usr/local/" folder contains the ports and need to be imported SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include") SET(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib") SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -L/usr/local/lib") endif() if (DEFINED ENABLE_PROFILING AND ENABLE_PROFILING) if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") message(WARNING "Enabling profiling on a non-debug build will not produce full information") endif() if (CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pg") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -pg") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -pg") else() message(FATAL_ERROR "Don't know how to enable profiling on your configuration") endif() endif() if (STATIC_BUILD) add_definitions(-DORTHANC_STATIC=1) else() add_definitions(-DORTHANC_STATIC=0) endif() OrthancWebViewer-2.3/Orthanc/Resources/CMake/DownloadPackage.cmake0000644000000000000000000001276313133653001023303 0ustar 00000000000000macro(GetUrlFilename TargetVariable Url) string(REGEX REPLACE "^.*/" "" ${TargetVariable} "${Url}") endmacro() macro(GetUrlExtension TargetVariable Url) #string(REGEX REPLACE "^.*/[^.]*\\." "" TMP "${Url}") string(REGEX REPLACE "^.*\\." "" TMP "${Url}") string(TOLOWER "${TMP}" "${TargetVariable}") endmacro() ## ## Setup the patch command-line tool ## if (NOT ORTHANC_DISABLE_PATCH) if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") set(PATCH_EXECUTABLE ${CMAKE_CURRENT_LIST_DIR}/../ThirdParty/patch/patch.exe) if (NOT EXISTS ${PATCH_EXECUTABLE}) message(FATAL_ERROR "Unable to find the patch.exe tool that is shipped with Orthanc") endif() else () find_program(PATCH_EXECUTABLE patch) if (${PATCH_EXECUTABLE} MATCHES "PATCH_EXECUTABLE-NOTFOUND") message(FATAL_ERROR "Please install the 'patch' standard command-line tool") endif() endif() endif() ## ## Check the existence of the required decompression tools ## if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") find_program(ZIP_EXECUTABLE 7z PATHS "$ENV{ProgramFiles}/7-Zip" "$ENV{ProgramW6432}/7-Zip" ) if (${ZIP_EXECUTABLE} MATCHES "ZIP_EXECUTABLE-NOTFOUND") message(FATAL_ERROR "Please install the '7-zip' software (http://www.7-zip.org/)") endif() else() find_program(UNZIP_EXECUTABLE unzip) if (${UNZIP_EXECUTABLE} MATCHES "UNZIP_EXECUTABLE-NOTFOUND") message(FATAL_ERROR "Please install the 'unzip' package") endif() find_program(TAR_EXECUTABLE tar) if (${TAR_EXECUTABLE} MATCHES "TAR_EXECUTABLE-NOTFOUND") message(FATAL_ERROR "Please install the 'tar' package") endif() endif() macro(DownloadPackage MD5 Url TargetDirectory) if (NOT IS_DIRECTORY "${TargetDirectory}") GetUrlFilename(TMP_FILENAME "${Url}") set(TMP_PATH "${CMAKE_SOURCE_DIR}/ThirdPartyDownloads/${TMP_FILENAME}") if (NOT EXISTS "${TMP_PATH}") message("Downloading ${Url}") # This fixes issue 6: "I think cmake shouldn't download the # packages which are not in the system, it should stop and let # user know." # https://code.google.com/p/orthanc/issues/detail?id=6 if (NOT STATIC_BUILD AND NOT ALLOW_DOWNLOADS) message(FATAL_ERROR "CMake is not allowed to download from Internet. Please set the ALLOW_DOWNLOADS option to ON") endif() file(DOWNLOAD "${Url}" "${TMP_PATH}" SHOW_PROGRESS EXPECTED_MD5 "${MD5}" TIMEOUT 60 INACTIVITY_TIMEOUT 60) else() message("Using local copy of ${Url}") endif() GetUrlExtension(TMP_EXTENSION "${Url}") #message(${TMP_EXTENSION}) message("Uncompressing ${TMP_FILENAME}") if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows") # How to silently extract files using 7-zip # http://superuser.com/questions/331148/7zip-command-line-extract-silently-quietly if (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz") OR ("${TMP_EXTENSION}" STREQUAL "xz")) execute_process( COMMAND ${ZIP_EXECUTABLE} e -y ${TMP_PATH} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure OUTPUT_QUIET ) if (Failure) message(FATAL_ERROR "Error while running the uncompression tool") endif() if ("${TMP_EXTENSION}" STREQUAL "tgz") string(REGEX REPLACE ".tgz$" ".tar" TMP_FILENAME2 "${TMP_FILENAME}") elseif ("${TMP_EXTENSION}" STREQUAL "gz") string(REGEX REPLACE ".gz$" "" TMP_FILENAME2 "${TMP_FILENAME}") elseif ("${TMP_EXTENSION}" STREQUAL "xz") string(REGEX REPLACE ".xz" "" TMP_FILENAME2 "${TMP_FILENAME}") endif() execute_process( COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_FILENAME2} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure OUTPUT_QUIET ) elseif ("${TMP_EXTENSION}" STREQUAL "zip") execute_process( COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_PATH} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure OUTPUT_QUIET ) else() message(FATAL_ERROR "Support your platform here") endif() else() if ("${TMP_EXTENSION}" STREQUAL "zip") execute_process( COMMAND sh -c "${UNZIP_EXECUTABLE} -q ${TMP_PATH}" WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure ) elseif (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz")) #message("tar xvfz ${TMP_PATH}") execute_process( COMMAND sh -c "${TAR_EXECUTABLE} xfz ${TMP_PATH}" WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure ) elseif ("${TMP_EXTENSION}" STREQUAL "bz2") execute_process( COMMAND sh -c "${TAR_EXECUTABLE} xfj ${TMP_PATH}" WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure ) elseif ("${TMP_EXTENSION}" STREQUAL "xz") execute_process( COMMAND sh -c "${TAR_EXECUTABLE} xf ${TMP_PATH}" WORKING_DIRECTORY ${CMAKE_BINARY_DIR} RESULT_VARIABLE Failure ) else() message(FATAL_ERROR "Unknown package format.") endif() endif() if (Failure) message(FATAL_ERROR "Error while running the uncompression tool") endif() if (NOT IS_DIRECTORY "${TargetDirectory}") message(FATAL_ERROR "The package was not uncompressed at the proper location. Check the CMake instructions.") endif() endif() endmacro() OrthancWebViewer-2.3/Orthanc/Resources/CMake/GoogleTestConfiguration.cmake0000644000000000000000000000321413133653001025053 0ustar 00000000000000if (USE_GTEST_DEBIAN_SOURCE_PACKAGE) find_path(GTEST_DEBIAN_SOURCES_DIR NAMES src/gtest-all.cc PATHS /usr/src/gtest /usr/src/googletest/googletest PATH_SUFFIXES src ) find_path(GTEST_DEBIAN_INCLUDE_DIR NAMES gtest.h PATHS /usr/include/gtest ) message("Path to the Debian Google Test sources: ${GTEST_DEBIAN_SOURCES_DIR}") message("Path to the Debian Google Test includes: ${GTEST_DEBIAN_INCLUDE_DIR}") set(GTEST_SOURCES ${GTEST_DEBIAN_SOURCES_DIR}/src/gtest-all.cc) include_directories(${GTEST_DEBIAN_SOURCES_DIR}) if (NOT EXISTS ${GTEST_SOURCES} OR NOT EXISTS ${GTEST_DEBIAN_INCLUDE_DIR}/gtest.h) message(FATAL_ERROR "Please install the libgtest-dev package") endif() elseif (STATIC_BUILD OR NOT USE_SYSTEM_GOOGLE_TEST) set(GTEST_SOURCES_DIR ${CMAKE_BINARY_DIR}/gtest-1.7.0) set(GTEST_URL "http://www.orthanc-server.com/downloads/third-party/gtest-1.7.0.zip") set(GTEST_MD5 "2d6ec8ccdf5c46b05ba54a9fd1d130d7") DownloadPackage(${GTEST_MD5} ${GTEST_URL} "${GTEST_SOURCES_DIR}") include_directories( ${GTEST_SOURCES_DIR}/include ${GTEST_SOURCES_DIR} ) set(GTEST_SOURCES ${GTEST_SOURCES_DIR}/src/gtest-all.cc ) # https://code.google.com/p/googletest/issues/detail?id=412 if (MSVC) # VS2012 does not support tuples correctly yet add_definitions(/D _VARIADIC_MAX=10) endif() source_group(ThirdParty\\GoogleTest REGULAR_EXPRESSION ${GTEST_SOURCES_DIR}/.*) else() include(FindGTest) if (NOT GTEST_FOUND) message(FATAL_ERROR "Unable to find GoogleTest") endif() include_directories(${GTEST_INCLUDE_DIRS}) link_libraries(${GTEST_LIBRARIES}) endif() OrthancWebViewer-2.3/Orthanc/Resources/CMake/JsonCppConfiguration.cmake0000644000000000000000000000400713133653001024354 0ustar 00000000000000if (STATIC_BUILD OR NOT USE_SYSTEM_JSONCPP) set(JSONCPP_SOURCES_DIR ${CMAKE_BINARY_DIR}/jsoncpp-0.10.5) set(JSONCPP_URL "http://www.orthanc-server.com/downloads/third-party/jsoncpp-0.10.5.tar.gz") set(JSONCPP_MD5 "db146bac5a126ded9bd728ab7b61ed6b") DownloadPackage(${JSONCPP_MD5} ${JSONCPP_URL} "${JSONCPP_SOURCES_DIR}") set(JSONCPP_SOURCES ${JSONCPP_SOURCES_DIR}/src/lib_json/json_reader.cpp ${JSONCPP_SOURCES_DIR}/src/lib_json/json_value.cpp ${JSONCPP_SOURCES_DIR}/src/lib_json/json_writer.cpp ) include_directories( ${JSONCPP_SOURCES_DIR}/include ) source_group(ThirdParty\\JsonCpp REGULAR_EXPRESSION ${JSONCPP_SOURCES_DIR}/.*) else() find_path(JSONCPP_INCLUDE_DIR json/reader.h /usr/include/jsoncpp /usr/local/include/jsoncpp ) message("JsonCpp include dir: ${JSONCPP_INCLUDE_DIR}") include_directories(${JSONCPP_INCLUDE_DIR}) link_libraries(jsoncpp) CHECK_INCLUDE_FILE_CXX(${JSONCPP_INCLUDE_DIR}/json/reader.h HAVE_JSONCPP_H) if (NOT HAVE_JSONCPP_H) message(FATAL_ERROR "Please install the libjsoncpp-dev package") endif() # Switch to the C++11 standard if the version of JsonCpp is 1.y.z if (EXISTS ${JSONCPP_INCLUDE_DIR}/json/version.h) file(STRINGS "${JSONCPP_INCLUDE_DIR}/json/version.h" JSONCPP_VERSION_MAJOR1 REGEX ".*define JSONCPP_VERSION_MAJOR.*") if (NOT JSONCPP_VERSION_MAJOR1) message(FATAL_ERROR "Unable to extract the major version of JsonCpp") endif() string(REGEX REPLACE ".*JSONCPP_VERSION_MAJOR.*([0-9]+)$" "\\1" JSONCPP_VERSION_MAJOR ${JSONCPP_VERSION_MAJOR1}) message("JsonCpp major version: ${JSONCPP_VERSION_MAJOR}") if (CMAKE_COMPILER_IS_GNUCXX AND JSONCPP_VERSION_MAJOR GREATER 0) message("Switching to C++11 standard, as version of JsonCpp is >= 1.0.0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wno-deprecated-declarations") endif() else() message("Unable to detect the major version of JsonCpp, assuming < 1.0.0") endif() endif() OrthancWebViewer-2.3/Orthanc/Resources/CMake/SQLiteConfiguration.cmake0000644000000000000000000000465013133653001024145 0ustar 00000000000000if (APPLE) # Under OS X, the binaries must always be linked against the # system-wide version of SQLite. Otherwise, if some Orthanc plugin # also uses its own version of SQLite (such as orthanc-webviewer), # this results in a crash in "sqlite3_mutex_enter(db->mutex);" (the # mutex is not initialized), probably because the EXE and the DYNLIB # share the same memory location for this mutex. set(SQLITE_STATIC OFF) elseif (STATIC_BUILD OR NOT USE_SYSTEM_SQLITE) set(SQLITE_STATIC ON) else() set(SQLITE_STATIC OFF) endif() if (SQLITE_STATIC) SET(SQLITE_SOURCES_DIR ${CMAKE_BINARY_DIR}/sqlite-amalgamation-3071300) SET(SQLITE_MD5 "5fbeff9645ab035a1f580e90b279a16d") SET(SQLITE_URL "http://www.orthanc-server.com/downloads/third-party/sqlite-amalgamation-3071300.zip") add_definitions(-DORTHANC_SQLITE_VERSION=3007013) DownloadPackage(${SQLITE_MD5} ${SQLITE_URL} "${SQLITE_SOURCES_DIR}") set(SQLITE_SOURCES ${SQLITE_SOURCES_DIR}/sqlite3.c ) add_definitions( # For SQLite to run in the "Serialized" thread-safe mode # http://www.sqlite.org/threadsafe.html -DSQLITE_THREADSAFE=1 -DSQLITE_OMIT_LOAD_EXTENSION # Disable SQLite plugins ) include_directories( ${SQLITE_SOURCES_DIR} ) source_group(ThirdParty\\SQLite REGULAR_EXPRESSION ${SQLITE_SOURCES_DIR}/.*) else() CHECK_INCLUDE_FILE_CXX(sqlite3.h HAVE_SQLITE_H) if (NOT HAVE_SQLITE_H) message(FATAL_ERROR "Please install the libsqlite3-dev package") endif() find_path(SQLITE_INCLUDE_DIR sqlite3.h /usr/include /usr/local/include ) message("SQLite include dir: ${SQLITE_INCLUDE_DIR}") # Autodetection of the version of SQLite file(STRINGS "${SQLITE_INCLUDE_DIR}/sqlite3.h" SQLITE_VERSION_NUMBER1 REGEX "#define SQLITE_VERSION_NUMBER.*$") string(REGEX REPLACE "#define SQLITE_VERSION_NUMBER(.*)$" "\\1" SQLITE_VERSION_NUMBER2 ${SQLITE_VERSION_NUMBER1}) # Remove the trailing spaces to convert the string to a proper integer string(STRIP ${SQLITE_VERSION_NUMBER2} SQLITE_VERSION_NUMBER) message("Detected version of SQLite: ${SQLITE_VERSION_NUMBER}") IF (${SQLITE_VERSION_NUMBER} LESS 3007000) # "sqlite3_create_function_v2" is not defined in SQLite < 3.7.0 message(FATAL_ERROR "SQLite version must be above 3.7.0. Please set the CMake variable USE_SYSTEM_SQLITE to OFF.") ENDIF() add_definitions(-DORTHANC_SQLITE_VERSION=${SQLITE_VERSION_NUMBER}) link_libraries(sqlite3) endif() OrthancWebViewer-2.3/Orthanc/Resources/EmbedResources.py0000755000000000000000000003016613133653001021557 0ustar 00000000000000#!/usr/bin/python # Orthanc - A Lightweight, RESTful DICOM Store # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics # Department, University Hospital of Liege, Belgium # Copyright (C) 2017 Osimis, Belgium # # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of this # program give permission to link the code of its release with the # OpenSSL project's "OpenSSL" library (or with modified versions of it # that use the same license as the "OpenSSL" library), and distribute # the linked executables. You must obey the GNU General Public License # in all respects for all of the code used other than "OpenSSL". If you # modify file(s) with this exception, you may extend this exception to # your version of the file(s), but you are not obligated to do so. If # you do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source files # in the program, then also delete it here. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys import os import os.path import pprint import re UPCASE_CHECK = True USE_SYSTEM_EXCEPTION = False EXCEPTION_CLASS = 'OrthancException' OUT_OF_RANGE_EXCEPTION = 'OrthancException(ErrorCode_ParameterOutOfRange)' INEXISTENT_PATH_EXCEPTION = 'OrthancException(ErrorCode_InexistentItem)' NAMESPACE = 'Orthanc' ARGS = [] for i in range(len(sys.argv)): if not sys.argv[i].startswith('--'): ARGS.append(sys.argv[i]) elif sys.argv[i].lower() == '--no-upcase-check': UPCASE_CHECK = False elif sys.argv[i].lower() == '--system-exception': USE_SYSTEM_EXCEPTION = True EXCEPTION_CLASS = '::std::runtime_error' OUT_OF_RANGE_EXCEPTION = '%s("Parameter out of range")' % EXCEPTION_CLASS INEXISTENT_PATH_EXCEPTION = '%s("Unknown path in a directory resource")' % EXCEPTION_CLASS elif sys.argv[i].startswith('--namespace='): NAMESPACE = sys.argv[i][sys.argv[i].find('=') + 1 : ] if len(ARGS) < 2 or len(ARGS) % 2 != 0: print ('Usage:') print ('python %s [--no-upcase-check] [--system-exception] [--namespace=] [ ]*' % sys.argv[0]) exit(-1) TARGET_BASE_FILENAME = ARGS[1] SOURCES = ARGS[2:] try: # Make sure the destination directory exists os.makedirs(os.path.normpath(os.path.join(TARGET_BASE_FILENAME, '..'))) except: pass ##################################################################### ## Read each resource file ##################################################################### def CheckNoUpcase(s): global UPCASE_CHECK if (UPCASE_CHECK and re.search('[A-Z]', s) != None): raise Exception("Path in a directory with an upcase letter: %s" % s) resources = {} counter = 0 i = 0 while i < len(SOURCES): resourceName = SOURCES[i].upper() pathName = SOURCES[i + 1] if not os.path.exists(pathName): raise Exception("Non existing path: %s" % pathName) if resourceName in resources: raise Exception("Twice the same resource: " + resourceName) if os.path.isdir(pathName): # The resource is a directory: Recursively explore its files content = {} for root, dirs, files in os.walk(pathName): base = os.path.relpath(root, pathName) # Fix issue #24 (Build fails on OSX when directory has .DS_Store files): # Ignore folders whose name starts with a dot (".") if base.find('/.') != -1: print('Ignoring folder: %s' % root) continue for f in files: if f.find('~') == -1: # Ignore Emacs backup files if base == '.': r = f else: r = os.path.join(base, f) CheckNoUpcase(r) r = '/' + r.replace('\\', '/') if r in content: raise Exception("Twice the same filename (check case): " + r) content[r] = { 'Filename' : os.path.join(root, f), 'Index' : counter } counter += 1 resources[resourceName] = { 'Type' : 'Directory', 'Files' : content } elif os.path.isfile(pathName): resources[resourceName] = { 'Type' : 'File', 'Index' : counter, 'Filename' : pathName } counter += 1 else: raise Exception("Not a regular file, nor a directory: " + pathName) i += 2 #pprint.pprint(resources) ##################################################################### ## Write .h header ##################################################################### header = open(TARGET_BASE_FILENAME + '.h', 'w') header.write(""" #pragma once #include #include #if defined(_MSC_VER) # pragma warning(disable: 4065) // "Switch statement contains 'default' but no 'case' labels" #endif namespace %s { namespace EmbeddedResources { enum FileResourceId { """ % NAMESPACE) isFirst = True for name in resources: if resources[name]['Type'] == 'File': if isFirst: isFirst = False else: header.write(',\n') header.write(' %s' % name) header.write(""" }; enum DirectoryResourceId { """) isFirst = True for name in resources: if resources[name]['Type'] == 'Directory': if isFirst: isFirst = False else: header.write(',\n') header.write(' %s' % name) header.write(""" }; const void* GetFileResourceBuffer(FileResourceId id); size_t GetFileResourceSize(FileResourceId id); void GetFileResource(std::string& result, FileResourceId id); const void* GetDirectoryResourceBuffer(DirectoryResourceId id, const char* path); size_t GetDirectoryResourceSize(DirectoryResourceId id, const char* path); void GetDirectoryResource(std::string& result, DirectoryResourceId id, const char* path); void ListResources(std::list& result, DirectoryResourceId id); } } """) header.close() ##################################################################### ## Write the resource content in the .cpp source ##################################################################### PYTHON_MAJOR_VERSION = sys.version_info[0] def WriteResource(cpp, item): cpp.write(' static const uint8_t resource%dBuffer[] = {' % item['Index']) f = open(item['Filename'], "rb") content = f.read() f.close() # http://stackoverflow.com/a/1035360 pos = 0 for b in content: if PYTHON_MAJOR_VERSION == 2: c = ord(b[0]) else: c = b if pos > 0: cpp.write(', ') if (pos % 16) == 0: cpp.write('\n ') if c < 0: raise Exception("Internal error") cpp.write("0x%02x" % c) pos += 1 # Zero-size array are disallowed, so we put one single void character in it. if pos == 0: cpp.write(' 0') cpp.write(' };\n') cpp.write(' static const size_t resource%dSize = %d;\n' % (item['Index'], pos)) cpp = open(TARGET_BASE_FILENAME + '.cpp', 'w') cpp.write('#include "%s.h"\n' % os.path.basename(TARGET_BASE_FILENAME)) if USE_SYSTEM_EXCEPTION: cpp.write('#include ') else: cpp.write('#include "%s/Core/OrthancException.h"' % os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) cpp.write(""" #include #include namespace %s { namespace EmbeddedResources { """ % NAMESPACE) for name in resources: if resources[name]['Type'] == 'File': WriteResource(cpp, resources[name]) else: for f in resources[name]['Files']: WriteResource(cpp, resources[name]['Files'][f]) ##################################################################### ## Write the accessors to the file resources in .cpp ##################################################################### cpp.write(""" const void* GetFileResourceBuffer(FileResourceId id) { switch (id) { """) for name in resources: if resources[name]['Type'] == 'File': cpp.write(' case %s:\n' % name) cpp.write(' return resource%dBuffer;\n' % resources[name]['Index']) cpp.write(""" default: throw %s; } } size_t GetFileResourceSize(FileResourceId id) { switch (id) { """ % OUT_OF_RANGE_EXCEPTION) for name in resources: if resources[name]['Type'] == 'File': cpp.write(' case %s:\n' % name) cpp.write(' return resource%dSize;\n' % resources[name]['Index']) cpp.write(""" default: throw %s; } } """ % OUT_OF_RANGE_EXCEPTION) ##################################################################### ## Write the accessors to the directory resources in .cpp ##################################################################### cpp.write(""" const void* GetDirectoryResourceBuffer(DirectoryResourceId id, const char* path) { switch (id) { """) for name in resources: if resources[name]['Type'] == 'Directory': cpp.write(' case %s:\n' % name) isFirst = True for path in resources[name]['Files']: cpp.write(' if (!strcmp(path, "%s"))\n' % path) cpp.write(' return resource%dBuffer;\n' % resources[name]['Files'][path]['Index']) cpp.write(' throw %s;\n\n' % INEXISTENT_PATH_EXCEPTION) cpp.write(""" default: throw %s; } } size_t GetDirectoryResourceSize(DirectoryResourceId id, const char* path) { switch (id) { """ % OUT_OF_RANGE_EXCEPTION) for name in resources: if resources[name]['Type'] == 'Directory': cpp.write(' case %s:\n' % name) isFirst = True for path in resources[name]['Files']: cpp.write(' if (!strcmp(path, "%s"))\n' % path) cpp.write(' return resource%dSize;\n' % resources[name]['Files'][path]['Index']) cpp.write(' throw %s;\n\n' % INEXISTENT_PATH_EXCEPTION) cpp.write(""" default: throw %s; } } """ % OUT_OF_RANGE_EXCEPTION) ##################################################################### ## List the resources in a directory ##################################################################### cpp.write(""" void ListResources(std::list& result, DirectoryResourceId id) { result.clear(); switch (id) { """) for name in resources: if resources[name]['Type'] == 'Directory': cpp.write(' case %s:\n' % name) for path in sorted(resources[name]['Files']): cpp.write(' result.push_back("%s");\n' % path) cpp.write(' break;\n\n') cpp.write(""" default: throw %s; } } """ % OUT_OF_RANGE_EXCEPTION) ##################################################################### ## Write the convenience wrappers in .cpp ##################################################################### cpp.write(""" void GetFileResource(std::string& result, FileResourceId id) { size_t size = GetFileResourceSize(id); result.resize(size); if (size > 0) memcpy(&result[0], GetFileResourceBuffer(id), size); } void GetDirectoryResource(std::string& result, DirectoryResourceId id, const char* path) { size_t size = GetDirectoryResourceSize(id, path); result.resize(size); if (size > 0) memcpy(&result[0], GetDirectoryResourceBuffer(id, path), size); } } } """) cpp.close() OrthancWebViewer-2.3/Orthanc/Resources/MinGW-W64-Toolchain32.cmake0000644000000000000000000000117113133653001022711 0ustar 00000000000000# the name of the target operating system set(CMAKE_SYSTEM_NAME Windows) # which compilers to use for C and C++ set(CMAKE_C_COMPILER i686-w64-mingw32-gcc) set(CMAKE_CXX_COMPILER i686-w64-mingw32-g++) set(CMAKE_RC_COMPILER i686-w64-mingw32-windres) # here is the target environment located set(CMAKE_FIND_ROOT_PATH /usr/i686-w64-mingw32) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) OrthancWebViewer-2.3/Orthanc/Resources/MinGW-W64-Toolchain64.cmake0000644000000000000000000000117713133653001022724 0ustar 00000000000000# the name of the target operating system set(CMAKE_SYSTEM_NAME Windows) # which compilers to use for C and C++ set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++) set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres) # here is the target environment located set(CMAKE_FIND_ROOT_PATH /usr/i686-w64-mingw32) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) OrthancWebViewer-2.3/Orthanc/Resources/MinGWToolchain.cmake0000644000000000000000000000117113133653001022111 0ustar 00000000000000# the name of the target operating system set(CMAKE_SYSTEM_NAME Windows) # which compilers to use for C and C++ set(CMAKE_C_COMPILER i586-mingw32msvc-gcc) set(CMAKE_CXX_COMPILER i586-mingw32msvc-g++) set(CMAKE_RC_COMPILER i586-mingw32msvc-windres) # here is the target environment located set(CMAKE_FIND_ROOT_PATH /usr/i586-mingw32msvc) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) OrthancWebViewer-2.3/Orthanc/Resources/ThirdParty/VisualStudio/stdint.h0000644000000000000000000001764513133653001024505 0ustar 00000000000000// ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2013 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the product nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif #if _MSC_VER >= 1600 // [ #include #else // ] _MSC_VER >= 1600 [ #include // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we should wrap include with 'extern "C++" {}' // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus extern "C" { #endif # include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants // These #ifndef's are needed to prevent collisions with . // Check out Issue 9 for the details. #ifndef INTMAX_C // [ # define INTMAX_C INT64_C #endif // INTMAX_C ] #ifndef UINTMAX_C // [ # define UINTMAX_C UINT64_C #endif // UINTMAX_C ] #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_VER >= 1600 ] #endif // _MSC_STDINT_H_ ] OrthancWebViewer-2.3/Orthanc/Resources/ThirdParty/base64/base64.cpp0000644000000000000000000000750013133653001023235 0ustar 00000000000000/* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #include "base64.h" #include static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(const std::string& stringToEncode) { const unsigned char* bytes_to_encode = reinterpret_cast (stringToEncode.size() > 0 ? &stringToEncode[0] : NULL); unsigned int in_len = stringToEncode.size(); std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::string base64_decode(const std::string& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } OrthancWebViewer-2.3/Orthanc/Resources/ThirdParty/base64/base64.h0000644000000000000000000000020213133653001022672 0ustar 00000000000000#include std::string base64_encode(const std::string& stringToEncode); std::string base64_decode(const std::string& s); OrthancWebViewer-2.3/Orthanc/Resources/WindowsResources.py0000755000000000000000000000664313133653001022200 0ustar 00000000000000#!/usr/bin/python # Orthanc - A Lightweight, RESTful DICOM Store # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics # Department, University Hospital of Liege, Belgium # Copyright (C) 2017 Osimis, Belgium # # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of this # program give permission to link the code of its release with the # OpenSSL project's "OpenSSL" library (or with modified versions of it # that use the same license as the "OpenSSL" library), and distribute # the linked executables. You must obey the GNU General Public License # in all respects for all of the code used other than "OpenSSL". If you # modify file(s) with this exception, you may extend this exception to # your version of the file(s), but you are not obligated to do so. If # you do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source files # in the program, then also delete it here. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import sys import datetime if len(sys.argv) != 5: sys.stderr.write('Usage: %s \n\n' % sys.argv[0]) sys.stderr.write('Example: %s 0.9.1 Orthanc Orthanc.exe "Lightweight, RESTful DICOM server for medical imaging"\n' % sys.argv[0]) sys.exit(-1) SOURCE = os.path.join(os.path.dirname(__file__), 'WindowsResources.rc') VERSION = sys.argv[1] PRODUCT = sys.argv[2] FILENAME = sys.argv[3] DESCRIPTION = sys.argv[4] if VERSION == 'mainline': VERSION = '999.999.999' RELEASE = 'This is a mainline build, not an official release' else: RELEASE = 'Release %s' % VERSION v = VERSION.split('.') if len(v) != 2 and len(v) != 3: sys.stderr.write('Bad version number: %s\n' % VERSION) sys.exit(-1) if len(v) == 2: v.append('0') extension = os.path.splitext(FILENAME)[1] if extension.lower() == '.dll': BLOCK = '040904E4' TYPE = 'VFT_DLL' elif extension.lower() == '.exe': #BLOCK = '040904B0' # LANG_ENGLISH/SUBLANG_ENGLISH_US, BLOCK = '040904E4' # Lang=US English, CharSet=Windows Multilingual TYPE = 'VFT_APP' else: sys.stderr.write('Unsupported extension (.EXE or .DLL only): %s\n' % extension) sys.exit(-1) with open(SOURCE, 'r') as source: content = source.read() content = content.replace('${VERSION_MAJOR}', v[0]) content = content.replace('${VERSION_MINOR}', v[1]) content = content.replace('${VERSION_PATCH}', v[2]) content = content.replace('${RELEASE}', RELEASE) content = content.replace('${DESCRIPTION}', DESCRIPTION) content = content.replace('${PRODUCT}', PRODUCT) content = content.replace('${FILENAME}', FILENAME) content = content.replace('${YEAR}', str(datetime.datetime.now().year)) content = content.replace('${BLOCK}', BLOCK) content = content.replace('${TYPE}', TYPE) sys.stdout.write(content) OrthancWebViewer-2.3/Orthanc/Resources/WindowsResources.rc0000644000000000000000000000217013133653001022140 0ustar 00000000000000#include VS_VERSION_INFO VERSIONINFO FILEVERSION ${VERSION_MAJOR},${VERSION_MINOR},0,${VERSION_PATCH} PRODUCTVERSION ${VERSION_MAJOR},${VERSION_MINOR},0,0 FILEOS VOS_NT_WINDOWS32 FILETYPE ${TYPE} BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "${BLOCK}" BEGIN VALUE "Comments", "${RELEASE}" VALUE "CompanyName", "University Hospital of Liege, Belgium" VALUE "FileDescription", "${DESCRIPTION}" VALUE "FileVersion", "${VERSION_MAJOR}.${VERSION_MINOR}.0.${VERSION_PATCH}" VALUE "InternalName", "${PRODUCT}" VALUE "LegalCopyright", "(c) 2012-${YEAR}, Sebastien Jodogne, University Hospital of Liege, Belgium" VALUE "LegalTrademarks", "Licensing information is available at http://www.orthanc-server.com/" VALUE "OriginalFilename", "${FILENAME}" VALUE "ProductName", "${PRODUCT}" VALUE "ProductVersion", "${VERSION_MAJOR}.${VERSION_MINOR}" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 // U.S. English END END OrthancWebViewer-2.3/Orthanc/Sdk-0.9.5/orthanc/OrthancCPlugin.h0000644000000000000000000047500313133653001022203 0ustar 00000000000000/** * \mainpage * * This C/C++ SDK allows external developers to create plugins that * can be loaded into Orthanc to extend its functionality. Each * Orthanc plugin must expose 4 public functions with the following * signatures: * * -# int32_t OrthancPluginInitialize(const OrthancPluginContext* context): * This function is invoked by Orthanc when it loads the plugin on startup. * The plugin must: * - Check its compatibility with the Orthanc version using * ::OrthancPluginCheckVersion(). * - Store the context pointer so that it can use the plugin * services of Orthanc. * - Register all its REST callbacks using ::OrthancPluginRegisterRestCallback(). * - Possibly register its callback for received DICOM instances using ::OrthancPluginRegisterOnStoredInstanceCallback(). * - Possibly register its callback for changes to the DICOM store using ::OrthancPluginRegisterOnChangeCallback(). * - Possibly register a custom storage area using ::OrthancPluginRegisterStorageArea(). * - Possibly register a custom database back-end area using OrthancPluginRegisterDatabaseBackendV2(). * - Possibly register a handler for C-Find SCP against DICOM worklists using OrthancPluginRegisterWorklistCallback(). * - Possibly register a custom decoder for DICOM images using OrthancPluginRegisterDecodeImageCallback(). * -# void OrthancPluginFinalize(): * This function is invoked by Orthanc during its shutdown. The plugin * must free all its memory. * -# const char* OrthancPluginGetName(): * The plugin must return a short string to identify itself. * -# const char* OrthancPluginGetVersion(): * The plugin must return a string containing its version number. * * The name and the version of a plugin is only used to prevent it * from being loaded twice. Note that, in C++, it is mandatory to * declare these functions within an extern "C" section. * * To ensure multi-threading safety, the various REST callbacks are * guaranteed to be executed in mutual exclusion since Orthanc * 0.8.5. If this feature is undesired (notably when developing * high-performance plugins handling simultaneous requests), use * ::OrthancPluginRegisterRestCallbackNoLock(). **/ /** * @defgroup Images Images and compression * @brief Functions to deal with images and compressed buffers. * * @defgroup REST REST * @brief Functions to answer REST requests in a callback. * * @defgroup Callbacks Callbacks * @brief Functions to register and manage callbacks by the plugins. * * @defgroup Worklists Worklists * @brief Functions to register and manage worklists. * * @defgroup Orthanc Orthanc * @brief Functions to access the content of the Orthanc server. **/ /** * @defgroup Toolbox Toolbox * @brief Generic functions to help with the creation of plugins. **/ /** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * In addition, as a special exception, the copyright holders of this * program give permission to link the code of its release with the * OpenSSL project's "OpenSSL" library (or with modified versions of it * that use the same license as the "OpenSSL" library), and distribute * the linked executables. You must obey the GNU General Public License * in all respects for all of the code used other than "OpenSSL". If you * modify file(s) with this exception, you may extend this exception to * your version of the file(s), but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source files * in the program, then also delete it here. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . **/ #pragma once #include #include #ifdef WIN32 #define ORTHANC_PLUGINS_API __declspec(dllexport) #else #define ORTHANC_PLUGINS_API #endif #define ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER 0 #define ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER 9 #define ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER 5 /******************************************************************** ** Check that function inlining is properly supported. The use of ** inlining is required, to avoid the duplication of object code ** between two compilation modules that would use the Orthanc Plugin ** API. ********************************************************************/ /* If the auto-detection of the "inline" keyword below does not work automatically and that your compiler is known to properly support inlining, uncomment the following #define and adapt the definition of "static inline". */ /* #define ORTHANC_PLUGIN_INLINE static inline */ #ifndef ORTHANC_PLUGIN_INLINE # if __STDC_VERSION__ >= 199901L /* This is C99 or above: http://predef.sourceforge.net/prestd.html */ # define ORTHANC_PLUGIN_INLINE static inline # elif defined(__cplusplus) /* This is C++ */ # define ORTHANC_PLUGIN_INLINE static inline # elif defined(__GNUC__) /* This is GCC running in C89 mode */ # define ORTHANC_PLUGIN_INLINE static __inline # elif defined(_MSC_VER) /* This is Visual Studio running in C89 mode */ # define ORTHANC_PLUGIN_INLINE static __inline # else # error Your compiler is not known to support the "inline" keyword # endif #endif /******************************************************************** ** Inclusion of standard libraries. ********************************************************************/ /** * For Microsoft Visual Studio, a compatibility "stdint.h" can be * downloaded at the following URL: * https://orthanc.googlecode.com/hg/Resources/ThirdParty/VisualStudio/stdint.h **/ #include #include /******************************************************************** ** Definition of the Orthanc Plugin API. ********************************************************************/ /** @{ */ #ifdef __cplusplus extern "C" { #endif /** * The various error codes that can be returned by the Orthanc core. **/ typedef enum { OrthancPluginErrorCode_InternalError = -1 /*!< Internal error */, OrthancPluginErrorCode_Success = 0 /*!< Success */, OrthancPluginErrorCode_Plugin = 1 /*!< Error encountered within the plugin engine */, OrthancPluginErrorCode_NotImplemented = 2 /*!< Not implemented yet */, OrthancPluginErrorCode_ParameterOutOfRange = 3 /*!< Parameter out of range */, OrthancPluginErrorCode_NotEnoughMemory = 4 /*!< Not enough memory */, OrthancPluginErrorCode_BadParameterType = 5 /*!< Bad type for a parameter */, OrthancPluginErrorCode_BadSequenceOfCalls = 6 /*!< Bad sequence of calls */, OrthancPluginErrorCode_InexistentItem = 7 /*!< Accessing an inexistent item */, OrthancPluginErrorCode_BadRequest = 8 /*!< Bad request */, OrthancPluginErrorCode_NetworkProtocol = 9 /*!< Error in the network protocol */, OrthancPluginErrorCode_SystemCommand = 10 /*!< Error while calling a system command */, OrthancPluginErrorCode_Database = 11 /*!< Error with the database engine */, OrthancPluginErrorCode_UriSyntax = 12 /*!< Badly formatted URI */, OrthancPluginErrorCode_InexistentFile = 13 /*!< Inexistent file */, OrthancPluginErrorCode_CannotWriteFile = 14 /*!< Cannot write to file */, OrthancPluginErrorCode_BadFileFormat = 15 /*!< Bad file format */, OrthancPluginErrorCode_Timeout = 16 /*!< Timeout */, OrthancPluginErrorCode_UnknownResource = 17 /*!< Unknown resource */, OrthancPluginErrorCode_IncompatibleDatabaseVersion = 18 /*!< Incompatible version of the database */, OrthancPluginErrorCode_FullStorage = 19 /*!< The file storage is full */, OrthancPluginErrorCode_CorruptedFile = 20 /*!< Corrupted file (e.g. inconsistent MD5 hash) */, OrthancPluginErrorCode_InexistentTag = 21 /*!< Inexistent tag */, OrthancPluginErrorCode_ReadOnly = 22 /*!< Cannot modify a read-only data structure */, OrthancPluginErrorCode_IncompatibleImageFormat = 23 /*!< Incompatible format of the images */, OrthancPluginErrorCode_IncompatibleImageSize = 24 /*!< Incompatible size of the images */, OrthancPluginErrorCode_SharedLibrary = 25 /*!< Error while using a shared library (plugin) */, OrthancPluginErrorCode_UnknownPluginService = 26 /*!< Plugin invoking an unknown service */, OrthancPluginErrorCode_UnknownDicomTag = 27 /*!< Unknown DICOM tag */, OrthancPluginErrorCode_BadJson = 28 /*!< Cannot parse a JSON document */, OrthancPluginErrorCode_Unauthorized = 29 /*!< Bad credentials were provided to an HTTP request */, OrthancPluginErrorCode_BadFont = 30 /*!< Badly formatted font file */, OrthancPluginErrorCode_DatabasePlugin = 31 /*!< The plugin implementing a custom database back-end does not fulfill the proper interface */, OrthancPluginErrorCode_StorageAreaPlugin = 32 /*!< Error in the plugin implementing a custom storage area */, OrthancPluginErrorCode_EmptyRequest = 33 /*!< The request is empty */, OrthancPluginErrorCode_NotAcceptable = 34 /*!< Cannot send a response which is acceptable according to the Accept HTTP header */, OrthancPluginErrorCode_SQLiteNotOpened = 1000 /*!< SQLite: The database is not opened */, OrthancPluginErrorCode_SQLiteAlreadyOpened = 1001 /*!< SQLite: Connection is already open */, OrthancPluginErrorCode_SQLiteCannotOpen = 1002 /*!< SQLite: Unable to open the database */, OrthancPluginErrorCode_SQLiteStatementAlreadyUsed = 1003 /*!< SQLite: This cached statement is already being referred to */, OrthancPluginErrorCode_SQLiteExecute = 1004 /*!< SQLite: Cannot execute a command */, OrthancPluginErrorCode_SQLiteRollbackWithoutTransaction = 1005 /*!< SQLite: Rolling back a nonexistent transaction (have you called Begin()?) */, OrthancPluginErrorCode_SQLiteCommitWithoutTransaction = 1006 /*!< SQLite: Committing a nonexistent transaction */, OrthancPluginErrorCode_SQLiteRegisterFunction = 1007 /*!< SQLite: Unable to register a function */, OrthancPluginErrorCode_SQLiteFlush = 1008 /*!< SQLite: Unable to flush the database */, OrthancPluginErrorCode_SQLiteCannotRun = 1009 /*!< SQLite: Cannot run a cached statement */, OrthancPluginErrorCode_SQLiteCannotStep = 1010 /*!< SQLite: Cannot step over a cached statement */, OrthancPluginErrorCode_SQLiteBindOutOfRange = 1011 /*!< SQLite: Bing a value while out of range (serious error) */, OrthancPluginErrorCode_SQLitePrepareStatement = 1012 /*!< SQLite: Cannot prepare a cached statement */, OrthancPluginErrorCode_SQLiteTransactionAlreadyStarted = 1013 /*!< SQLite: Beginning the same transaction twice */, OrthancPluginErrorCode_SQLiteTransactionCommit = 1014 /*!< SQLite: Failure when committing the transaction */, OrthancPluginErrorCode_SQLiteTransactionBegin = 1015 /*!< SQLite: Cannot start a transaction */, OrthancPluginErrorCode_DirectoryOverFile = 2000 /*!< The directory to be created is already occupied by a regular file */, OrthancPluginErrorCode_FileStorageCannotWrite = 2001 /*!< Unable to create a subdirectory or a file in the file storage */, OrthancPluginErrorCode_DirectoryExpected = 2002 /*!< The specified path does not point to a directory */, OrthancPluginErrorCode_HttpPortInUse = 2003 /*!< The TCP port of the HTTP server is already in use */, OrthancPluginErrorCode_DicomPortInUse = 2004 /*!< The TCP port of the DICOM server is already in use */, OrthancPluginErrorCode_BadHttpStatusInRest = 2005 /*!< This HTTP status is not allowed in a REST API */, OrthancPluginErrorCode_RegularFileExpected = 2006 /*!< The specified path does not point to a regular file */, OrthancPluginErrorCode_PathToExecutable = 2007 /*!< Unable to get the path to the executable */, OrthancPluginErrorCode_MakeDirectory = 2008 /*!< Cannot create a directory */, OrthancPluginErrorCode_BadApplicationEntityTitle = 2009 /*!< An application entity title (AET) cannot be empty or be longer than 16 characters */, OrthancPluginErrorCode_NoCFindHandler = 2010 /*!< No request handler factory for DICOM C-FIND SCP */, OrthancPluginErrorCode_NoCMoveHandler = 2011 /*!< No request handler factory for DICOM C-MOVE SCP */, OrthancPluginErrorCode_NoCStoreHandler = 2012 /*!< No request handler factory for DICOM C-STORE SCP */, OrthancPluginErrorCode_NoApplicationEntityFilter = 2013 /*!< No application entity filter */, OrthancPluginErrorCode_NoSopClassOrInstance = 2014 /*!< DicomUserConnection: Unable to find the SOP class and instance */, OrthancPluginErrorCode_NoPresentationContext = 2015 /*!< DicomUserConnection: No acceptable presentation context for modality */, OrthancPluginErrorCode_DicomFindUnavailable = 2016 /*!< DicomUserConnection: The C-FIND command is not supported by the remote SCP */, OrthancPluginErrorCode_DicomMoveUnavailable = 2017 /*!< DicomUserConnection: The C-MOVE command is not supported by the remote SCP */, OrthancPluginErrorCode_CannotStoreInstance = 2018 /*!< Cannot store an instance */, OrthancPluginErrorCode_CreateDicomNotString = 2019 /*!< Only string values are supported when creating DICOM instances */, OrthancPluginErrorCode_CreateDicomOverrideTag = 2020 /*!< Trying to override a value inherited from a parent module */, OrthancPluginErrorCode_CreateDicomUseContent = 2021 /*!< Use \"Content\" to inject an image into a new DICOM instance */, OrthancPluginErrorCode_CreateDicomNoPayload = 2022 /*!< No payload is present for one instance in the series */, OrthancPluginErrorCode_CreateDicomUseDataUriScheme = 2023 /*!< The payload of the DICOM instance must be specified according to Data URI scheme */, OrthancPluginErrorCode_CreateDicomBadParent = 2024 /*!< Trying to attach a new DICOM instance to an inexistent resource */, OrthancPluginErrorCode_CreateDicomParentIsInstance = 2025 /*!< Trying to attach a new DICOM instance to an instance (must be a series, study or patient) */, OrthancPluginErrorCode_CreateDicomParentEncoding = 2026 /*!< Unable to get the encoding of the parent resource */, OrthancPluginErrorCode_UnknownModality = 2027 /*!< Unknown modality */, OrthancPluginErrorCode_BadJobOrdering = 2028 /*!< Bad ordering of filters in a job */, OrthancPluginErrorCode_JsonToLuaTable = 2029 /*!< Cannot convert the given JSON object to a Lua table */, OrthancPluginErrorCode_CannotCreateLua = 2030 /*!< Cannot create the Lua context */, OrthancPluginErrorCode_CannotExecuteLua = 2031 /*!< Cannot execute a Lua command */, OrthancPluginErrorCode_LuaAlreadyExecuted = 2032 /*!< Arguments cannot be pushed after the Lua function is executed */, OrthancPluginErrorCode_LuaBadOutput = 2033 /*!< The Lua function does not give the expected number of outputs */, OrthancPluginErrorCode_NotLuaPredicate = 2034 /*!< The Lua function is not a predicate (only true/false outputs allowed) */, OrthancPluginErrorCode_LuaReturnsNoString = 2035 /*!< The Lua function does not return a string */, OrthancPluginErrorCode_StorageAreaAlreadyRegistered = 2036 /*!< Another plugin has already registered a custom storage area */, OrthancPluginErrorCode_DatabaseBackendAlreadyRegistered = 2037 /*!< Another plugin has already registered a custom database back-end */, OrthancPluginErrorCode_DatabaseNotInitialized = 2038 /*!< Plugin trying to call the database during its initialization */, OrthancPluginErrorCode_SslDisabled = 2039 /*!< Orthanc has been built without SSL support */, OrthancPluginErrorCode_CannotOrderSlices = 2040 /*!< Unable to order the slices of the series */, OrthancPluginErrorCode_NoWorklistHandler = 2041 /*!< No request handler factory for DICOM C-Find Modality SCP */, _OrthancPluginErrorCode_INTERNAL = 0x7fffffff } OrthancPluginErrorCode; /** * Forward declaration of one of the mandatory functions for Orthanc * plugins. **/ ORTHANC_PLUGINS_API const char* OrthancPluginGetName(); /** * The various HTTP methods for a REST call. **/ typedef enum { OrthancPluginHttpMethod_Get = 1, /*!< GET request */ OrthancPluginHttpMethod_Post = 2, /*!< POST request */ OrthancPluginHttpMethod_Put = 3, /*!< PUT request */ OrthancPluginHttpMethod_Delete = 4, /*!< DELETE request */ _OrthancPluginHttpMethod_INTERNAL = 0x7fffffff } OrthancPluginHttpMethod; /** * @brief The parameters of a REST request. * @ingroup Callbacks **/ typedef struct { /** * @brief The HTTP method. **/ OrthancPluginHttpMethod method; /** * @brief The number of groups of the regular expression. **/ uint32_t groupsCount; /** * @brief The matched values for the groups of the regular expression. **/ const char* const* groups; /** * @brief For a GET request, the number of GET parameters. **/ uint32_t getCount; /** * @brief For a GET request, the keys of the GET parameters. **/ const char* const* getKeys; /** * @brief For a GET request, the values of the GET parameters. **/ const char* const* getValues; /** * @brief For a PUT or POST request, the content of the body. **/ const char* body; /** * @brief For a PUT or POST request, the number of bytes of the body. **/ uint32_t bodySize; /* -------------------------------------------------- New in version 0.8.1 -------------------------------------------------- */ /** * @brief The number of HTTP headers. **/ uint32_t headersCount; /** * @brief The keys of the HTTP headers (always converted to low-case). **/ const char* const* headersKeys; /** * @brief The values of the HTTP headers. **/ const char* const* headersValues; } OrthancPluginHttpRequest; typedef enum { /* Generic services */ _OrthancPluginService_LogInfo = 1, _OrthancPluginService_LogWarning = 2, _OrthancPluginService_LogError = 3, _OrthancPluginService_GetOrthancPath = 4, _OrthancPluginService_GetOrthancDirectory = 5, _OrthancPluginService_GetConfigurationPath = 6, _OrthancPluginService_SetPluginProperty = 7, _OrthancPluginService_GetGlobalProperty = 8, _OrthancPluginService_SetGlobalProperty = 9, _OrthancPluginService_GetCommandLineArgumentsCount = 10, _OrthancPluginService_GetCommandLineArgument = 11, _OrthancPluginService_GetExpectedDatabaseVersion = 12, _OrthancPluginService_GetConfiguration = 13, _OrthancPluginService_BufferCompression = 14, _OrthancPluginService_ReadFile = 15, _OrthancPluginService_WriteFile = 16, _OrthancPluginService_GetErrorDescription = 17, _OrthancPluginService_CallHttpClient = 18, _OrthancPluginService_RegisterErrorCode = 19, _OrthancPluginService_RegisterDictionaryTag = 20, _OrthancPluginService_DicomBufferToJson = 21, _OrthancPluginService_DicomInstanceToJson = 22, _OrthancPluginService_CreateDicom = 23, _OrthancPluginService_ComputeMd5 = 24, _OrthancPluginService_ComputeSha1 = 25, _OrthancPluginService_LookupDictionary = 26, /* Registration of callbacks */ _OrthancPluginService_RegisterRestCallback = 1000, _OrthancPluginService_RegisterOnStoredInstanceCallback = 1001, _OrthancPluginService_RegisterStorageArea = 1002, _OrthancPluginService_RegisterOnChangeCallback = 1003, _OrthancPluginService_RegisterRestCallbackNoLock = 1004, _OrthancPluginService_RegisterWorklistCallback = 1005, _OrthancPluginService_RegisterDecodeImageCallback = 1006, /* Sending answers to REST calls */ _OrthancPluginService_AnswerBuffer = 2000, _OrthancPluginService_CompressAndAnswerPngImage = 2001, /* Unused as of Orthanc 0.9.4 */ _OrthancPluginService_Redirect = 2002, _OrthancPluginService_SendHttpStatusCode = 2003, _OrthancPluginService_SendUnauthorized = 2004, _OrthancPluginService_SendMethodNotAllowed = 2005, _OrthancPluginService_SetCookie = 2006, _OrthancPluginService_SetHttpHeader = 2007, _OrthancPluginService_StartMultipartAnswer = 2008, _OrthancPluginService_SendMultipartItem = 2009, _OrthancPluginService_SendHttpStatus = 2010, _OrthancPluginService_CompressAndAnswerImage = 2011, /* Access to the Orthanc database and API */ _OrthancPluginService_GetDicomForInstance = 3000, _OrthancPluginService_RestApiGet = 3001, _OrthancPluginService_RestApiPost = 3002, _OrthancPluginService_RestApiDelete = 3003, _OrthancPluginService_RestApiPut = 3004, _OrthancPluginService_LookupPatient = 3005, _OrthancPluginService_LookupStudy = 3006, _OrthancPluginService_LookupSeries = 3007, _OrthancPluginService_LookupInstance = 3008, _OrthancPluginService_LookupStudyWithAccessionNumber = 3009, _OrthancPluginService_RestApiGetAfterPlugins = 3010, _OrthancPluginService_RestApiPostAfterPlugins = 3011, _OrthancPluginService_RestApiDeleteAfterPlugins = 3012, _OrthancPluginService_RestApiPutAfterPlugins = 3013, _OrthancPluginService_ReconstructMainDicomTags = 3014, _OrthancPluginService_RestApiGet2 = 3015, /* Access to DICOM instances */ _OrthancPluginService_GetInstanceRemoteAet = 4000, _OrthancPluginService_GetInstanceSize = 4001, _OrthancPluginService_GetInstanceData = 4002, _OrthancPluginService_GetInstanceJson = 4003, _OrthancPluginService_GetInstanceSimplifiedJson = 4004, _OrthancPluginService_HasInstanceMetadata = 4005, _OrthancPluginService_GetInstanceMetadata = 4006, _OrthancPluginService_GetInstanceOrigin = 4007, /* Services for plugins implementing a database back-end */ _OrthancPluginService_RegisterDatabaseBackend = 5000, _OrthancPluginService_DatabaseAnswer = 5001, _OrthancPluginService_RegisterDatabaseBackendV2 = 5002, _OrthancPluginService_StorageAreaCreate = 5003, _OrthancPluginService_StorageAreaRead = 5004, _OrthancPluginService_StorageAreaRemove = 5005, /* Primitives for handling images */ _OrthancPluginService_GetImagePixelFormat = 6000, _OrthancPluginService_GetImageWidth = 6001, _OrthancPluginService_GetImageHeight = 6002, _OrthancPluginService_GetImagePitch = 6003, _OrthancPluginService_GetImageBuffer = 6004, _OrthancPluginService_UncompressImage = 6005, _OrthancPluginService_FreeImage = 6006, _OrthancPluginService_CompressImage = 6007, _OrthancPluginService_ConvertPixelFormat = 6008, _OrthancPluginService_GetFontsCount = 6009, _OrthancPluginService_GetFontInfo = 6010, _OrthancPluginService_DrawText = 6011, _OrthancPluginService_CreateImage = 6012, _OrthancPluginService_CreateImageAccessor = 6013, _OrthancPluginService_DecodeDicomImage = 6014, /* Primitives for handling worklists */ _OrthancPluginService_WorklistAddAnswer = 7000, _OrthancPluginService_WorklistMarkIncomplete = 7001, _OrthancPluginService_WorklistIsMatch = 7002, _OrthancPluginService_WorklistGetDicomQuery = 7003, _OrthancPluginService_INTERNAL = 0x7fffffff } _OrthancPluginService; typedef enum { _OrthancPluginProperty_Description = 1, _OrthancPluginProperty_RootUri = 2, _OrthancPluginProperty_OrthancExplorer = 3, _OrthancPluginProperty_INTERNAL = 0x7fffffff } _OrthancPluginProperty; /** * The memory layout of the pixels of an image. * @ingroup Images **/ typedef enum { /** * @brief Graylevel 8bpp image. * * The image is graylevel. Each pixel is unsigned and stored in * one byte. **/ OrthancPluginPixelFormat_Grayscale8 = 1, /** * @brief Graylevel, unsigned 16bpp image. * * The image is graylevel. Each pixel is unsigned and stored in * two bytes. **/ OrthancPluginPixelFormat_Grayscale16 = 2, /** * @brief Graylevel, signed 16bpp image. * * The image is graylevel. Each pixel is signed and stored in two * bytes. **/ OrthancPluginPixelFormat_SignedGrayscale16 = 3, /** * @brief Color image in RGB24 format. * * This format describes a color image. The pixels are stored in 3 * consecutive bytes. The memory layout is RGB. **/ OrthancPluginPixelFormat_RGB24 = 4, /** * @brief Color image in RGBA32 format. * * This format describes a color image. The pixels are stored in 4 * consecutive bytes. The memory layout is RGBA. **/ OrthancPluginPixelFormat_RGBA32 = 5, OrthancPluginPixelFormat_Unknown = 6, /*!< Unknown pixel format */ _OrthancPluginPixelFormat_INTERNAL = 0x7fffffff } OrthancPluginPixelFormat; /** * The content types that are supported by Orthanc plugins. **/ typedef enum { OrthancPluginContentType_Unknown = 0, /*!< Unknown content type */ OrthancPluginContentType_Dicom = 1, /*!< DICOM */ OrthancPluginContentType_DicomAsJson = 2, /*!< JSON summary of a DICOM file */ _OrthancPluginContentType_INTERNAL = 0x7fffffff } OrthancPluginContentType; /** * The supported types of DICOM resources. **/ typedef enum { OrthancPluginResourceType_Patient = 0, /*!< Patient */ OrthancPluginResourceType_Study = 1, /*!< Study */ OrthancPluginResourceType_Series = 2, /*!< Series */ OrthancPluginResourceType_Instance = 3, /*!< Instance */ OrthancPluginResourceType_None = 4, /*!< Unavailable resource type */ _OrthancPluginResourceType_INTERNAL = 0x7fffffff } OrthancPluginResourceType; /** * The supported types of changes that can happen to DICOM resources. * @ingroup Callbacks **/ typedef enum { OrthancPluginChangeType_CompletedSeries = 0, /*!< Series is now complete */ OrthancPluginChangeType_Deleted = 1, /*!< Deleted resource */ OrthancPluginChangeType_NewChildInstance = 2, /*!< A new instance was added to this resource */ OrthancPluginChangeType_NewInstance = 3, /*!< New instance received */ OrthancPluginChangeType_NewPatient = 4, /*!< New patient created */ OrthancPluginChangeType_NewSeries = 5, /*!< New series created */ OrthancPluginChangeType_NewStudy = 6, /*!< New study created */ OrthancPluginChangeType_StablePatient = 7, /*!< Timeout: No new instance in this patient */ OrthancPluginChangeType_StableSeries = 8, /*!< Timeout: No new instance in this series */ OrthancPluginChangeType_StableStudy = 9, /*!< Timeout: No new instance in this study */ OrthancPluginChangeType_OrthancStarted = 10, /*!< Orthanc has started */ OrthancPluginChangeType_OrthancStopped = 11, /*!< Orthanc is stopping */ OrthancPluginChangeType_UpdatedAttachment = 12, /*!< Some user-defined attachment has changed for this resource */ OrthancPluginChangeType_UpdatedMetadata = 13, /*!< Some user-defined metadata has changed for this resource */ _OrthancPluginChangeType_INTERNAL = 0x7fffffff } OrthancPluginChangeType; /** * The compression algorithms that are supported by the Orthanc core. * @ingroup Images **/ typedef enum { OrthancPluginCompressionType_Zlib = 0, /*!< Standard zlib compression */ OrthancPluginCompressionType_ZlibWithSize = 1, /*!< zlib, prefixed with uncompressed size (uint64_t) */ OrthancPluginCompressionType_Gzip = 2, /*!< Standard gzip compression */ OrthancPluginCompressionType_GzipWithSize = 3, /*!< gzip, prefixed with uncompressed size (uint64_t) */ _OrthancPluginCompressionType_INTERNAL = 0x7fffffff } OrthancPluginCompressionType; /** * The image formats that are supported by the Orthanc core. * @ingroup Images **/ typedef enum { OrthancPluginImageFormat_Png = 0, /*!< Image compressed using PNG */ OrthancPluginImageFormat_Jpeg = 1, /*!< Image compressed using JPEG */ OrthancPluginImageFormat_Dicom = 2, /*!< Image compressed using DICOM */ _OrthancPluginImageFormat_INTERNAL = 0x7fffffff } OrthancPluginImageFormat; /** * The value representations present in the DICOM standard (version 2013). * @ingroup Toolbox **/ typedef enum { OrthancPluginValueRepresentation_AE = 1, /*!< Application Entity */ OrthancPluginValueRepresentation_AS = 2, /*!< Age String */ OrthancPluginValueRepresentation_AT = 3, /*!< Attribute Tag */ OrthancPluginValueRepresentation_CS = 4, /*!< Code String */ OrthancPluginValueRepresentation_DA = 5, /*!< Date */ OrthancPluginValueRepresentation_DS = 6, /*!< Decimal String */ OrthancPluginValueRepresentation_DT = 7, /*!< Date Time */ OrthancPluginValueRepresentation_FD = 8, /*!< Floating Point Double */ OrthancPluginValueRepresentation_FL = 9, /*!< Floating Point Single */ OrthancPluginValueRepresentation_IS = 10, /*!< Integer String */ OrthancPluginValueRepresentation_LO = 11, /*!< Long String */ OrthancPluginValueRepresentation_LT = 12, /*!< Long Text */ OrthancPluginValueRepresentation_OB = 13, /*!< Other Byte String */ OrthancPluginValueRepresentation_OF = 14, /*!< Other Float String */ OrthancPluginValueRepresentation_OW = 15, /*!< Other Word String */ OrthancPluginValueRepresentation_PN = 16, /*!< Person Name */ OrthancPluginValueRepresentation_SH = 17, /*!< Short String */ OrthancPluginValueRepresentation_SL = 18, /*!< Signed Long */ OrthancPluginValueRepresentation_SQ = 19, /*!< Sequence of Items */ OrthancPluginValueRepresentation_SS = 20, /*!< Signed Short */ OrthancPluginValueRepresentation_ST = 21, /*!< Short Text */ OrthancPluginValueRepresentation_TM = 22, /*!< Time */ OrthancPluginValueRepresentation_UI = 23, /*!< Unique Identifier (UID) */ OrthancPluginValueRepresentation_UL = 24, /*!< Unsigned Long */ OrthancPluginValueRepresentation_UN = 25, /*!< Unknown */ OrthancPluginValueRepresentation_US = 26, /*!< Unsigned Short */ OrthancPluginValueRepresentation_UT = 27, /*!< Unlimited Text */ _OrthancPluginValueRepresentation_INTERNAL = 0x7fffffff } OrthancPluginValueRepresentation; /** * The possible output formats for a DICOM-to-JSON conversion. * @ingroup Toolbox * @see OrthancPluginDicomToJson() **/ typedef enum { OrthancPluginDicomToJsonFormat_Full = 1, /*!< Full output, with most details */ OrthancPluginDicomToJsonFormat_Short = 2, /*!< Tags output as hexadecimal numbers */ OrthancPluginDicomToJsonFormat_Human = 3, /*!< Human-readable JSON */ _OrthancPluginDicomToJsonFormat_INTERNAL = 0x7fffffff } OrthancPluginDicomToJsonFormat; /** * Flags to customize a DICOM-to-JSON conversion. By default, binary * tags are formatted using Data URI scheme. * @ingroup Toolbox **/ typedef enum { OrthancPluginDicomToJsonFlags_IncludeBinary = (1 << 0), /*!< Include the binary tags */ OrthancPluginDicomToJsonFlags_IncludePrivateTags = (1 << 1), /*!< Include the private tags */ OrthancPluginDicomToJsonFlags_IncludeUnknownTags = (1 << 2), /*!< Include the tags unknown by the dictionary */ OrthancPluginDicomToJsonFlags_IncludePixelData = (1 << 3), /*!< Include the pixel data */ OrthancPluginDicomToJsonFlags_ConvertBinaryToAscii = (1 << 4), /*!< Output binary tags as-is, dropping non-ASCII */ OrthancPluginDicomToJsonFlags_ConvertBinaryToNull = (1 << 5), /*!< Signal binary tags as null values */ _OrthancPluginDicomToJsonFlags_INTERNAL = 0x7fffffff } OrthancPluginDicomToJsonFlags; /** * Flags to the creation of a DICOM file. * @ingroup Toolbox * @see OrthancPluginCreateDicom() **/ typedef enum { OrthancPluginCreateDicomFlags_DecodeDataUriScheme = (1 << 0), /*!< Decode fields encoded using data URI scheme */ OrthancPluginCreateDicomFlags_GenerateIdentifiers = (1 << 1), /*!< Automatically generate DICOM identifiers */ _OrthancPluginCreateDicomFlags_INTERNAL = 0x7fffffff } OrthancPluginCreateDicomFlags; /** * The constraints on the DICOM identifiers that must be supported * by the database plugins. **/ typedef enum { OrthancPluginIdentifierConstraint_Equal = 1, /*!< Equal */ OrthancPluginIdentifierConstraint_SmallerOrEqual = 2, /*!< Less or equal */ OrthancPluginIdentifierConstraint_GreaterOrEqual = 3, /*!< More or equal */ OrthancPluginIdentifierConstraint_Wildcard = 4, /*!< Case-sensitive wildcard matching (with * and ?) */ _OrthancPluginIdentifierConstraint_INTERNAL = 0x7fffffff } OrthancPluginIdentifierConstraint; /** * The origin of a DICOM instance that has been received by Orthanc. **/ typedef enum { OrthancPluginInstanceOrigin_Unknown = 1, /*!< Unknown origin */ OrthancPluginInstanceOrigin_DicomProtocol = 2, /*!< Instance received through DICOM protocol */ OrthancPluginInstanceOrigin_RestApi = 3, /*!< Instance received through REST API of Orthanc */ OrthancPluginInstanceOrigin_Plugin = 4, /*!< Instance added to Orthanc by a plugin */ OrthancPluginInstanceOrigin_Lua = 5, /*!< Instance added to Orthanc by a Lua script */ _OrthancPluginInstanceOrigin_INTERNAL = 0x7fffffff } OrthancPluginInstanceOrigin; /** * @brief A memory buffer allocated by the core system of Orthanc. * * A memory buffer allocated by the core system of Orthanc. When the * content of the buffer is not useful anymore, it must be free by a * call to ::OrthancPluginFreeMemoryBuffer(). **/ typedef struct { /** * @brief The content of the buffer. **/ void* data; /** * @brief The number of bytes in the buffer. **/ uint32_t size; } OrthancPluginMemoryBuffer; /** * @brief Opaque structure that represents the HTTP connection to the client application. * @ingroup Callback **/ typedef struct _OrthancPluginRestOutput_t OrthancPluginRestOutput; /** * @brief Opaque structure that represents a DICOM instance received by Orthanc. **/ typedef struct _OrthancPluginDicomInstance_t OrthancPluginDicomInstance; /** * @brief Opaque structure that represents an image that is uncompressed in memory. * @ingroup Images **/ typedef struct _OrthancPluginImage_t OrthancPluginImage; /** * @brief Opaque structure that represents the storage area that is actually used by Orthanc. * @ingroup Images **/ typedef struct _OrthancPluginStorageArea_t OrthancPluginStorageArea; /** * @brief Opaque structure to an object that represents a C-Find query. * @ingroup Worklists **/ typedef struct _OrthancPluginWorklistQuery_t OrthancPluginWorklistQuery; /** * @brief Opaque structure to an object that represents the answers to a C-Find query. * @ingroup Worklists **/ typedef struct _OrthancPluginWorklistAnswers_t OrthancPluginWorklistAnswers; /** * @brief Signature of a callback function that answers to a REST request. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginRestCallback) ( OrthancPluginRestOutput* output, const char* url, const OrthancPluginHttpRequest* request); /** * @brief Signature of a callback function that is triggered when Orthanc receives a DICOM instance. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginOnStoredInstanceCallback) ( OrthancPluginDicomInstance* instance, const char* instanceId); /** * @brief Signature of a callback function that is triggered when a change happens to some DICOM resource. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginOnChangeCallback) ( OrthancPluginChangeType changeType, OrthancPluginResourceType resourceType, const char* resourceId); /** * @brief Signature of a callback function to decode a DICOM instance as an image. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginDecodeImageCallback) ( OrthancPluginImage** target, const void* dicom, const uint32_t size, uint32_t frameIndex); /** * @brief Signature of a function to free dynamic memory. **/ typedef void (*OrthancPluginFree) (void* buffer); /** * @brief Callback for writing to the storage area. * * Signature of a callback function that is triggered when Orthanc writes a file to the storage area. * * @param uuid The UUID of the file. * @param content The content of the file. * @param size The size of the file. * @param type The content type corresponding to this file. * @return 0 if success, other value if error. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginStorageCreate) ( const char* uuid, const void* content, int64_t size, OrthancPluginContentType type); /** * @brief Callback for reading from the storage area. * * Signature of a callback function that is triggered when Orthanc reads a file from the storage area. * * @param content The content of the file (output). * @param size The size of the file (output). * @param uuid The UUID of the file of interest. * @param type The content type corresponding to this file. * @return 0 if success, other value if error. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginStorageRead) ( void** content, int64_t* size, const char* uuid, OrthancPluginContentType type); /** * @brief Callback for removing a file from the storage area. * * Signature of a callback function that is triggered when Orthanc deletes a file from the storage area. * * @param uuid The UUID of the file to be removed. * @param type The content type corresponding to this file. * @return 0 if success, other value if error. * @ingroup Callbacks **/ typedef OrthancPluginErrorCode (*OrthancPluginStorageRemove) ( const char* uuid, OrthancPluginContentType type); /** * @brief Callback to handle the C-Find SCP requests received by Orthanc. * * Signature of a callback function that is triggered when Orthanc * receives a C-Find SCP request against modality worklists. * * @param answers The target structure where answers must be stored. * @param query The worklist query. * @param remoteAet The Application Entity Title (AET) of the modality from which the request originates. * @param calledAet The Application Entity Title (AET) of the modality that is called by the request. * @return 0 if success, other value if error. * @ingroup Worklists **/ typedef OrthancPluginErrorCode (*OrthancPluginWorklistCallback) ( OrthancPluginWorklistAnswers* answers, const OrthancPluginWorklistQuery* query, const char* remoteAet, const char* calledAet); /** * @brief Data structure that contains information about the Orthanc core. **/ typedef struct _OrthancPluginContext_t { void* pluginsManager; const char* orthancVersion; OrthancPluginFree Free; OrthancPluginErrorCode (*InvokeService) (struct _OrthancPluginContext_t* context, _OrthancPluginService service, const void* params); } OrthancPluginContext; /** * @brief An entry in the dictionary of DICOM tags. **/ typedef struct { uint16_t group; /*!< The group of the tag */ uint16_t element; /*!< The element of the tag */ OrthancPluginValueRepresentation vr; /*!< The value representation of the tag */ uint32_t minMultiplicity; /*!< The minimum multiplicity of the tag */ uint32_t maxMultiplicity; /*!< The maximum multiplicity of the tag (0 means arbitrary) */ } OrthancPluginDictionaryEntry; /** * @brief Free a string. * * Free a string that was allocated by the core system of Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param str The string to be freed. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginFreeString( OrthancPluginContext* context, char* str) { if (str != NULL) { context->Free(str); } } /** * @brief Check the compatibility of the plugin wrt. the version of its hosting Orthanc. * * This function checks whether the version of this C header is * compatible with the current version of Orthanc. The result of * this function should always be checked in the * OrthancPluginInitialize() entry point of the plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return 1 if and only if the versions are compatible. If the * result is 0, the initialization of the plugin should fail. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE int OrthancPluginCheckVersion( OrthancPluginContext* context) { int major, minor, revision; if (sizeof(int32_t) != sizeof(OrthancPluginErrorCode) || sizeof(int32_t) != sizeof(OrthancPluginHttpMethod) || sizeof(int32_t) != sizeof(_OrthancPluginService) || sizeof(int32_t) != sizeof(_OrthancPluginProperty) || sizeof(int32_t) != sizeof(OrthancPluginPixelFormat) || sizeof(int32_t) != sizeof(OrthancPluginContentType) || sizeof(int32_t) != sizeof(OrthancPluginResourceType) || sizeof(int32_t) != sizeof(OrthancPluginChangeType) || sizeof(int32_t) != sizeof(OrthancPluginCompressionType) || sizeof(int32_t) != sizeof(OrthancPluginImageFormat) || sizeof(int32_t) != sizeof(OrthancPluginValueRepresentation) || sizeof(int32_t) != sizeof(OrthancPluginDicomToJsonFormat) || sizeof(int32_t) != sizeof(OrthancPluginDicomToJsonFlags) || sizeof(int32_t) != sizeof(OrthancPluginCreateDicomFlags) || sizeof(int32_t) != sizeof(OrthancPluginIdentifierConstraint) || sizeof(int32_t) != sizeof(OrthancPluginInstanceOrigin)) { /* Mismatch in the size of the enumerations */ return 0; } /* Assume compatibility with the mainline */ if (!strcmp(context->orthancVersion, "mainline")) { return 1; } /* Parse the version of the Orthanc core */ if ( #ifdef _MSC_VER sscanf_s #else sscanf #endif (context->orthancVersion, "%4d.%4d.%4d", &major, &minor, &revision) != 3) { return 0; } /* Check the major number of the version */ if (major > ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER) { return 1; } if (major < ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER) { return 0; } /* Check the minor number of the version */ if (minor > ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER) { return 1; } if (minor < ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER) { return 0; } /* Check the revision number of the version */ if (revision >= ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER) { return 1; } else { return 0; } } /** * @brief Free a memory buffer. * * Free a memory buffer that was allocated by the core system of Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param buffer The memory buffer to release. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginFreeMemoryBuffer( OrthancPluginContext* context, OrthancPluginMemoryBuffer* buffer) { context->Free(buffer->data); } /** * @brief Log an error. * * Log an error message using the Orthanc logging system. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param message The message to be logged. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginLogError( OrthancPluginContext* context, const char* message) { context->InvokeService(context, _OrthancPluginService_LogError, message); } /** * @brief Log a warning. * * Log a warning message using the Orthanc logging system. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param message The message to be logged. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginLogWarning( OrthancPluginContext* context, const char* message) { context->InvokeService(context, _OrthancPluginService_LogWarning, message); } /** * @brief Log an information. * * Log an information message using the Orthanc logging system. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param message The message to be logged. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginLogInfo( OrthancPluginContext* context, const char* message) { context->InvokeService(context, _OrthancPluginService_LogInfo, message); } typedef struct { const char* pathRegularExpression; OrthancPluginRestCallback callback; } _OrthancPluginRestCallback; /** * @brief Register a REST callback. * * This function registers a REST callback against a regular * expression for a URI. This function must be called during the * initialization of the plugin, i.e. inside the * OrthancPluginInitialize() public function. * * Each REST callback is guaranteed to run in mutual exclusion. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param pathRegularExpression Regular expression for the URI. May contain groups. * @param callback The callback function to handle the REST call. * @see OrthancPluginRegisterRestCallbackNoLock() * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRegisterRestCallback( OrthancPluginContext* context, const char* pathRegularExpression, OrthancPluginRestCallback callback) { _OrthancPluginRestCallback params; params.pathRegularExpression = pathRegularExpression; params.callback = callback; context->InvokeService(context, _OrthancPluginService_RegisterRestCallback, ¶ms); } /** * @brief Register a REST callback, without locking. * * This function registers a REST callback against a regular * expression for a URI. This function must be called during the * initialization of the plugin, i.e. inside the * OrthancPluginInitialize() public function. * * Contrarily to OrthancPluginRegisterRestCallback(), the callback * will NOT be invoked in mutual exclusion. This can be useful for * high-performance plugins that must handle concurrent requests * (Orthanc uses a pool of threads, one thread being assigned to * each incoming HTTP request). Of course, it is up to the plugin to * implement the required locking mechanisms. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param pathRegularExpression Regular expression for the URI. May contain groups. * @param callback The callback function to handle the REST call. * @see OrthancPluginRegisterRestCallback() * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRegisterRestCallbackNoLock( OrthancPluginContext* context, const char* pathRegularExpression, OrthancPluginRestCallback callback) { _OrthancPluginRestCallback params; params.pathRegularExpression = pathRegularExpression; params.callback = callback; context->InvokeService(context, _OrthancPluginService_RegisterRestCallbackNoLock, ¶ms); } typedef struct { OrthancPluginOnStoredInstanceCallback callback; } _OrthancPluginOnStoredInstanceCallback; /** * @brief Register a callback for received instances. * * This function registers a callback function that is called * whenever a new DICOM instance is stored into the Orthanc core. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param callback The callback function. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRegisterOnStoredInstanceCallback( OrthancPluginContext* context, OrthancPluginOnStoredInstanceCallback callback) { _OrthancPluginOnStoredInstanceCallback params; params.callback = callback; context->InvokeService(context, _OrthancPluginService_RegisterOnStoredInstanceCallback, ¶ms); } typedef struct { OrthancPluginRestOutput* output; const char* answer; uint32_t answerSize; const char* mimeType; } _OrthancPluginAnswerBuffer; /** * @brief Answer to a REST request. * * This function answers to a REST request with the content of a memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param answer Pointer to the memory buffer containing the answer. * @param answerSize Number of bytes of the answer. * @param mimeType The MIME type of the answer. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginAnswerBuffer( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* answer, uint32_t answerSize, const char* mimeType) { _OrthancPluginAnswerBuffer params; params.output = output; params.answer = answer; params.answerSize = answerSize; params.mimeType = mimeType; context->InvokeService(context, _OrthancPluginService_AnswerBuffer, ¶ms); } typedef struct { OrthancPluginRestOutput* output; OrthancPluginPixelFormat format; uint32_t width; uint32_t height; uint32_t pitch; const void* buffer; } _OrthancPluginCompressAndAnswerPngImage; typedef struct { OrthancPluginRestOutput* output; OrthancPluginImageFormat imageFormat; OrthancPluginPixelFormat pixelFormat; uint32_t width; uint32_t height; uint32_t pitch; const void* buffer; uint8_t quality; } _OrthancPluginCompressAndAnswerImage; /** * @brief Answer to a REST request with a PNG image. * * This function answers to a REST request with a PNG image. The * parameters of this function describe a memory buffer that * contains an uncompressed image. The image will be automatically compressed * as a PNG image by the core system of Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param format The memory layout of the uncompressed image. * @param width The width of the image. * @param height The height of the image. * @param pitch The pitch of the image (i.e. the number of bytes * between 2 successive lines of the image in the memory buffer). * @param buffer The memory buffer containing the uncompressed image. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginCompressAndAnswerPngImage( OrthancPluginContext* context, OrthancPluginRestOutput* output, OrthancPluginPixelFormat format, uint32_t width, uint32_t height, uint32_t pitch, const void* buffer) { _OrthancPluginCompressAndAnswerImage params; params.output = output; params.imageFormat = OrthancPluginImageFormat_Png; params.pixelFormat = format; params.width = width; params.height = height; params.pitch = pitch; params.buffer = buffer; params.quality = 0; /* No quality for PNG */ context->InvokeService(context, _OrthancPluginService_CompressAndAnswerImage, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; const char* instanceId; } _OrthancPluginGetDicomForInstance; /** * @brief Retrieve a DICOM instance using its Orthanc identifier. * * Retrieve a DICOM instance using its Orthanc identifier. The DICOM * file is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param instanceId The Orthanc identifier of the DICOM instance of interest. * @return 0 if success, or the error code if failure. * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginGetDicomForInstance( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* instanceId) { _OrthancPluginGetDicomForInstance params; params.target = target; params.instanceId = instanceId; return context->InvokeService(context, _OrthancPluginService_GetDicomForInstance, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; const char* uri; } _OrthancPluginRestApiGet; /** * @brief Make a GET call to the built-in Orthanc REST API. * * Make a GET call to the built-in Orthanc REST API. The result to * the query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiGetAfterPlugins * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiGet( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri) { _OrthancPluginRestApiGet params; params.target = target; params.uri = uri; return context->InvokeService(context, _OrthancPluginService_RestApiGet, ¶ms); } /** * @brief Make a GET call to the REST API, as tainted by the plugins. * * Make a GET call to the Orthanc REST API, after all the plugins * are applied. In other words, if some plugin overrides or adds the * called URI to the built-in Orthanc REST API, this call will * return the result provided by this plugin. The result to the * query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiGet * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiGetAfterPlugins( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri) { _OrthancPluginRestApiGet params; params.target = target; params.uri = uri; return context->InvokeService(context, _OrthancPluginService_RestApiGetAfterPlugins, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; const char* uri; const char* body; uint32_t bodySize; } _OrthancPluginRestApiPostPut; /** * @brief Make a POST call to the built-in Orthanc REST API. * * Make a POST call to the built-in Orthanc REST API. The result to * the query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @param body The body of the POST request. * @param bodySize The size of the body. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiPostAfterPlugins * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiPost( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri, const char* body, uint32_t bodySize) { _OrthancPluginRestApiPostPut params; params.target = target; params.uri = uri; params.body = body; params.bodySize = bodySize; return context->InvokeService(context, _OrthancPluginService_RestApiPost, ¶ms); } /** * @brief Make a POST call to the REST API, as tainted by the plugins. * * Make a POST call to the Orthanc REST API, after all the plugins * are applied. In other words, if some plugin overrides or adds the * called URI to the built-in Orthanc REST API, this call will * return the result provided by this plugin. The result to the * query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @param body The body of the POST request. * @param bodySize The size of the body. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiPost * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiPostAfterPlugins( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri, const char* body, uint32_t bodySize) { _OrthancPluginRestApiPostPut params; params.target = target; params.uri = uri; params.body = body; params.bodySize = bodySize; return context->InvokeService(context, _OrthancPluginService_RestApiPostAfterPlugins, ¶ms); } /** * @brief Make a DELETE call to the built-in Orthanc REST API. * * Make a DELETE call to the built-in Orthanc REST API. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param uri The URI to delete in the built-in Orthanc API. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiDeleteAfterPlugins * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiDelete( OrthancPluginContext* context, const char* uri) { return context->InvokeService(context, _OrthancPluginService_RestApiDelete, uri); } /** * @brief Make a DELETE call to the REST API, as tainted by the plugins. * * Make a DELETE call to the Orthanc REST API, after all the plugins * are applied. In other words, if some plugin overrides or adds the * called URI to the built-in Orthanc REST API, this call will * return the result provided by this plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param uri The URI to delete in the built-in Orthanc API. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiDelete * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiDeleteAfterPlugins( OrthancPluginContext* context, const char* uri) { return context->InvokeService(context, _OrthancPluginService_RestApiDeleteAfterPlugins, uri); } /** * @brief Make a PUT call to the built-in Orthanc REST API. * * Make a PUT call to the built-in Orthanc REST API. The result to * the query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @param body The body of the PUT request. * @param bodySize The size of the body. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiPutAfterPlugins * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiPut( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri, const char* body, uint32_t bodySize) { _OrthancPluginRestApiPostPut params; params.target = target; params.uri = uri; params.body = body; params.bodySize = bodySize; return context->InvokeService(context, _OrthancPluginService_RestApiPut, ¶ms); } /** * @brief Make a PUT call to the REST API, as tainted by the plugins. * * Make a PUT call to the Orthanc REST API, after all the plugins * are applied. In other words, if some plugin overrides or adds the * called URI to the built-in Orthanc REST API, this call will * return the result provided by this plugin. The result to the * query is stored into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @param body The body of the PUT request. * @param bodySize The size of the body. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiPut * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiPutAfterPlugins( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri, const char* body, uint32_t bodySize) { _OrthancPluginRestApiPostPut params; params.target = target; params.uri = uri; params.body = body; params.bodySize = bodySize; return context->InvokeService(context, _OrthancPluginService_RestApiPutAfterPlugins, ¶ms); } typedef struct { OrthancPluginRestOutput* output; const char* argument; } _OrthancPluginOutputPlusArgument; /** * @brief Redirect a REST request. * * This function answers to a REST request by redirecting the user * to another URI using HTTP status 301. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param redirection Where to redirect. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRedirect( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* redirection) { _OrthancPluginOutputPlusArgument params; params.output = output; params.argument = redirection; context->InvokeService(context, _OrthancPluginService_Redirect, ¶ms); } typedef struct { char** result; const char* argument; } _OrthancPluginRetrieveDynamicString; /** * @brief Look for a patient. * * Look for a patient stored in Orthanc, using its Patient ID tag (0x0010, 0x0020). * This function uses the database index to run as fast as possible (it does not loop * over all the stored patients). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param patientID The Patient ID of interest. * @return The NULL value if the patient is non-existent, or a string containing the * Orthanc ID of the patient. This string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginLookupPatient( OrthancPluginContext* context, const char* patientID) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = patientID; if (context->InvokeService(context, _OrthancPluginService_LookupPatient, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Look for a study. * * Look for a study stored in Orthanc, using its Study Instance UID tag (0x0020, 0x000d). * This function uses the database index to run as fast as possible (it does not loop * over all the stored studies). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param studyUID The Study Instance UID of interest. * @return The NULL value if the study is non-existent, or a string containing the * Orthanc ID of the study. This string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginLookupStudy( OrthancPluginContext* context, const char* studyUID) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = studyUID; if (context->InvokeService(context, _OrthancPluginService_LookupStudy, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Look for a study, using the accession number. * * Look for a study stored in Orthanc, using its Accession Number tag (0x0008, 0x0050). * This function uses the database index to run as fast as possible (it does not loop * over all the stored studies). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param accessionNumber The Accession Number of interest. * @return The NULL value if the study is non-existent, or a string containing the * Orthanc ID of the study. This string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginLookupStudyWithAccessionNumber( OrthancPluginContext* context, const char* accessionNumber) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = accessionNumber; if (context->InvokeService(context, _OrthancPluginService_LookupStudyWithAccessionNumber, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Look for a series. * * Look for a series stored in Orthanc, using its Series Instance UID tag (0x0020, 0x000e). * This function uses the database index to run as fast as possible (it does not loop * over all the stored series). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param seriesUID The Series Instance UID of interest. * @return The NULL value if the series is non-existent, or a string containing the * Orthanc ID of the series. This string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginLookupSeries( OrthancPluginContext* context, const char* seriesUID) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = seriesUID; if (context->InvokeService(context, _OrthancPluginService_LookupSeries, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Look for an instance. * * Look for an instance stored in Orthanc, using its SOP Instance UID tag (0x0008, 0x0018). * This function uses the database index to run as fast as possible (it does not loop * over all the stored instances). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param sopInstanceUID The SOP Instance UID of interest. * @return The NULL value if the instance is non-existent, or a string containing the * Orthanc ID of the instance. This string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginLookupInstance( OrthancPluginContext* context, const char* sopInstanceUID) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = sopInstanceUID; if (context->InvokeService(context, _OrthancPluginService_LookupInstance, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginRestOutput* output; uint16_t status; } _OrthancPluginSendHttpStatusCode; /** * @brief Send a HTTP status code. * * This function answers to a REST request by sending a HTTP status * code (such as "400 - Bad Request"). Note that: * - Successful requests (status 200) must use ::OrthancPluginAnswerBuffer(). * - Redirections (status 301) must use ::OrthancPluginRedirect(). * - Unauthorized access (status 401) must use ::OrthancPluginSendUnauthorized(). * - Methods not allowed (status 405) must use ::OrthancPluginSendMethodNotAllowed(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param status The HTTP status code to be sent. * @ingroup REST * @see OrthancPluginSendHttpStatus() **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSendHttpStatusCode( OrthancPluginContext* context, OrthancPluginRestOutput* output, uint16_t status) { _OrthancPluginSendHttpStatusCode params; params.output = output; params.status = status; context->InvokeService(context, _OrthancPluginService_SendHttpStatusCode, ¶ms); } /** * @brief Signal that a REST request is not authorized. * * This function answers to a REST request by signaling that it is * not authorized. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param realm The realm for the authorization process. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSendUnauthorized( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* realm) { _OrthancPluginOutputPlusArgument params; params.output = output; params.argument = realm; context->InvokeService(context, _OrthancPluginService_SendUnauthorized, ¶ms); } /** * @brief Signal that this URI does not support this HTTP method. * * This function answers to a REST request by signaling that the * queried URI does not support this method. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param allowedMethods The allowed methods for this URI (e.g. "GET,POST" after a PUT or a POST request). * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSendMethodNotAllowed( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* allowedMethods) { _OrthancPluginOutputPlusArgument params; params.output = output; params.argument = allowedMethods; context->InvokeService(context, _OrthancPluginService_SendMethodNotAllowed, ¶ms); } typedef struct { OrthancPluginRestOutput* output; const char* key; const char* value; } _OrthancPluginSetHttpHeader; /** * @brief Set a cookie. * * This function sets a cookie in the HTTP client. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param cookie The cookie to be set. * @param value The value of the cookie. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSetCookie( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* cookie, const char* value) { _OrthancPluginSetHttpHeader params; params.output = output; params.key = cookie; params.value = value; context->InvokeService(context, _OrthancPluginService_SetCookie, ¶ms); } /** * @brief Set some HTTP header. * * This function sets a HTTP header in the HTTP answer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param key The HTTP header to be set. * @param value The value of the HTTP header. * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSetHttpHeader( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* key, const char* value) { _OrthancPluginSetHttpHeader params; params.output = output; params.key = key; params.value = value; context->InvokeService(context, _OrthancPluginService_SetHttpHeader, ¶ms); } typedef struct { char** resultStringToFree; const char** resultString; int64_t* resultInt64; const char* key; OrthancPluginDicomInstance* instance; OrthancPluginInstanceOrigin* resultOrigin; /* New in Orthanc 0.9.5 SDK */ } _OrthancPluginAccessDicomInstance; /** * @brief Get the AET of a DICOM instance. * * This function returns the Application Entity Title (AET) of the * DICOM modality from which a DICOM instance originates. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The AET if success, NULL if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE const char* OrthancPluginGetInstanceRemoteAet( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { const char* result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultString = &result; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceRemoteAet, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Get the size of a DICOM file. * * This function returns the number of bytes of the given DICOM instance. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The size of the file, -1 in case of error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE int64_t OrthancPluginGetInstanceSize( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { int64_t size; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultInt64 = &size; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceSize, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return -1; } else { return size; } } /** * @brief Get the data of a DICOM file. * * This function returns a pointer to the content of the given DICOM instance. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The pointer to the DICOM data, NULL in case of error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE const char* OrthancPluginGetInstanceData( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { const char* result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultString = &result; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceData, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Get the DICOM tag hierarchy as a JSON file. * * This function returns a pointer to a newly created string * containing a JSON file. This JSON file encodes the tag hierarchy * of the given DICOM instance. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The NULL value in case of error, or a string containing the JSON file. * This string must be freed by OrthancPluginFreeString(). * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginGetInstanceJson( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { char* result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultStringToFree = &result; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceJson, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Get the DICOM tag hierarchy as a JSON file (with simplification). * * This function returns a pointer to a newly created string * containing a JSON file. This JSON file encodes the tag hierarchy * of the given DICOM instance. In contrast with * ::OrthancPluginGetInstanceJson(), the returned JSON file is in * its simplified version. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The NULL value in case of error, or a string containing the JSON file. * This string must be freed by OrthancPluginFreeString(). * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginGetInstanceSimplifiedJson( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { char* result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultStringToFree = &result; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceSimplifiedJson, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Check whether a DICOM instance is associated with some metadata. * * This function checks whether the DICOM instance of interest is * associated with some metadata. As of Orthanc 0.8.1, in the * callbacks registered by * ::OrthancPluginRegisterOnStoredInstanceCallback(), the only * possibly available metadata are "ReceptionDate", "RemoteAET" and * "IndexInSeries". * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @param metadata The metadata of interest. * @return 1 if the metadata is present, 0 if it is absent, -1 in case of error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE int OrthancPluginHasInstanceMetadata( OrthancPluginContext* context, OrthancPluginDicomInstance* instance, const char* metadata) { int64_t result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultInt64 = &result; params.instance = instance; params.key = metadata; if (context->InvokeService(context, _OrthancPluginService_HasInstanceMetadata, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return -1; } else { return (result != 0); } } /** * @brief Get the value of some metadata associated with a given DICOM instance. * * This functions returns the value of some metadata that is associated with the DICOM instance of interest. * Before calling this function, the existence of the metadata must have been checked with * ::OrthancPluginHasInstanceMetadata(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @param metadata The metadata of interest. * @return The metadata value if success, NULL if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE const char* OrthancPluginGetInstanceMetadata( OrthancPluginContext* context, OrthancPluginDicomInstance* instance, const char* metadata) { const char* result; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultString = &result; params.instance = instance; params.key = metadata; if (context->InvokeService(context, _OrthancPluginService_GetInstanceMetadata, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginStorageCreate create; OrthancPluginStorageRead read; OrthancPluginStorageRemove remove; OrthancPluginFree free; } _OrthancPluginRegisterStorageArea; /** * @brief Register a custom storage area. * * This function registers a custom storage area, to replace the * built-in way Orthanc stores its files on the filesystem. This * function must be called during the initialization of the plugin, * i.e. inside the OrthancPluginInitialize() public function. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param create The callback function to store a file on the custom storage area. * @param read The callback function to read a file from the custom storage area. * @param remove The callback function to remove a file from the custom storage area. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRegisterStorageArea( OrthancPluginContext* context, OrthancPluginStorageCreate create, OrthancPluginStorageRead read, OrthancPluginStorageRemove remove) { _OrthancPluginRegisterStorageArea params; params.create = create; params.read = read; params.remove = remove; #ifdef __cplusplus params.free = ::free; #else params.free = free; #endif context->InvokeService(context, _OrthancPluginService_RegisterStorageArea, ¶ms); } /** * @brief Return the path to the Orthanc executable. * * This function returns the path to the Orthanc executable. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return NULL in the case of an error, or a newly allocated string * containing the path. This string must be freed by * OrthancPluginFreeString(). **/ ORTHANC_PLUGIN_INLINE char *OrthancPluginGetOrthancPath(OrthancPluginContext* context) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = NULL; if (context->InvokeService(context, _OrthancPluginService_GetOrthancPath, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Return the directory containing the Orthanc. * * This function returns the path to the directory containing the Orthanc executable. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return NULL in the case of an error, or a newly allocated string * containing the path. This string must be freed by * OrthancPluginFreeString(). **/ ORTHANC_PLUGIN_INLINE char *OrthancPluginGetOrthancDirectory(OrthancPluginContext* context) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = NULL; if (context->InvokeService(context, _OrthancPluginService_GetOrthancDirectory, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Return the path to the configuration file(s). * * This function returns the path to the configuration file(s) that * was specified when starting Orthanc. Since version 0.9.1, this * path can refer to a folder that stores a set of configuration * files. This function is deprecated in favor of * OrthancPluginGetConfiguration(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return NULL in the case of an error, or a newly allocated string * containing the path. This string must be freed by * OrthancPluginFreeString(). * @see OrthancPluginGetConfiguration() **/ ORTHANC_PLUGIN_INLINE char *OrthancPluginGetConfigurationPath(OrthancPluginContext* context) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = NULL; if (context->InvokeService(context, _OrthancPluginService_GetConfigurationPath, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginOnChangeCallback callback; } _OrthancPluginOnChangeCallback; /** * @brief Register a callback to monitor changes. * * This function registers a callback function that is called * whenever a change happens to some DICOM resource. * * @warning If your change callback has to call the REST API of * Orthanc, you should make these calls in a separate thread (with * the events passing through a message queue). Otherwise, this * could result in deadlocks in the presence of other plugins or Lua * script. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param callback The callback function. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE void OrthancPluginRegisterOnChangeCallback( OrthancPluginContext* context, OrthancPluginOnChangeCallback callback) { _OrthancPluginOnChangeCallback params; params.callback = callback; context->InvokeService(context, _OrthancPluginService_RegisterOnChangeCallback, ¶ms); } typedef struct { const char* plugin; _OrthancPluginProperty property; const char* value; } _OrthancPluginSetPluginProperty; /** * @brief Set the URI where the plugin provides its Web interface. * * For plugins that come with a Web interface, this function * declares the entry path where to find this interface. This * information is notably used in the "Plugins" page of Orthanc * Explorer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param uri The root URI for this plugin. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSetRootUri( OrthancPluginContext* context, const char* uri) { _OrthancPluginSetPluginProperty params; params.plugin = OrthancPluginGetName(); params.property = _OrthancPluginProperty_RootUri; params.value = uri; context->InvokeService(context, _OrthancPluginService_SetPluginProperty, ¶ms); } /** * @brief Set a description for this plugin. * * Set a description for this plugin. It is displayed in the * "Plugins" page of Orthanc Explorer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param description The description. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSetDescription( OrthancPluginContext* context, const char* description) { _OrthancPluginSetPluginProperty params; params.plugin = OrthancPluginGetName(); params.property = _OrthancPluginProperty_Description; params.value = description; context->InvokeService(context, _OrthancPluginService_SetPluginProperty, ¶ms); } /** * @brief Extend the JavaScript code of Orthanc Explorer. * * Add JavaScript code to customize the default behavior of Orthanc * Explorer. This can for instance be used to add new buttons. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param javascript The custom JavaScript code. **/ ORTHANC_PLUGIN_INLINE void OrthancPluginExtendOrthancExplorer( OrthancPluginContext* context, const char* javascript) { _OrthancPluginSetPluginProperty params; params.plugin = OrthancPluginGetName(); params.property = _OrthancPluginProperty_OrthancExplorer; params.value = javascript; context->InvokeService(context, _OrthancPluginService_SetPluginProperty, ¶ms); } typedef struct { char** result; int32_t property; const char* value; } _OrthancPluginGlobalProperty; /** * @brief Get the value of a global property. * * Get the value of a global property that is stored in the Orthanc database. Global * properties whose index is below 1024 are reserved by Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param property The global property of interest. * @param defaultValue The value to return, if the global property is unset. * @return The value of the global property, or NULL in the case of an error. This * string must be freed by OrthancPluginFreeString(). * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginGetGlobalProperty( OrthancPluginContext* context, int32_t property, const char* defaultValue) { char* result; _OrthancPluginGlobalProperty params; params.result = &result; params.property = property; params.value = defaultValue; if (context->InvokeService(context, _OrthancPluginService_GetGlobalProperty, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Set the value of a global property. * * Set the value of a global property into the Orthanc * database. Setting a global property can be used by plugins to * save their internal parameters. Plugins are only allowed to set * properties whose index are above or equal to 1024 (properties * below 1024 are read-only and reserved by Orthanc). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param property The global property of interest. * @param value The value to be set in the global property. * @return 0 if success, or the error code if failure. * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginSetGlobalProperty( OrthancPluginContext* context, int32_t property, const char* value) { _OrthancPluginGlobalProperty params; params.result = NULL; params.property = property; params.value = value; return context->InvokeService(context, _OrthancPluginService_SetGlobalProperty, ¶ms); } typedef struct { int32_t *resultInt32; uint32_t *resultUint32; int64_t *resultInt64; uint64_t *resultUint64; } _OrthancPluginReturnSingleValue; /** * @brief Get the number of command-line arguments. * * Retrieve the number of command-line arguments that were used to launch Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return The number of arguments. **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetCommandLineArgumentsCount( OrthancPluginContext* context) { uint32_t count = 0; _OrthancPluginReturnSingleValue params; memset(¶ms, 0, sizeof(params)); params.resultUint32 = &count; if (context->InvokeService(context, _OrthancPluginService_GetCommandLineArgumentsCount, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return 0; } else { return count; } } /** * @brief Get the value of a command-line argument. * * Get the value of one of the command-line arguments that were used * to launch Orthanc. The number of available arguments can be * retrieved by OrthancPluginGetCommandLineArgumentsCount(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param argument The index of the argument. * @return The value of the argument, or NULL in the case of an error. This * string must be freed by OrthancPluginFreeString(). **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginGetCommandLineArgument( OrthancPluginContext* context, uint32_t argument) { char* result; _OrthancPluginGlobalProperty params; params.result = &result; params.property = (int32_t) argument; params.value = NULL; if (context->InvokeService(context, _OrthancPluginService_GetCommandLineArgument, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Get the expected version of the database schema. * * Retrieve the expected version of the database schema. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return The version. * @ingroup Callbacks * @deprecated Please instead use IDatabaseBackend::UpgradeDatabase() **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetExpectedDatabaseVersion( OrthancPluginContext* context) { uint32_t count = 0; _OrthancPluginReturnSingleValue params; memset(¶ms, 0, sizeof(params)); params.resultUint32 = &count; if (context->InvokeService(context, _OrthancPluginService_GetExpectedDatabaseVersion, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return 0; } else { return count; } } /** * @brief Return the content of the configuration file(s). * * This function returns the content of the configuration that is * used by Orthanc, formatted as a JSON string. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return NULL in the case of an error, or a newly allocated string * containing the configuration. This string must be freed by * OrthancPluginFreeString(). **/ ORTHANC_PLUGIN_INLINE char *OrthancPluginGetConfiguration(OrthancPluginContext* context) { char* result; _OrthancPluginRetrieveDynamicString params; params.result = &result; params.argument = NULL; if (context->InvokeService(context, _OrthancPluginService_GetConfiguration, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginRestOutput* output; const char* subType; const char* contentType; } _OrthancPluginStartMultipartAnswer; /** * @brief Start an HTTP multipart answer. * * Initiates a HTTP multipart answer, as the result of a REST request. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param subType The sub-type of the multipart answer ("mixed" or "related"). * @param contentType The MIME type of the items in the multipart answer. * @return 0 if success, or the error code if failure. * @see OrthancPluginSendMultipartItem() * @ingroup REST **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginStartMultipartAnswer( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* subType, const char* contentType) { _OrthancPluginStartMultipartAnswer params; params.output = output; params.subType = subType; params.contentType = contentType; return context->InvokeService(context, _OrthancPluginService_StartMultipartAnswer, ¶ms); } /** * @brief Send an item as a part of some HTTP multipart answer. * * This function sends an item as a part of some HTTP multipart * answer that was initiated by OrthancPluginStartMultipartAnswer(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param answer Pointer to the memory buffer containing the item. * @param answerSize Number of bytes of the item. * @return 0 if success, or the error code if failure (this notably happens * if the connection is closed by the client). * @ingroup REST **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginSendMultipartItem( OrthancPluginContext* context, OrthancPluginRestOutput* output, const char* answer, uint32_t answerSize) { _OrthancPluginAnswerBuffer params; params.output = output; params.answer = answer; params.answerSize = answerSize; params.mimeType = NULL; return context->InvokeService(context, _OrthancPluginService_SendMultipartItem, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; const void* source; uint32_t size; OrthancPluginCompressionType compression; uint8_t uncompress; } _OrthancPluginBufferCompression; /** * @brief Compress or decompress a buffer. * * This function compresses or decompresses a buffer, using the * version of the zlib library that is used by the Orthanc core. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param source The source buffer. * @param size The size in bytes of the source buffer. * @param compression The compression algorithm. * @param uncompress If set to "0", the buffer must be compressed. * If set to "1", the buffer must be uncompressed. * @return 0 if success, or the error code if failure. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginBufferCompression( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const void* source, uint32_t size, OrthancPluginCompressionType compression, uint8_t uncompress) { _OrthancPluginBufferCompression params; params.target = target; params.source = source; params.size = size; params.compression = compression; params.uncompress = uncompress; return context->InvokeService(context, _OrthancPluginService_BufferCompression, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; const char* path; } _OrthancPluginReadFile; /** * @brief Read a file. * * Read the content of a file on the filesystem, and returns it into * a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param path The path of the file to be read. * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginReadFile( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* path) { _OrthancPluginReadFile params; params.target = target; params.path = path; return context->InvokeService(context, _OrthancPluginService_ReadFile, ¶ms); } typedef struct { const char* path; const void* data; uint32_t size; } _OrthancPluginWriteFile; /** * @brief Write a file. * * Write the content of a memory buffer to the filesystem. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param path The path of the file to be written. * @param data The content of the memory buffer. * @param size The size of the memory buffer. * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginWriteFile( OrthancPluginContext* context, const char* path, const void* data, uint32_t size) { _OrthancPluginWriteFile params; params.path = path; params.data = data; params.size = size; return context->InvokeService(context, _OrthancPluginService_WriteFile, ¶ms); } typedef struct { const char** target; OrthancPluginErrorCode error; } _OrthancPluginGetErrorDescription; /** * @brief Get the description of a given error code. * * This function returns the description of a given error code. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param error The error code of interest. * @return The error description. This is a statically-allocated * string, do not free it. **/ ORTHANC_PLUGIN_INLINE const char* OrthancPluginGetErrorDescription( OrthancPluginContext* context, OrthancPluginErrorCode error) { const char* result = NULL; _OrthancPluginGetErrorDescription params; params.target = &result; params.error = error; if (context->InvokeService(context, _OrthancPluginService_GetErrorDescription, ¶ms) != OrthancPluginErrorCode_Success || result == NULL) { return "Unknown error code"; } else { return result; } } typedef struct { OrthancPluginRestOutput* output; uint16_t status; const char* body; uint32_t bodySize; } _OrthancPluginSendHttpStatus; /** * @brief Send a HTTP status, with a custom body. * * This function answers to a HTTP request by sending a HTTP status * code (such as "400 - Bad Request"), together with a body * describing the error. The body will only be returned if the * configuration option "HttpDescribeErrors" of Orthanc is set to "true". * * Note that: * - Successful requests (status 200) must use ::OrthancPluginAnswerBuffer(). * - Redirections (status 301) must use ::OrthancPluginRedirect(). * - Unauthorized access (status 401) must use ::OrthancPluginSendUnauthorized(). * - Methods not allowed (status 405) must use ::OrthancPluginSendMethodNotAllowed(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param status The HTTP status code to be sent. * @param body The body of the answer. * @param bodySize The size of the body. * @see OrthancPluginSendHttpStatusCode() * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginSendHttpStatus( OrthancPluginContext* context, OrthancPluginRestOutput* output, uint16_t status, const char* body, uint32_t bodySize) { _OrthancPluginSendHttpStatus params; params.output = output; params.status = status; params.body = body; params.bodySize = bodySize; context->InvokeService(context, _OrthancPluginService_SendHttpStatus, ¶ms); } typedef struct { const OrthancPluginImage* image; uint32_t* resultUint32; OrthancPluginPixelFormat* resultPixelFormat; void** resultBuffer; } _OrthancPluginGetImageInfo; /** * @brief Return the pixel format of an image. * * This function returns the type of memory layout for the pixels of the given image. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image of interest. * @return The pixel format. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginPixelFormat OrthancPluginGetImagePixelFormat( OrthancPluginContext* context, const OrthancPluginImage* image) { OrthancPluginPixelFormat target; _OrthancPluginGetImageInfo params; memset(¶ms, 0, sizeof(params)); params.image = image; params.resultPixelFormat = ⌖ if (context->InvokeService(context, _OrthancPluginService_GetImagePixelFormat, ¶ms) != OrthancPluginErrorCode_Success) { return OrthancPluginPixelFormat_Unknown; } else { return (OrthancPluginPixelFormat) target; } } /** * @brief Return the width of an image. * * This function returns the width of the given image. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image of interest. * @return The width. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetImageWidth( OrthancPluginContext* context, const OrthancPluginImage* image) { uint32_t width; _OrthancPluginGetImageInfo params; memset(¶ms, 0, sizeof(params)); params.image = image; params.resultUint32 = &width; if (context->InvokeService(context, _OrthancPluginService_GetImageWidth, ¶ms) != OrthancPluginErrorCode_Success) { return 0; } else { return width; } } /** * @brief Return the height of an image. * * This function returns the height of the given image. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image of interest. * @return The height. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetImageHeight( OrthancPluginContext* context, const OrthancPluginImage* image) { uint32_t height; _OrthancPluginGetImageInfo params; memset(¶ms, 0, sizeof(params)); params.image = image; params.resultUint32 = &height; if (context->InvokeService(context, _OrthancPluginService_GetImageHeight, ¶ms) != OrthancPluginErrorCode_Success) { return 0; } else { return height; } } /** * @brief Return the pitch of an image. * * This function returns the pitch of the given image. The pitch is * defined as the number of bytes between 2 successive lines of the * image in the memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image of interest. * @return The pitch. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetImagePitch( OrthancPluginContext* context, const OrthancPluginImage* image) { uint32_t pitch; _OrthancPluginGetImageInfo params; memset(¶ms, 0, sizeof(params)); params.image = image; params.resultUint32 = &pitch; if (context->InvokeService(context, _OrthancPluginService_GetImagePitch, ¶ms) != OrthancPluginErrorCode_Success) { return 0; } else { return pitch; } } /** * @brief Return a pointer to the content of an image. * * This function returns a pointer to the memory buffer that * contains the pixels of the image. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image of interest. * @return The pointer. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE void* OrthancPluginGetImageBuffer( OrthancPluginContext* context, const OrthancPluginImage* image) { void* target = NULL; _OrthancPluginGetImageInfo params; memset(¶ms, 0, sizeof(params)); params.resultBuffer = ⌖ params.image = image; if (context->InvokeService(context, _OrthancPluginService_GetImageBuffer, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } typedef struct { OrthancPluginImage** target; const void* data; uint32_t size; OrthancPluginImageFormat format; } _OrthancPluginUncompressImage; /** * @brief Decode a compressed image. * * This function decodes a compressed image from a memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param data Pointer to a memory buffer containing the compressed image. * @param size Size of the memory buffer containing the compressed image. * @param format The file format of the compressed image. * @return The uncompressed image. It must be freed with OrthancPluginFreeImage(). * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginImage *OrthancPluginUncompressImage( OrthancPluginContext* context, const void* data, uint32_t size, OrthancPluginImageFormat format) { OrthancPluginImage* target = NULL; _OrthancPluginUncompressImage params; memset(¶ms, 0, sizeof(params)); params.target = ⌖ params.data = data; params.size = size; params.format = format; if (context->InvokeService(context, _OrthancPluginService_UncompressImage, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } typedef struct { OrthancPluginImage* image; } _OrthancPluginFreeImage; /** * @brief Free an image. * * This function frees an image that was decoded with OrthancPluginUncompressImage(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE void OrthancPluginFreeImage( OrthancPluginContext* context, OrthancPluginImage* image) { _OrthancPluginFreeImage params; params.image = image; context->InvokeService(context, _OrthancPluginService_FreeImage, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; OrthancPluginImageFormat imageFormat; OrthancPluginPixelFormat pixelFormat; uint32_t width; uint32_t height; uint32_t pitch; const void* buffer; uint8_t quality; } _OrthancPluginCompressImage; /** * @brief Encode a PNG image. * * This function compresses the given memory buffer containing an * image using the PNG specification, and stores the result of the * compression into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param format The memory layout of the uncompressed image. * @param width The width of the image. * @param height The height of the image. * @param pitch The pitch of the image (i.e. the number of bytes * between 2 successive lines of the image in the memory buffer). * @param buffer The memory buffer containing the uncompressed image. * @return 0 if success, or the error code if failure. * @see OrthancPluginCompressAndAnswerPngImage() * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginCompressPngImage( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, OrthancPluginPixelFormat format, uint32_t width, uint32_t height, uint32_t pitch, const void* buffer) { _OrthancPluginCompressImage params; memset(¶ms, 0, sizeof(params)); params.target = target; params.imageFormat = OrthancPluginImageFormat_Png; params.pixelFormat = format; params.width = width; params.height = height; params.pitch = pitch; params.buffer = buffer; params.quality = 0; /* Unused for PNG */ return context->InvokeService(context, _OrthancPluginService_CompressImage, ¶ms); } /** * @brief Encode a JPEG image. * * This function compresses the given memory buffer containing an * image using the JPEG specification, and stores the result of the * compression into a newly allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param format The memory layout of the uncompressed image. * @param width The width of the image. * @param height The height of the image. * @param pitch The pitch of the image (i.e. the number of bytes * between 2 successive lines of the image in the memory buffer). * @param buffer The memory buffer containing the uncompressed image. * @param quality The quality of the JPEG encoding, between 1 (worst * quality, best compression) and 100 (best quality, worst * compression). * @return 0 if success, or the error code if failure. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginCompressJpegImage( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, OrthancPluginPixelFormat format, uint32_t width, uint32_t height, uint32_t pitch, const void* buffer, uint8_t quality) { _OrthancPluginCompressImage params; memset(¶ms, 0, sizeof(params)); params.target = target; params.imageFormat = OrthancPluginImageFormat_Jpeg; params.pixelFormat = format; params.width = width; params.height = height; params.pitch = pitch; params.buffer = buffer; params.quality = quality; return context->InvokeService(context, _OrthancPluginService_CompressImage, ¶ms); } /** * @brief Answer to a REST request with a JPEG image. * * This function answers to a REST request with a JPEG image. The * parameters of this function describe a memory buffer that * contains an uncompressed image. The image will be automatically compressed * as a JPEG image by the core system of Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param output The HTTP connection to the client application. * @param format The memory layout of the uncompressed image. * @param width The width of the image. * @param height The height of the image. * @param pitch The pitch of the image (i.e. the number of bytes * between 2 successive lines of the image in the memory buffer). * @param buffer The memory buffer containing the uncompressed image. * @param quality The quality of the JPEG encoding, between 1 (worst * quality, best compression) and 100 (best quality, worst * compression). * @ingroup REST **/ ORTHANC_PLUGIN_INLINE void OrthancPluginCompressAndAnswerJpegImage( OrthancPluginContext* context, OrthancPluginRestOutput* output, OrthancPluginPixelFormat format, uint32_t width, uint32_t height, uint32_t pitch, const void* buffer, uint8_t quality) { _OrthancPluginCompressAndAnswerImage params; params.output = output; params.imageFormat = OrthancPluginImageFormat_Jpeg; params.pixelFormat = format; params.width = width; params.height = height; params.pitch = pitch; params.buffer = buffer; params.quality = quality; context->InvokeService(context, _OrthancPluginService_CompressAndAnswerImage, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; OrthancPluginHttpMethod method; const char* url; const char* username; const char* password; const char* body; uint32_t bodySize; } _OrthancPluginCallHttpClient; /** * @brief Issue a HTTP GET call. * * Make a HTTP GET call to the given URL. The result to the query is * stored into a newly allocated memory buffer. Favor * OrthancPluginRestApiGet() if calling the built-in REST API of the * Orthanc instance that hosts this plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param url The URL of interest. * @param username The username (can be NULL if no password protection). * @param password The password (can be NULL if no password protection). * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginHttpGet( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* url, const char* username, const char* password) { _OrthancPluginCallHttpClient params; memset(¶ms, 0, sizeof(params)); params.target = target; params.method = OrthancPluginHttpMethod_Get; params.url = url; params.username = username; params.password = password; return context->InvokeService(context, _OrthancPluginService_CallHttpClient, ¶ms); } /** * @brief Issue a HTTP POST call. * * Make a HTTP POST call to the given URL. The result to the query * is stored into a newly allocated memory buffer. Favor * OrthancPluginRestApiPost() if calling the built-in REST API of * the Orthanc instance that hosts this plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param url The URL of interest. * @param body The content of the body of the request. * @param bodySize The size of the body of the request. * @param username The username (can be NULL if no password protection). * @param password The password (can be NULL if no password protection). * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginHttpPost( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* url, const char* body, uint32_t bodySize, const char* username, const char* password) { _OrthancPluginCallHttpClient params; memset(¶ms, 0, sizeof(params)); params.target = target; params.method = OrthancPluginHttpMethod_Post; params.url = url; params.body = body; params.bodySize = bodySize; params.username = username; params.password = password; return context->InvokeService(context, _OrthancPluginService_CallHttpClient, ¶ms); } /** * @brief Issue a HTTP PUT call. * * Make a HTTP PUT call to the given URL. The result to the query is * stored into a newly allocated memory buffer. Favor * OrthancPluginRestApiPut() if calling the built-in REST API of the * Orthanc instance that hosts this plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param url The URL of interest. * @param body The content of the body of the request. * @param bodySize The size of the body of the request. * @param username The username (can be NULL if no password protection). * @param password The password (can be NULL if no password protection). * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginHttpPut( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* url, const char* body, uint32_t bodySize, const char* username, const char* password) { _OrthancPluginCallHttpClient params; memset(¶ms, 0, sizeof(params)); params.target = target; params.method = OrthancPluginHttpMethod_Put; params.url = url; params.body = body; params.bodySize = bodySize; params.username = username; params.password = password; return context->InvokeService(context, _OrthancPluginService_CallHttpClient, ¶ms); } /** * @brief Issue a HTTP DELETE call. * * Make a HTTP DELETE call to the given URL. Favor * OrthancPluginRestApiDelete() if calling the built-in REST API of * the Orthanc instance that hosts this plugin. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param url The URL of interest. * @param username The username (can be NULL if no password protection). * @param password The password (can be NULL if no password protection). * @return 0 if success, or the error code if failure. **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginHttpDelete( OrthancPluginContext* context, const char* url, const char* username, const char* password) { _OrthancPluginCallHttpClient params; memset(¶ms, 0, sizeof(params)); params.method = OrthancPluginHttpMethod_Delete; params.url = url; params.username = username; params.password = password; return context->InvokeService(context, _OrthancPluginService_CallHttpClient, ¶ms); } typedef struct { OrthancPluginImage** target; const OrthancPluginImage* source; OrthancPluginPixelFormat targetFormat; } _OrthancPluginConvertPixelFormat; /** * @brief Change the pixel format of an image. * * This function creates a new image, changing the memory layout of the pixels. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param source The source image. * @param targetFormat The target pixel format. * @return The resulting image. It must be freed with OrthancPluginFreeImage(). * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginImage *OrthancPluginConvertPixelFormat( OrthancPluginContext* context, const OrthancPluginImage* source, OrthancPluginPixelFormat targetFormat) { OrthancPluginImage* target = NULL; _OrthancPluginConvertPixelFormat params; params.target = ⌖ params.source = source; params.targetFormat = targetFormat; if (context->InvokeService(context, _OrthancPluginService_ConvertPixelFormat, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } /** * @brief Return the number of available fonts. * * This function returns the number of fonts that are built in the * Orthanc core. These fonts can be used to draw texts on images * through OrthancPluginDrawText(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @return The number of fonts. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetFontsCount( OrthancPluginContext* context) { uint32_t count = 0; _OrthancPluginReturnSingleValue params; memset(¶ms, 0, sizeof(params)); params.resultUint32 = &count; if (context->InvokeService(context, _OrthancPluginService_GetFontsCount, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return 0; } else { return count; } } typedef struct { uint32_t fontIndex; /* in */ const char** name; /* out */ uint32_t* size; /* out */ } _OrthancPluginGetFontInfo; /** * @brief Return the name of a font. * * This function returns the name of a font that is built in the Orthanc core. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param fontIndex The index of the font. This value must be less than OrthancPluginGetFontsCount(). * @return The font name. This is a statically-allocated string, do not free it. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE const char* OrthancPluginGetFontName( OrthancPluginContext* context, uint32_t fontIndex) { const char* result = NULL; _OrthancPluginGetFontInfo params; memset(¶ms, 0, sizeof(params)); params.name = &result; params.fontIndex = fontIndex; if (context->InvokeService(context, _OrthancPluginService_GetFontInfo, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return result; } } /** * @brief Return the size of a font. * * This function returns the size of a font that is built in the Orthanc core. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param fontIndex The index of the font. This value must be less than OrthancPluginGetFontsCount(). * @return The font size. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE uint32_t OrthancPluginGetFontSize( OrthancPluginContext* context, uint32_t fontIndex) { uint32_t result; _OrthancPluginGetFontInfo params; memset(¶ms, 0, sizeof(params)); params.size = &result; params.fontIndex = fontIndex; if (context->InvokeService(context, _OrthancPluginService_GetFontInfo, ¶ms) != OrthancPluginErrorCode_Success) { return 0; } else { return result; } } typedef struct { OrthancPluginImage* image; uint32_t fontIndex; const char* utf8Text; int32_t x; int32_t y; uint8_t r; uint8_t g; uint8_t b; } _OrthancPluginDrawText; /** * @brief Draw text on an image. * * This function draws some text on some image. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param image The image upon which to draw the text. * @param fontIndex The index of the font. This value must be less than OrthancPluginGetFontsCount(). * @param utf8Text The text to be drawn, encoded as an UTF-8 zero-terminated string. * @param x The X position of the text over the image. * @param y The Y position of the text over the image. * @param r The value of the red color channel of the text. * @param g The value of the green color channel of the text. * @param b The value of the blue color channel of the text. * @return 0 if success, other value if error. * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginDrawText( OrthancPluginContext* context, OrthancPluginImage* image, uint32_t fontIndex, const char* utf8Text, int32_t x, int32_t y, uint8_t r, uint8_t g, uint8_t b) { _OrthancPluginDrawText params; memset(¶ms, 0, sizeof(params)); params.image = image; params.fontIndex = fontIndex; params.utf8Text = utf8Text; params.x = x; params.y = y; params.r = r; params.g = g; params.b = b; return context->InvokeService(context, _OrthancPluginService_DrawText, ¶ms); } typedef struct { OrthancPluginStorageArea* storageArea; const char* uuid; const void* content; uint64_t size; OrthancPluginContentType type; } _OrthancPluginStorageAreaCreate; /** * @brief Create a file inside the storage area. * * This function creates a new file inside the storage area that is * currently used by Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param storageArea The storage area. * @param uuid The identifier of the file to be created. * @param content The content to store in the newly created file. * @param size The size of the content. * @param type The type of the file content. * @return 0 if success, other value if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginStorageAreaCreate( OrthancPluginContext* context, OrthancPluginStorageArea* storageArea, const char* uuid, const void* content, uint64_t size, OrthancPluginContentType type) { _OrthancPluginStorageAreaCreate params; params.storageArea = storageArea; params.uuid = uuid; params.content = content; params.size = size; params.type = type; return context->InvokeService(context, _OrthancPluginService_StorageAreaCreate, ¶ms); } typedef struct { OrthancPluginMemoryBuffer* target; OrthancPluginStorageArea* storageArea; const char* uuid; OrthancPluginContentType type; } _OrthancPluginStorageAreaRead; /** * @brief Read a file from the storage area. * * This function reads the content of a given file from the storage * area that is currently used by Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param storageArea The storage area. * @param uuid The identifier of the file to be read. * @param type The type of the file content. * @return 0 if success, other value if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginStorageAreaRead( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, OrthancPluginStorageArea* storageArea, const char* uuid, OrthancPluginContentType type) { _OrthancPluginStorageAreaRead params; params.target = target; params.storageArea = storageArea; params.uuid = uuid; params.type = type; return context->InvokeService(context, _OrthancPluginService_StorageAreaRead, ¶ms); } typedef struct { OrthancPluginStorageArea* storageArea; const char* uuid; OrthancPluginContentType type; } _OrthancPluginStorageAreaRemove; /** * @brief Remove a file from the storage area. * * This function removes a given file from the storage area that is * currently used by Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param storageArea The storage area. * @param uuid The identifier of the file to be removed. * @param type The type of the file content. * @return 0 if success, other value if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginStorageAreaRemove( OrthancPluginContext* context, OrthancPluginStorageArea* storageArea, const char* uuid, OrthancPluginContentType type) { _OrthancPluginStorageAreaRemove params; params.storageArea = storageArea; params.uuid = uuid; params.type = type; return context->InvokeService(context, _OrthancPluginService_StorageAreaRemove, ¶ms); } typedef struct { OrthancPluginErrorCode* target; int32_t code; uint16_t httpStatus; const char* message; } _OrthancPluginRegisterErrorCode; /** * @brief Declare a custom error code for this plugin. * * This function declares a custom error code that can be generated * by this plugin. This declaration is used to enrich the body of * the HTTP answer in the case of an error, and to set the proper * HTTP status code. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param code The error code that is internal to this plugin. * @param httpStatus The HTTP status corresponding to this error. * @param message The description of the error. * @return The error code that has been assigned inside the Orthanc core. * @ingroup Toolbox **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRegisterErrorCode( OrthancPluginContext* context, int32_t code, uint16_t httpStatus, const char* message) { OrthancPluginErrorCode target; _OrthancPluginRegisterErrorCode params; params.target = ⌖ params.code = code; params.httpStatus = httpStatus; params.message = message; if (context->InvokeService(context, _OrthancPluginService_RegisterErrorCode, ¶ms) == OrthancPluginErrorCode_Success) { return target; } else { /* There was an error while assigned the error. Use a generic code. */ return OrthancPluginErrorCode_Plugin; } } typedef struct { uint16_t group; uint16_t element; OrthancPluginValueRepresentation vr; const char* name; uint32_t minMultiplicity; uint32_t maxMultiplicity; } _OrthancPluginRegisterDictionaryTag; /** * @brief Register a new tag into the DICOM dictionary. * * This function declares a new tag in the dictionary of DICOM tags * that are known to Orthanc. This function should be used in the * OrthancPluginInitialize() callback. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param group The group of the tag. * @param element The element of the tag. * @param vr The value representation of the tag. * @param name The nickname of the tag. * @param minMultiplicity The minimum multiplicity of the tag (must be above 0). * @param maxMultiplicity The maximum multiplicity of the tag. A value of 0 means * an arbitrary multiplicity ("n"). * @return 0 if success, other value if error. * @ingroup Toolbox **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRegisterDictionaryTag( OrthancPluginContext* context, uint16_t group, uint16_t element, OrthancPluginValueRepresentation vr, const char* name, uint32_t minMultiplicity, uint32_t maxMultiplicity) { _OrthancPluginRegisterDictionaryTag params; params.group = group; params.element = element; params.vr = vr; params.name = name; params.minMultiplicity = minMultiplicity; params.maxMultiplicity = maxMultiplicity; return context->InvokeService(context, _OrthancPluginService_RegisterDictionaryTag, ¶ms); } typedef struct { OrthancPluginStorageArea* storageArea; OrthancPluginResourceType level; } _OrthancPluginReconstructMainDicomTags; /** * @brief Reconstruct the main DICOM tags. * * This function requests the Orthanc core to reconstruct the main * DICOM tags of all the resources of the given type. This function * can only be used as a part of the upgrade of a custom database * back-end * (cf. OrthancPlugins::IDatabaseBackend::UpgradeDatabase). A * database transaction will be automatically setup. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param storageArea The storage area. * @param level The type of the resources of interest. * @return 0 if success, other value if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginReconstructMainDicomTags( OrthancPluginContext* context, OrthancPluginStorageArea* storageArea, OrthancPluginResourceType level) { _OrthancPluginReconstructMainDicomTags params; params.level = level; params.storageArea = storageArea; return context->InvokeService(context, _OrthancPluginService_ReconstructMainDicomTags, ¶ms); } typedef struct { char** result; const char* instanceId; const char* buffer; uint32_t size; OrthancPluginDicomToJsonFormat format; OrthancPluginDicomToJsonFlags flags; uint32_t maxStringLength; } _OrthancPluginDicomToJson; /** * @brief Format a DICOM memory buffer as a JSON string. * * This function takes as input a memory buffer containing a DICOM * file, and outputs a JSON string representing the tags of this * DICOM file. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param buffer The memory buffer containing the DICOM file. * @param size The size of the memory buffer. * @param format The output format. * @param flags Flags governing the output. * @param maxStringLength The maximum length of a field. Too long fields will * be output as "null". The 0 value means no maximum length. * @return The NULL value if the case of an error, or the JSON * string. This string must be freed by OrthancPluginFreeString(). * @ingroup Toolbox * @see OrthancPluginDicomInstanceToJson **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginDicomBufferToJson( OrthancPluginContext* context, const char* buffer, uint32_t size, OrthancPluginDicomToJsonFormat format, OrthancPluginDicomToJsonFlags flags, uint32_t maxStringLength) { char* result; _OrthancPluginDicomToJson params; memset(¶ms, 0, sizeof(params)); params.result = &result; params.buffer = buffer; params.size = size; params.format = format; params.flags = flags; params.maxStringLength = maxStringLength; if (context->InvokeService(context, _OrthancPluginService_DicomBufferToJson, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Format a DICOM instance as a JSON string. * * This function formats a DICOM instance that is stored in Orthanc, * and outputs a JSON string representing the tags of this DICOM * instance. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instanceId The Orthanc identifier of the instance. * @param format The output format. * @param flags Flags governing the output. * @param maxStringLength The maximum length of a field. Too long fields will * be output as "null". The 0 value means no maximum length. * @return The NULL value if the case of an error, or the JSON * string. This string must be freed by OrthancPluginFreeString(). * @ingroup Toolbox * @see OrthancPluginDicomInstanceToJson **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginDicomInstanceToJson( OrthancPluginContext* context, const char* instanceId, OrthancPluginDicomToJsonFormat format, OrthancPluginDicomToJsonFlags flags, uint32_t maxStringLength) { char* result; _OrthancPluginDicomToJson params; memset(¶ms, 0, sizeof(params)); params.result = &result; params.instanceId = instanceId; params.format = format; params.flags = flags; params.maxStringLength = maxStringLength; if (context->InvokeService(context, _OrthancPluginService_DicomInstanceToJson, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginMemoryBuffer* target; const char* uri; uint32_t headersCount; const char* const* headersKeys; const char* const* headersValues; int32_t afterPlugins; } _OrthancPluginRestApiGet2; /** * @brief Make a GET call to the Orthanc REST API, with custom HTTP headers. * * Make a GET call to the Orthanc REST API with extended * parameters. The result to the query is stored into a newly * allocated memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param uri The URI in the built-in Orthanc API. * @param headersCount The number of HTTP headers. * @param headersKeys Array containing the keys of the HTTP headers. * @param headersValues Array containing the values of the HTTP headers. * @param afterPlugins If 0, the built-in API of Orthanc is used. * If 1, the API is tainted by the plugins. * @return 0 if success, or the error code if failure. * @see OrthancPluginRestApiGet, OrthancPluginRestApiGetAfterPlugins * @ingroup Orthanc **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRestApiGet2( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* uri, uint32_t headersCount, const char* const* headersKeys, const char* const* headersValues, int32_t afterPlugins) { _OrthancPluginRestApiGet2 params; params.target = target; params.uri = uri; params.headersCount = headersCount; params.headersKeys = headersKeys; params.headersValues = headersValues; params.afterPlugins = afterPlugins; return context->InvokeService(context, _OrthancPluginService_RestApiGet2, ¶ms); } typedef struct { OrthancPluginWorklistCallback callback; } _OrthancPluginWorklistCallback; /** * @brief Register a callback to handle modality worklists requests. * * This function registers a callback to handle C-Find SCP requests * on modality worklists. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param callback The callback. * @return 0 if success, other value if error. * @ingroup Worklists **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRegisterWorklistCallback( OrthancPluginContext* context, OrthancPluginWorklistCallback callback) { _OrthancPluginWorklistCallback params; params.callback = callback; return context->InvokeService(context, _OrthancPluginService_RegisterWorklistCallback, ¶ms); } typedef struct { OrthancPluginWorklistAnswers* answers; const OrthancPluginWorklistQuery* query; const void* dicom; uint32_t size; } _OrthancPluginWorklistAnswersOperation; /** * @brief Add one answer to some modality worklist request. * * This function adds one worklist (encoded as a DICOM file) to the * set of answers corresponding to some C-Find SCP request against * modality worklists. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param answers The set of answers. * @param query The worklist query, as received by the callback. * @param dicom The worklist to answer, encoded as a DICOM file. * @param size The size of the DICOM file. * @return 0 if success, other value if error. * @ingroup Worklists **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginWorklistAddAnswer( OrthancPluginContext* context, OrthancPluginWorklistAnswers* answers, const OrthancPluginWorklistQuery* query, const void* dicom, uint32_t size) { _OrthancPluginWorklistAnswersOperation params; params.answers = answers; params.query = query; params.dicom = dicom; params.size = size; return context->InvokeService(context, _OrthancPluginService_WorklistAddAnswer, ¶ms); } /** * @brief Mark the set of worklist answers as incomplete. * * This function marks as incomplete the set of answers * corresponding to some C-Find SCP request against modality * worklists. This must be used if canceling the handling of a * request when too many answers are to be returned. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param answers The set of answers. * @return 0 if success, other value if error. * @ingroup Worklists **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginWorklistMarkIncomplete( OrthancPluginContext* context, OrthancPluginWorklistAnswers* answers) { _OrthancPluginWorklistAnswersOperation params; params.answers = answers; params.query = NULL; params.dicom = NULL; params.size = 0; return context->InvokeService(context, _OrthancPluginService_WorklistMarkIncomplete, ¶ms); } typedef struct { const OrthancPluginWorklistQuery* query; const void* dicom; uint32_t size; int32_t* isMatch; OrthancPluginMemoryBuffer* target; } _OrthancPluginWorklistQueryOperation; /** * @brief Test whether a worklist matches the query. * * This function checks whether one worklist (encoded as a DICOM * file) matches the C-Find SCP query against modality * worklists. This function must be called before adding the * worklist as an answer through OrthancPluginWorklistAddAnswer(). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param query The worklist query, as received by the callback. * @param dicom The worklist to answer, encoded as a DICOM file. * @param size The size of the DICOM file. * @return 1 if the worklist matches the query, 0 otherwise. * @ingroup Worklists **/ ORTHANC_PLUGIN_INLINE int32_t OrthancPluginWorklistIsMatch( OrthancPluginContext* context, const OrthancPluginWorklistQuery* query, const void* dicom, uint32_t size) { int32_t isMatch = 0; _OrthancPluginWorklistQueryOperation params; params.query = query; params.dicom = dicom; params.size = size; params.isMatch = &isMatch; params.target = NULL; if (context->InvokeService(context, _OrthancPluginService_WorklistIsMatch, ¶ms) == OrthancPluginErrorCode_Success) { return isMatch; } else { /* Error: Assume non-match */ return 0; } } /** * @brief Retrieve the worklist query as a DICOM file. * * This function retrieves the DICOM file that underlies a C-Find * SCP query against modality worklists. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target Memory buffer where to store the DICOM file. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param query The worklist query, as received by the callback. * @return 0 if success, other value if error. * @ingroup Worklists **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginWorklistGetDicomQuery( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const OrthancPluginWorklistQuery* query) { _OrthancPluginWorklistQueryOperation params; params.query = query; params.dicom = NULL; params.size = 0; params.isMatch = NULL; params.target = target; return context->InvokeService(context, _OrthancPluginService_WorklistGetDicomQuery, ¶ms); } /** * @brief Get the origin of a DICOM file. * * This function returns the origin of a DICOM instance that has been received by Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param instance The instance of interest. * @return The origin of the instance. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginInstanceOrigin OrthancPluginGetInstanceOrigin( OrthancPluginContext* context, OrthancPluginDicomInstance* instance) { OrthancPluginInstanceOrigin origin; _OrthancPluginAccessDicomInstance params; memset(¶ms, 0, sizeof(params)); params.resultOrigin = &origin; params.instance = instance; if (context->InvokeService(context, _OrthancPluginService_GetInstanceOrigin, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return OrthancPluginInstanceOrigin_Unknown; } else { return origin; } } typedef struct { OrthancPluginMemoryBuffer* target; const char* json; const OrthancPluginImage* pixelData; OrthancPluginCreateDicomFlags flags; } _OrthancPluginCreateDicom; /** * @brief Create a DICOM instance from a JSON string and an image. * * This function takes as input a string containing a JSON file * describing the content of a DICOM instance. As an output, it * writes the corresponding DICOM instance to a newly allocated * memory buffer. Additionally, an image to be encoded within the * DICOM instance can also be provided. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target The target memory buffer. It must be freed with OrthancPluginFreeMemoryBuffer(). * @param json The input JSON file. * @param pixelData The image. Can be NULL, if the pixel data is encoded inside the JSON with the data URI scheme. * @param flags Flags governing the output. * @return 0 if success, other value if error. * @ingroup Toolbox * @see OrthancPluginDicomBufferToJson **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginCreateDicom( OrthancPluginContext* context, OrthancPluginMemoryBuffer* target, const char* json, const OrthancPluginImage* pixelData, OrthancPluginCreateDicomFlags flags) { _OrthancPluginCreateDicom params; params.target = target; params.json = json; params.pixelData = pixelData; params.flags = flags; return context->InvokeService(context, _OrthancPluginService_CreateDicom, ¶ms); } typedef struct { OrthancPluginDecodeImageCallback callback; } _OrthancPluginDecodeImageCallback; /** * @brief Register a callback to handle the decoding of DICOM images. * * This function registers a custom callback to the decoding of * DICOM images, replacing the built-in decoder of Orthanc. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param callback The callback. * @return 0 if success, other value if error. * @ingroup Callbacks **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginRegisterDecodeImageCallback( OrthancPluginContext* context, OrthancPluginDecodeImageCallback callback) { _OrthancPluginDecodeImageCallback params; params.callback = callback; return context->InvokeService(context, _OrthancPluginService_RegisterDecodeImageCallback, ¶ms); } typedef struct { OrthancPluginImage** target; OrthancPluginPixelFormat format; uint32_t width; uint32_t height; uint32_t pitch; void* buffer; const void* constBuffer; uint32_t bufferSize; uint32_t frameIndex; } _OrthancPluginCreateImage; /** * @brief Create an image. * * This function creates an image of given size and format. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param format The format of the pixels. * @param width The width of the image. * @param height The height of the image. * @return The newly allocated image. It must be freed with OrthancPluginFreeImage(). * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginImage* OrthancPluginCreateImage( OrthancPluginContext* context, OrthancPluginPixelFormat format, uint32_t width, uint32_t height) { OrthancPluginImage* target = NULL; _OrthancPluginCreateImage params; memset(¶ms, 0, sizeof(params)); params.target = ⌖ params.format = format; params.width = width; params.height = height; if (context->InvokeService(context, _OrthancPluginService_CreateImage, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } /** * @brief Create an image pointing to a memory buffer. * * This function creates an image whose content points to a memory * buffer managed by the plugin. Note that the buffer is directly * accessed, no memory is allocated and no data is copied. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param format The format of the pixels. * @param width The width of the image. * @param height The height of the image. * @param pitch The pitch of the image (i.e. the number of bytes * between 2 successive lines of the image in the memory buffer). * @param buffer The memory buffer. * @return The newly allocated image. It must be freed with OrthancPluginFreeImage(). * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginImage* OrthancPluginCreateImageAccessor( OrthancPluginContext* context, OrthancPluginPixelFormat format, uint32_t width, uint32_t height, uint32_t pitch, void* buffer) { OrthancPluginImage* target = NULL; _OrthancPluginCreateImage params; memset(¶ms, 0, sizeof(params)); params.target = ⌖ params.format = format; params.width = width; params.height = height; params.pitch = pitch; params.buffer = buffer; if (context->InvokeService(context, _OrthancPluginService_CreateImageAccessor, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } /** * @brief Decode one frame from a DICOM instance. * * This function decodes one frame of a DICOM image that is stored * in a memory buffer. This function will give the same result as * OrthancPluginUncompressImage() for single-frame DICOM images. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param buffer Pointer to a memory buffer containing the DICOM image. * @param bufferSize Size of the memory buffer containing the DICOM image. * @param frameIndex The index of the frame of interest in a multi-frame image. * @return The uncompressed image. It must be freed with OrthancPluginFreeImage(). * @ingroup Images **/ ORTHANC_PLUGIN_INLINE OrthancPluginImage* OrthancPluginDecodeDicomImage( OrthancPluginContext* context, const void* buffer, uint32_t bufferSize, uint32_t frameIndex) { OrthancPluginImage* target = NULL; _OrthancPluginCreateImage params; memset(¶ms, 0, sizeof(params)); params.target = ⌖ params.constBuffer = buffer; params.bufferSize = bufferSize; params.frameIndex = frameIndex; if (context->InvokeService(context, _OrthancPluginService_DecodeDicomImage, ¶ms) != OrthancPluginErrorCode_Success) { return NULL; } else { return target; } } typedef struct { char** result; const void* buffer; uint32_t size; } _OrthancPluginComputeHash; /** * @brief Compute an MD5 hash. * * This functions computes the MD5 cryptographic hash of the given memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param buffer The source memory buffer. * @param size The size in bytes of the source buffer. * @return The NULL value in case of error, or a string containing the cryptographic hash. * This string must be freed by OrthancPluginFreeString(). * @ingroup Toolbox **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginComputeMd5( OrthancPluginContext* context, const void* buffer, uint32_t size) { char* result; _OrthancPluginComputeHash params; params.result = &result; params.buffer = buffer; params.size = size; if (context->InvokeService(context, _OrthancPluginService_ComputeMd5, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } /** * @brief Compute a SHA-1 hash. * * This functions computes the SHA-1 cryptographic hash of the given memory buffer. * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param buffer The source memory buffer. * @param size The size in bytes of the source buffer. * @return The NULL value in case of error, or a string containing the cryptographic hash. * This string must be freed by OrthancPluginFreeString(). * @ingroup Toolbox **/ ORTHANC_PLUGIN_INLINE char* OrthancPluginComputeSha1( OrthancPluginContext* context, const void* buffer, uint32_t size) { char* result; _OrthancPluginComputeHash params; params.result = &result; params.buffer = buffer; params.size = size; if (context->InvokeService(context, _OrthancPluginService_ComputeSha1, ¶ms) != OrthancPluginErrorCode_Success) { /* Error */ return NULL; } else { return result; } } typedef struct { OrthancPluginDictionaryEntry* target; const char* name; } _OrthancPluginLookupDictionary; /** * @brief Get information about the given DICOM tag. * * This functions makes a lookup in the dictionary of DICOM tags * that are known to Orthanc, and returns information about this * tag. The tag can be specified using its human-readable name * (e.g. "PatientName") or a set of two hexadecimal numbers * (e.g. "0010-0020"). * * @param context The Orthanc plugin context, as received by OrthancPluginInitialize(). * @param target Where to store the information about the tag. * @param name The name of the DICOM tag. * @return 0 if success, other value if error. * @ingroup Toolbox **/ ORTHANC_PLUGIN_INLINE OrthancPluginErrorCode OrthancPluginLookupDictionary( OrthancPluginContext* context, OrthancPluginDictionaryEntry* target, const char* name) { _OrthancPluginLookupDictionary params; params.target = target; params.name = name; return context->InvokeService(context, _OrthancPluginService_LookupDictionary, ¶ms); } #ifdef __cplusplus } #endif /** @} */ OrthancWebViewer-2.3/Plugin/Cache/CacheIndex.h0000644000000000000000000000313613133653001017325 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "../../Orthanc/Core/IDynamicObject.h" #include namespace OrthancPlugins { class CacheIndex : public Orthanc::IDynamicObject { private: int bundle_; std::string item_; public: CacheIndex(const CacheIndex& other) : bundle_(other.bundle_), item_(other.item_) { } CacheIndex(int bundle, const std::string& item) : bundle_(bundle), item_(item) { } int GetBundle() const { return bundle_; } const std::string& GetItem() const { return item_; } bool operator== (const CacheIndex& other) const { return (bundle_ == other.bundle_ && item_ == other.item_); } }; } OrthancWebViewer-2.3/Plugin/Cache/CacheManager.cpp0000644000000000000000000003735113133653001020171 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "CacheManager.h" #include "../../Orthanc/Core/SystemToolbox.h" #include "../../Orthanc/Core/SQLite/Transaction.h" #include namespace OrthancPlugins { class CacheManager::Bundle { private: uint32_t count_; uint64_t space_; public: Bundle() : count_(0), space_(0) { } Bundle(uint32_t count, uint64_t space) : count_(count), space_(space) { } uint32_t GetCount() const { return count_; } uint64_t GetSpace() const { return space_; } void Remove(uint64_t fileSize) { if (count_ == 0 || space_ < fileSize) { throw std::runtime_error("Internal error"); } count_ -= 1; space_ -= fileSize; } void Add(uint64_t fileSize) { count_ += 1; space_ += fileSize; } }; class CacheManager::BundleQuota { private: uint32_t maxCount_; uint64_t maxSpace_; public: BundleQuota(uint32_t maxCount, uint64_t maxSpace) : maxCount_(maxCount), maxSpace_(maxSpace) { } BundleQuota() { // Default quota maxCount_ = 0; // No limit on the number of files maxSpace_ = 100 * 1024 * 1024; // Max 100MB per bundle } uint32_t GetMaxCount() const { return maxCount_; } uint64_t GetMaxSpace() const { return maxSpace_; } bool IsSatisfied(const Bundle& bundle) const { if (maxCount_ != 0 && bundle.GetCount() > maxCount_) { return false; } if (maxSpace_ != 0 && bundle.GetSpace() > maxSpace_) { return false; } return true; } }; struct CacheManager::PImpl { OrthancPluginContext* context_; Orthanc::SQLite::Connection& db_; Orthanc::FilesystemStorage& storage_; bool sanityCheck_; Bundles bundles_; BundleQuota defaultQuota_; BundleQuotas quotas_; PImpl(OrthancPluginContext* context, Orthanc::SQLite::Connection& db, Orthanc::FilesystemStorage& storage) : context_(context), db_(db), storage_(storage), sanityCheck_(false) { } }; const CacheManager::BundleQuota& CacheManager::GetBundleQuota(int bundleIndex) const { BundleQuotas::const_iterator found = pimpl_->quotas_.find(bundleIndex); if (found == pimpl_->quotas_.end()) { return pimpl_->defaultQuota_; } else { return found->second; } } CacheManager::Bundle CacheManager::GetBundle(int bundleIndex) const { Bundles::const_iterator it = pimpl_->bundles_.find(bundleIndex); if (it == pimpl_->bundles_.end()) { return Bundle(); } else { return it->second; } } void CacheManager::MakeRoom(Bundle& bundle, std::list& toRemove, int bundleIndex, const BundleQuota& quota) { using namespace Orthanc; toRemove.clear(); // Make room in the bundle while (!quota.IsSatisfied(bundle)) { SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? ORDER BY seq"); s.BindInt(0, bundleIndex); if (s.Step()) { SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?"); t.BindInt64(0, s.ColumnInt64(0)); t.Run(); toRemove.push_back(s.ColumnString(1)); bundle.Remove(s.ColumnInt64(2)); } else { // Should never happen throw std::runtime_error("Internal error"); } } } void CacheManager::EnsureQuota(int bundleIndex, const BundleQuota& quota) { using namespace Orthanc; // Remove the cached files that exceed the quota std::auto_ptr transaction(new SQLite::Transaction(pimpl_->db_)); transaction->Begin(); Bundle bundle = GetBundle(bundleIndex); std::list toRemove; MakeRoom(bundle, toRemove, bundleIndex, quota); transaction->Commit(); for (std::list::const_iterator it = toRemove.begin(); it != toRemove.end(); it++) { pimpl_->storage_.Remove(*it, Orthanc::FileContentType_Unknown); } pimpl_->bundles_[bundleIndex] = bundle; } void CacheManager::ReadBundleStatistics() { using namespace Orthanc; pimpl_->bundles_.clear(); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT bundle,COUNT(*),SUM(fileSize) FROM Cache GROUP BY bundle"); while (s.Step()) { int index = s.ColumnInt(0); Bundle bundle(static_cast(s.ColumnInt(1)), static_cast(s.ColumnInt64(2))); pimpl_->bundles_[index] = bundle; } } void CacheManager::SanityCheck() { if (!pimpl_->sanityCheck_) { return; } using namespace Orthanc; SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT bundle,COUNT(*),SUM(fileSize) FROM Cache GROUP BY bundle"); while (s.Step()) { const Bundle& bundle = GetBundle(s.ColumnInt(0)); if (bundle.GetCount() != static_cast(s.ColumnInt(1)) || bundle.GetSpace() != static_cast(s.ColumnInt64(2))) { throw std::runtime_error("SANITY ERROR in cache: " + boost::lexical_cast(bundle.GetCount()) + "/" + boost::lexical_cast(bundle.GetSpace()) + " vs " + boost::lexical_cast(s.ColumnInt(1)) + "/" + boost::lexical_cast(s.ColumnInt64(2))); } } } CacheManager::CacheManager(OrthancPluginContext* context, Orthanc::SQLite::Connection& db, Orthanc::FilesystemStorage& storage) : pimpl_(new PImpl(context, db, storage)) { Open(); ReadBundleStatistics(); } OrthancPluginContext* CacheManager::GetPluginContext() const { return pimpl_->context_; } void CacheManager::SetSanityCheckEnabled(bool enabled) { pimpl_->sanityCheck_ = enabled; } void CacheManager::Open() { if (!pimpl_->db_.DoesTableExist("Cache")) { pimpl_->db_.Execute("CREATE TABLE Cache(seq INTEGER PRIMARY KEY, bundle INTEGER, item TEXT, fileUuid TEXT, fileSize INT);"); pimpl_->db_.Execute("CREATE INDEX CacheBundles ON Cache(bundle);"); pimpl_->db_.Execute("CREATE INDEX CacheIndex ON Cache(bundle, item);"); } if (!pimpl_->db_.DoesTableExist("CacheProperties")) { pimpl_->db_.Execute("CREATE TABLE CacheProperties(property INTEGER PRIMARY KEY, value TEXT);"); } // Performance tuning of SQLite with PRAGMAs // http://www.sqlite.org/pragma.html pimpl_->db_.Execute("PRAGMA SYNCHRONOUS=OFF;"); pimpl_->db_.Execute("PRAGMA JOURNAL_MODE=WAL;"); pimpl_->db_.Execute("PRAGMA LOCKING_MODE=EXCLUSIVE;"); } void CacheManager::Store(int bundleIndex, const std::string& item, const std::string& content) { SanityCheck(); const BundleQuota quota = GetBundleQuota(bundleIndex); if (quota.GetMaxSpace() > 0 && content.size() > quota.GetMaxSpace()) { // Cannot store such a large instance into the cache, forget about it return; } using namespace Orthanc; std::auto_ptr transaction(new SQLite::Transaction(pimpl_->db_)); transaction->Begin(); Bundle bundle = GetBundle(bundleIndex); std::list toRemove; bundle.Add(content.size()); MakeRoom(bundle, toRemove, bundleIndex, quota); // Store the cached content on the disk const char* data = content.size() ? &content[0] : NULL; std::string uuid = SystemToolbox::GenerateUuid(); pimpl_->storage_.Create(uuid, data, content.size(), Orthanc::FileContentType_Unknown); bool ok = true; // Remove the previous cached value. This might happen if the same // item is accessed very quickly twice: Another factory could have // been cached a value before the check for existence in Access(). { SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?"); s.BindInt(0, bundleIndex); s.BindString(1, item); if (s.Step()) { SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?"); t.BindInt64(0, s.ColumnInt64(0)); t.Run(); toRemove.push_back(s.ColumnString(1)); bundle.Remove(s.ColumnInt64(2)); } } if (ok) { SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "INSERT INTO Cache VALUES(NULL, ?, ?, ?, ?)"); s.BindInt(0, bundleIndex); s.BindString(1, item); s.BindString(2, uuid); s.BindInt64(3, content.size()); if (!s.Run()) { ok = false; } } if (!ok) { // Error: Remove the stored file pimpl_->storage_.Remove(uuid, Orthanc::FileContentType_Unknown); } else { transaction->Commit(); pimpl_->bundles_[bundleIndex] = bundle; for (std::list::const_iterator it = toRemove.begin(); it != toRemove.end(); it++) { pimpl_->storage_.Remove(*it, Orthanc::FileContentType_Unknown); } } SanityCheck(); } bool CacheManager::LocateInCache(std::string& uuid, uint64_t& size, int bundle, const std::string& item) { using namespace Orthanc; SanityCheck(); std::auto_ptr transaction(new SQLite::Transaction(pimpl_->db_)); transaction->Begin(); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?"); s.BindInt(0, bundle); s.BindString(1, item); if (!s.Step()) { return false; } int64_t seq = s.ColumnInt64(0); uuid = s.ColumnString(1); size = s.ColumnInt64(2); // Touch the cache to fulfill the LRU scheme. SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?"); t.BindInt64(0, seq); if (t.Run()) { SQLite::Statement u(pimpl_->db_, SQLITE_FROM_HERE, "INSERT INTO Cache VALUES(NULL, ?, ?, ?, ?)"); u.BindInt(0, bundle); u.BindString(1, item); u.BindString(2, uuid); u.BindInt64(3, size); if (u.Run()) { // Everything was OK. Commit the changes to the cache. transaction->Commit(); return true; } } return false; } bool CacheManager::IsCached(int bundle, const std::string& item) { std::string uuid; uint64_t size; return LocateInCache(uuid, size, bundle, item); } bool CacheManager::Access(std::string& content, int bundle, const std::string& item) { std::string uuid; uint64_t size; if (!LocateInCache(uuid, size, bundle, item)) { return false; } bool ok; try { pimpl_->storage_.Read(content, uuid, Orthanc::FileContentType_Unknown); ok = (content.size() == size); } catch (std::runtime_error&) { ok = false; } if (ok) { return true; } else { throw std::runtime_error("Error in the filesystem"); } } void CacheManager::Invalidate(int bundleIndex, const std::string& item) { using namespace Orthanc; SanityCheck(); std::auto_ptr transaction(new SQLite::Transaction(pimpl_->db_)); transaction->Begin(); Bundle bundle = GetBundle(bundleIndex); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT seq, fileUuid, fileSize FROM Cache WHERE bundle=? AND item=?"); s.BindInt(0, bundleIndex); s.BindString(1, item); if (s.Step()) { int64_t seq = s.ColumnInt64(0); const std::string uuid = s.ColumnString(1); uint64_t expectedSize = s.ColumnInt64(2); bundle.Remove(expectedSize); SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE seq=?"); t.BindInt64(0, seq); if (t.Run()) { transaction->Commit(); pimpl_->bundles_[bundleIndex] = bundle; pimpl_->storage_.Remove(uuid, Orthanc::FileContentType_Unknown); } } } void CacheManager::SetBundleQuota(int bundle, uint32_t maxCount, uint64_t maxSpace) { SanityCheck(); const BundleQuota quota(maxCount, maxSpace); EnsureQuota(bundle, quota); pimpl_->quotas_[bundle] = quota; SanityCheck(); } void CacheManager::SetDefaultQuota(uint32_t maxCount, uint64_t maxSpace) { using namespace Orthanc; SanityCheck(); pimpl_->defaultQuota_ = BundleQuota(maxCount, maxSpace); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT DISTINCT bundle FROM Cache"); while (s.Step()) { EnsureQuota(s.ColumnInt(0), pimpl_->defaultQuota_); } SanityCheck(); } void CacheManager::Clear() { using namespace Orthanc; SanityCheck(); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT fileUuid FROM Cache"); while (s.Step()) { pimpl_->storage_.Remove(s.ColumnString(0), Orthanc::FileContentType_Unknown); } SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache"); t.Run(); ReadBundleStatistics(); SanityCheck(); } void CacheManager::Clear(int bundle) { using namespace Orthanc; SanityCheck(); SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT fileUuid FROM Cache WHERE bundle=?"); s.BindInt(0, bundle); while (s.Step()) { pimpl_->storage_.Remove(s.ColumnString(0), Orthanc::FileContentType_Unknown); } SQLite::Statement t(pimpl_->db_, SQLITE_FROM_HERE, "DELETE FROM Cache WHERE bundle=?"); t.BindInt(0, bundle); t.Run(); ReadBundleStatistics(); SanityCheck(); } void CacheManager::SetProperty(CacheProperty property, const std::string& value) { Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "INSERT OR REPLACE INTO CacheProperties VALUES(?, ?)"); s.BindInt(0, property); s.BindString(1, value); s.Run(); } bool CacheManager::LookupProperty(std::string& target, CacheProperty property) { Orthanc::SQLite::Statement s(pimpl_->db_, SQLITE_FROM_HERE, "SELECT value FROM CacheProperties WHERE property=?"); s.BindInt(0, property); if (!s.Step()) { return false; } else { target = s.ColumnString(0); return true; } } } OrthancWebViewer-2.3/Plugin/Cache/CacheManager.h0000644000000000000000000000612513133653001017631 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "../../Orthanc/Core/SQLite/Connection.h" #include "../../Orthanc/Core/FileStorage/FilesystemStorage.h" #include namespace OrthancPlugins { enum CacheProperty { CacheProperty_OrthancVersion, CacheProperty_WebViewerVersion }; class CacheManager : public boost::noncopyable { private: struct PImpl; boost::shared_ptr pimpl_; class Bundle; class BundleQuota; typedef std::map Bundles; typedef std::map BundleQuotas; const BundleQuota& GetBundleQuota(int bundleIndex) const; Bundle GetBundle(int bundleIndex) const; void MakeRoom(Bundle& bundle, std::list& toRemove, int bundleIndex, const BundleQuota& quota); void EnsureQuota(int bundleIndex, const BundleQuota& quota); void ReadBundleStatistics(); void Open(); bool LocateInCache(std::string& uuid, uint64_t& size, int bundle, const std::string& item); void SanityCheck(); // Only for debug public: CacheManager(OrthancPluginContext* context, Orthanc::SQLite::Connection& db, Orthanc::FilesystemStorage& storage); OrthancPluginContext* GetPluginContext() const; void SetSanityCheckEnabled(bool enabled); void Clear(); void Clear(int bundle); void SetBundleQuota(int bundle, uint32_t maxCount, uint64_t maxSpace); void SetDefaultQuota(uint32_t maxCount, uint64_t maxSpace); bool IsCached(int bundle, const std::string& item); bool Access(std::string& content, int bundle, const std::string& item); void Invalidate(int bundle, const std::string& item); void Store(int bundle, const std::string& item, const std::string& content); void SetProperty(CacheProperty property, const std::string& value); bool LookupProperty(std::string& target, CacheProperty property); }; } OrthancWebViewer-2.3/Plugin/Cache/CacheScheduler.cpp0000644000000000000000000002567213133653001020540 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "CacheScheduler.h" #include "CacheIndex.h" #include "../../Orthanc/Core/OrthancException.h" #include namespace OrthancPlugins { class DynamicString : public Orthanc::IDynamicObject { private: std::string value_; public: DynamicString(const std::string& value) : value_(value) { } const std::string& GetValue() const { return value_; } }; class CacheScheduler::PrefetchQueue : public boost::noncopyable { private: boost::mutex mutex_; Orthanc::SharedMessageQueue queue_; std::set content_; public: PrefetchQueue(size_t maxSize) : queue_(maxSize) { queue_.SetLifoPolicy(); } void Enqueue(const std::string& item) { boost::mutex::scoped_lock lock(mutex_); if (content_.find(item) != content_.end()) { // This cache index is already pending in the queue return; } content_.insert(item); queue_.Enqueue(new DynamicString(item)); } DynamicString* Dequeue(int32_t msTimeout) { std::auto_ptr message(queue_.Dequeue(msTimeout)); if (message.get() == NULL) { return NULL; } const DynamicString& index = dynamic_cast(*message); { boost::mutex::scoped_lock lock(mutex_); content_.erase(index.GetValue()); } return dynamic_cast(message.release()); } }; class CacheScheduler::Prefetcher : public boost::noncopyable { private: int bundleIndex_; ICacheFactory& factory_; CacheManager& cache_; boost::mutex& cacheMutex_; PrefetchQueue& queue_; bool done_; boost::thread thread_; boost::mutex invalidatedMutex_; bool invalidated_; std::string prefetching_; static void Worker(Prefetcher* that) { while (!(that->done_)) { std::auto_ptr prefetch(that->queue_.Dequeue(500)); try { if (prefetch.get() != NULL) { { boost::mutex::scoped_lock lock(that->invalidatedMutex_); that->invalidated_ = false; that->prefetching_ = prefetch->GetValue(); } { boost::mutex::scoped_lock lock(that->cacheMutex_); if (that->cache_.IsCached(that->bundleIndex_, prefetch->GetValue())) { // This item is already cached continue; } } std::string content; try { if (!that->factory_.Create(content, prefetch->GetValue())) { // The factory cannot generate this item continue; } } catch (...) { // Exception continue; } { boost::mutex::scoped_lock lock(that->invalidatedMutex_); if (that->invalidated_) { // This item has been invalidated continue; } { boost::mutex::scoped_lock lock2(that->cacheMutex_); that->cache_.Store(that->bundleIndex_, prefetch->GetValue(), content); } } } } catch (std::bad_alloc&) { OrthancPluginLogError(that->cache_.GetPluginContext(), "Not enough memory for the prefetcher of the Web viewer to work"); } catch (...) { OrthancPluginLogError(that->cache_.GetPluginContext(), "Unhandled native exception inside the prefetcher of the Web viewer"); } } } public: Prefetcher(int bundleIndex, ICacheFactory& factory, CacheManager& cache, boost::mutex& cacheMutex, PrefetchQueue& queue) : bundleIndex_(bundleIndex), factory_(factory), cache_(cache), cacheMutex_(cacheMutex), queue_(queue) { done_ = false; thread_ = boost::thread(Worker, this); } ~Prefetcher() { done_ = true; if (thread_.joinable()) { thread_.join(); } } void SignalInvalidated(const std::string& item) { boost::mutex::scoped_lock lock(invalidatedMutex_); if (prefetching_ == item) { invalidated_ = true; } } }; class CacheScheduler::BundleScheduler { private: std::auto_ptr factory_; PrefetchQueue queue_; std::vector prefetchers_; public: BundleScheduler(int bundleIndex, ICacheFactory* factory, CacheManager& cache, boost::mutex& cacheMutex, size_t numThreads, size_t queueSize) : factory_(factory), queue_(queueSize) { prefetchers_.resize(numThreads, NULL); for (size_t i = 0; i < numThreads; i++) { prefetchers_[i] = new Prefetcher(bundleIndex, *factory_, cache, cacheMutex, queue_); } } ~BundleScheduler() { for (size_t i = 0; i < prefetchers_.size(); i++) { if (prefetchers_[i] != NULL) delete prefetchers_[i]; } } void Invalidate(const std::string& item) { for (size_t i = 0; i < prefetchers_.size(); i++) { prefetchers_[i]->SignalInvalidated(item); } } void Prefetch(const std::string& item) { queue_.Enqueue(item); } bool CallFactory(std::string& content, const std::string& item) { content.clear(); return factory_->Create(content, item); } ICacheFactory& GetFactory() { return *factory_; } }; CacheScheduler::BundleScheduler& CacheScheduler::GetBundleScheduler(unsigned int bundleIndex) { boost::mutex::scoped_lock lock(factoryMutex_); BundleSchedulers::iterator it = bundles_.find(bundleIndex); if (it == bundles_.end()) { // No factory associated with this bundle throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); } return *(it->second); } CacheScheduler::CacheScheduler(CacheManager& cache, unsigned int maxPrefetchSize) : maxPrefetchSize_(maxPrefetchSize), cache_(cache), policy_(NULL) { } CacheScheduler::~CacheScheduler() { for (BundleSchedulers::iterator it = bundles_.begin(); it != bundles_.end(); it++) { delete it->second; } } void CacheScheduler::Register(int bundle, ICacheFactory* factory /* takes ownership */, size_t numThreads) { boost::mutex::scoped_lock lock(factoryMutex_); BundleSchedulers::iterator it = bundles_.find(bundle); if (it != bundles_.end()) { // This bundle is already registered throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); } bundles_[bundle] = new BundleScheduler(bundle, factory, cache_, cacheMutex_, numThreads, maxPrefetchSize_); } void CacheScheduler::SetQuota(int bundle, uint32_t maxCount, uint64_t maxSpace) { boost::mutex::scoped_lock lock(cacheMutex_); cache_.SetBundleQuota(bundle, maxCount, maxSpace); } void CacheScheduler::Invalidate(int bundle, const std::string& item) { { boost::mutex::scoped_lock lock(cacheMutex_); cache_.Invalidate(bundle, item); } GetBundleScheduler(bundle).Invalidate(item); } void CacheScheduler::ApplyPrefetchPolicy(int bundle, const std::string& item, const std::string& content) { boost::recursive_mutex::scoped_lock lock(policyMutex_); if (policy_.get() != NULL) { std::list toPrefetch; { policy_->Apply(toPrefetch, *this, CacheIndex(bundle, item), content); } for (std::list::const_reverse_iterator it = toPrefetch.rbegin(); it != toPrefetch.rend(); ++it) { Prefetch(it->GetBundle(), it->GetItem()); } } } bool CacheScheduler::Access(std::string& content, int bundle, const std::string& item) { bool existing; { boost::mutex::scoped_lock lock(cacheMutex_); existing = cache_.Access(content, bundle, item); } if (existing) { ApplyPrefetchPolicy(bundle, item, content); return true; } if (!GetBundleScheduler(bundle).CallFactory(content, item)) { // This item cannot be generated by the factory return false; } { boost::mutex::scoped_lock lock(cacheMutex_); cache_.Store(bundle, item, content); } ApplyPrefetchPolicy(bundle, item, content); return true; } void CacheScheduler::Prefetch(int bundle, const std::string& item) { GetBundleScheduler(bundle).Prefetch(item); } void CacheScheduler::RegisterPolicy(IPrefetchPolicy* policy) { boost::recursive_mutex::scoped_lock lock(policyMutex_); policy_.reset(policy); } ICacheFactory& CacheScheduler::GetFactory(int bundle) { return GetBundleScheduler(bundle).GetFactory(); } void CacheScheduler::SetProperty(CacheProperty property, const std::string& value) { boost::mutex::scoped_lock lock(cacheMutex_); cache_.SetProperty(property, value); } bool CacheScheduler::LookupProperty(std::string& target, CacheProperty property) { boost::mutex::scoped_lock lock(cacheMutex_); return cache_.LookupProperty(target, property); } void CacheScheduler::Clear() { boost::mutex::scoped_lock lock(cacheMutex_); return cache_.Clear(); } } OrthancWebViewer-2.3/Plugin/Cache/CacheScheduler.h0000644000000000000000000000543713133653001020202 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "CacheManager.h" #include "ICacheFactory.h" #include "IPrefetchPolicy.h" #include "../../Orthanc/Core/MultiThreading/SharedMessageQueue.h" #include #include namespace OrthancPlugins { class CacheScheduler : public boost::noncopyable { private: class Prefetcher; class PrefetchQueue; class BundleScheduler; typedef std::map BundleSchedulers; size_t maxPrefetchSize_; boost::mutex cacheMutex_; boost::mutex factoryMutex_; boost::recursive_mutex policyMutex_; CacheManager& cache_; std::auto_ptr policy_; BundleSchedulers bundles_; void ApplyPrefetchPolicy(int bundle, const std::string& item, const std::string& content); BundleScheduler& GetBundleScheduler(unsigned int bundleIndex); public: CacheScheduler(CacheManager& cache, unsigned int maxPrefetchSize); ~CacheScheduler(); void Register(int bundle, ICacheFactory* factory /* takes ownership */, size_t numThreads); void SetQuota(int bundle, uint32_t maxCount, uint64_t maxSpace); void RegisterPolicy(IPrefetchPolicy* policy /* takes ownership */); void Invalidate(int bundle, const std::string& item); bool Access(std::string& content, int bundle, const std::string& item); void Prefetch(int bundle, const std::string& item); ICacheFactory& GetFactory(int bundle); void SetProperty(CacheProperty property, const std::string& value); bool LookupProperty(std::string& target, CacheProperty property); void Clear(); }; } OrthancWebViewer-2.3/Plugin/Cache/ICacheFactory.h0000644000000000000000000000242513133653001017776 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include #include namespace OrthancPlugins { class ICacheFactory : public boost::noncopyable { public: virtual ~ICacheFactory() { } // WARNING: No mutual exclusion is enforced! Several threads could // call this method at the same time. virtual bool Create(std::string& content, const std::string& key) = 0; }; } OrthancWebViewer-2.3/Plugin/Cache/IPrefetchPolicy.h0000644000000000000000000000271013133653001020360 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "CacheIndex.h" #include #include namespace OrthancPlugins { class CacheScheduler; class IPrefetchPolicy : public boost::noncopyable { public: virtual ~IPrefetchPolicy() { } // Mutual exclusion is enforced when calling this method. // "toPrefetch" must be listed from top-priority to low-priority. virtual void Apply(std::list& toPrefetch, CacheScheduler& cache, const CacheIndex& index, const std::string& content) = 0; }; } OrthancWebViewer-2.3/Plugin/DecodedImageAdapter.cpp0000644000000000000000000003310413133653001020453 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "DecodedImageAdapter.h" #include "../Orthanc/Core/Images/ImageBuffer.h" #include "../Orthanc/Core/Images/ImageProcessing.h" #include "../Orthanc/Core/OrthancException.h" #include "../Orthanc/Core/Toolbox.h" #include "../Orthanc/Plugins/Samples/GdcmDecoder/OrthancImageWrapper.h" #include "../Orthanc/Resources/ThirdParty/base64/base64.h" #include "ViewerToolbox.h" #include #include #include #include namespace OrthancPlugins { static bool GetStringTag(std::string& value, const Json::Value& tags, const std::string& tag) { if (tags.type() == Json::objectValue && tags.isMember(tag) && tags[tag].type() == Json::objectValue && tags[tag].isMember("Type") && tags[tag].isMember("Value") && tags[tag]["Type"].type() == Json::stringValue && tags[tag]["Value"].type() == Json::stringValue && tags[tag]["Type"].asString() == "String") { value = tags[tag]["Value"].asString(); return true; } else { return false; } } static float GetFloatTag(const Json::Value& tags, const std::string& tag, float defaultValue) { std::string tmp; if (GetStringTag(tmp, tags, tag)) { try { return boost::lexical_cast(Orthanc::Toolbox::StripSpaces(tmp)); } catch (boost::bad_lexical_cast&) { } } return defaultValue; } bool DecodedImageAdapter::ParseUri(CompressionType& type, uint8_t& compressionLevel, std::string& instanceId, unsigned int& frameIndex, const std::string& uri) { boost::regex pattern("^([a-z0-9]+)-([a-z0-9-]+)_([0-9]+)$"); boost::cmatch what; if (!regex_match(uri.c_str(), what, pattern)) { return false; } std::string compression(what[1]); instanceId = what[2]; frameIndex = boost::lexical_cast(what[3]); if (compression == "deflate") { type = CompressionType_Deflate; } else if (boost::starts_with(compression, "jpeg")) { type = CompressionType_Jpeg; int level = boost::lexical_cast(compression.substr(4)); if (level <= 0 || level > 100) { return false; } compressionLevel = static_cast(level); } else { return false; } return true; } bool DecodedImageAdapter::Create(std::string& content, const std::string& uri) { std::string message = "Decoding DICOM instance: " + uri; OrthancPluginLogInfo(context_, message.c_str()); CompressionType type; uint8_t level; std::string instanceId; unsigned int frameIndex; if (!ParseUri(type, level, instanceId, frameIndex, uri)) { return false; } bool ok = false; Json::Value tags; std::string dicom; if (!GetStringFromOrthanc(dicom, context_, "/instances/" + instanceId + "/file") || !GetJsonFromOrthanc(tags, context_, "/instances/" + instanceId + "/tags")) { throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource); } std::auto_ptr image(new OrthancImageWrapper(context_, OrthancPluginDecodeDicomImage(context_, dicom.c_str(), dicom.size(), frameIndex))); Json::Value json; if (GetCornerstoneMetadata(json, tags, *image)) { if (type == CompressionType_Deflate) { ok = EncodeUsingDeflate(json, *image, 9); } else if (type == CompressionType_Jpeg) { ok = EncodeUsingJpeg(json, *image, level); } } if (ok) { std::string photometric; if (GetStringTag(photometric, tags, "0028,0004")) { json["Orthanc"]["PhotometricInterpretation"] = photometric; } Json::FastWriter writer; content = writer.write(json); return true; } else { char msg[1024]; sprintf(msg, "Unable to decode the following instance: %s", uri.c_str()); OrthancPluginLogWarning(context_, msg); return false; } } bool DecodedImageAdapter::GetCornerstoneMetadata(Json::Value& result, const Json::Value& tags, OrthancImageWrapper& image) { using namespace Orthanc; float windowCenter, windowWidth; Orthanc::ImageAccessor accessor; accessor.AssignReadOnly(OrthancPlugins::Convert(image.GetFormat()), image.GetWidth(), image.GetHeight(), image.GetPitch(), image.GetBuffer()); switch (accessor.GetFormat()) { case PixelFormat_Grayscale8: case PixelFormat_Grayscale16: case PixelFormat_SignedGrayscale16: { int64_t a, b; Orthanc::ImageProcessing::GetMinMaxValue(a, b, accessor); result["minPixelValue"] = (a < 0 ? static_cast(a) : 0); result["maxPixelValue"] = (b > 0 ? static_cast(b) : 1); result["color"] = false; windowCenter = static_cast(a + b) / 2.0f; if (a == b) { windowWidth = 256.0f; // Arbitrary value } else { windowWidth = static_cast(b - a) / 2.0f; } break; } case PixelFormat_RGB24: result["minPixelValue"] = 0; result["maxPixelValue"] = 255; result["color"] = true; windowCenter = 127.5f; windowWidth = 256.0f; break; default: return false; } float slope = GetFloatTag(tags, "0028,1053", 1.0f); float intercept = GetFloatTag(tags, "0028,1052", 0.0f); result["slope"] = slope; result["intercept"] = intercept; result["rows"] = image.GetHeight(); result["columns"] = image.GetWidth(); result["height"] = image.GetHeight(); result["width"] = image.GetWidth(); bool ok = false; std::string pixelSpacing; if (GetStringTag(pixelSpacing, tags, "0028,0030")) { std::vector tokens; Orthanc::Toolbox::TokenizeString(tokens, pixelSpacing, '\\'); if (tokens.size() >= 2) { try { result["columnPixelSpacing"] = boost::lexical_cast(Orthanc::Toolbox::StripSpaces(tokens[1])); result["rowPixelSpacing"] = boost::lexical_cast(Orthanc::Toolbox::StripSpaces(tokens[0])); ok = true; } catch (boost::bad_lexical_cast&) { } } } if (!ok) { result["columnPixelSpacing"] = 1.0f; result["rowPixelSpacing"] = 1.0f; } result["windowCenter"] = GetFloatTag(tags, "0028,1050", windowCenter * slope + intercept); result["windowWidth"] = GetFloatTag(tags, "0028,1051", windowWidth * slope); return true; } bool DecodedImageAdapter::EncodeUsingDeflate(Json::Value& result, OrthancImageWrapper& image, uint8_t compressionLevel /* between 0 and 9 */) { Orthanc::ImageAccessor accessor; accessor.AssignReadOnly(OrthancPlugins::Convert(image.GetFormat()), image.GetWidth(), image.GetHeight(), image.GetPitch(), image.GetBuffer()); std::auto_ptr buffer; Orthanc::ImageAccessor converted; switch (accessor.GetFormat()) { case Orthanc::PixelFormat_RGB24: converted = accessor; break; case Orthanc::PixelFormat_Grayscale8: case Orthanc::PixelFormat_Grayscale16: buffer.reset(new Orthanc::ImageBuffer(Orthanc::PixelFormat_Grayscale16, accessor.GetWidth(), accessor.GetHeight(), true /* force minimal pitch */)); converted = buffer->GetAccessor(); Orthanc::ImageProcessing::Convert(converted, accessor); break; case Orthanc::PixelFormat_SignedGrayscale16: converted = accessor; break; default: // Unsupported pixel format return false; } result["Orthanc"]["IsSigned"] = (accessor.GetFormat() == Orthanc::PixelFormat_SignedGrayscale16); // Sanity check: The pitch must be minimal assert(converted.GetSize() == converted.GetWidth() * converted.GetHeight() * GetBytesPerPixel(converted.GetFormat())); result["Orthanc"]["Compression"] = "Deflate"; result["sizeInBytes"] = converted.GetSize(); std::string z; CompressUsingDeflate(z, image.GetContext(), converted.GetConstBuffer(), converted.GetSize()); result["Orthanc"]["PixelData"] = base64_encode(z); return true; } template static void ChangeDynamics(Orthanc::ImageAccessor& target, const Orthanc::ImageAccessor& source, SourceType source1, TargetType target1, SourceType source2, TargetType target2) { if (source.GetWidth() != target.GetWidth() || source.GetHeight() != target.GetHeight()) { throw Orthanc::OrthancException(Orthanc::ErrorCode_IncompatibleImageSize); } float scale = static_cast(target2 - target1) / static_cast(source2 - source1); float offset = static_cast(target1) - scale * static_cast(source1); const float minValue = static_cast(std::numeric_limits::min()); const float maxValue = static_cast(std::numeric_limits::max()); for (unsigned int y = 0; y < source.GetHeight(); y++) { const SourceType* p = reinterpret_cast(source.GetConstRow(y)); TargetType* q = reinterpret_cast(target.GetRow(y)); for (unsigned int x = 0; x < source.GetWidth(); x++, p++, q++) { float v = (scale * static_cast(*p)) + offset; if (v > maxValue) { *q = std::numeric_limits::max(); } else if (v < minValue) { *q = std::numeric_limits::min(); } else { //*q = static_cast(boost::math::iround(v)); // http://stackoverflow.com/a/485546/881731 *q = static_cast(floor(v + 0.5f)); } } } } bool DecodedImageAdapter::EncodeUsingJpeg(Json::Value& result, OrthancImageWrapper& image, uint8_t quality /* between 0 and 100 */) { Orthanc::ImageAccessor accessor; accessor.AssignReadOnly(OrthancPlugins::Convert(image.GetFormat()), image.GetWidth(), image.GetHeight(), image.GetPitch(), image.GetBuffer()); std::auto_ptr buffer; Orthanc::ImageAccessor converted; if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale8 || accessor.GetFormat() == Orthanc::PixelFormat_RGB24) { result["Orthanc"]["Stretched"] = false; converted = accessor; } else if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale16 || accessor.GetFormat() == Orthanc::PixelFormat_SignedGrayscale16) { result["Orthanc"]["Stretched"] = true; buffer.reset(new Orthanc::ImageBuffer(Orthanc::PixelFormat_Grayscale8, accessor.GetWidth(), accessor.GetHeight(), true /* force minimal pitch */)); converted = buffer->GetAccessor(); int64_t a, b; Orthanc::ImageProcessing::GetMinMaxValue(a, b, accessor); result["Orthanc"]["StretchLow"] = static_cast(a); result["Orthanc"]["StretchHigh"] = static_cast(b); if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale16) { ChangeDynamics(converted, accessor, a, 0, b, 255); } else { ChangeDynamics(converted, accessor, a, 0, b, 255); } } else { return false; } result["Orthanc"]["IsSigned"] = (accessor.GetFormat() == Orthanc::PixelFormat_SignedGrayscale16); result["Orthanc"]["Compression"] = "Jpeg"; result["sizeInBytes"] = converted.GetSize(); std::string jpeg; WriteJpegToMemory(jpeg, image.GetContext(), converted, quality); result["Orthanc"]["PixelData"] = base64_encode(jpeg); return true; } } OrthancWebViewer-2.3/Plugin/DecodedImageAdapter.h0000644000000000000000000000446013133653001020123 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "Cache/ICacheFactory.h" #include #include #include #include "../Orthanc/Plugins/Samples/GdcmDecoder/OrthancImageWrapper.h" namespace OrthancPlugins { class DecodedImageAdapter : public ICacheFactory { private: enum CompressionType { CompressionType_Jpeg, CompressionType_Deflate }; static bool ParseUri(CompressionType& type, uint8_t& compressionLevel, std::string& instanceId, unsigned int& frameIndex, const std::string& uri); static bool GetCornerstoneMetadata(Json::Value& result, const Json::Value& tags, OrthancImageWrapper& image); static bool EncodeUsingDeflate(Json::Value& result, OrthancImageWrapper& image, uint8_t compressionLevel /* between 0 and 9 */); static bool EncodeUsingJpeg(Json::Value& result, OrthancImageWrapper& image, uint8_t quality /* between 0 and 100 */); OrthancPluginContext* context_; public: DecodedImageAdapter(OrthancPluginContext* context) : context_(context) { } virtual bool Create(std::string& content, const std::string& uri); }; } OrthancWebViewer-2.3/Plugin/Plugin.cpp0000644000000000000000000005457713133653001016137 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include #include #include #include #include "../Orthanc/Core/OrthancException.h" #include "../Orthanc/Core/DicomFormat/DicomMap.h" #include "ViewerToolbox.h" #include "ViewerPrefetchPolicy.h" #include "DecodedImageAdapter.h" #include "SeriesInformationAdapter.h" #include "../Orthanc/Plugins/Samples/GdcmDecoder/GdcmDecoderCache.h" #include "../Orthanc/Core/Toolbox.h" #include "../Orthanc/Core/SystemToolbox.h" static OrthancPluginContext* context_ = NULL; static bool restrictTransferSyntaxes_ = false; static std::set enabledTransferSyntaxes_; class CacheContext { private: class DynamicString : public Orthanc::IDynamicObject { private: std::string value_; public: DynamicString(const char* value) : value_(value) { } const std::string& GetValue() const { return value_; } }; Orthanc::FilesystemStorage storage_; Orthanc::SQLite::Connection db_; std::auto_ptr cache_; std::auto_ptr scheduler_; Orthanc::SharedMessageQueue newInstances_; bool stop_; boost::thread newInstancesThread_; OrthancPlugins::GdcmDecoderCache decoder_; static void NewInstancesThread(CacheContext* cache) { while (!cache->stop_) { std::auto_ptr obj(cache->newInstances_.Dequeue(100)); if (obj.get() != NULL) { const std::string& instanceId = dynamic_cast(*obj).GetValue(); // On the reception of a new instance, indalidate the parent series of the instance std::string uri = "/instances/" + std::string(instanceId); Json::Value instance; if (OrthancPlugins::GetJsonFromOrthanc(instance, context_, uri)) { std::string seriesId = instance["ParentSeries"].asString(); cache->GetScheduler().Invalidate(OrthancPlugins::CacheBundle_SeriesInformation, seriesId); } } } } public: CacheContext(const std::string& path) : storage_(path), stop_(false) { boost::filesystem::path p(path); db_.Open((p / "cache.db").string()); cache_.reset(new OrthancPlugins::CacheManager(context_, db_, storage_)); //cache_->SetSanityCheckEnabled(true); // For debug scheduler_.reset(new OrthancPlugins::CacheScheduler(*cache_, 100)); newInstancesThread_ = boost::thread(NewInstancesThread, this); } ~CacheContext() { stop_ = true; if (newInstancesThread_.joinable()) { newInstancesThread_.join(); } scheduler_.reset(NULL); cache_.reset(NULL); } OrthancPlugins::CacheScheduler& GetScheduler() { return *scheduler_; } void SignalNewInstance(const char* instanceId) { newInstances_.Enqueue(new DynamicString(instanceId)); } OrthancPlugins::GdcmDecoderCache& GetDecoder() { return decoder_; } }; static CacheContext* cache_ = NULL; static OrthancPluginErrorCode OnChangeCallback(OrthancPluginChangeType changeType, OrthancPluginResourceType resourceType, const char* resourceId) { try { if (changeType == OrthancPluginChangeType_NewInstance && resourceType == OrthancPluginResourceType_Instance) { cache_->SignalNewInstance(resourceId); } return OrthancPluginErrorCode_Success; } catch (std::runtime_error& e) { OrthancPluginLogError(context_, e.what()); return OrthancPluginErrorCode_Success; // Ignore error } } template static OrthancPluginErrorCode ServeCache(OrthancPluginRestOutput* output, const char* url, const OrthancPluginHttpRequest* request) { try { if (request->method != OrthancPluginHttpMethod_Get) { OrthancPluginSendMethodNotAllowed(context_, output, "GET"); return OrthancPluginErrorCode_Success; } const std::string id = request->groups[0]; std::string content; if (cache_->GetScheduler().Access(content, bundle, id)) { OrthancPluginAnswerBuffer(context_, output, content.c_str(), content.size(), "application/json"); } else { OrthancPluginSendHttpStatusCode(context_, output, 404); } return OrthancPluginErrorCode_Success; } catch (Orthanc::OrthancException& e) { OrthancPluginLogError(context_, e.What()); return OrthancPluginErrorCode_Plugin; } catch (std::runtime_error& e) { OrthancPluginLogError(context_, e.what()); return OrthancPluginErrorCode_Plugin; } catch (boost::bad_lexical_cast&) { OrthancPluginLogError(context_, "Bad lexical cast"); return OrthancPluginErrorCode_Plugin; } } #if ORTHANC_STANDALONE == 0 static OrthancPluginErrorCode ServeWebViewer(OrthancPluginRestOutput* output, const char* url, const OrthancPluginHttpRequest* request) { if (request->method != OrthancPluginHttpMethod_Get) { OrthancPluginSendMethodNotAllowed(context_, output, "GET"); return OrthancPluginErrorCode_Success; } const std::string path = std::string(WEB_VIEWER_PATH) + std::string(request->groups[0]); const char* mime = OrthancPlugins::GetMimeType(path); std::string s; try { Orthanc::SystemToolbox::ReadFile(s, path); const char* resource = s.size() ? s.c_str() : NULL; OrthancPluginAnswerBuffer(context_, output, resource, s.size(), mime); } catch (Orthanc::OrthancException&) { std::string s = "Inexistent file in served folder: " + path; OrthancPluginLogError(context_, s.c_str()); OrthancPluginSendHttpStatusCode(context_, output, 404); } return OrthancPluginErrorCode_Success; } #endif template static OrthancPluginErrorCode ServeEmbeddedFolder(OrthancPluginRestOutput* output, const char* url, const OrthancPluginHttpRequest* request) { if (request->method != OrthancPluginHttpMethod_Get) { OrthancPluginSendMethodNotAllowed(context_, output, "GET"); return OrthancPluginErrorCode_Success; } std::string path = "/" + std::string(request->groups[0]); const char* mime = OrthancPlugins::GetMimeType(path); try { std::string s; Orthanc::EmbeddedResources::GetDirectoryResource(s, folder, path.c_str()); const char* resource = s.size() ? s.c_str() : NULL; OrthancPluginAnswerBuffer(context_, output, resource, s.size(), mime); return OrthancPluginErrorCode_Success; } catch (std::runtime_error&) { std::string s = "Unknown static resource in plugin: " + std::string(request->groups[0]); OrthancPluginLogError(context_, s.c_str()); OrthancPluginSendHttpStatusCode(context_, output, 404); return OrthancPluginErrorCode_Success; } } static OrthancPluginErrorCode IsStableSeries(OrthancPluginRestOutput* output, const char* url, const OrthancPluginHttpRequest* request) { try { if (request->method != OrthancPluginHttpMethod_Get) { OrthancPluginSendMethodNotAllowed(context_, output, "GET"); return OrthancPluginErrorCode_Success; } const std::string id = request->groups[0]; Json::Value series; if (OrthancPlugins::GetJsonFromOrthanc(series, context_, "/series/" + id) && series.type() == Json::objectValue) { bool value = (series["IsStable"].asBool() || series["Status"].asString() == "Complete"); std::string answer = value ? "true" : "false"; OrthancPluginAnswerBuffer(context_, output, answer.c_str(), answer.size(), "application/json"); } else { OrthancPluginSendHttpStatusCode(context_, output, 404); } return OrthancPluginErrorCode_Success; } catch (Orthanc::OrthancException& e) { OrthancPluginLogError(context_, e.What()); return OrthancPluginErrorCode_Plugin; } catch (std::runtime_error& e) { OrthancPluginLogError(context_, e.what()); return OrthancPluginErrorCode_Plugin; } catch (boost::bad_lexical_cast&) { OrthancPluginLogError(context_, "Bad lexical cast"); return OrthancPluginErrorCode_Plugin; } } static bool ExtractTransferSyntax(std::string& transferSyntax, const void* dicom, const uint32_t size) { Orthanc::DicomMap header; if (!Orthanc::DicomMap::ParseDicomMetaInformation(header, reinterpret_cast(dicom), size)) { return false; } const Orthanc::DicomValue* tag = header.TestAndGetValue(0x0002, 0x0010); if (tag == NULL || tag->IsNull() || tag->IsBinary()) { return false; } else { // Stripping spaces should not be required, as this is a UI value // representation whose stripping is supported by the Orthanc // core, but let's be careful... transferSyntax = Orthanc::Toolbox::StripSpaces(tag->GetContent()); return true; } } static bool IsTransferSyntaxEnabled(const void* dicom, const uint32_t size) { std::string formattedSize; { char tmp[16]; sprintf(tmp, "%0.1fMB", static_cast(size) / (1024.0f * 1024.0f)); formattedSize.assign(tmp); } if (!restrictTransferSyntaxes_) { std::string s = "Decoding one DICOM instance of " + formattedSize + " using GDCM"; OrthancPluginLogInfo(context_, s.c_str()); return true; } std::string transferSyntax; if (!ExtractTransferSyntax(transferSyntax, dicom, size)) { std::string s = ("Cannot extract the transfer syntax of this instance of " + formattedSize + ", will use GDCM to decode it"); OrthancPluginLogInfo(context_, s.c_str()); return true; } if (enabledTransferSyntaxes_.find(transferSyntax) != enabledTransferSyntaxes_.end()) { // Decoding for this transfer syntax is enabled std::string s = ("Using GDCM to decode this instance of " + formattedSize + " with transfer syntax " + transferSyntax); OrthancPluginLogInfo(context_, s.c_str()); return true; } else { std::string s = ("Won't use GDCM to decode this instance of " + formattedSize + ", as its transfer syntax " + transferSyntax + " is disabled"); OrthancPluginLogInfo(context_, s.c_str()); return false; } } static OrthancPluginErrorCode DecodeImageCallback(OrthancPluginImage** target, const void* dicom, const uint32_t size, uint32_t frameIndex) { try { if (!IsTransferSyntaxEnabled(dicom, size)) { *target = NULL; return OrthancPluginErrorCode_Success; } std::auto_ptr image; #if 0 // Do not use the cache OrthancPlugins::GdcmImageDecoder decoder(dicom, size); image.reset(new OrthancPlugins::OrthancImageWrapper(context_, decoder, frameIndex)); #else using namespace OrthancPlugins; image.reset(cache_->GetDecoder().Decode(context_, dicom, size, frameIndex)); #endif *target = image->Release(); return OrthancPluginErrorCode_Success; } catch (Orthanc::OrthancException& e) { *target = NULL; std::string s = "Cannot decode image using GDCM: " + std::string(e.What()); OrthancPluginLogError(context_, s.c_str()); return OrthancPluginErrorCode_Plugin; } catch (std::runtime_error& e) { *target = NULL; std::string s = "Cannot decode image using GDCM: " + std::string(e.what()); OrthancPluginLogError(context_, s.c_str()); return OrthancPluginErrorCode_Plugin; } } void ParseConfiguration(bool& enableGdcm, int& decodingThreads, boost::filesystem::path& cachePath, int& cacheSize) { /* Read the configuration of the Web viewer */ Json::Value configuration; if (!OrthancPlugins::ReadConfiguration(configuration, context_)) { throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat); } // By default, the cache of the Web viewer is located inside the // "StorageDirectory" of Orthanc cachePath = OrthancPlugins::GetStringValue(configuration, "StorageDirectory", "."); cachePath /= "WebViewerCache"; static const char* CONFIG_WEB_VIEWER = "WebViewer"; if (configuration.isMember(CONFIG_WEB_VIEWER)) { std::string key = "CachePath"; if (!configuration[CONFIG_WEB_VIEWER].isMember(key)) { // For backward compatibility with the initial release of the Web viewer key = "Cache"; } cachePath = OrthancPlugins::GetStringValue(configuration[CONFIG_WEB_VIEWER], key, cachePath.string()); cacheSize = OrthancPlugins::GetIntegerValue(configuration[CONFIG_WEB_VIEWER], "CacheSize", cacheSize); decodingThreads = OrthancPlugins::GetIntegerValue(configuration[CONFIG_WEB_VIEWER], "Threads", decodingThreads); static const char* CONFIG_ENABLE_GDCM = "EnableGdcm"; if (configuration[CONFIG_WEB_VIEWER].isMember(CONFIG_ENABLE_GDCM)) { if (configuration[CONFIG_WEB_VIEWER][CONFIG_ENABLE_GDCM].type() != Json::booleanValue) { throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat); } else { enableGdcm = configuration[CONFIG_WEB_VIEWER][CONFIG_ENABLE_GDCM].asBool(); } } static const char* CONFIG_RESTRICT_TRANSFER_SYNTAXES = "RestrictTransferSyntaxes"; if (enableGdcm) { if (configuration[CONFIG_WEB_VIEWER].isMember(CONFIG_RESTRICT_TRANSFER_SYNTAXES)) { const Json::Value& config = configuration[CONFIG_WEB_VIEWER][CONFIG_RESTRICT_TRANSFER_SYNTAXES]; if (config.type() != Json::arrayValue) { throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat); } restrictTransferSyntaxes_ = true; for (Json::Value::ArrayIndex i = 0; i < config.size(); i++) { if (config[i].type() != Json::stringValue) { throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat); } else { std::string s = "Web viewer will use GDCM to decode transfer syntax " + config[i].asString(); enabledTransferSyntaxes_.insert(config[i].asString()); OrthancPluginLogWarning(context_, s.c_str()); } } } } } if (decodingThreads <= 0 || cacheSize <= 0) { throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); } } static bool DisplayPerformanceWarning() { (void) DisplayPerformanceWarning; // Disable warning about unused function OrthancPluginLogWarning(context_, "Performance warning in Web viewer: " "Non-release build, runtime debug assertions are turned on"); return true; } extern "C" { ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* context) { using namespace OrthancPlugins; context_ = context; assert(DisplayPerformanceWarning()); OrthancPluginLogWarning(context_, "Initializing the Web viewer"); /* Check the version of the Orthanc core */ if (OrthancPluginCheckVersion(context_) == 0) { char info[1024]; sprintf(info, "Your version of Orthanc (%s) must be above %d.%d.%d to run this plugin", context_->orthancVersion, ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER, ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER, ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER); OrthancPluginLogError(context_, info); return -1; } OrthancPluginSetDescription(context_, "Provides a Web viewer of DICOM series within Orthanc."); /* By default, use half of the available processing cores for the decoding of DICOM images */ int decodingThreads = boost::thread::hardware_concurrency() / 2; if (decodingThreads == 0) { decodingThreads = 1; } /* By default, use GDCM */ bool enableGdcm = true; /* By default, a cache of 100 MB is used */ int cacheSize = 100; try { boost::filesystem::path cachePath; ParseConfiguration(enableGdcm, decodingThreads, cachePath, cacheSize); std::string message = ("Web viewer using " + boost::lexical_cast(decodingThreads) + " threads for the decoding of the DICOM images"); OrthancPluginLogWarning(context_, message.c_str()); message = "Storing the cache of the Web viewer in folder: " + cachePath.string(); OrthancPluginLogWarning(context_, message.c_str()); /* Create the cache */ cache_ = new CacheContext(cachePath.string()); CacheScheduler& scheduler = cache_->GetScheduler(); /* Look for a change in the versions */ std::string orthancVersion("unknown"), webViewerVersion("unknown"); bool clear = false; if (!scheduler.LookupProperty(orthancVersion, CacheProperty_OrthancVersion) || orthancVersion != std::string(context_->orthancVersion)) { std::string s = ("The version of Orthanc has changed from \"" + orthancVersion + "\" to \"" + std::string(context_->orthancVersion) + "\": The cache of the Web viewer will be cleared"); OrthancPluginLogWarning(context_, s.c_str()); clear = true; } if (!scheduler.LookupProperty(webViewerVersion, CacheProperty_WebViewerVersion) || webViewerVersion != std::string(ORTHANC_WEBVIEWER_VERSION)) { std::string s = ("The version of the Web viewer plugin has changed from \"" + webViewerVersion + "\" to \"" + std::string(ORTHANC_WEBVIEWER_VERSION) + "\": The cache of the Web viewer will be cleared"); OrthancPluginLogWarning(context_, s.c_str()); clear = true; } /* Clear the cache if needed */ if (clear) { OrthancPluginLogWarning(context_, "Clearing the cache of the Web viewer"); scheduler.Clear(); scheduler.SetProperty(CacheProperty_OrthancVersion, context_->orthancVersion); scheduler.SetProperty(CacheProperty_WebViewerVersion, ORTHANC_WEBVIEWER_VERSION); } else { OrthancPluginLogInfo(context_, "No change in the versions, no need to clear the cache of the Web viewer"); } /* Configure the cache */ scheduler.RegisterPolicy(new ViewerPrefetchPolicy(context_)); scheduler.Register(CacheBundle_SeriesInformation, new SeriesInformationAdapter(context_, scheduler), 1); scheduler.Register(CacheBundle_DecodedImage, new DecodedImageAdapter(context_), decodingThreads); /* Set the quotas */ scheduler.SetQuota(CacheBundle_SeriesInformation, 1000, 0); // Keep info about 1000 series message = "Web viewer using a cache of " + boost::lexical_cast(cacheSize) + " MB"; OrthancPluginLogWarning(context_, message.c_str()); scheduler.SetQuota(CacheBundle_DecodedImage, 0, static_cast(cacheSize) * 1024 * 1024); } catch (std::runtime_error& e) { OrthancPluginLogError(context_, e.what()); return -1; } catch (Orthanc::OrthancException& e) { if (e.GetErrorCode() == Orthanc::ErrorCode_BadFileFormat) { OrthancPluginLogError(context_, "Unable to read the configuration of the Web viewer plugin"); } else { OrthancPluginLogError(context_, e.What()); } return -1; } /* Configure the DICOM decoder */ if (enableGdcm) { // Replace the default decoder of DICOM images that is built in Orthanc OrthancPluginLogWarning(context_, "Using GDCM instead of the DICOM decoder that is built in Orthanc"); OrthancPluginRegisterDecodeImageCallback(context_, DecodeImageCallback); } else { OrthancPluginLogWarning(context_, "Using the DICOM decoder that is built in Orthanc (not using GDCM)"); } /* Install the callbacks */ OrthancPluginRegisterRestCallback(context_, "/web-viewer/series/(.*)", ServeCache); OrthancPluginRegisterRestCallback(context_, "/web-viewer/is-stable-series/(.*)", IsStableSeries); OrthancPluginRegisterRestCallback(context_, "/web-viewer/instances/(.*)", ServeCache); OrthancPluginRegisterRestCallback(context, "/web-viewer/libs/(.*)", ServeEmbeddedFolder); #if ORTHANC_STANDALONE == 1 OrthancPluginRegisterRestCallback(context, "/web-viewer/app/(.*)", ServeEmbeddedFolder); #else OrthancPluginRegisterRestCallback(context, "/web-viewer/app/(.*)", ServeWebViewer); #endif OrthancPluginRegisterOnChangeCallback(context, OnChangeCallback); /* Extend the default Orthanc Explorer with custom JavaScript */ std::string explorer; Orthanc::EmbeddedResources::GetFileResource(explorer, Orthanc::EmbeddedResources::ORTHANC_EXPLORER); OrthancPluginExtendOrthancExplorer(context_, explorer.c_str()); return 0; } ORTHANC_PLUGINS_API void OrthancPluginFinalize() { OrthancPluginLogWarning(context_, "Finalizing the Web viewer"); if (cache_ != NULL) { delete cache_; cache_ = NULL; } } ORTHANC_PLUGINS_API const char* OrthancPluginGetName() { return "web-viewer"; } ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion() { return ORTHANC_WEBVIEWER_VERSION; } } OrthancWebViewer-2.3/Plugin/SeriesInformationAdapter.cpp0000644000000000000000000000525413133653001021626 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "SeriesInformationAdapter.h" #include "ViewerToolbox.h" #include namespace OrthancPlugins { bool SeriesInformationAdapter::Create(std::string& content, const std::string& seriesId) { std::string message = "Ordering instances of series: " + seriesId; OrthancPluginLogInfo(context_, message.c_str()); Json::Value series, study, patient, ordered; if (!GetJsonFromOrthanc(series, context_, "/series/" + seriesId) || !GetJsonFromOrthanc(study, context_, "/studies/" + series["ID"].asString() + "/module?simplify") || !GetJsonFromOrthanc(patient, context_, "/studies/" + series["ID"].asString() + "/module-patient?simplify") || !GetJsonFromOrthanc(ordered, context_, "/series/" + series["ID"].asString() + "/ordered-slices") || !series.isMember("Instances") || series["Instances"].type() != Json::arrayValue) { return false; } Json::Value result; result["ID"] = seriesId; result["SeriesDescription"] = series["MainDicomTags"]["SeriesDescription"].asString(); result["StudyDescription"] = study["StudyDescription"].asString(); result["PatientID"] = patient["PatientID"].asString(); result["PatientName"] = patient["PatientName"].asString(); result["Type"] = ordered["Type"]; result["Slices"] = ordered["Slices"]; boost::regex pattern("^/instances/([a-f0-9-]+)/frames/([0-9]+)$"); for (Json::Value::ArrayIndex i = 0; i < result["Slices"].size(); i++) { boost::cmatch what; if (regex_match(result["Slices"][i].asCString(), what, pattern)) { result["Slices"][i] = std::string(what[1]) + "_" + std::string(what[2]); } else { return false; } } content = result.toStyledString(); return true; } } OrthancWebViewer-2.3/Plugin/SeriesInformationAdapter.h0000644000000000000000000000267213133653001021274 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "Cache/ICacheFactory.h" #include "Cache/CacheScheduler.h" #include namespace OrthancPlugins { class SeriesInformationAdapter : public ICacheFactory { private: OrthancPluginContext* context_; CacheScheduler& cache_; public: SeriesInformationAdapter(OrthancPluginContext* context, CacheScheduler& cache) : context_(context), cache_(cache) { } virtual bool Create(std::string& content, const std::string& seriesId); }; } OrthancWebViewer-2.3/Plugin/ViewerPrefetchPolicy.cpp0000644000000000000000000001065113133653001020764 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "ViewerPrefetchPolicy.h" #include "ViewerToolbox.h" #include "Cache/CacheScheduler.h" #include #include static const Json::Value::ArrayIndex PREFETCH_FORWARD = 10; static const Json::Value::ArrayIndex PREFETCH_BACKWARD = 3; namespace OrthancPlugins { void ViewerPrefetchPolicy::ApplySeries(std::list& toPrefetch, CacheScheduler& cache, const std::string& series, const std::string& content) { Json::Value json; Json::Reader reader; if (!reader.parse(content, json) || !json.isMember("Slices")) { return; } const Json::Value& instances = json["Slices"]; if (instances.type() != Json::arrayValue) { return; } for (Json::Value::ArrayIndex i = 0; i < instances.size() && i < PREFETCH_FORWARD; i++) { std::string item = "jpeg95-" + instances[i].asString(); toPrefetch.push_back(CacheIndex(CacheBundle_DecodedImage, item)); } } void ViewerPrefetchPolicy::ApplyInstance(std::list& toPrefetch, CacheScheduler& cache, const std::string& path) { size_t separator = path.find('-'); if (separator == std::string::npos) { return; } std::string compression = path.substr(0, separator + 1); std::string instanceAndFrame = path.substr(separator + 1); std::string instanceId = instanceAndFrame.substr(0, instanceAndFrame.find('_')); Json::Value instance; if (!GetJsonFromOrthanc(instance, context_, "/instances/" + instanceId) || !instance.isMember("ParentSeries")) { return; } std::string tmp; if (!cache.Access(tmp, CacheBundle_SeriesInformation, instance["ParentSeries"].asString())) { return; } Json::Value series; Json::Reader reader; if (!reader.parse(tmp, series) || !series.isMember("Slices")) { return; } const Json::Value& instances = series["Slices"]; if (instances.type() != Json::arrayValue) { return; } Json::Value::ArrayIndex position = 0; while (position < instances.size()) { if (instances[position] == instanceAndFrame) { break; } position++; } if (position == instances.size()) { return; } for (Json::Value::ArrayIndex i = position; i < instances.size() && i < position + PREFETCH_FORWARD; i++) { std::string item = compression + instances[i].asString(); toPrefetch.push_back(CacheIndex(CacheBundle_DecodedImage, item)); } for (Json::Value::ArrayIndex i = position; i >= 0 && i > position - PREFETCH_BACKWARD; ) { i--; std::string item = compression + instances[i].asString(); toPrefetch.push_back(CacheIndex(CacheBundle_DecodedImage, item)); } } void ViewerPrefetchPolicy::Apply(std::list& toPrefetch, CacheScheduler& cache, const CacheIndex& accessed, const std::string& content) { switch (accessed.GetBundle()) { case CacheBundle_SeriesInformation: ApplySeries(toPrefetch, cache, accessed.GetItem(), content); return; case CacheBundle_DecodedImage: ApplyInstance(toPrefetch, cache, accessed.GetItem()); return; default: return; } } } OrthancWebViewer-2.3/Plugin/ViewerPrefetchPolicy.h0000644000000000000000000000335013133653001020427 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include "Cache/IPrefetchPolicy.h" #include namespace OrthancPlugins { class ViewerPrefetchPolicy : public IPrefetchPolicy { private: OrthancPluginContext* context_; void ApplySeries(std::list& toPrefetch, CacheScheduler& cache, const std::string& series, const std::string& content); void ApplyInstance(std::list& toPrefetch, CacheScheduler& cache, const std::string& path); public: ViewerPrefetchPolicy(OrthancPluginContext* context) : context_(context) { } virtual void Apply(std::list& toPrefetch, CacheScheduler& cache, const CacheIndex& accessed, const std::string& content); }; } OrthancWebViewer-2.3/Plugin/ViewerToolbox.cpp0000644000000000000000000002321013133653001017465 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include "ViewerToolbox.h" #include "../Orthanc/Core/OrthancException.h" #include "../Orthanc/Core/Toolbox.h" #include #include #include #include namespace OrthancPlugins { bool GetStringFromOrthanc(std::string& content, OrthancPluginContext* context, const std::string& uri) { OrthancPluginMemoryBuffer answer; if (OrthancPluginRestApiGet(context, &answer, uri.c_str())) { return false; } if (answer.size) { try { content.assign(reinterpret_cast(answer.data), answer.size); } catch (std::bad_alloc&) { OrthancPluginFreeMemoryBuffer(context, &answer); throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory); } } OrthancPluginFreeMemoryBuffer(context, &answer); return true; } bool GetJsonFromOrthanc(Json::Value& json, OrthancPluginContext* context, const std::string& uri) { OrthancPluginMemoryBuffer answer; if (OrthancPluginRestApiGet(context, &answer, uri.c_str())) { return false; } if (answer.size) { try { const char* data = reinterpret_cast(answer.data); Json::Reader reader; if (!reader.parse(data, data + answer.size, json, false /* don't collect comments */)) { return false; } } catch (std::runtime_error&) { OrthancPluginFreeMemoryBuffer(context, &answer); return false; } } OrthancPluginFreeMemoryBuffer(context, &answer); return true; } bool TokenizeVector(std::vector& result, const std::string& value, unsigned int expectedSize) { std::vector tokens; Orthanc::Toolbox::TokenizeString(tokens, value, '\\'); if (tokens.size() != expectedSize) { return false; } result.resize(tokens.size()); for (size_t i = 0; i < tokens.size(); i++) { try { result[i] = boost::lexical_cast(tokens[i]); } catch (boost::bad_lexical_cast&) { return false; } } return true; } void CompressUsingDeflate(std::string& compressed, OrthancPluginContext* context, const void* uncompressed, size_t uncompressedSize) { OrthancPluginMemoryBuffer tmp; OrthancPluginErrorCode code = OrthancPluginBufferCompression( context, &tmp, uncompressed, uncompressedSize, OrthancPluginCompressionType_Zlib, 0 /*compress*/); if (code != OrthancPluginErrorCode_Success) { throw Orthanc::OrthancException(static_cast(code)); } try { compressed.assign(reinterpret_cast(tmp.data), tmp.size); } catch (...) { throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory); } OrthancPluginFreeMemoryBuffer(context, &tmp); } const char* GetMimeType(const std::string& path) { size_t dot = path.find_last_of('.'); std::string extension = (dot == std::string::npos) ? "" : path.substr(dot); std::transform(extension.begin(), extension.end(), extension.begin(), tolower); if (extension == ".html") { return "text/html"; } else if (extension == ".css") { return "text/css"; } else if (extension == ".js") { return "application/javascript"; } else if (extension == ".gif") { return "image/gif"; } else if (extension == ".svg") { return "image/svg+xml"; } else if (extension == ".json") { return "application/json"; } else if (extension == ".xml") { return "application/xml"; } else if (extension == ".png") { return "image/png"; } else if (extension == ".jpg" || extension == ".jpeg") { return "image/jpeg"; } else { return "application/octet-stream"; } } bool ReadConfiguration(Json::Value& configuration, OrthancPluginContext* context) { std::string s; { char* tmp = OrthancPluginGetConfiguration(context); if (tmp == NULL) { OrthancPluginLogError(context, "Error while retrieving the configuration from Orthanc"); return false; } s.assign(tmp); OrthancPluginFreeString(context, tmp); } Json::Reader reader; if (reader.parse(s, configuration)) { return true; } else { OrthancPluginLogError(context, "Unable to parse the configuration"); return false; } } std::string GetStringValue(const Json::Value& configuration, const std::string& key, const std::string& defaultValue) { if (configuration.type() != Json::objectValue || !configuration.isMember(key) || configuration[key].type() != Json::stringValue) { return defaultValue; } else { return configuration[key].asString(); } } int GetIntegerValue(const Json::Value& configuration, const std::string& key, int defaultValue) { if (configuration.type() != Json::objectValue || !configuration.isMember(key) || configuration[key].type() != Json::intValue) { return defaultValue; } else { return configuration[key].asInt(); } } OrthancPluginPixelFormat Convert(Orthanc::PixelFormat format) { switch (format) { case Orthanc::PixelFormat_Grayscale16: return OrthancPluginPixelFormat_Grayscale16; case Orthanc::PixelFormat_Grayscale8: return OrthancPluginPixelFormat_Grayscale8; case Orthanc::PixelFormat_RGB24: return OrthancPluginPixelFormat_RGB24; case Orthanc::PixelFormat_RGBA32: return OrthancPluginPixelFormat_RGBA32; case Orthanc::PixelFormat_SignedGrayscale16: return OrthancPluginPixelFormat_SignedGrayscale16; default: throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); } } Orthanc::PixelFormat Convert(OrthancPluginPixelFormat format) { switch (format) { case OrthancPluginPixelFormat_Grayscale16: return Orthanc::PixelFormat_Grayscale16; case OrthancPluginPixelFormat_Grayscale8: return Orthanc::PixelFormat_Grayscale8; case OrthancPluginPixelFormat_RGB24: return Orthanc::PixelFormat_RGB24; case OrthancPluginPixelFormat_RGBA32: return Orthanc::PixelFormat_RGBA32; case OrthancPluginPixelFormat_SignedGrayscale16: return Orthanc::PixelFormat_SignedGrayscale16; default: throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); } } void WriteJpegToMemory(std::string& result, OrthancPluginContext* context, const Orthanc::ImageAccessor& accessor, uint8_t quality) { OrthancPluginMemoryBuffer tmp; OrthancPluginErrorCode code = OrthancPluginCompressJpegImage (context, &tmp, Convert(accessor.GetFormat()), accessor.GetWidth(), accessor.GetHeight(), accessor.GetPitch(), accessor.GetConstBuffer(), quality); if (code != OrthancPluginErrorCode_Success) { throw Orthanc::OrthancException(static_cast(code)); } try { result.assign(reinterpret_cast(tmp.data), tmp.size); } catch (...) { throw Orthanc::OrthancException(Orthanc::ErrorCode_NotEnoughMemory); } OrthancPluginFreeMemoryBuffer(context, &tmp); } ImageReader::ImageReader(OrthancPluginContext* context, const std::string& image, OrthancPluginImageFormat format) : context_(context) { image_ = OrthancPluginUncompressImage(context_, image.c_str(), image.size(), format); if (image_ == NULL) { throw Orthanc::OrthancException(Orthanc::ErrorCode_CorruptedFile); } } ImageReader::~ImageReader() { OrthancPluginFreeImage(context_, image_); } Orthanc::ImageAccessor ImageReader::GetAccessor() const { Orthanc::ImageAccessor accessor; accessor.AssignReadOnly(Convert(OrthancPluginGetImagePixelFormat(context_, image_)), OrthancPluginGetImageWidth(context_, image_), OrthancPluginGetImageHeight(context_, image_), OrthancPluginGetImagePitch(context_, image_), OrthancPluginGetImageBuffer(context_, image_)); return accessor; } } OrthancWebViewer-2.3/Plugin/ViewerToolbox.h0000644000000000000000000000575013133653001017143 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #pragma once #include #include #include #include "../Orthanc/Core/Images/ImageAccessor.h" namespace OrthancPlugins { enum CacheBundle { CacheBundle_DecodedImage = 1, CacheBundle_InstanceInformation = 2, CacheBundle_SeriesInformation = 3 }; bool GetStringFromOrthanc(std::string& content, OrthancPluginContext* context, const std::string& uri); bool GetJsonFromOrthanc(Json::Value& json, OrthancPluginContext* context, const std::string& uri); bool TokenizeVector(std::vector& result, const std::string& value, unsigned int expectedSize); void CompressUsingDeflate(std::string& compressed, OrthancPluginContext* context, const void* uncompressed, size_t uncompressedSize); const char* GetMimeType(const std::string& path); bool ReadConfiguration(Json::Value& configuration, OrthancPluginContext* context); std::string GetStringValue(const Json::Value& configuration, const std::string& key, const std::string& defaultValue); int GetIntegerValue(const Json::Value& configuration, const std::string& key, int defaultValue); OrthancPluginPixelFormat Convert(Orthanc::PixelFormat format); Orthanc::PixelFormat Convert(OrthancPluginPixelFormat format); void WriteJpegToMemory(std::string& result, OrthancPluginContext* context, const Orthanc::ImageAccessor& accessor, uint8_t quality); class ImageReader { private: OrthancPluginContext* context_; OrthancPluginImage* image_; public: ImageReader(OrthancPluginContext* context, const std::string& image, OrthancPluginImageFormat format); ~ImageReader(); Orthanc::ImageAccessor GetAccessor() const; }; } OrthancWebViewer-2.3/README0000644000000000000000000000332513133653001013600 0ustar 00000000000000Web Viewer plugin for Orthanc ============================= General Information ------------------- This repository contains the source code of a plugin implementing a Web viewer for Orthanc, the lightweight, RESTful DICOM server. Dependencies ------------ The Web viewer is based upon the following projects: * Cornerstone, a client-side JavaScript library to display medical images in Web browsers, by Chris Hafey : https://github.com/chafey/cornerstone * GDCM, an open-source implementation of the DICOM standard with advanced features for image decoding, by Mathieu Malaterre : http://sourceforge.net/projects/gdcm/ Installation and usage ---------------------- Build and usage instructions are available in the Orthanc Book: https://orthanc.chu.ulg.ac.be/book/plugins/webviewer.html Licensing --------- The Web viewer plugin for Orthanc is licensed under the AGPL license. We also kindly ask scientific works and clinical studies that make use of Orthanc to cite Orthanc in their associated publications. Similarly, we ask open-source and closed-source products that make use of Orthanc to warn us about this use. You can cite our work using the following BibTeX entry: @inproceedings{Jodogne:ISBI2013, author = {Jodogne, S. and Bernard, C. and Devillers, M. and Lenaerts, E. and Coucke, P.}, title = {Orthanc -- {A} Lightweight, {REST}ful {DICOM} Server for Healthcare and Medical Research}, booktitle={Biomedical Imaging ({ISBI}), {IEEE} 10th International Symposium on}, year={2013}, pages={190-193}, ISSN={1945-7928}, month=apr, url={http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=6556444}, address={San Francisco, {CA}, {USA}} } OrthancWebViewer-2.3/Resources/BuildInstructions.txt0000644000000000000000000000152213133653001021114 0ustar 00000000000000Generic GNU/Linux (static linking) ================================== # mkdir Build # cd Build # cmake .. -DCMAKE_BUILD_TYPE=Debug -DALLOW_DOWNLOADS=ON -DSTATIC_BUILD=ON # make Debian Sid (dynamic linking) ============================ # sudo apt-get install build-essential unzip cmake libgdcm2-dev libjpeg-dev \ uuid-dev libgtest-dev libpng-dev libsqlite3-dev \ zlib1g-dev libboost-all-dev libjsoncpp-dev # mkdir Build # cd Build # cmake .. -DCMAKE_BUILD_TYPE=Debug -DALLOW_DOWNLOADS=ON -DUSE_SYSTEM_GOOGLE_TEST=OFF -DSTANDALONE_BUILD=ON # make Cross-compiling for Windows from GNU/Linux using MinGW ====================================================== # mkdir Build # cd Build # cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_TOOLCHAIN_FILE=`pwd`/../Orthanc/Resources/MinGWToolchain.cmake # make OrthancWebViewer-2.3/Resources/CMake/GdcmConfiguration.cmake0000644000000000000000000000703313133653001022256 0ustar 00000000000000# Orthanc - A Lightweight, RESTful DICOM Store # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics # Department, University Hospital of Liege, Belgium # Copyright (C) 2017 Osimis, Belgium # # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . if (STATIC_BUILD OR NOT USE_SYSTEM_GDCM) # If using gcc, build GDCM with the "-fPIC" argument to allow its # embedding into the shared library containing the Orthanc plugin if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR ${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD" OR ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD") set(AdditionalFlags "-fPIC") endif() set(Flags "-DCMAKE_C_FLAGS=${CMAKE_C_FLAGS} ${AdditionalFlags}" "-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} ${AdditionalFlags}" -DCMAKE_C_FLAGS_DEBUG=${CMAKE_C_FLAGS_DEBUG} -DCMAKE_CXX_FLAGS_DEBUG=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_C_FLAGS_RELEASE=${CMAKE_C_FLAGS_RELEASE} -DCMAKE_CXX_FLAGS_RELEASE=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_FLAGS_MINSIZEREL=${CMAKE_C_FLAGS_MINSIZEREL} -DCMAKE_CXX_FLAGS_MINSIZEREL=${CMAKE_CXX_FLAGS_MINSIZEREL} -DCMAKE_C_FLAGS_RELWITHDEBINFO=${CMAKE_C_FLAGS_RELWITHDEBINFO} -DCMAKE_CXX_FLAGS_RELWITHDEBINFO=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ) if (CMAKE_TOOLCHAIN_FILE) list(APPEND Flags -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}) endif() include(ExternalProject) externalproject_add(GDCM URL "http://www.orthanc-server.com/downloads/third-party/gdcm-2.6.0.tar.gz" URL_MD5 "978afe57af448b1c97c9f116790aca9c" TIMEOUT 60 CMAKE_ARGS -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} ${Flags} #-DLIBRARY_OUTPUT_PATH=${CMAKE_CURRENT_BINARY_DIR} INSTALL_COMMAND "" # Skip the install step ) if(MSVC) set(Suffix ".lib") set(Prefix "") else() set(Suffix ".a") list(GET CMAKE_FIND_LIBRARY_PREFIXES 0 Prefix) endif() set(GDCM_LIBRARIES ${Prefix}gdcmMSFF${Suffix} ${Prefix}gdcmcharls${Suffix} ${Prefix}gdcmDICT${Suffix} ${Prefix}gdcmDSED${Suffix} ${Prefix}gdcmIOD${Suffix} ${Prefix}gdcmjpeg8${Suffix} ${Prefix}gdcmjpeg12${Suffix} ${Prefix}gdcmjpeg16${Suffix} ${Prefix}gdcmMEXD${Suffix} ${Prefix}gdcmopenjpeg${Suffix} ${Prefix}gdcmzlib${Suffix} ${Prefix}socketxx${Suffix} ${Prefix}gdcmCommon${Suffix} ${Prefix}gdcmexpat${Suffix} #${Prefix}gdcmgetopt${Suffix} #${Prefix}gdcmuuid${Suffix} ) ExternalProject_Get_Property(GDCM binary_dir) include_directories(${binary_dir}/Source/Common) link_directories(${binary_dir}/bin) ExternalProject_Get_Property(GDCM source_dir) include_directories( ${source_dir}/Source/Common ${source_dir}/Source/MediaStorageAndFileFormat ${source_dir}/Source/DataStructureAndEncodingDefinition ) else() find_package(GDCM REQUIRED) if (GDCM_FOUND) include(${GDCM_USE_FILE}) set(GDCM_LIBRARIES gdcmCommon gdcmMSFF) else(GDCM_FOUND) message(FATAL_ERROR "Cannot find GDCM, did you set GDCM_DIR?") endif(GDCM_FOUND) endif() OrthancWebViewer-2.3/Resources/CMake/JavaScriptLibraries.cmake0000644000000000000000000000502313133653001022554 0ustar 00000000000000# Orthanc - A Lightweight, RESTful DICOM Store # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics # Department, University Hospital of Liege, Belgium # Copyright (C) 2017 Osimis, Belgium # # This program is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General Public License # as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . set(BASE_URL "http://www.orthanc-server.com/downloads/third-party/WebViewer") DownloadPackage( "dbf236ede85e7b7871c9a42edad16d81" "${BASE_URL}/cornerstone-0.11.0.zip" "cornerstone-0.11.0") DownloadPackage( "cb943ac26be9ee755e8741ea232389e2" "${BASE_URL}/jquery-ui-1.11.3.zip" "jquery-ui-1.11.3") DownloadPackage( "169c56338f9ff812cae3e91ef72bda2e" "${BASE_URL}/jsPanel-2.3.3-fixed.zip" "jspanel") DownloadPackage( "8392ad105d913c3a83a7787c8f148055" "${BASE_URL}/pako-0.2.5.zip" "pako-0.2.5") DownloadPackage( "7ebea0b624cd62445a124d264dfa2a53" "${BASE_URL}/js-url-1.8.6.zip" "js-url-1.8.6") set(JAVASCRIPT_LIBS_DIR ${CMAKE_CURRENT_BINARY_DIR}/javascript-libs) file(MAKE_DIRECTORY ${JAVASCRIPT_LIBS_DIR}) file(COPY ${CMAKE_CURRENT_BINARY_DIR}/cornerstone-0.11.0/example/cornerstone.css ${CMAKE_CURRENT_BINARY_DIR}/cornerstone-0.11.0/dist/cornerstone.min.js ${CMAKE_CURRENT_BINARY_DIR}/jquery-ui-1.11.3/external/jquery/jquery.js ${CMAKE_CURRENT_BINARY_DIR}/jquery-ui-1.11.3/images ${CMAKE_CURRENT_BINARY_DIR}/jquery-ui-1.11.3/jquery-ui.min.css ${CMAKE_CURRENT_BINARY_DIR}/jquery-ui-1.11.3/jquery-ui.min.js ${CMAKE_CURRENT_BINARY_DIR}/jquery-ui-1.11.3/jquery-ui.theme.min.css ${CMAKE_CURRENT_BINARY_DIR}/js-url-1.8.6/url.min.js ${CMAKE_CURRENT_BINARY_DIR}/jspanel/fonts ${CMAKE_CURRENT_BINARY_DIR}/jspanel/images ${CMAKE_CURRENT_BINARY_DIR}/jspanel/jquery.jspanel.min.css ${CMAKE_CURRENT_BINARY_DIR}/jspanel/jquery.jspanel.min.js ${CMAKE_CURRENT_BINARY_DIR}/vendor/jquery.ui.touch-punch.min.js ${CMAKE_CURRENT_BINARY_DIR}/vendor/mobile-detect.min.js ${CMAKE_CURRENT_BINARY_DIR}/pako-0.2.5/dist/pako_inflate.min.js DESTINATION ${JAVASCRIPT_LIBS_DIR} ) OrthancWebViewer-2.3/Resources/ImplementationNotes.txt0000644000000000000000000000121513133653001021425 0ustar 00000000000000Possible combinations returned by the plugin: Compression | Color | Depth (bpp) | Colorspace | Stretched ------------+-------+-------------+------------+----------- Deflate | False | 16 | int16_t | Never JPEG | False | 8 | uint8_t | Possible Deflate | True | 8 | RGB24 | Never JPEG | True | 8 | RGB24 | Never In the viewer, grayscale images are always converted to int16_t. Note for Cornerstone < 0.7.1: 1 must be added to "maxPixelValue", as the range [minPixelValue, maxPixelValue[ is taken into consideration by Cornerstone (i.e. "maxPixelValue" is not inclusive). OrthancWebViewer-2.3/Resources/OrthancExplorer.js0000644000000000000000000000077013133653001020350 0ustar 00000000000000$('#series').live('pagebeforecreate', function() { //$('#series-preview').parent().remove(); var b = $('') .attr('data-role', 'button') .attr('href', '#') .attr('data-icon', 'search') .attr('data-theme', 'e') .text('Orthanc Web Viewer'); b.insertBefore($('#series-delete').parent().parent()); b.click(function() { if ($.mobile.pageData) { var series = $.mobile.pageData.uuid; window.open('../web-viewer/app/viewer.html?series=' + series); } }); }); OrthancWebViewer-2.3/Resources/SyncOrthancFolder.py0000755000000000000000000001004713133653001020635 0ustar 00000000000000#!/usr/bin/python # # This maintenance script updates the content of the "Orthanc" folder # to match the latest version of the Orthanc source code. # import multiprocessing import os import stat import urllib2 TARGET = os.path.join(os.path.dirname(__file__), '..', 'Orthanc') PLUGIN_SDK_VERSION = '0.9.5' REPOSITORY = 'https://bitbucket.org/sjodogne/orthanc/raw' FILES = [ 'Core/ChunkedBuffer.cpp', 'Core/ChunkedBuffer.h', 'Core/Enumerations.cpp', 'Core/Enumerations.h', 'Core/Endianness.h', 'Core/DicomFormat/DicomMap.h', 'Core/DicomFormat/DicomMap.cpp', 'Core/DicomFormat/DicomTag.h', 'Core/DicomFormat/DicomTag.cpp', 'Core/DicomFormat/DicomValue.h', 'Core/DicomFormat/DicomValue.cpp', 'Core/FileStorage/FilesystemStorage.cpp', 'Core/FileStorage/FilesystemStorage.h', 'Core/FileStorage/IStorageArea.h', 'Core/IDynamicObject.h', 'Core/Images/ImageAccessor.cpp', 'Core/Images/ImageAccessor.h', 'Core/Images/ImageBuffer.cpp', 'Core/Images/ImageBuffer.h', 'Core/Images/ImageProcessing.cpp', 'Core/Images/ImageProcessing.h', 'Core/Logging.h', 'Core/MultiThreading/SharedMessageQueue.cpp', 'Core/MultiThreading/SharedMessageQueue.h', 'Core/OrthancException.h', 'Core/PrecompiledHeaders.cpp', 'Core/PrecompiledHeaders.h', 'Core/SQLite/Connection.cpp', 'Core/SQLite/Connection.h', 'Core/SQLite/FunctionContext.cpp', 'Core/SQLite/FunctionContext.h', 'Core/SQLite/IScalarFunction.h', 'Core/SQLite/ITransaction.h', 'Core/SQLite/NonCopyable.h', 'Core/SQLite/OrthancSQLiteException.h', 'Core/SQLite/SQLiteTypes.h', 'Core/SQLite/Statement.cpp', 'Core/SQLite/Statement.h', 'Core/SQLite/StatementId.cpp', 'Core/SQLite/StatementId.h', 'Core/SQLite/StatementReference.cpp', 'Core/SQLite/StatementReference.h', 'Core/SQLite/Transaction.cpp', 'Core/SQLite/Transaction.h', 'Core/SystemToolbox.cpp', 'Core/SystemToolbox.h', 'Core/Toolbox.cpp', 'Core/Toolbox.h', 'Plugins/Samples/Common/ExportedSymbols.list', 'Plugins/Samples/Common/VersionScript.map', 'Plugins/Samples/GdcmDecoder/README', 'Plugins/Samples/GdcmDecoder/GdcmImageDecoder.h', 'Plugins/Samples/GdcmDecoder/GdcmImageDecoder.cpp', 'Plugins/Samples/GdcmDecoder/GdcmDecoderCache.h', 'Plugins/Samples/GdcmDecoder/GdcmDecoderCache.cpp', 'Plugins/Samples/GdcmDecoder/OrthancImageWrapper.h', 'Plugins/Samples/GdcmDecoder/OrthancImageWrapper.cpp', 'Resources/CMake/AutoGeneratedCode.cmake', 'Resources/CMake/BoostConfiguration.cmake', 'Resources/CMake/Compiler.cmake', 'Resources/CMake/DownloadPackage.cmake', 'Resources/CMake/GoogleTestConfiguration.cmake', 'Resources/CMake/JsonCppConfiguration.cmake', 'Resources/CMake/SQLiteConfiguration.cmake', 'Resources/EmbedResources.py', 'Resources/MinGW-W64-Toolchain32.cmake', 'Resources/MinGW-W64-Toolchain64.cmake', 'Resources/MinGWToolchain.cmake', 'Resources/ThirdParty/VisualStudio/stdint.h', 'Resources/ThirdParty/base64/base64.cpp', 'Resources/ThirdParty/base64/base64.h', 'Resources/WindowsResources.py', 'Resources/WindowsResources.rc', ] SDK = [ 'orthanc/OrthancCPlugin.h', ] EXE = [ 'Resources/EmbedResources.py', 'Resources/WindowsResources.py', ] def Download(x): branch = x[0] source = x[1] target = os.path.join(TARGET, x[2]) print target try: os.makedirs(os.path.dirname(target)) except: pass url = '%s/%s/%s' % (REPOSITORY, branch, source) with open(target, 'w') as f: f.write(urllib2.urlopen(url).read()) commands = [] for f in FILES: commands.append([ 'default', f, f ]) for f in SDK: commands.append([ 'Orthanc-%s' % PLUGIN_SDK_VERSION, 'Plugins/Include/%s' % f, 'Sdk-%s/%s' % (PLUGIN_SDK_VERSION, f) ]) pool = multiprocessing.Pool(10) # simultaneous downloads pool.map(Download, commands) for exe in EXE: path = os.path.join(TARGET, exe) st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IEXEC) OrthancWebViewer-2.3/UnitTestsSources/UnitTestsMain.cpp0000644000000000000000000001111413133653001021474 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ #include #include static int argc_; static char** argv_; #include "../Orthanc/Core/OrthancException.h" #include "../Orthanc/Core/SystemToolbox.h" #include "../Plugin/Cache/CacheManager.h" #include "../Plugin/Cache/CacheScheduler.h" #include "../Plugin/Cache/ICacheFactory.h" #include "../Plugin/Cache/ICacheFactory.h" using namespace OrthancPlugins; class CacheManagerTest : public testing::Test { private: std::auto_ptr storage_; std::auto_ptr db_; std::auto_ptr cache_; public: virtual void SetUp() { storage_.reset(new Orthanc::FilesystemStorage("UnitTestsResults")); storage_->Clear(); Orthanc::SystemToolbox::RemoveFile("UnitTestsResults/cache.db"); db_.reset(new Orthanc::SQLite::Connection()); db_->Open("UnitTestsResults/cache.db"); cache_.reset(new CacheManager(NULL, *db_, *storage_)); cache_->SetSanityCheckEnabled(true); } virtual void TearDown() { cache_.reset(NULL); db_.reset(NULL); storage_.reset(NULL); } CacheManager& GetCache() { return *cache_; } Orthanc::FilesystemStorage& GetStorage() { return *storage_; } }; class TestF : public ICacheFactory { private: int bundle_; public: TestF(int bundle) : bundle_(bundle) { } virtual bool Create(std::string& content, const std::string& key) { content = "Bundle " + boost::lexical_cast(bundle_) + ", item " + key; return true; } }; TEST_F(CacheManagerTest, DefaultQuota) { std::set f; GetStorage().ListAllFiles(f); ASSERT_EQ(0u, f.size()); GetCache().SetDefaultQuota(10, 0); for (unsigned int i = 0; i < 30; i++) { GetStorage().ListAllFiles(f); ASSERT_EQ(i >= 10 ? 10u : i, f.size()); std::string s = boost::lexical_cast(i); GetCache().Store(0, s, "Test " + s); } GetStorage().ListAllFiles(f); ASSERT_EQ(10u, f.size()); for (int i = 0; i < 30; i++) { ASSERT_EQ(i >= 20, GetCache().IsCached(0, boost::lexical_cast(i))); } GetCache().SetDefaultQuota(5, 0); GetStorage().ListAllFiles(f); ASSERT_EQ(5u, f.size()); for (int i = 0; i < 30; i++) { ASSERT_EQ(i >= 25, GetCache().IsCached(0, boost::lexical_cast(i))); } for (int i = 0; i < 15; i++) { std::string s = boost::lexical_cast(i); GetCache().Store(0, s, "Test " + s); } GetStorage().ListAllFiles(f); ASSERT_EQ(5u, f.size()); for (int i = 0; i < 50; i++) { std::string s = boost::lexical_cast(i); if (i >= 10 && i < 15) { std::string tmp; ASSERT_TRUE(GetCache().IsCached(0, s)); ASSERT_TRUE(GetCache().Access(tmp, 0, s)); ASSERT_EQ("Test " + s, tmp); } else { ASSERT_FALSE(GetCache().IsCached(0, s)); } } } TEST_F(CacheManagerTest, Invalidate) { GetCache().SetDefaultQuota(10, 0); for (int i = 0; i < 30; i++) { std::string s = boost::lexical_cast(i); GetCache().Store(0, s, "Test " + s); } std::set f; GetStorage().ListAllFiles(f); ASSERT_EQ(10u, f.size()); GetCache().Invalidate(0, "25"); GetStorage().ListAllFiles(f); ASSERT_EQ(9u, f.size()); for (int i = 0; i < 50; i++) { std::string s = boost::lexical_cast(i); ASSERT_EQ((i >= 20 && i < 30 && i != 25), GetCache().IsCached(0, s)); } for (int i = 0; i < 50; i++) { GetCache().Invalidate(0, boost::lexical_cast(i)); } GetStorage().ListAllFiles(f); ASSERT_EQ(0u, f.size()); } int main(int argc, char **argv) { argc_ = argc; argv_ = argv; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } OrthancWebViewer-2.3/WebApplication/images/bone.png0000644000000000000000000000077413133653001020524 0ustar 00000000000000‰PNG  IHDRóÿabKGDÿÿÿ ½§“ pHYs  šœtIMEÞ ,Z·s‰IDAT8Ëc` h¨+¡ðµµÕÈÊõuùûMÍôëÈÒ]W—ÿñã‡ËÿçÎéüc"F£¾&77'ËÏŸ?´µUJKÓï000(±ÒüÿÿFFF++Kc.&&&qqQ†°0oå{÷ÍcÄ¥‘‡‡›áË—¯ FF:ËW­œqþ†ýûO0prr0<}úâ力±jî驆Zssñ×ß¿nÿÏÎŽûÏÀÀà„×¹ââÂp¶¡vÁ¾½KÿŸ;»å¿™™Á.˜¸´´8ª&~~^tskjr_ýþuçkKé†bÚžÁ][[uú™Ó›þ¿~uîllà'Q Ü:ccƒ6?~tüÿ—ÏWÿûzýÿ‘#kþkjªl†Ç3þ˜fùû÷ïA†wï>üÿøñ3cVVÍòë×ïDÁüû÷°ûŒt¶úxùÿåK;þkh(÷‘“Juwl_ø?##ú?/I:åå¥aL b“6UqPˆ7˜IEND®B`‚OrthancWebViewer-2.3/WebApplication/images/default.png0000644000000000000000000000104413133653001021214 0ustar 00000000000000‰PNG  IHDRµú7êbKGDÿ‡Ì¿ pHYs  šœtIMEÞ  )ºŒµIDAT(Ï]Ð?H”‡ñç÷ú¦/z”!w™KfÙ“®.LB²(D‚ƒ¤¥Z‚ˆ#H¤!’[\ ¢¡!.ŠÈá‚úãP`jhu‡)§Eç^ïûm‰ŸýY>¨'û#ûDÀS•X“zæÚ”,¨_a€ŒÉ‘&“ÉÐñÔ·6¡ºã§Æ´yÍÿ9»[¡õ:¯±Œº´S{Õ>EÕâ6¤íŸ!°mªµÜ£ÐlϳÎ:s,¤ö•ª¡WoË~ç˜Ûg§é¤¤7¶:¸© Güp*²½É@øOïö61ÏG¢$õK/h¤Âˆ3ªË)T[¼Zº%iFÍ:¬Š×uMª×£¼v¹_'NÖ‘ÐOî[35ôÑÂ$4°Š—gÖ)v|g Óꥨ ò(hïø£4]Àsbñ¡ÌŽ:óVo¯m›v†öŸÀÁqí¥æ¦ÒÅÖKÎòœiñ”³þ/ºÁÀþîŸç}Â}úÎNæVN%º£¯†ýî'œŠ¤™–Í·wÍÒJ¹–ù«T™±l>{íËû&‘šôôNª=#_½xâÐPÈç†Í,.`sΈ½Ž|a½˜½¾úNö³33ý£“ÎxÔ?GðÊûÇG‡ge…s@ˆ=˰8‡Í› €^ÛÁÏÙâ÷–%¬g»NÑ@j²gt8ñ»Ç%S&¿ŒRyK†ýK{Èów,âí‹F´Ç²†a£Z7P©PÎ9ˆ$¯Ç9Ô4lº˜¹ ‡ÃÁÿÝÚI-|žs 5o y^ï銎EÂ>·Íôº Ëk XÀ«ve–VËí‘@Öæ|Ñ4ù"—N–æ>zéíùlñÈÂÒ­¿G†€€ •Ö·Ð{(>áÓÔbU¿'çÇG8öƒàGÕv-p! ÀäÛBÞ Š,ÕTU1÷Ó¤¦â‰Ã±ÙŽXзkØðÈ2ˆ.‰_›î팜ˆ0"bËå-ÚØÜy+—N©©ãŒÐù¿Ÿ§¤ºäÞágŽœÑë&„Ø«Š[Îÿ˜7—Nàj:yÀø:³¬¶únÙAÕ7>¾t”15Mަ…]ÃÇw—ÿœ^ÛØþp¿8¿Ý¨ê û9(²tœøýËÀAèî?íל/?úü9’$‰6X׃.™=¥o7Oz}-ç$"‚€ƒ1X¶zÓ†/è=yLùæN{`1ëúbóÎâO+¹ •£#éÁî-Ÿ”Êzý‡_o–UµU‚àLrÊwu ¶°µjzÝ€ÍÖh¤¿­=ôéæáNÔO ™‡|­°Œ1(-^èå‚Ä-C^ùgÓ:?=“Ò‚‘¾þccšÏç¬5L4 .É¥Bsª2{c\ V»g”oäßt„{_8ùÇõÂ\þÛ÷æW—.nß,Î7™ÏãñhªË)1Æ p†a¡z·²vûêå±ÂìÙÿ~ƒu*ý¾eIEND®B`‚OrthancWebViewer-2.3/WebApplication/images/lung.png0000644000000000000000000000103513133653001020535 0ustar 00000000000000‰PNG  IHDRµú7êbKGDÿ‡Ì¿ pHYs  šœtIMEÞ Ð<Úþ®IDAT(ÏÁ¿kaÀáÏ÷}ßËå'½†4ÅR,B t ´%h)¸éPB±t)ÎÅUpÐMpªc§®‡tp+‚€8ˆ‚ÕRMè%×Ë›÷^ŸGvx Àýæüÿ½ú+Vé¼jü~Þÿ °ƒÀ6=Ö;ï«­^ŽTéQ™¿_>Ýûüs›j“°v´Ðš!$»ÉRÈ ­µ#豉Z×ð`¿Þ­Rö§(øˆzwoÖµ>óõÙ;Ç‹7BKJ˜7õ ¤èC±o¯>ŒlDí9W%ÀñO':# Æœ‹Ú[ V¢ÊnDÅÏR‘Æ6v”ˆ¨øˆÊîJ¤ZËùNÑFdøóìËIDATHÇm•ilTU†Ÿsçv¦ mYl!amY,d”Fk‘…²XD BÙ„D ¸•¨,šhé"²•J ‹¦e“% (&& •.Ò¦E,…2s眯$$Ü?ÏÌw–÷ÛÎ9*11+ëÀ¶ æm3œö¾atª¡Þbh%6\`¥Zã95;­©©âü™¾îeµÊÊõü³½¿o0t¯ªlÃÆpÃ⫆yÿÙæGv¡áŠ)"´” 4†hÂO#ÝPX(•LqÄx¨«ø…¿é¨¿qsuVp,uüEŸŠQø9Á1j)Rjù”­Rû3»$l.½C#ÝINnhŽ“B’éö6›"Ömݽâ@ô|Ã{»Ýµ¡ÅnZÙ´¤i™ý®3B¿{† ßø‰fõðEõ¼ÕY-Ì?ÇN]ÎæûíyuD§ÞÇAÍSUÊw¢vÜT·köDîSC‰·—ç¦/ÝwxkÍ¥®y½7/)›cÕØUvĽE7Y`¯0Z_qz—¹Ž“ãîNtÈÒ·õw ¿nC“Wš®9hz%¹ʉú'qÐa9ý³% ˆs¡ô@·às'¶¹É¡m¡èZ3mì4ÚˆÞâæ ‡N ‘hl|„é à>pBjvYøOütká)1\ÇKQzQÄÓž ÀMP½e|‘eX_oèßÇQVò½³šüFCdâMéæ$Q‹ [û(™'ãÔRÎ}AìÖ©:Ù)5æÛçE·Òvû‡®¸UY VQ}|åè[÷*ÚëŽz­Žì~’³l}Ç,h=ËpÝt9VE(h3Uæ½mØÐuî ·À*õ\9uuzå§ñaÎάC¡ÑzžýôÙ—¿è;P(€¤‡¯ê·Bƒ›œÀÀ¯fC{„a§ã†…â@ÈÀ'¥ôôûEŽb3›Ñ)güÒ^`mtÇ5 h£(Øîšùá™êáM.÷%Ii¢aCŽáÙÿOÉ’¡gű¯Åo<Ý­qö>7M?õÌ‘A ]Üz:zÒ‹j$€|iÂví¤k‡J¤Z6–ÈI1pVÏ1,?ùxÆî”y™â@36éê.©–XÛí &qÒ„ÍoJ’/”+“"‰\"¦“5Fìƒyâ§’…ã­Ó4é;*Í-®±Ç˜uË©ûªÅÉÂFÙÀTž ÉPî ùãëf=ÒLòÃ΃í*_¿ºÏé`ö\*È ÞÚïÙ¿å0c½;"‚•³TO¼Ý <^26‹@cža\gÃdñ´LzaO±,XcÐf8)a?„¿wgq`E~ýë~jÕdï¤Èñ±—`ïó.Û¿›tr¨¦Ðù$ØÞ—Âû߀a@1­ä*ö·\ÅÅk ߕڭ“”7Êq¢äñ7Fs—º{ñÂN½.v7ìºÆ± ÿAmÛB`+ŽþÅ1•G*Šb[4yŒŠ[£‚¹" ÿ§ù £¥ºJz@žã€ 8õ @³{E$mûPôQ/.˜yn¥I¬Ê6ÂÕïˆpŒ´ÞúÿÛ9Ð-1iÈ%tEXtdate:create2016-05-25T07:45:46+02:00þwˆñ%tEXtdate:modify2016-05-25T07:45:46+02:00*0MIEND®B`‚OrthancWebViewer-2.3/WebApplication/images/orthanc-logo.png0000644000000000000000000000473013133653001022171 0ustar 00000000000000‰PNG  IHDRe  é¶gAMA± üasRGB®Îé cHRMz&€„ú€èu0ê`:˜pœºQ<bKGDÿÿÿ ½§“ pHYs  šœÍIDAThÞíš}UuÇ?çÞ³/,pA’ Eˆe§É ›oaV ©‰•ŒS˜šö"šš™VS9å4™¹Jd:Ì€o“̬$Æ›ÄîÈ[²H°(,/»Ëî½çœþø>g﹇{/›ÿìNs¿3gÎ=ç÷þ¼|Ÿç9»PFe”QFeüßÂè ÃÄV†?'_Î-°÷,°p-p°} Ïw&$z%–³€ °Y|xí±ë¤é«#ò.Úo?RÊ\à jÌ¥ß賕ĠôÃùÀÇí÷Ÿßïõ2žONÂq’•n8l}VAð÷lw·ø>ŽãàVW'œdr(ðSà‹À` ðî@®\€tSKøœ>ÌF§µmB|ì¯YRö¯>TAdÎ8nãZ€NdÊ—S‘ÕƒM¹bó³†à8Uöþ­ê5»ÆÏ:o40 yø±„›Üæ@öåÅ ˜·|牄ãd<Ïo È&’Ém;_\µ¯óÐÁ-¦”!våÁÎsp0Ô^¿lˆœà“È{àM`K¬Ï‡/]‘öJ`ŠÍ1Þä±ø'ðoÀs­cø p+âñä8¼QÂ2à±tSË{>ðK;L@>çg¬~Œ8ÿëÀWúa(ïtwt6“›1¨9k(\Ãì o ßÇqNó&GK¹È’]dññàŸ@^Rm÷¤ãô+Á\QÈHgÿ8m+9ÌAqï–tSKg>Ѿ3€Gm ‘sc{ds5¸ÀEÀý…üËoA³È®!ÈÒ÷÷’OYíÀ7LÛ.¢À»m¡Ù@xxÒøQà7fM§€ *pî æN|¿õ•­û!Ì }úƒ‹P"2œÛã`cº©¥Ô:‹Í=Rd?Rú½…BßlÏŸF^éϹÀ·LxïKÈ·ŽW£ÀÍÈÝËÉ ½(~ì¶çÍ6çÝ6f*¢•½Ö>ž-xÀ`ãš%õìÎ¥Ä! ™{1z_ÈrCêrSŒDìð(JŸÇ¢8ô;òé)Žjà{Ș› ´ûÀ%À<{> |øcD†ÍˆêÏV$€ÏE&øS¨P@ÈÅ~^Ⱥ >.¸LlcÅPŒ_Ž#>^ ìOT$ãíC½ÌJ7µ4¢Zf:Š7}HVV¼{°ÞÅTO@†õ[Tû€ò< Ãv!ã‡Ø¦®ÀYÀÅäˆ À ,i29¦˜gÏEn ²ö¾l#¼›5íGuBŠ3cÉ·žpžNû]â ÈZbó•„ŸõB]mJë^›Šw«VÆ„D”Û‡TݼõɧìÀ 1ºùv.P¦´X¼¤Q÷ÓÀ±ØúbŒéÈÓæw™R£[aJ Ñ œˆNq€>afu…A²€¢'Ö^‹Ü±×3ÑÈóÖœQLI7ST|ï9Ó\ |fúë ´|Ö|{Ѽd¿ÿìDé÷'PFúRl%<÷X¿(æv“_”û&—)“ÑiЬ¹¾‹òÊtSKO̪ÉÅ“¶á(*€BùMàäiý†) %À‡U±n{Q²ÖAâä[í®¹ömÁ#y ¤ÛI¸ûLjŸ5a†²¸ \˜Ab÷EȰ2±=$L~÷ tzp£É#Dc Ãlà¿¢õ‹ t¹È5ëíåBT(>a)žƒÜs)9Ëßd×äÈBÇ€§P±4¹~Å¡pº‹ö)”þR ýðÐ1  (QéS ½] ƒ™ jœ1“Ãù¯Žp¢¡BH›¶i_mç^Ja¶iF†9Þäv?pWº©eµ¾ig½ÏEEáŨ M¢à¶†—¡€‡ ýaT“D]´’» 횆*þE¦ä£˜¥2ªø;§ÀÈ ú”7 d±³í};òj/6¾8ÑÜ•%”’~J±¶°¥ÀK‘7\es¿e{jD G s‘Kßx.èâ »¢ØÜ<aìDõÈCÈj¾ƒ>Y´–Þ‡Ãÿ>Gà•7ߔ̮i½!(`ßë飯ʿ2Á.@i}±šå¢±Éä(1;FâÚóˆ–*íÜG"í](5•£LiL&Þš%õƒó/v¸à”n?‰¬¯—œ§:¦œÃþö¿vy›V 'ðGÝÇ=|§:• éF?ÝïB1òݵk_ècÅ`þ{Jø9ûr”ÿ_J>E:HIßFÊûNâGNÍHȧµ*ôQdågòÊÇ`VÊqäç ¯©+Чf*IáZ ä]뀟=ƒÙK`*%ÂÏë§—úlj°ÝŒÒòxŸÓþq¢Œ2Ê(£Œ2Ê(cÀð_Fi¾>p¹_‚%tEXtdate:create2016-05-25T07:47:00+02:00c %tEXtdate:modify2016-05-25T07:47:00+02:00lEÛ°IEND®B`‚OrthancWebViewer-2.3/WebApplication/images/stretch.png0000644000000000000000000000064013133653001021245 0ustar 00000000000000‰PNG  IHDRµú7êbKGDÿ‡Ì¿ pHYs  šœtIMEÞ H.÷1IDAT(ÏmпKÔqÇñÇ}ï›$6¤r™Ò¤˜Rˆ’äh‡h N“Sƒ“£ˆíÑÿ ÿ€Pâ‰?Q—#rD-Ïó×§Á¯ˆæó½½Ÿ¼ÞoxÁe¿ü0ì†Ï–l({9s^ºÍ[Ëö=qaÊ'Cê­‰¥rªtšbÚrì‹W¥=öG…y¬;Mã·UA$#£Y;6#4ÀU9´«Z„QÕêt{¡Ï‘o~*Y1ë\¿9•1"}ê,XD,òWYÁ€íR1lÚ³§Õ¼‡j}ð\F^­%¨Ô¨I‹,FAѶži¾ÓŽ1!™-]'¢Æ„6ß½õz­8»NF:|”’ü¥à½èöù“‰º¬Éú.ùDï¤ÜÃxòâDÓÕâug^ `|IIEND®B`‚OrthancWebViewer-2.3/WebApplication/images/throbber.gif0000644000000000000000000002232313133653001021363 0ustar 00000000000000GIF89a öÿÿÿ((($$$DDD~~~ttt>>>vvv€€€^^^ŽŽŽ¬¬¬||| ‚‚‚\\\PPPÈÈÈÄÄľ¾¾”””""" „„„XXX666ÂÂÂ’’’```†††@@@,,,ÊÊÊÆÆÆRRR888222***ÎÎÎJJJBBBVVVlll&&&xxxìììîîîÚÚÚðððÐÐÐddd NNNbbbhhhœœœpppjjj¸¸¸²²²®®®ººº´´´nnn000¶¶¶¼¼¼...<<<°°°fffäääÖÖÖÌÌÌèèèêêêFFF¤¤¤ªªªZZZŒŒŒ¦¦¦   ššš¢¢¢¨¨¨ÜÜÜÞÞÞàààÔÔÔ444:::–––HHH˜˜˜ÒÒÒTTTæææžžžâââŠŠŠˆˆˆLLLØØØzzzÀÀÀrrròòò!ÿ NETSCAPE2.0!þCreated with ajaxload.info!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„ 964“‚!ƒ5:;™ "‚";=5ž ­?‚ 7@Ž)26<>(B(Ñ.*0£‚Ñ(#"3†B/(8’$+1Á†˜ ú‹ $”—¨"p A&X("®["hDÐB´hHàÀ‡ ÀA ˆÂD ¤ÌÔÏED^:*ÀÅ‹i…H¬é[´ ‚@ÌÄNç"Ñ^`:àæG@=ðIBTDø "ïƒnD ‹¦ ¦(ºº-$`‚ܹxóêÝËwR !ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‡Ž*X[“‹ VY\™ƒ 1-ƒLQ ¡ IJ3‚¨ZQ ‚ $FJLP² TVZ]  7@ºŒGKMQLSUW<^B(Û. &KP‚R¥Û(“@KJ†B/(8¡B12Ë„4“ :¬jÄ/Q "E¬ˆ¨Ø%¢à ¡ 'R‘PÇAˆ!BZ¸¡HÛ¶ŽŠ€$0 ã‰Ep"q‘€‚¬ºè€ˆBÍG‚ xÑ­‰z@2=P'©.8ÔýdÄaÛ‹Gð4‰¢¨££/H"°-)dA^N8èÆ¶ ƒp†J‡BHΆ ¼ÞÝË·¯ß¿€!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ†$N?h6b-(.$ b\H!!‚US((”Ò1†@/(8£.'SÎ u ± Ä.F‘±bÅ”ƒ‡ @@^"C.¬˜ÁA x(:*zr¢ä ~‰„€™ˆÂ/š)*€ƒ@‹3_=sÑëœÏ‚À Wˆ„> ›€œ È   . “ Ñ½TÂ#êÈÅ€$€‡À‚AG•‹ cXn] ›ƒ7AƒdXhJ £‚+_[‚\«¢6_l F«F n8_km-oHZ=pS.?b-i‚m=eG4• Då'†GXDÏ›!i "¯RŽ2ñ‚Å2€%E8Ö…P³@  9,š¤ EBJŠT$ÇÀA ÈE™¯ºèuˆÂM_AP¼8YˆÄ @6}³XD%2")TžÑ½Rš¬DaÀ‚€L `©ˆ ½1–TNBT…¼=T`ѹxóêÝËWo !ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ†BCHQ"E•‹ kQq ›„ ƒb`¦£DNj‚*c¢ .•  # )JO6 (3PQCUrY:?N9+RO‚#Þ:•.ã9,†6p;a›(/‡ ¼âªQƒnÜÀ±¨ö)r¢" ŠHXt6ÑâEEB66Ä¡pÂHA$6,hÐ¥CT>*įB$^ ²IcE“ÃÂaQ&£ _`ÌyƒRÈŠ7) 0€„ yêºDh¥ÝÈ:(,KHQ<[¨‰¨lãÊK·î¨@!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ†.+l %T3•‹ &M#›‰sŸb ‚ /•Ol(‚ tPk¢ _nQRŽ^?Hi It _egrN¾+ENu`l?vÎVuŽ So6[/±FfrpFjo%½…GðF$› A‚¢ðÆ‚Q@P(ЈhÑ‚@‡EPhDAC‰0nä¨HHFn܈¨¨@.2bˆ°Q2 Q˜·©@/\"±ȦY‚ÇFžŽh|Ñ‘è‹&5 }‚Àh4 `Á L+Ñpcì µ5LÐx0®¡$¶ÚÝË·¯ß¿}!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ†Žl#m2”‹ mcš‰ wž_ ‚ 2C$(©\t$)nGŽ j1“Gm\ 0hvc¶Œ!«382#F™)ÌB™­¯†u+\|jb‚>FB˜°hB7d, Š~ˆòèØ˜D"Š/*:Ò£d‹ܸÁPÑT¨„ªY£.Þ¢@áS (^,D¦I$B¶Œ$GÈžX|ñªèUBB…Gà5,U ¤€ÏA7Ä2KsЋÛ*@b«Ü»xóêÝ‹7!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‡ i! ‘‹SH 2—‰Cš?‚,2–H96.GM%/BuHw¸ NTPL²Œ7((//?/C]ML3@Î(‚$âÚx¨Ž Ï.†^Lxð.ц[u4Œ@LèÅH=hƒ ›E€û—Ȇ+V”€Pq¢"YBj\dðFBEĈXòà¡”9·Î}÷‚¼3Dâ ‘H€; Bp8=pöâ_Ϩ„€³ÇŽÀ ‚8 `Á £"…Ðìç ±.'8#è²PT ÛÊK·®Ý¹!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽˆ$ ‘ŒC37•Š,Cƒ/j ‚%4Dmc$/B‚iD%F\] ®((/@u²]K¾Ž8É(‚4$‚Nc]T9¥Ž È/4†däë.̆ '[ð›ŠABƉ„ 0aT$ù’Ï€Úºc§"+2€˜Lb!fBš±c@‘ 7 *z°! &Nè3T ƒÍGò: b1Dg¼ Ê\"‘àK¡µ´©!@6)P@zL[7t Ñ–ë”ßHDЂ8âtƒì µú&$ë:³PHëêÝË·¯_¾!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽˆ ‘ŒBO,$•Ši2,ƒ@‘ ƒ7i2‚o&-B/7B‚[S+&k((/B-jÀb[8Å(‚ 4‚_kFH Ä/Û…[q6ç.Ȇ ,'ñ›Š @@öˆBš)â0‡J&bP$0ÀZ»C9R¤ÀBÂ)D*ºã¦cGŠ\¸!0J”P™Càž¡b^dô®Ã!C†Ø„T ˆ1†hÑ2è#ÖN”Š1 =(f‰Z6…À£‡$#5Ȉ‚€2*”t‡ª˜Y^.M(v+n¡$ŒÚÝË·¯ß¿›!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽˆ‘7 ”Š((„ “¢/‚ D™Ž477B‚§R2G9(A¨B(.R6 ŸŽ8( ‚ ¯uÌ&^¥Œ œ/Ã…jt‘.á… O!çš‹$88ëˆ.‹@cdº@À•èT'ŠŽ0‰ÂPƒEQ L”'ƒE‹Q pƒŸ¢ È€SáYè(x¤,[@/¾°€„+XN<Aà X(<) àK™§^"‰t‘­hxÀ¢dÀ']ˆ€âpõS F~ÜË·¯ß¿!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„ “‰8(( ™ƒ˜ƒœƒ.‘7B‚£(A‚/(8œ/B¼œ-/ œ‚ ²(-j@(/À…B-S(¡.Ö†B—Ÿ‹§܈‹B+EN6­‰¯(4Š1 [ÝË—è—ƒc(Rw£"!D$ܹã9B 2vs±Ë‹l:v BÍ"!440ÙˆÄ1‡OJ)à‚Ež"=È•ˆ 4«øÀ‚—G V‘ôBÅŽ1@xŠa„€hƒZøØA“>Rüøô⊎"¦Ø„üDáH•œãÊK·.¤@!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„$$“Š8(( ˜ˆ›ƒ‘ B‚ (A‚//—›/¥BB›­ ¿ ¯¿ª(/¼…¾(8’.І4žŒ Ç‹‹S++R‹¬(Û‰,UEHH?ðŸ¿ø‡S þ 6\(w£ÜÀ7HlaÇ­–¹(eˆF  "âL`¡M" ØÇˆÄ¯rZ¸!F*y(6ªål[9X p BC*+ pã:à)BBÏ$& @’ €Œ¤a¤ºð "ŠOm’þDÁFOŽüÙ°­Û·pãF !ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„$$“Š(( ˜ˆ›ƒ ‘ B‚ (A‚/4›/B7¹›(8 ¿‚š›ª(/½…B›Á‘.Ò†³ž‹ Œß/j ,̉¬(݈7uC'‹ïñ‡RþQàp㜢f¼‰qÉ[!âš¹Àeˆ† 5¥ Í…!/cÚTÑֈįsžâK.qª(xT Ú,ð0$N›s<ñB ’ØaÂX•0?@P ;>Ú £àÄH›˜¨ÀªU‚1#QPbÇ͇….à¡’n¡$ìêÝË—P !ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„$.“Š(($˜ˆ›ƒ‘ B‚ (A‚ š(/B7¹›( ¿Á¤‚¿ª¶½…B/(8’.І4žŒ¥‹@»Õ‹¬(܉ÿٟ¿íˆï›ñ‡7äŠA/¤ëFðZ†@ ¸R³"X~’ÁÀÆ„ 0³‚±4/Œ9©p盆fXég€"”$``É<-¥Éà&€KRà¹cÌËØ@"ñ@ &)D|)ÕÁ‚‰;R0=Z㛀®0¹h’"ƒ ‚…¢P…Î< ÐG°Ø˜8€àÇ 0èZ¸iÁ#" q  •Ìõx6R“§ˆšPnl @IF’‰Ú¤ $!^ ¸-dv®Ý»xó !ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„B.“Š(($˜ƒBƒ›ž-M)E‚£(A‚$@Y:VB7»›(¿ pZ;‚´ÁÃŽ8Tpg†B/(8’%[Ì…44B4àŠéˆisdK¡‰@‰ 5QQxˆ("ì"tš(T8C‘`@I1ѦÍóÀ! Ä".\@3uˆFšëQéÈ……†B/(8’‡4îØ‹ó‰/GsNï‰@(H$ Ïš6mÄa£ˆÄ6 þ|™8‘X¢eÌ &âP'º*€cˆE:PJ‘BQéDˆO."QNã£Sž ØÄI8¶ÑtBè‹w<tP¶Mg£P¼€@FA nà¨ÇHÁ«7˜áDvf Z0ášÜ»xóêÝ‹)!ù , ÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’„ E3 “‚B!„t;:G™"‚x;=&™4\)*¬D‚$@ X26ÜP©€‹ƒn8 2(_K£(¬¶4$àÚµpãÊKWn ;OrthancWebViewer-2.3/WebApplication/jpeg-decoder.js0000644000000000000000000007634713133653001020525 0ustar 00000000000000/** * SOURCE: https://github.com/notmasteryet/jpgjs/blob/master/jpg.js **/ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2011 notmasteryet Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. */ // - The JPEG specification can be found in the ITU CCITT Recommendation T.81 // (www.w3.org/Graphics/JPEG/itu-t81.pdf) // - The JFIF specification can be found in the JPEG File Interchange Format // (www.w3.org/Graphics/JPEG/jfif3.pdf) // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters // in PostScript Level 2, Technical Note #5116 // (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf) var JpegImage = (function jpegImage() { "use strict"; var dctZigZag = new Int32Array([ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 ]); var dctCos1 = 4017 // cos(pi/16) var dctSin1 = 799 // sin(pi/16) var dctCos3 = 3406 // cos(3*pi/16) var dctSin3 = 2276 // sin(3*pi/16) var dctCos6 = 1567 // cos(6*pi/16) var dctSin6 = 3784 // sin(6*pi/16) var dctSqrt2 = 5793 // sqrt(2) var dctSqrt1d2 = 2896 // sqrt(2) / 2 function constructor() { } function buildHuffmanTable(codeLengths, values) { var k = 0, code = [], i, j, length = 16; while (length > 0 && !codeLengths[length - 1]) length--; code.push({children: [], index: 0}); var p = code[0], q; for (i = 0; i < length; i++) { for (j = 0; j < codeLengths[i]; j++) { p = code.pop(); p.children[p.index] = values[k]; while (p.index > 0) { p = code.pop(); } p.index++; code.push(p); while (code.length <= i) { code.push(q = {children: [], index: 0}); p.children[p.index] = q.children; p = q; } k++; } if (i + 1 < length) { // p here points to last code code.push(q = {children: [], index: 0}); p.children[p.index] = q.children; p = q; } } return code[0].children; } function getBlockBufferOffset(component, row, col) { return 64 * ((component.blocksPerLine + 1) * row + col); } function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive) { var precision = frame.precision; var samplesPerLine = frame.samplesPerLine; var scanLines = frame.scanLines; var mcusPerLine = frame.mcusPerLine; var progressive = frame.progressive; var maxH = frame.maxH, maxV = frame.maxV; var startOffset = offset, bitsData = 0, bitsCount = 0; function readBit() { if (bitsCount > 0) { bitsCount--; return (bitsData >> bitsCount) & 1; } bitsData = data[offset++]; if (bitsData == 0xFF) { var nextByte = data[offset++]; if (nextByte) { throw "unexpected marker: " + ((bitsData << 8) | nextByte).toString(16); } // unstuff 0 } bitsCount = 7; return bitsData >>> 7; } function decodeHuffman(tree) { var node = tree; var bit; while ((bit = readBit()) !== null) { node = node[bit]; if (typeof node === 'number') return node; if (typeof node !== 'object') throw "invalid huffman sequence"; } return null; } function receive(length) { var n = 0; while (length > 0) { var bit = readBit(); if (bit === null) return; n = (n << 1) | bit; length--; } return n; } function receiveAndExtend(length) { var n = receive(length); if (n >= 1 << (length - 1)) return n; return n + (-1 << length) + 1; } function decodeBaseline(component, offset) { var t = decodeHuffman(component.huffmanTableDC); var diff = t === 0 ? 0 : receiveAndExtend(t); component.blockData[offset] = (component.pred += diff); var k = 1; while (k < 64) { var rs = decodeHuffman(component.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) break; k += 16; continue; } k += r; var z = dctZigZag[k]; component.blockData[offset + z] = receiveAndExtend(s); k++; } } function decodeDCFirst(component, offset) { var t = decodeHuffman(component.huffmanTableDC); var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive); component.blockData[offset] = (component.pred += diff); } function decodeDCSuccessive(component, offset) { component.blockData[offset] |= readBit() << successive; } var eobrun = 0; function decodeACFirst(component, offset) { if (eobrun > 0) { eobrun--; return; } var k = spectralStart, e = spectralEnd; while (k <= e) { var rs = decodeHuffman(component.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) { eobrun = receive(r) + (1 << r) - 1; break; } k += 16; continue; } k += r; var z = dctZigZag[k]; component.blockData[offset + z] = receiveAndExtend(s) * (1 << successive); k++; } } var successiveACState = 0, successiveACNextValue; function decodeACSuccessive(component, offset) { var k = spectralStart, e = spectralEnd, r = 0; while (k <= e) { var z = dctZigZag[k]; switch (successiveACState) { case 0: // initial state var rs = decodeHuffman(component.huffmanTableAC); var s = rs & 15, r = rs >> 4; if (s === 0) { if (r < 15) { eobrun = receive(r) + (1 << r); successiveACState = 4; } else { r = 16; successiveACState = 1; } } else { if (s !== 1) throw "invalid ACn encoding"; successiveACNextValue = receiveAndExtend(s); successiveACState = r ? 2 : 3; } continue; case 1: // skipping r zero items case 2: if (component.blockData[offset + z]) { component.blockData[offset + z] += (readBit() << successive); } else { r--; if (r === 0) successiveACState = successiveACState == 2 ? 3 : 0; } break; case 3: // set value for a zero item if (component.blockData[offset + z]) { component.blockData[offset + z] += (readBit() << successive); } else { component.blockData[offset + z] = successiveACNextValue << successive; successiveACState = 0; } break; case 4: // eob if (component.blockData[offset + z]) { component.blockData[offset + z] += (readBit() << successive); } break; } k++; } if (successiveACState === 4) { eobrun--; if (eobrun === 0) successiveACState = 0; } } function decodeMcu(component, decode, mcu, row, col) { var mcuRow = (mcu / mcusPerLine) | 0; var mcuCol = mcu % mcusPerLine; var blockRow = mcuRow * component.v + row; var blockCol = mcuCol * component.h + col; var offset = getBlockBufferOffset(component, blockRow, blockCol); decode(component, offset); } function decodeBlock(component, decode, mcu) { var blockRow = (mcu / component.blocksPerLine) | 0; var blockCol = mcu % component.blocksPerLine; var offset = getBlockBufferOffset(component, blockRow, blockCol); decode(component, offset); } var componentsLength = components.length; var component, i, j, k, n; var decodeFn; if (progressive) { if (spectralStart === 0) decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; else decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; } else { decodeFn = decodeBaseline; } var mcu = 0, marker; var mcuExpected; if (componentsLength == 1) { mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; } else { mcuExpected = mcusPerLine * frame.mcusPerColumn; } if (!resetInterval) { resetInterval = mcuExpected; } var h, v; while (mcu < mcuExpected) { // reset interval stuff for (i = 0; i < componentsLength; i++) { components[i].pred = 0; } eobrun = 0; if (componentsLength == 1) { component = components[0]; for (n = 0; n < resetInterval; n++) { decodeBlock(component, decodeFn, mcu); mcu++; } } else { for (n = 0; n < resetInterval; n++) { for (i = 0; i < componentsLength; i++) { component = components[i]; h = component.h; v = component.v; for (j = 0; j < v; j++) { for (k = 0; k < h; k++) { decodeMcu(component, decodeFn, mcu, j, k); } } } mcu++; } } // find marker bitsCount = 0; marker = (data[offset] << 8) | data[offset + 1]; if (marker <= 0xFF00) { throw "marker was not found"; } if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx offset += 2; } else { break; } } return offset - startOffset; } // A port of poppler's IDCT method which in turn is taken from: // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz, // "Practical Fast 1-D DCT Algorithms with 11 Multiplications", // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989, // 988-991. function quantizeAndInverse(component, blockBufferOffset, p) { var qt = component.quantizationTable; var v0, v1, v2, v3, v4, v5, v6, v7, t; var i; // dequant for (i = 0; i < 64; i++) { p[i] = component.blockData[blockBufferOffset + i] * qt[i]; } // inverse DCT on rows for (i = 0; i < 8; ++i) { var row = 8 * i; // check for all-zero AC coefficients if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) { t = (dctSqrt2 * p[0 + row] + 512) >> 10; p[0 + row] = t; p[1 + row] = t; p[2 + row] = t; p[3 + row] = t; p[4 + row] = t; p[5 + row] = t; p[6 + row] = t; p[7 + row] = t; continue; } // stage 4 v0 = (dctSqrt2 * p[0 + row] + 128) >> 8; v1 = (dctSqrt2 * p[4 + row] + 128) >> 8; v2 = p[2 + row]; v3 = p[6 + row]; v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8; v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8; v5 = p[3 + row] << 4; v6 = p[5 + row] << 4; // stage 3 t = (v0 - v1+ 1) >> 1; v0 = (v0 + v1 + 1) >> 1; v1 = t; t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; v3 = t; t = (v4 - v6 + 1) >> 1; v4 = (v4 + v6 + 1) >> 1; v6 = t; t = (v7 + v5 + 1) >> 1; v5 = (v7 - v5 + 1) >> 1; v7 = t; // stage 2 t = (v0 - v3 + 1) >> 1; v0 = (v0 + v3 + 1) >> 1; v3 = t; t = (v1 - v2 + 1) >> 1; v1 = (v1 + v2 + 1) >> 1; v2 = t; t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; v7 = t; t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; v6 = t; // stage 1 p[0 + row] = v0 + v7; p[7 + row] = v0 - v7; p[1 + row] = v1 + v6; p[6 + row] = v1 - v6; p[2 + row] = v2 + v5; p[5 + row] = v2 - v5; p[3 + row] = v3 + v4; p[4 + row] = v3 - v4; } // inverse DCT on columns for (i = 0; i < 8; ++i) { var col = i; // check for all-zero AC coefficients if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 && p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 && p[7*8 + col] == 0) { t = (dctSqrt2 * p[i+0] + 8192) >> 14; p[0*8 + col] = t; p[1*8 + col] = t; p[2*8 + col] = t; p[3*8 + col] = t; p[4*8 + col] = t; p[5*8 + col] = t; p[6*8 + col] = t; p[7*8 + col] = t; continue; } // stage 4 v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12; v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12; v2 = p[2*8 + col]; v3 = p[6*8 + col]; v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12; v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12; v5 = p[3*8 + col]; v6 = p[5*8 + col]; // stage 3 t = (v0 - v1 + 1) >> 1; v0 = (v0 + v1 + 1) >> 1; v1 = t; t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; v3 = t; t = (v4 - v6 + 1) >> 1; v4 = (v4 + v6 + 1) >> 1; v6 = t; t = (v7 + v5 + 1) >> 1; v5 = (v7 - v5 + 1) >> 1; v7 = t; // stage 2 t = (v0 - v3 + 1) >> 1; v0 = (v0 + v3 + 1) >> 1; v3 = t; t = (v1 - v2 + 1) >> 1; v1 = (v1 + v2 + 1) >> 1; v2 = t; t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; v7 = t; t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; v6 = t; // stage 1 p[0*8 + col] = v0 + v7; p[7*8 + col] = v0 - v7; p[1*8 + col] = v1 + v6; p[6*8 + col] = v1 - v6; p[2*8 + col] = v2 + v5; p[5*8 + col] = v2 - v5; p[3*8 + col] = v3 + v4; p[4*8 + col] = v3 - v4; } // convert to 8-bit integers for (i = 0; i < 64; ++i) { var index = blockBufferOffset + i; var q = p[i]; q = (q <= -2056) ? 0 : (q >= 2024) ? 255 : (q + 2056) >> 4; component.blockData[index] = q; } } function buildComponentData(frame, component) { var lines = []; var blocksPerLine = component.blocksPerLine; var blocksPerColumn = component.blocksPerColumn; var samplesPerLine = blocksPerLine << 3; var computationBuffer = new Int32Array(64); var i, j, ll = 0; for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { var offset = getBlockBufferOffset(component, blockRow, blockCol) quantizeAndInverse(component, offset, computationBuffer); } } return component.blockData; } function clampToUint8(a) { return a <= 0 ? 0 : a >= 255 ? 255 : a | 0; } constructor.prototype = { load: function load(path) { var handleData = (function(data) { this.parse(data); if (this.onload) this.onload(); }).bind(this); if (path.indexOf("data:") > -1) { var offset = path.indexOf("base64,")+7; var data = atob(path.substring(offset)); var arr = new Uint8Array(data.length); for (var i = data.length - 1; i >= 0; i--) { arr[i] = data.charCodeAt(i); } handleData(data); } else { var xhr = new XMLHttpRequest(); xhr.open("GET", path, true); xhr.responseType = "arraybuffer"; xhr.onload = (function() { // TODO catch parse error var data = new Uint8Array(xhr.response); handleData(data); }).bind(this); xhr.send(null); } }, parse: function parse(data) { function readUint16() { var value = (data[offset] << 8) | data[offset + 1]; offset += 2; return value; } function readDataBlock() { var length = readUint16(); var array = data.subarray(offset, offset + length - 2); offset += array.length; return array; } function prepareComponents(frame) { var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH); var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV); for (var i = 0; i < frame.components.length; i++) { component = frame.components[i]; var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / frame.maxH); var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / frame.maxV); var blocksPerLineForMcu = mcusPerLine * component.h; var blocksPerColumnForMcu = mcusPerColumn * component.v; var blocksBufferSize = 64 * blocksPerColumnForMcu * (blocksPerLineForMcu + 1); component.blockData = new Int16Array(blocksBufferSize); component.blocksPerLine = blocksPerLine; component.blocksPerColumn = blocksPerColumn; } frame.mcusPerLine = mcusPerLine; frame.mcusPerColumn = mcusPerColumn; } var offset = 0, length = data.length; var jfif = null; var adobe = null; var pixels = null; var frame, resetInterval; var quantizationTables = []; var huffmanTablesAC = [], huffmanTablesDC = []; var fileMarker = readUint16(); if (fileMarker != 0xFFD8) { // SOI (Start of Image) throw "SOI not found"; } fileMarker = readUint16(); while (fileMarker != 0xFFD9) { // EOI (End of image) var i, j, l; switch(fileMarker) { case 0xFFE0: // APP0 (Application Specific) case 0xFFE1: // APP1 case 0xFFE2: // APP2 case 0xFFE3: // APP3 case 0xFFE4: // APP4 case 0xFFE5: // APP5 case 0xFFE6: // APP6 case 0xFFE7: // APP7 case 0xFFE8: // APP8 case 0xFFE9: // APP9 case 0xFFEA: // APP10 case 0xFFEB: // APP11 case 0xFFEC: // APP12 case 0xFFED: // APP13 case 0xFFEE: // APP14 case 0xFFEF: // APP15 case 0xFFFE: // COM (Comment) var appData = readDataBlock(); if (fileMarker === 0xFFE0) { if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00' jfif = { version: { major: appData[5], minor: appData[6] }, densityUnits: appData[7], xDensity: (appData[8] << 8) | appData[9], yDensity: (appData[10] << 8) | appData[11], thumbWidth: appData[12], thumbHeight: appData[13], thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) }; } } // TODO APP1 - Exif if (fileMarker === 0xFFEE) { if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00' adobe = { version: appData[6], flags0: (appData[7] << 8) | appData[8], flags1: (appData[9] << 8) | appData[10], transformCode: appData[11] }; } } break; case 0xFFDB: // DQT (Define Quantization Tables) var quantizationTablesLength = readUint16(); var quantizationTablesEnd = quantizationTablesLength + offset - 2; while (offset < quantizationTablesEnd) { var quantizationTableSpec = data[offset++]; var tableData = new Int32Array(64); if ((quantizationTableSpec >> 4) === 0) { // 8 bit values for (j = 0; j < 64; j++) { var z = dctZigZag[j]; tableData[z] = data[offset++]; } } else if ((quantizationTableSpec >> 4) === 1) { //16 bit for (j = 0; j < 64; j++) { var z = dctZigZag[j]; tableData[z] = readUint16(); } } else throw "DQT: invalid table spec"; quantizationTables[quantizationTableSpec & 15] = tableData; } break; case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT) case 0xFFC1: // SOF1 (Start of Frame, Extended DCT) case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT) if (frame) { throw "Only single frame JPEGs supported"; } readUint16(); // skip data length frame = {}; frame.extended = (fileMarker === 0xFFC1); frame.progressive = (fileMarker === 0xFFC2); frame.precision = data[offset++]; frame.scanLines = readUint16(); frame.samplesPerLine = readUint16(); frame.components = []; frame.componentIds = {}; var componentsCount = data[offset++], componentId; var maxH = 0, maxV = 0; for (i = 0; i < componentsCount; i++) { componentId = data[offset]; var h = data[offset + 1] >> 4; var v = data[offset + 1] & 15; if (maxH < h) maxH = h; if (maxV < v) maxV = v; var qId = data[offset + 2]; var l = frame.components.push({ h: h, v: v, quantizationTable: quantizationTables[qId] }); frame.componentIds[componentId] = l - 1; offset += 3; } frame.maxH = maxH; frame.maxV = maxV; prepareComponents(frame); break; case 0xFFC4: // DHT (Define Huffman Tables) var huffmanLength = readUint16(); for (i = 2; i < huffmanLength;) { var huffmanTableSpec = data[offset++]; var codeLengths = new Uint8Array(16); var codeLengthSum = 0; for (j = 0; j < 16; j++, offset++) codeLengthSum += (codeLengths[j] = data[offset]); var huffmanValues = new Uint8Array(codeLengthSum); for (j = 0; j < codeLengthSum; j++, offset++) huffmanValues[j] = data[offset]; i += 17 + codeLengthSum; ((huffmanTableSpec >> 4) === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues); } break; case 0xFFDD: // DRI (Define Restart Interval) readUint16(); // skip data length resetInterval = readUint16(); break; case 0xFFDA: // SOS (Start of Scan) var scanLength = readUint16(); var selectorsCount = data[offset++]; var components = [], component; for (i = 0; i < selectorsCount; i++) { var componentIndex = frame.componentIds[data[offset++]]; component = frame.components[componentIndex]; var tableSpec = data[offset++]; component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; components.push(component); } var spectralStart = data[offset++]; var spectralEnd = data[offset++]; var successiveApproximation = data[offset++]; var processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15); offset += processed; break; default: if (data[offset - 3] == 0xFF && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) { // could be incorrect encoding -- last 0xFF byte of the previous // block was eaten by the encoder offset -= 3; break; } throw "unknown JPEG marker " + fileMarker.toString(16); } fileMarker = readUint16(); } this.width = frame.samplesPerLine; this.height = frame.scanLines; this.jfif = jfif; this.adobe = adobe; this.components = []; for (var i = 0; i < frame.components.length; i++) { var component = frame.components[i]; this.components.push({ output: buildComponentData(frame, component), scaleX: component.h / frame.maxH, scaleY: component.v / frame.maxV, blocksPerLine: component.blocksPerLine, blocksPerColumn: component.blocksPerColumn }); } }, getData: function getData(width, height) { var scaleX = this.width / width, scaleY = this.height / height; var component, componentScaleX, componentScaleY; var x, y, i; var offset = 0; var Y, Cb, Cr, K, C, M, Ye, R, G, B; var colorTransform; var numComponents = this.components.length; var dataLength = width * height * numComponents; var data = new Uint8Array(dataLength); var componentLine; // lineData is reused for all components. Assume first component is // the biggest var lineData = new Uint8Array((this.components[0].blocksPerLine << 3) * this.components[0].blocksPerColumn * 8); // First construct image data ... for (i = 0; i < numComponents; i++) { component = this.components[i]; var blocksPerLine = component.blocksPerLine; var blocksPerColumn = component.blocksPerColumn; var samplesPerLine = blocksPerLine << 3; var j, k, ll = 0; var lineOffset = 0; for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { var scanLine = blockRow << 3; for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { var bufferOffset = getBlockBufferOffset(component, blockRow, blockCol); var offset = 0, sample = blockCol << 3; for (j = 0; j < 8; j++) { var lineOffset = (scanLine + j) * samplesPerLine; for (k = 0; k < 8; k++) { lineData[lineOffset + sample + k] = component.output[bufferOffset + offset++]; } } } } componentScaleX = component.scaleX * scaleX; componentScaleY = component.scaleY * scaleY; offset = i; var cx, cy; var index; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cy = 0 | (y * componentScaleY); cx = 0 | (x * componentScaleX); index = cy * samplesPerLine + cx; data[offset] = lineData[index]; offset += numComponents; } } } // ... then transform colors, if necessary switch (numComponents) { case 1: case 2: break; // no color conversion for one or two compoenents case 3: // The default transform for three components is true colorTransform = true; // The adobe transform marker overrides any previous setting if (this.adobe && this.adobe.transformCode) colorTransform = true; else if (typeof this.colorTransform !== 'undefined') colorTransform = !!this.colorTransform; if (colorTransform) { for (i = 0; i < dataLength; i += numComponents) { Y = data[i ]; Cb = data[i + 1]; Cr = data[i + 2]; R = clampToUint8(Y - 179.456 + 1.402 * Cr); G = clampToUint8(Y + 135.459 - 0.344 * Cb - 0.714 * Cr); B = clampToUint8(Y - 226.816 + 1.772 * Cb); data[i ] = R; data[i + 1] = G; data[i + 2] = B; } } break; case 4: if (!this.adobe) throw 'Unsupported color mode (4 components)'; // The default transform for four components is false colorTransform = false; // The adobe transform marker overrides any previous setting if (this.adobe && this.adobe.transformCode) colorTransform = true; else if (typeof this.colorTransform !== 'undefined') colorTransform = !!this.colorTransform; if (colorTransform) { for (i = 0; i < dataLength; i += numComponents) { Y = data[i]; Cb = data[i + 1]; Cr = data[i + 2]; C = clampToUint8(434.456 - Y - 1.402 * Cr); M = clampToUint8(119.541 - Y + 0.344 * Cb + 0.714 * Cr); Y = clampToUint8(481.816 - Y - 1.772 * Cb); data[i ] = C; data[i + 1] = M; data[i + 2] = Y; // K is unchanged } } break; default: throw 'Unsupported color mode'; } return data; }, copyToImageData: function copyToImageData(imageData) { var width = imageData.width, height = imageData.height; var imageDataBytes = width * height * 4; var imageDataArray = imageData.data; var data = this.getData(width, height); var i = 0, j = 0, k0, k1; var Y, K, C, M, R, G, B; switch (this.components.length) { case 1: while (j < imageDataBytes) { Y = data[i++]; imageDataArray[j++] = Y; imageDataArray[j++] = Y; imageDataArray[j++] = Y; imageDataArray[j++] = 255; } break; case 3: while (j < imageDataBytes) { R = data[i++]; G = data[i++]; B = data[i++]; imageDataArray[j++] = R; imageDataArray[j++] = G; imageDataArray[j++] = B; imageDataArray[j++] = 255; } break; case 4: while (j < imageDataBytes) { C = data[i++]; M = data[i++]; Y = data[i++]; K = data[i++]; k0 = 255 - K; k1 = k0 / 255; R = clampToUint8(k0 - C * k1); G = clampToUint8(k0 - M * k1); B = clampToUint8(k0 - Y * k1); imageDataArray[j++] = R; imageDataArray[j++] = G; imageDataArray[j++] = B; imageDataArray[j++] = 255; } break; default: throw 'Unsupported color mode'; } } }; return constructor; })(); OrthancWebViewer-2.3/WebApplication/viewer.css0000644000000000000000000000372313133653001017636 0ustar 00000000000000.jsPanel-hdr-r { display: none; } .ui-button-icon-only { padding-top: 6px; padding-bottom: 6px; } .jsPanel-content { padding: 4px; overflow-y: visible !important; } .jsPanel-hdr img { padding-top: 4px; padding-bottom: 4px; display: block; margin-left: auto; margin-right: auto; } .ui-slider .ui-slider-handle { height: 20px; } .ui-icon-custom-default { background-image: url(images/default.png) !important; } .ui-icon-custom-orthanc { background-image: url(images/orthanc-icon.png) !important; } .ui-icon-custom-stretch { background-image: url(images/stretch.png) !important; } .ui-icon-custom-bone { background-image: url(images/bone.png) !important; } .ui-icon-custom-lung { background-image: url(images/lung.png) !important; } .ui-icon-custom-interpolation { background-image: url(images/interpolation.png) !important; } .ui-icon-custom-inversion { background-image: url(images/inversion.png) !important; } #dicomImageWrapper { top: 0px; left: 0px; width: 100%; height: 100%; position: absolute; background-color: black; color: white; overflow: hidden; font-family: Arial, Helvetica, sans-serif; } #dicomImage { width: 100%; height: 100%; top: 0px; left: 0px; position: absolute; } #topleft { position: absolute; top: 10px; left: 10px; } #topleft img { vertical-align: middle; } #topright { position: absolute; top: 10px; right: 10px; text-align: right; } #bottomright { position: absolute; bottom:25px; right:10px; } #bottomleft { position: absolute; bottom: 25px; left: 10px; } #bottomcenter { position: absolute; bottom: 25px; left: 10px; right: 10px; width: 100%; text-align: center; } #bottom { position: absolute; bottom: 0px; left: 0px; height: 20px; width: 100%; } .alert { color: #f00; font-weight: bold; } OrthancWebViewer-2.3/WebApplication/viewer.html0000644000000000000000000000613013133653001020005 0ustar 00000000000000 Orthanc Web Viewer
 
Render Time:
Zoom:
WW/WC:
Not for diagnostic purpose
OrthancWebViewer-2.3/WebApplication/viewer.js0000644000000000000000000004014013133653001017454 0ustar 00000000000000/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017 Osimis, Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . **/ // Set the default compression var compression = 'jpeg95'; var isFirst = true; //var compression = 'deflate'; // Prevent the access to IE if(navigator.appVersion.indexOf("MSIE ") != -1) { alert("Please use Mozilla Firefox or Google Chrome. Microsoft Internet Explorer is not supported."); } function ResizeCornerstone() { $('#dicomImage').height($(window).height() - $('#slider').parent().height()); var element = $('#dicomImage').get(0); cornerstone.resize(element, true); } function SetWindowing(center, width) { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); viewport.voi.windowCenter = center; viewport.voi.windowWidth = width; cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } function SetFullWindowing() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); var image = cornerstone.getEnabledElement(element).image; if (image.color) { // Ignore color images return; } var minValue = image.minPixelValue; var maxValue = image.maxPixelValue; if (minValue == undefined || maxValue == undefined || minValue == maxValue) { return; } if (image.slope != undefined && image.intercept != undefined) { minValue = minValue * image.slope + image.intercept; maxValue = maxValue * image.slope + image.intercept; } viewport.voi.windowCenter = (minValue + maxValue) / 2.0; viewport.voi.windowWidth = (maxValue - minValue) / 2.0; cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } function SetDefaultWindowing() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); var image = cornerstone.getEnabledElement(element).image; viewport.voi.windowCenter = image.windowCenter; viewport.voi.windowWidth = image.windowWidth; cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } function SetBoneWindowing() { SetWindowing(300, 2000); } function SetLungWindowing() { SetWindowing(-600, 1600); } function UpdateViewportInformation() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); $('#bottomleft').text('WW/WL:' + Math.round(viewport.voi.windowWidth) + '/' + Math.round(viewport.voi.windowCenter)); $('#bottomright').text('Zoom: ' + viewport.scale.toFixed(2) + 'x'); } function ToggleSeriesInformation() { $('#topright').toggle(); } function ToggleInterpolation() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); if (viewport.pixelReplication === true) { viewport.pixelReplication = false; } else { viewport.pixelReplication = true; } cornerstone.setViewport(element, viewport); } function ToggleInversion() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); if (viewport.invert === true) { viewport.invert = false; } else { viewport.invert = true; } cornerstone.setViewport(element, viewport); } function DownloadInstance(instance) { // http://stackoverflow.com/a/3749395/881731 var hiddenIFrameID = 'hiddenDownloader', iframe = document.getElementById(hiddenIFrameID); if (iframe === null) { iframe = document.createElement('iframe'); iframe.id = hiddenIFrameID; iframe.style.display = 'none'; document.body.appendChild(iframe); } iframe.src = '../../instances/' + instance + '/file'; } function AdjustZoom() { var element = $('#dicomImage').get(0); cornerstone.fitToWindow(element); } function ZoomIn() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); viewport.scale /= 0.5; cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } function ZoomOut() { var element = $('#dicomImage').get(0); var viewport = cornerstone.getViewport(element); viewport.scale *= 0.5; cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } (function (cornerstone) { 'use strict'; function PrintRange(pixels) { var a = Infinity; var b = -Infinity; for (var i = 0, length = pixels.length; i < length; i++) { if (pixels[i] < a) a = pixels[i]; if (pixels[i] > b) b = pixels[i]; } console.log(a + ' ' + b); } function ChangeDynamics(pixels, source1, target1, source2, target2) { var scale = (target2 - target1) / (source2 - source1); var offset = (target1) - scale * source1; for (var i = 0, length = pixels.length; i < length; i++) { pixels[i] = scale * pixels[i] + offset; } } function getPixelDataDeflate(image) { // Decompresses the base64 buffer that was compressed with Deflate var s = pako.inflate(window.atob(image.Orthanc.PixelData)); var pixels = null; if (image.color) { var buf = new ArrayBuffer(s.length / 3 * 4); // RGB32 pixels = new Uint8Array(buf); var index = 0; for (var i = 0, length = s.length; i < length; i += 3) { pixels[index++] = s[i]; pixels[index++] = s[i + 1]; pixels[index++] = s[i + 2]; pixels[index++] = 255; // Alpha channel } } else{ var buf = new ArrayBuffer(s.length * 2); // uint16_t or int16_t if (image.Orthanc.IsSigned) { pixels = new Int16Array(buf); } else { pixels = new Uint16Array(buf); } var index = 0; for (var i = 0, length = s.length; i < length; i += 2) { var lower = s[i]; var upper = s[i + 1]; pixels[index] = lower + upper * 256; index++; } } return pixels; } // http://stackoverflow.com/a/11058858/881731 function str2ab(str) { var buf = new ArrayBuffer(str.length); var pixels = new Uint8Array(buf); for (var i = 0, strLen=str.length; i' + volume.PatientName + '
' + volume.StudyDescription + '
' + volume.SeriesDescription + '
'); } }, failure: function() { alert('Error: This image is not supported by the Web viewer.'); } }); if (instances.length == 0) { console.log('No image in this series'); return; } $.ajax({ type: 'GET', url: '../is-stable-series/' + series, dataType: 'json', cache: false, async: true, success: function(stable) { if (!stable) { $('#unstable').show(); } } }); var currentImageIndex = 0; // updates the image display function updateTheImage(imageIndex) { return cornerstone.loadAndCacheImage(instances[imageIndex]).then(function(image) { currentImageIndex = imageIndex; var viewport = cornerstone.getViewport(element); cornerstone.displayImage(element, image, viewport); }); } // image enable the element var element = $('#dicomImage').get(0); cornerstone.enable(element); // set event handlers /*function onImageRendered(e, eventData) { $('#topright').text('Render Time:' + eventData.renderTimeInMs + ' ms'); } $(element).on('CornerstoneImageRendered', onImageRendered);*/ // load and display the image var imagePromise = updateTheImage(0); // add handlers for mouse events once the image is loaded. imagePromise.then(function() { viewport = cornerstone.getViewport(element); UpdateViewportInformation(); // add event handlers to pan image on mouse move $('#dicomImage').mousedown(function (e) { var lastX = e.pageX; var lastY = e.pageY; var mouseButton = e.which; $(toolbar).hide(); $(document).mousemove(function (e) { var deltaX = e.pageX - lastX, deltaY = e.pageY - lastY; lastX = e.pageX; lastY = e.pageY; if (mouseButton == 1) { var viewport = cornerstone.getViewport(element); viewport.voi.windowWidth += (deltaX / viewport.scale); viewport.voi.windowCenter += (deltaY / viewport.scale); cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } else if (mouseButton == 2) { var viewport = cornerstone.getViewport(element); viewport.translation.x += (deltaX / viewport.scale); viewport.translation.y += (deltaY / viewport.scale); cornerstone.setViewport(element, viewport); } else if (mouseButton == 3) { var viewport = cornerstone.getViewport(element); viewport.scale += (deltaY / 100); cornerstone.setViewport(element, viewport); UpdateViewportInformation(); } }); $(document).mouseup(function (e) { $(document).unbind('mousemove'); $(document).unbind('mouseup'); }); }); $('#dicomImage').on('mousewheel DOMMouseScroll', function (e) { // Firefox e.originalEvent.detail > 0 scroll back, < 0 scroll forward // chrome/safari e.originalEvent.wheelDelta < 0 scroll back, > 0 scroll forward if (e.originalEvent.wheelDelta < 0 || e.originalEvent.detail > 0) { currentImageIndex ++; if (currentImageIndex >= instances.length) { currentImageIndex = instances.length - 1; } } else { currentImageIndex --; if (currentImageIndex < 0) { currentImageIndex = 0; } } updateTheImage(currentImageIndex); $('#slider').slider("option", "value", currentImageIndex); //prevent page fom scrolling return false; }); }); $('#slider').slider({ min: 0, max: instances.length - 1, slide: function(event, ui) { updateTheImage(ui.value); } }); var toolbar = $.jsPanel({ position: { top: 50, left: 10 }, size: { width: 155, height: 200 }, content: $('#toolbar-content').clone().show(), controls: { buttons: 'none' }, title: '
' }); $('#open-toolbar').click(function() { toolbar.toggle(); }); $(toolbar).hide(); $('.toolbar-view', toolbar).buttonset() .children().first().button({ icons: { primary: 'ui-icon-info' }, text: false }).click(ToggleSeriesInformation).next().button({ icons: { primary: 'ui-icon-custom-inversion' }, text: false }).click(ToggleInversion).next().button({ icons: { primary: 'ui-icon-custom-interpolation' }, text: false }).click(ToggleInterpolation).next().button({ icons: { primary: 'ui-icon-circle-triangle-s' }, text: false }).click(function() { DownloadInstance(instances[currentImageIndex]); }); $('.toolbar-zoom', toolbar).buttonset() .children().first().button({ icons: { primary: 'ui-icon-image' }, text: false }).click(AdjustZoom).next().button({ icons: { primary: 'ui-icon-zoomin' }, text: false }).click(ZoomIn).next().button({ icons: { primary: 'ui-icon-zoomout' }, text: false }).click(ZoomOut); $('.toolbar-windowing', toolbar).buttonset() .children().first().button({ icons: { primary: 'ui-icon-custom-default' }, text: false }).click(SetDefaultWindowing).next().button({ icons: { primary: 'ui-icon-custom-stretch' }, text: false }).click(SetFullWindowing).next().button({ icons: { primary: 'ui-icon-custom-lung' }, text: false }).click(SetLungWindowing).next().button({ icons: { primary: 'ui-icon-custom-bone' }, text: false }).click(SetBoneWindowing); function SetCompression(c) { compression = c; cornerstone.imageCache.purgeCache(); updateTheImage(currentImageIndex); cornerstone.invalidateImageId(instances[currentImageIndex]); } $('.toolbar-quality', toolbar).buttonset() .children().first().button({ label: 'L' }).click(function() { SetCompression('jpeg80'); }).next().button({ label: 'M' }).click(function() { SetCompression('jpeg95'); }).next().button({ label: 'H' }).click(function() { SetCompression('deflate'); }); ResizeCornerstone(); $(window).resize(function(e) { if (!$(e.target).hasClass('jsPanel')) // Ignore toolbar resizing { ResizeCornerstone(); } }); });