# HG changeset patch # User Sebastien Jodogne # Date 1593096670 -7200 # Node ID fb74ed5d8c22a57fcc9df0aeb816cd99c38294e4 # Parent 5a3ef478deb665840f96f026eab1219ff50032b0 initial commit of the Stone Web viewer diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/COPYING --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/COPYING Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,661 @@ + 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 +. diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Plugin/CMakeLists.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Plugin/CMakeLists.txt Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 2.8.3) + +project(StoneWebViewerPlugin) + +set(ORTHANC_ROOT ${CMAKE_CURRENT_LIST_DIR}/../../../orthanc CACHE PATH "") +set(STONE_BINARIES CACHE PATH "") + +include(${ORTHANC_ROOT}/Resources/CMake/OrthancFrameworkParameters.cmake) +set(ENABLE_MODULE_IMAGES OFF) +set(ENABLE_MODULE_JOBS OFF) +set(ENABLE_MODULE_DICOM OFF) +include(${ORTHANC_ROOT}/Resources/CMake/OrthancFrameworkConfiguration.cmake) + +include_directories( + ${ORTHANC_ROOT}/Core + ${ORTHANC_ROOT}/Plugins/Samples/Common + ${ORTHANC_ROOT}/Plugins/Include # TODO => Fix a version + ) + +add_definitions( + -DHAS_ORTHANC_EXCEPTION=1 + -DPLUGIN_VERSION="mainline" # TODO + -DPLUGIN_NAME="stone-webviewer" + ) + +EmbedResources( + ORTHANC_EXPLORER ${CMAKE_SOURCE_DIR}/OrthancExplorer.js + STONE_WRAPPER ${STONE_BINARIES}/stone.js + STONE_WEB_VIEWER_JS ${STONE_BINARIES}/StoneWebViewer.js + STONE_WEB_VIEWER_WASM ${STONE_BINARIES}/StoneWebViewer.wasm + WEB_APPLICATION ${CMAKE_SOURCE_DIR}/../WebApplication + IMAGES ${STONE_BINARIES}/img/ + ) + +add_library(StoneWebViewer SHARED + Plugin.cpp + ${AUTOGENERATED_SOURCES} + ${ORTHANC_ROOT}/Plugins/Samples/Common/OrthancPluginCppWrapper.cpp + ${ORTHANC_CORE_SOURCES} + ) diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Plugin/OrthancExplorer.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Plugin/OrthancExplorer.js Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,57 @@ +$('#study').live('pagebeforecreate', function() { + var b = $('') + .attr('data-role', 'button') + .attr('href', '#') + .attr('data-icon', 'search') + .attr('data-theme', 'e') + .text('Stone Web Viewer'); + + b.insertBefore($('#study-delete').parent().parent()); + b.click(function() { + if ($.mobile.pageData) { + $.ajax({ + url: '../studies/' + $.mobile.pageData.uuid, + dataType: 'json', + cache: false, + success: function(study) { + var studyInstanceUid = study.MainDicomTags.StudyInstanceUID; + window.open('../stone-webviewer/index.html?study=' + studyInstanceUid); + } + }); + } + }); +}); + + +$('#series').live('pagebeforecreate', function() { + var b = $('') + .attr('data-role', 'button') + .attr('href', '#') + .attr('data-icon', 'search') + .attr('data-theme', 'e') + .text('Stone Web Viewer'); + + b.insertBefore($('#series-delete').parent().parent()); + b.click(function() { + if ($.mobile.pageData) { + $.ajax({ + url: '../series/' + $.mobile.pageData.uuid, + dataType: 'json', + cache: false, + success: function(series) { + $.ajax({ + url: '../studies/' + series.ParentStudy, + dataType: 'json', + cache: false, + success: function(study) { + var studyInstanceUid = study.MainDicomTags.StudyInstanceUID; + var seriesInstanceUid = series.MainDicomTags.SeriesInstanceUID; + window.open('../stone-webviewer/index.html?study=' + studyInstanceUid + + '&series=' + seriesInstanceUid); + } + }); + } + }); + } + }); +}); diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Plugin/Plugin.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Plugin/Plugin.cpp Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,235 @@ +/** + * Stone of Orthanc + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * Copyright (C) 2017-2020 Osimis S.A., 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 + +OrthancPluginErrorCode OnChangeCallback(OrthancPluginChangeType changeType, + OrthancPluginResourceType resourceType, + const char* resourceId) +{ + try + { + if (changeType == OrthancPluginChangeType_OrthancStarted) + { + Json::Value info; + if (!OrthancPlugins::RestApiGet(info, "/plugins/dicom-web", false)) + { + throw Orthanc::OrthancException( + Orthanc::ErrorCode_InternalError, + "The Stone Web viewer requires the DICOMweb plugin to be installed"); + } + + if (info.type() != Json::objectValue || + !info.isMember("ID") || + !info.isMember("Version") || + info["ID"].type() != Json::stringValue || + info["Version"].type() != Json::stringValue || + info["ID"].asString() != "dicom-web") + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError, + "The DICOMweb plugin is not properly installed"); + } + + std::string version = info["Version"].asString(); + if (version != "mainline") + { + std::vector tokens; + Orthanc::Toolbox::TokenizeString(tokens, version, '.'); + if (tokens.size() != 2) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError, + "Bad version of the DICOMweb plugin: " + version); + } + + int major, minor; + + try + { + major = boost::lexical_cast(tokens[0]); + minor = boost::lexical_cast(tokens[1]); + } + catch (boost::bad_lexical_cast&) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError, + "Bad version of the DICOMweb plugin: " + version); + } + + if (major <= 0 || + (major == 1 && minor <= 1)) + { + throw Orthanc::OrthancException( + Orthanc::ErrorCode_InternalError, + "The Stone Web viewer requires DICOMweb plugin with version >= 1.2, found: " + version); + } + + if (major <= 0 || + (major == 1 && minor == 2)) + { + /** + * DICOMweb 1.3 is better than 1.2 for 2 reasons: (1) + * MONOCHROME1 images are not properly rendered in DICOMweb + * 1.2, and (2) DICOMweb 1.2 cannot transcode images (this + * causes issues on JPEG2k images). + **/ + LOG(WARNING) << "The Stone Web viewer has some incompatibilities " + << "with DICOMweb plugin 1.2, consider upgrading the DICOMweb plugin"; + } + } + } + } + catch (Orthanc::OrthancException& e) + { + LOG(ERROR) << "Exception: " << e.What(); + return static_cast(e.GetErrorCode()); + } + + return OrthancPluginErrorCode_Success; +} + + +template +void ServeEmbeddedFolder(OrthancPluginRestOutput* output, + const char* url, + const OrthancPluginHttpRequest* request) +{ + OrthancPluginContext* context = OrthancPlugins::GetGlobalContext(); + + if (request->method != OrthancPluginHttpMethod_Get) + { + OrthancPluginSendMethodNotAllowed(context, output, "GET"); + } + else + { + std::string path = "/" + std::string(request->groups[0]); + const char* mime = Orthanc::EnumerationToString(Orthanc::SystemToolbox::AutodetectMimeType(path)); + + 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); + } +} + + +template +void ServeEmbeddedFile(OrthancPluginRestOutput* output, + const char* url, + const OrthancPluginHttpRequest* request) +{ + OrthancPluginContext* context = OrthancPlugins::GetGlobalContext(); + + if (request->method != OrthancPluginHttpMethod_Get) + { + OrthancPluginSendMethodNotAllowed(context, output, "GET"); + } + else + { + const char* mime = Orthanc::EnumerationToString(Orthanc::SystemToolbox::AutodetectMimeType(url)); + + std::string s; + Orthanc::EmbeddedResources::GetFileResource(s, file); + + const char* resource = s.size() ? s.c_str() : NULL; + OrthancPluginAnswerBuffer(context, output, resource, s.size(), mime); + } +} + + +extern "C" +{ + ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* context) + { + OrthancPlugins::SetGlobalContext(context); + Orthanc::Logging::InitializePluginContext(context); + + /* 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; + } + + try + { + std::string explorer; + Orthanc::EmbeddedResources::GetFileResource( + explorer, Orthanc::EmbeddedResources::ORTHANC_EXPLORER); + OrthancPluginExtendOrthancExplorer(OrthancPlugins::GetGlobalContext(), explorer.c_str()); + + OrthancPlugins::RegisterRestCallback + > + ("/stone-webviewer/StoneWebViewer.wasm", true); + + OrthancPlugins::RegisterRestCallback + > + ("/stone-webviewer/StoneWebViewer.js", true); + + OrthancPlugins::RegisterRestCallback + > + ("/stone-webviewer/stone.js", true); + + OrthancPlugins::RegisterRestCallback + > + ("/stone-webviewer/img/(.*)", true); + + OrthancPlugins::RegisterRestCallback + > + ("/stone-webviewer/(.*)", true); + + OrthancPluginRegisterOnChangeCallback(context, OnChangeCallback); + } + catch (...) + { + OrthancPlugins::LogError("Exception while initializing the Stone Web viewer plugin"); + return -1; + } + + return 0; + } + + + ORTHANC_PLUGINS_API void OrthancPluginFinalize() + { + } + + + ORTHANC_PLUGINS_API const char* OrthancPluginGetName() + { + return PLUGIN_NAME; + } + + + ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion() + { + return PLUGIN_VERSION; + } +} diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Resources/GenerateImages.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Resources/GenerateImages.py Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,88 @@ +#!/usr/bin/env python + +# Stone of Orthanc +# Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics +# Department, University Hospital of Liege, Belgium +# Copyright (C) 2017-2020 Osimis S.A., 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 . + + +import os +from PIL import Image + +SOURCE = os.path.dirname(os.path.abspath(__file__)) +TARGET = os.path.join(SOURCE, '..', 'WebApplication', 'img') + +try: + os.makedirs(TARGET) +except: # Directory already exists + pass + +color = (217, 217, 217, 255) +border = 3 +width = 32 +height = 32 + + + +image = Image.new('RGBA', (width, height)) + +for x in range(0, width): + for y in range(0, height): + image.putpixel((x, y), color) + +image.save(os.path.join(TARGET, 'grid1x1.png'), 'PNG') + + + +image = Image.new('RGBA', (width, height)) + +for x in range(0, width / 2 - border): + for y in range(0, height / 2 - border): + image.putpixel((x, y), color) + for y in range(height / 2 + border, height): + image.putpixel((x, y), color) + +for x in range(width / 2 + border, width): + for y in range(0, height / 2 - border): + image.putpixel((x, y), color) + for y in range(height / 2 + border, height): + image.putpixel((x, y), color) + +image.save(os.path.join(TARGET, 'grid2x2.png'), 'PNG') + + + +image = Image.new('RGBA', (width, height)) + +for y in range(0, height): + for x in range(0, width / 2 - border): + image.putpixel((x, y), color) + for x in range(width / 2 + border, width): + image.putpixel((x, y), color) + +image.save(os.path.join(TARGET, 'grid2x1.png'), 'PNG') + + + +image = Image.new('RGBA', (width, height)) + +for x in range(0, width): + for y in range(0, height / 2 - border): + image.putpixel((x, y), color) + for y in range(height / 2 + border, height): + image.putpixel((x, y), color) + +image.save(os.path.join(TARGET, 'grid1x2.png'), 'PNG') diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Resources/NOTES.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Resources/NOTES.txt Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,15 @@ + +Origin of SCSS +============== + +The "Styles" folder is a copy of: +https://bitbucket.org/osimis/osimis-webviewer-plugin/src/master/frontend/src/styles/ + + + +Generation of CSS from the SCSS +=============================== + +$ npm install node-sass +$ ./node_modules/node-sass/bin/node-sass ./Styles/styles.scss > ../WebApplication/app.css +$ ./GenerateImages.py diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/Resources/Styles/_button.scss --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/Resources/Styles/_button.scss Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,205 @@ +// clean icon buttons +.wvButton { + // Remove default styles. Take care - this class may either be used + // with or + + + + +
+
+ +
+
+ + +
+
+ +
+
+
+ + +
+ +
+
+ +
+
+ +
+ +

For patients, teachers and researchers.

+
+
+ +
+
+
+
+ + + + + {{ study.tags['0008,1030'] }} +
+ {{ study.tags['0008,0020'] }} +
+ +
+
    +
  • +
    +
    + +
    + + + + + + +
    + + + + +
    {{ series[seriesIndex].length }}
    +
    +
    + +
    +

    + [{{ series[seriesIndex].tags['0008,0060'] }}] + {{ series[seriesIndex].tags['0008,103e'] }} +

    +
    +
  • +
+
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ + + +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+ + +
+
+ + + + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/CMakeLists.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/CMakeLists.txt Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,125 @@ +cmake_minimum_required(VERSION 2.8.3) + +project(OrthancStone) + +# Configuration of the Emscripten compiler for WebAssembly target +# --------------------------------------------------------------- +set(USE_WASM ON CACHE BOOL "") +set(ORTHANC_FRAMEWORK_ROOT ${CMAKE_CURRENT_LIST_DIR}/../../../orthanc CACHE PATH "") +set(STONE_ROOT ${CMAKE_CURRENT_LIST_DIR}/../../) + +set(EMSCRIPTEN_SET_LLVM_WASM_BACKEND ON CACHE BOOL "") + +set(WASM_FLAGS "-s WASM=1 -s FETCH=1") +if (CMAKE_BUILD_TYPE STREQUAL "Debug") + set(WASM_FLAGS "${WASM_FLAGS} -s SAFE_HEAP=1") +endif() + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WASM_FLAGS}") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WASM_FLAGS}") + +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s EXTRA_EXPORTED_RUNTIME_METHODS='[\"ccall\", \"cwrap\"]'") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s ERROR_ON_UNDEFINED_SYMBOLS=1") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s ASSERTIONS=1 -s DISABLE_EXCEPTION_CATCHING=0") +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s ALLOW_MEMORY_GROWTH=1 -s TOTAL_MEMORY=268435456") # 256MB + resize +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s DISABLE_DEPRECATED_FIND_EVENT_TARGET_BEHAVIOR=1") +add_definitions( + -DDISABLE_DEPRECATED_FIND_EVENT_TARGET_BEHAVIOR=1 +) + +# Stone of Orthanc configuration +# --------------------------------------------------------------- +set(ALLOW_DOWNLOADS ON) +set(ORTHANC_FRAMEWORK_SOURCE "path") + +include(${STONE_ROOT}/Resources/CMake/OrthancStoneParameters.cmake) +include(${ORTHANC_ROOT}/Resources/CMake/AutoGeneratedCode.cmake) +include(${ORTHANC_ROOT}/Resources/CMake/DownloadPackage.cmake) + +SET(ENABLE_DCMTK ON) +SET(ENABLE_DCMTK_NETWORKING OFF) +SET(ENABLE_DCMTK_TRANSCODING OFF) +SET(ENABLE_GOOGLE_TEST OFF) +SET(ENABLE_LOCALE ON) # Necessary for text rendering +SET(ENABLE_WASM ON) +SET(ORTHANC_SANDBOXED ON) + +# this will set up the build system for Stone of Orthanc and will +# populate the ORTHANC_STONE_SOURCES CMake variable +include(${STONE_ROOT}/Resources/CMake/OrthancStoneConfiguration.cmake) + + +################################################################################ + +project(StoneWebViewer) + + +# Create the wrapper to call C++ from JavaScript +# --------------------------------------------------------------- + +set(LIBCLANG "libclang-4.0.so.1" CACHE PATH "Version of clang to generate the code model") +set(STONE_WRAPPER ${CMAKE_CURRENT_BINARY_DIR}/stone.js) + +add_custom_command( + COMMAND + ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/ParseWebAssemblyExports.py --libclang=${LIBCLANG} ${CMAKE_SOURCE_DIR}/Test.cpp > ${STONE_WRAPPER} + DEPENDS + ${CMAKE_SOURCE_DIR}/Test.cpp + ${CMAKE_SOURCE_DIR}/ParseWebAssemblyExports.py + OUTPUT + ${STONE_WRAPPER} + ) + +add_custom_target(StoneWrapper + DEPENDS + ${STONE_WRAPPER} + ) + + +# Define the WASM module +# --------------------------------------------------------------- + +add_executable(StoneWebViewer + ${ORTHANC_STONE_SOURCES} + ${AUTOGENERATED_SOURCES} + Test.cpp + ) + +# Make sure to have the wrapper generated +add_dependencies(StoneWebViewer StoneWrapper) + + +# Declare installation files for the module +# --------------------------------------------------------------- + +install( + TARGETS StoneWebViewer + RUNTIME DESTINATION . + ) + + +# Declare installation files for the companion files (web scaffolding) +# please note that ${CMAKE_CURRENT_BINARY_DIR}/StoneWebViewer.js +# (the generated JS loader for the WASM module) is handled by the `install1` +# section above: it is considered to be the binary output of +# the linker. +# --------------------------------------------------------------- +install( + FILES + ${CMAKE_CURRENT_BINARY_DIR}/StoneWebViewer.wasm + ${CMAKE_SOURCE_DIR}/../WebApplication/app.css + ${CMAKE_SOURCE_DIR}/../WebApplication/app.js + ${CMAKE_SOURCE_DIR}/../WebApplication/index.html + ${STONE_WRAPPER} + DESTINATION . + ) + +install( + FILES + ${CMAKE_SOURCE_DIR}/../WebApplication/img/grid1x1.png + ${CMAKE_SOURCE_DIR}/../WebApplication/img/grid1x2.png + ${CMAKE_SOURCE_DIR}/../WebApplication/img/grid2x1.png + ${CMAKE_SOURCE_DIR}/../WebApplication/img/grid2x2.png + ${CMAKE_SOURCE_DIR}/../WebApplication/img/loading.gif + DESTINATION img + ) diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/NOTES.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/NOTES.txt Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,2 @@ +# source ~/Downloads/emsdk/emsdk_env.sh +# cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=${EMSDK}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake -G Ninja diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/ParseWebAssemblyExports.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/ParseWebAssemblyExports.py Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,196 @@ +#!/usr/bin/env python + +# Stone of Orthanc +# Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics +# Department, University Hospital of Liege, Belgium +# Copyright (C) 2017-2020 Osimis S.A., 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 . + + + +# Ubuntu 18.04: +# sudo apt-get install python-clang-4.0 +# ./ParseWebAssemblyExports.py --libclang=libclang-4.0.so.1 ./Test.cpp + + +# Ubuntu 14.04: +# ./ParseWebAssemblyExports.py --libclang=libclang-3.6.so.1 ./Test.cpp + + +import sys +import clang.cindex +import pystache +import argparse + + + +## +## Parse the command-line arguments +## + +parser = argparse.ArgumentParser(description = 'Parse WebAssembly C++ source file, and create a basic JavaScript wrapper.') +parser.add_argument('--libclang', + default = '', + help = 'manually provides the path to the libclang shared library') +parser.add_argument('source', + help = 'Input C++ file') + +args = parser.parse_args() + + + +if len(args.libclang) != 0: + clang.cindex.Config.set_library_file(args.libclang) + +index = clang.cindex.Index.create() + +# PARSE_SKIP_FUNCTION_BODIES prevents clang from failing because of +# undefined types, which prevents compilation of functions +tu = index.parse(args.source, + [ '-DEMSCRIPTEN_KEEPALIVE=__attribute__((annotate("WebAssembly")))' ], + options = clang.cindex.TranslationUnit.PARSE_SKIP_FUNCTION_BODIES) + + + +TEMPLATE = ''' +const Stone = function() { + {{#enumerations}} + this.{{name}} = { + {{#values}} + {{name}}: {{value}}{{separator}} + {{/values}} + }; + + {{/enumerations}} + {{#functions}} + this._{{name}} = undefined; + {{/functions}} +}; + +Stone.prototype.Setup = function(Module) { + {{#functions}} + this._{{name}} = Module.cwrap('{{name}}', {{{returnType}}}, [ {{#args}}{{{type}}}{{^last}}, {{/last}}{{/args}} ]); + {{/functions}} +}; + +{{#functions}} +Stone.prototype.{{name}} = function({{#args}}{{name}}{{^last}}, {{/last}}{{/args}}) { + {{#hasReturn}}return {{/hasReturn}}this._{{name}}({{#args}}{{name}}{{^last}}, {{/last}}{{/args}}); +}; + +{{/functions}} +var stone = new Stone(); +''' + + + + +# WARNING: Undefined types are mapped as "int" + +functions = [] +enumerations = [] + +def ToUpperCase(source): + target = source[0] + for c in source[1:]: + if c.isupper(): + target += '_' + target += c.upper() + return target + + + +def IsExported(node): + for child in node.get_children(): + if (child.kind == clang.cindex.CursorKind.ANNOTATE_ATTR and + child.displayname == 'WebAssembly'): + return True + + return False + + +def Explore(node): + if node.kind == clang.cindex.CursorKind.ENUM_DECL: + if IsExported(node): + name = node.spelling + values = [] + for value in node.get_children(): + if (value.spelling.startswith(name + '_')): + s = value.spelling[len(name) + 1:] + if len(values) > 0: + values[-1]['separator'] = ',' + values.append({ + 'name' : ToUpperCase(s), + 'value' : value.enum_value + }) + + enumerations.append({ + 'name' : name, + 'values' : values + }) + + if node.kind == clang.cindex.CursorKind.FUNCTION_DECL: + if IsExported(node): + f = { + 'name' : node.spelling, + 'args' : [], + } + + returnType = node.result_type.spelling + if returnType == 'void': + f['hasReturn'] = False + f['returnType'] = "null" + elif returnType == 'const char *': + f['hasReturn'] = True + f['returnType'] = "'string'" + elif returnType in [ 'int', 'unsigned int' ]: + f['hasReturn'] = True + f['returnType'] = "'int'" + else: + raise Exception('Unknown return type in function "%s()": %s' % (node.spelling, returnType)) + + for child in node.get_children(): + if child.kind == clang.cindex.CursorKind.PARM_DECL: + arg = { + 'name' : child.displayname, + } + + argType = child.type.spelling + if argType == 'int': + arg['type'] = "'int'" + elif argType == 'const char *': + arg['type'] = "'string'" + else: + raise Exception('Unknown type for argument "%s" in function "%s()": %s' % + (child.displayname, node.spelling, argType)) + + f['args'].append(arg) + + if len(f['args']) != 0: + f['args'][-1]['last'] = True + + functions.append(f) + + for child in node.get_children(): + Explore(child) + +Explore(tu.cursor) + + + +print(pystache.render(TEMPLATE, { + 'functions' : functions, + 'enumerations' : enumerations +})) diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/Test.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/Test.cpp Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,2246 @@ +/** + * Stone of Orthanc + * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics + * Department, University Hospital of Liege, Belgium + * Copyright (C) 2017-2020 Osimis S.A., 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 + + +#define DISPATCH_JAVASCRIPT_EVENT(name) \ + EM_ASM( \ + const customEvent = document.createEvent("CustomEvent"); \ + customEvent.initCustomEvent(name, false, false, undefined); \ + window.dispatchEvent(customEvent); \ + ); + + +#define EXTERN_CATCH_EXCEPTIONS \ + catch (Orthanc::OrthancException& e) \ + { \ + LOG(ERROR) << "OrthancException: " << e.What(); \ + DISPATCH_JAVASCRIPT_EVENT("StoneException"); \ + } \ + catch (OrthancStone::StoneException& e) \ + { \ + LOG(ERROR) << "StoneException: " << e.What(); \ + DISPATCH_JAVASCRIPT_EVENT("StoneException"); \ + } \ + catch (std::exception& e) \ + { \ + LOG(ERROR) << "Runtime error: " << e.what(); \ + DISPATCH_JAVASCRIPT_EVENT("StoneException"); \ + } \ + catch (...) \ + { \ + LOG(ERROR) << "Native exception"; \ + DISPATCH_JAVASCRIPT_EVENT("StoneException"); \ + } + + +#include +#include +#include +#include +#include +#include +#include + +#include "../../Framework/Loaders/DicomResourcesLoader.h" +#include "../../Framework/Loaders/SeriesMetadataLoader.h" +#include "../../Framework/Loaders/SeriesThumbnailsLoader.h" +#include "../../Framework/Loaders/WebAssemblyLoadersContext.h" +#include "../../Framework/Messages/ObserverBase.h" +#include "../../Framework/Oracle/ParseDicomFromWadoCommand.h" +#include "../../Framework/Scene2D/ColorTextureSceneLayer.h" +#include "../../Framework/Scene2D/FloatTextureSceneLayer.h" +#include "../../Framework/Scene2D/PolylineSceneLayer.h" +#include "../../Framework/StoneException.h" +#include "../../Framework/Toolbox/DicomInstanceParameters.h" +#include "../../Framework/Toolbox/GeometryToolbox.h" +#include "../../Framework/Toolbox/SortedFrames.h" +#include "../../Framework/Viewport/WebGLViewport.h" + +#include +#include + + +enum EMSCRIPTEN_KEEPALIVE ThumbnailType +{ + ThumbnailType_Image, + ThumbnailType_NoPreview, + ThumbnailType_Pdf, + ThumbnailType_Video, + ThumbnailType_Loading, + ThumbnailType_Unknown +}; + + +enum EMSCRIPTEN_KEEPALIVE DisplayedFrameQuality +{ +DisplayedFrameQuality_None, + DisplayedFrameQuality_Low, + DisplayedFrameQuality_High + }; + + + +static const int PRIORITY_HIGH = -100; +static const int PRIORITY_LOW = 100; +static const int PRIORITY_NORMAL = 0; + +static const unsigned int QUALITY_JPEG = 0; +static const unsigned int QUALITY_FULL = 1; + +class ResourcesLoader : public OrthancStone::ObserverBase +{ +public: + class IObserver : public boost::noncopyable + { + public: + virtual ~IObserver() + { + } + + virtual void SignalResourcesLoaded() = 0; + + virtual void SignalSeriesThumbnailLoaded(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) = 0; + + virtual void SignalSeriesMetadataLoaded(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) = 0; + }; + +private: + std::unique_ptr observer_; + OrthancStone::DicomSource source_; + size_t pending_; + boost::shared_ptr studies_; + boost::shared_ptr series_; + boost::shared_ptr resourcesLoader_; + boost::shared_ptr thumbnailsLoader_; + boost::shared_ptr metadataLoader_; + + ResourcesLoader(const OrthancStone::DicomSource& source) : + source_(source), + pending_(0), + studies_(new OrthancStone::LoadedDicomResources(Orthanc::DICOM_TAG_STUDY_INSTANCE_UID)), + series_(new OrthancStone::LoadedDicomResources(Orthanc::DICOM_TAG_SERIES_INSTANCE_UID)) + { + } + + void Handle(const OrthancStone::DicomResourcesLoader::SuccessMessage& message) + { + const Orthanc::SingleValueObject& payload = + dynamic_cast&>(message.GetUserPayload()); + + OrthancStone::LoadedDicomResources& dicom = *message.GetResources(); + + LOG(INFO) << "resources loaded: " << dicom.GetSize() + << ", " << Orthanc::EnumerationToString(payload.GetValue()); + + if (payload.GetValue() == Orthanc::ResourceType_Series) + { + for (size_t i = 0; i < dicom.GetSize(); i++) + { + std::string studyInstanceUid, seriesInstanceUid; + if (dicom.GetResource(i).LookupStringValue( + studyInstanceUid, Orthanc::DICOM_TAG_STUDY_INSTANCE_UID, false) && + dicom.GetResource(i).LookupStringValue( + seriesInstanceUid, Orthanc::DICOM_TAG_SERIES_INSTANCE_UID, false)) + { + thumbnailsLoader_->ScheduleLoadThumbnail(source_, "", studyInstanceUid, seriesInstanceUid); + metadataLoader_->ScheduleLoadSeries(PRIORITY_LOW + 1, source_, studyInstanceUid, seriesInstanceUid); + } + } + } + + if (pending_ == 0) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError); + } + else + { + pending_ --; + if (pending_ == 0 && + observer_.get() != NULL) + { + observer_->SignalResourcesLoaded(); + } + } + } + + void Handle(const OrthancStone::SeriesThumbnailsLoader::SuccessMessage& message) + { + if (observer_.get() != NULL) + { + observer_->SignalSeriesThumbnailLoaded( + message.GetStudyInstanceUid(), message.GetSeriesInstanceUid()); + } + } + + void Handle(const OrthancStone::SeriesMetadataLoader::SuccessMessage& message) + { + if (observer_.get() != NULL) + { + observer_->SignalSeriesMetadataLoaded( + message.GetStudyInstanceUid(), message.GetSeriesInstanceUid()); + } + } + + void FetchInternal(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) + { + // Firstly, load the study + Orthanc::DicomMap filter; + filter.SetValue(Orthanc::DICOM_TAG_STUDY_INSTANCE_UID, studyInstanceUid, false); + + std::set tags; + tags.insert(Orthanc::DICOM_TAG_STUDY_DESCRIPTION); // Necessary for Orthanc DICOMweb plugin + + resourcesLoader_->ScheduleQido( + studies_, PRIORITY_HIGH, source_, Orthanc::ResourceType_Study, filter, tags, + new Orthanc::SingleValueObject(Orthanc::ResourceType_Study)); + + // Secondly, load the series + if (!seriesInstanceUid.empty()) + { + filter.SetValue(Orthanc::DICOM_TAG_SERIES_INSTANCE_UID, seriesInstanceUid, false); + } + + tags.insert(Orthanc::DICOM_TAG_SERIES_NUMBER); // Necessary for Google Cloud Platform + + resourcesLoader_->ScheduleQido( + series_, PRIORITY_HIGH, source_, Orthanc::ResourceType_Series, filter, tags, + new Orthanc::SingleValueObject(Orthanc::ResourceType_Series)); + + pending_ += 2; + } + +public: + static boost::shared_ptr Create(OrthancStone::ILoadersContext::ILock& lock, + const OrthancStone::DicomSource& source) + { + boost::shared_ptr loader(new ResourcesLoader(source)); + + loader->resourcesLoader_ = OrthancStone::DicomResourcesLoader::Create(lock); + loader->thumbnailsLoader_ = OrthancStone::SeriesThumbnailsLoader::Create(lock, PRIORITY_LOW); + loader->metadataLoader_ = OrthancStone::SeriesMetadataLoader::Create(lock); + + loader->Register( + *loader->resourcesLoader_, &ResourcesLoader::Handle); + + loader->Register( + *loader->thumbnailsLoader_, &ResourcesLoader::Handle); + + loader->Register( + *loader->metadataLoader_, &ResourcesLoader::Handle); + + return loader; + } + + void FetchAllStudies() + { + FetchInternal("", ""); + } + + void FetchStudy(const std::string& studyInstanceUid) + { + FetchInternal(studyInstanceUid, ""); + } + + void FetchSeries(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) + { + FetchInternal(studyInstanceUid, seriesInstanceUid); + } + + size_t GetStudiesCount() const + { + return studies_->GetSize(); + } + + size_t GetSeriesCount() const + { + return series_->GetSize(); + } + + void GetStudy(Orthanc::DicomMap& target, + size_t i) + { + target.Assign(studies_->GetResource(i)); + } + + void GetSeries(Orthanc::DicomMap& target, + size_t i) + { + target.Assign(series_->GetResource(i)); + + // Complement with the study-level tags + std::string studyInstanceUid; + if (target.LookupStringValue(studyInstanceUid, Orthanc::DICOM_TAG_STUDY_INSTANCE_UID, false) && + studies_->HasResource(studyInstanceUid)) + { + studies_->MergeResource(target, studyInstanceUid); + } + } + + OrthancStone::SeriesThumbnailType GetSeriesThumbnail(std::string& image, + std::string& mime, + const std::string& seriesInstanceUid) + { + return thumbnailsLoader_->GetSeriesThumbnail(image, mime, seriesInstanceUid); + } + + void FetchSeriesMetadata(int priority, + const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) + { + metadataLoader_->ScheduleLoadSeries(priority, source_, studyInstanceUid, seriesInstanceUid); + } + + bool IsSeriesComplete(const std::string& seriesInstanceUid) + { + OrthancStone::SeriesMetadataLoader::Accessor accessor(*metadataLoader_, seriesInstanceUid); + return accessor.IsComplete(); + } + + bool SortSeriesFrames(OrthancStone::SortedFrames& target, + const std::string& seriesInstanceUid) + { + OrthancStone::SeriesMetadataLoader::Accessor accessor(*metadataLoader_, seriesInstanceUid); + + if (accessor.IsComplete()) + { + target.Clear(); + + for (size_t i = 0; i < accessor.GetInstancesCount(); i++) + { + target.AddInstance(accessor.GetInstance(i)); + } + + target.Sort(); + + return true; + } + else + { + return false; + } + } + + void AcquireObserver(IObserver* observer) + { + observer_.reset(observer); + } +}; + + + +class FramesCache : public boost::noncopyable +{ +private: + class CachedImage : public Orthanc::ICacheable + { + private: + std::unique_ptr image_; + unsigned int quality_; + + public: + CachedImage(Orthanc::ImageAccessor* image, + unsigned int quality) : + image_(image), + quality_(quality) + { + assert(image != NULL); + } + + virtual size_t GetMemoryUsage() const + { + assert(image_.get() != NULL); + return (image_->GetBytesPerPixel() * image_->GetPitch() * image_->GetHeight()); + } + + const Orthanc::ImageAccessor& GetImage() const + { + assert(image_.get() != NULL); + return *image_; + } + + unsigned int GetQuality() const + { + return quality_; + } + }; + + + static std::string GetKey(const std::string& sopInstanceUid, + size_t frameIndex) + { + return sopInstanceUid + "|" + boost::lexical_cast(frameIndex); + } + + + Orthanc::MemoryObjectCache cache_; + +public: + FramesCache() + { + SetMaximumSize(100 * 1024 * 1024); // 100 MB + } + + size_t GetMaximumSize() + { + return cache_.GetMaximumSize(); + } + + void SetMaximumSize(size_t size) + { + cache_.SetMaximumSize(size); + } + + /** + * Returns "true" iff the provided image has better quality than the + * previously cached one, or if no cache was previously available. + **/ + bool Acquire(const std::string& sopInstanceUid, + size_t frameIndex, + Orthanc::ImageAccessor* image /* transfer ownership */, + unsigned int quality) + { + std::unique_ptr protection(image); + + if (image == NULL) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer); + } + else if (image->GetFormat() != Orthanc::PixelFormat_Float32 && + image->GetFormat() != Orthanc::PixelFormat_RGB24) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_IncompatibleImageFormat); + } + + const std::string& key = GetKey(sopInstanceUid, frameIndex); + + bool invalidate = false; + + { + /** + * Access the previous cached entry, with side effect of tagging + * it as the most recently accessed frame (update of LRU recycling) + **/ + Orthanc::MemoryObjectCache::Accessor accessor(cache_, key, false /* unique lock */); + + if (accessor.IsValid()) + { + const CachedImage& previous = dynamic_cast(accessor.GetValue()); + + // There is already a cached image for this frame + if (previous.GetQuality() < quality) + { + // The previously stored image has poorer quality + invalidate = true; + } + else + { + // No update in the quality, don't change the cache + return false; + } + } + else + { + invalidate = false; + } + } + + if (invalidate) + { + cache_.Invalidate(key); + } + + cache_.Acquire(key, new CachedImage(protection.release(), quality)); + return true; + } + + class Accessor : public boost::noncopyable + { + private: + Orthanc::MemoryObjectCache::Accessor accessor_; + + const CachedImage& GetCachedImage() const + { + if (IsValid()) + { + return dynamic_cast(accessor_.GetValue()); + } + else + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); + } + } + + public: + Accessor(FramesCache& that, + const std::string& sopInstanceUid, + size_t frameIndex) : + accessor_(that.cache_, GetKey(sopInstanceUid, frameIndex), false /* shared lock */) + { + } + + bool IsValid() const + { + return accessor_.IsValid(); + } + + const Orthanc::ImageAccessor& GetImage() const + { + return GetCachedImage().GetImage(); + } + + unsigned int GetQuality() const + { + return GetCachedImage().GetQuality(); + } + }; +}; + + + +class SeriesCursor : public boost::noncopyable +{ +public: + enum Action + { + Action_FastPlus, + Action_Plus, + Action_None, + Action_Minus, + Action_FastMinus + }; + +private: + std::vector prefetch_; + int framesCount_; + int currentFrame_; + bool isCircular_; + int fastDelta_; + Action lastAction_; + + int ComputeNextFrame(int currentFrame, + Action action) const + { + if (framesCount_ == 0) + { + assert(currentFrame == 0); + return 0; + } + + int nextFrame = currentFrame; + + switch (action) + { + case Action_FastPlus: + nextFrame += fastDelta_; + break; + + case Action_Plus: + nextFrame += 1; + break; + + case Action_None: + break; + + case Action_Minus: + nextFrame -= 1; + break; + + case Action_FastMinus: + nextFrame -= fastDelta_; + break; + + default: + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + + if (isCircular_) + { + while (nextFrame < 0) + { + nextFrame += framesCount_; + } + + while (nextFrame >= framesCount_) + { + nextFrame -= framesCount_; + } + } + else + { + if (nextFrame < 0) + { + nextFrame = 0; + } + else if (nextFrame >= framesCount_) + { + nextFrame = framesCount_ - 1; + } + } + + return nextFrame; + } + + void UpdatePrefetch() + { + /** + * This method will order the frames of the series according to + * the number of "actions" (i.e. mouse wheels) that are necessary + * to reach them, starting from the current frame. It is assumed + * that once one action is done, it is more likely that the user + * will do the same action just afterwards. + **/ + + prefetch_.clear(); + + if (framesCount_ == 0) + { + return; + } + + prefetch_.reserve(framesCount_); + + // Breadth-first search using a FIFO. The queue associates a frame + // and the action that is the most likely in this frame + typedef std::list< std::pair > Queue; + + Queue queue; + std::set visited; // Frames that have already been visited + + queue.push_back(std::make_pair(currentFrame_, lastAction_)); + + while (!queue.empty()) + { + int frame = queue.front().first; + Action previousAction = queue.front().second; + queue.pop_front(); + + if (visited.find(frame) == visited.end()) + { + visited.insert(frame); + prefetch_.push_back(frame); + + switch (previousAction) + { + case Action_None: + case Action_Plus: + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Plus), Action_Plus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Minus), Action_Minus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastPlus), Action_FastPlus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastMinus), Action_FastMinus)); + break; + + case Action_Minus: + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Minus), Action_Minus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Plus), Action_Plus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastMinus), Action_FastMinus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastPlus), Action_FastPlus)); + break; + + case Action_FastPlus: + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastPlus), Action_FastPlus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastMinus), Action_FastMinus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Plus), Action_Plus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Minus), Action_Minus)); + break; + + case Action_FastMinus: + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastMinus), Action_FastMinus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_FastPlus), Action_FastPlus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Minus), Action_Minus)); + queue.push_back(std::make_pair(ComputeNextFrame(frame, Action_Plus), Action_Plus)); + break; + + default: + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + } + } + + assert(prefetch_.size() == framesCount_); + } + + bool CheckFrameIndex(int frame) const + { + return ((framesCount_ == 0 && frame == 0) || + (framesCount_ > 0 && frame >= 0 && frame < framesCount_)); + } + +public: + SeriesCursor(size_t framesCount) : + framesCount_(framesCount), + currentFrame_(framesCount / 2), // Start at the middle frame + isCircular_(false), + lastAction_(Action_None) + { + SetFastDelta(framesCount / 20); + UpdatePrefetch(); + } + + void SetCircular(bool isCircular) + { + isCircular_ = isCircular; + UpdatePrefetch(); + } + + void SetFastDelta(int delta) + { + fastDelta_ = (delta < 0 ? -delta : delta); + + if (fastDelta_ <= 0) + { + fastDelta_ = 1; + } + } + + void SetCurrentIndex(size_t frame) + { + if (frame >= framesCount_) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + else + { + currentFrame_ = frame; + lastAction_ = Action_None; + UpdatePrefetch(); + } + } + + size_t GetCurrentIndex() const + { + assert(CheckFrameIndex(currentFrame_)); + return static_cast(currentFrame_); + } + + void Apply(Action action) + { + currentFrame_ = ComputeNextFrame(currentFrame_, action); + lastAction_ = action; + UpdatePrefetch(); + } + + size_t GetPrefetchSize() const + { + assert(prefetch_.size() == framesCount_); + return prefetch_.size(); + } + + size_t GetPrefetchFrameIndex(size_t i) const + { + if (i >= prefetch_.size()) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + else + { + assert(CheckFrameIndex(prefetch_[i])); + return static_cast(prefetch_[i]); + } + } +}; + + + + +class FrameGeometry +{ +private: + bool isValid_; + std::string frameOfReferenceUid_; + OrthancStone::CoordinateSystem3D coordinates_; + double pixelSpacingX_; + double pixelSpacingY_; + OrthancStone::Extent2D extent_; + +public: + FrameGeometry() : + isValid_(false) + { + } + + FrameGeometry(const Orthanc::DicomMap& tags) : + isValid_(false), + coordinates_(tags) + { + if (!tags.LookupStringValue( + frameOfReferenceUid_, Orthanc::DICOM_TAG_FRAME_OF_REFERENCE_UID, false)) + { + frameOfReferenceUid_.clear(); + } + + OrthancStone::GeometryToolbox::GetPixelSpacing(pixelSpacingX_, pixelSpacingY_, tags); + + unsigned int rows, columns; + if (tags.HasTag(Orthanc::DICOM_TAG_IMAGE_POSITION_PATIENT) && + tags.HasTag(Orthanc::DICOM_TAG_IMAGE_ORIENTATION_PATIENT) && + tags.ParseUnsignedInteger32(rows, Orthanc::DICOM_TAG_ROWS) && + tags.ParseUnsignedInteger32(columns, Orthanc::DICOM_TAG_COLUMNS)) + { + double ox = -pixelSpacingX_ / 2.0; + double oy = -pixelSpacingY_ / 2.0; + extent_.AddPoint(ox, oy); + extent_.AddPoint(ox + pixelSpacingX_ * static_cast(columns), + oy + pixelSpacingY_ * static_cast(rows)); + + isValid_ = true; + } + } + + bool IsValid() const + { + return isValid_; + } + + const std::string& GetFrameOfReferenceUid() const + { + if (isValid_) + { + return frameOfReferenceUid_; + } + else + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); + } + } + + const OrthancStone::CoordinateSystem3D& GetCoordinates() const + { + if (isValid_) + { + return coordinates_; + } + else + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); + } + } + + double GetPixelSpacingX() const + { + if (isValid_) + { + return pixelSpacingX_; + } + else + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); + } + } + + double GetPixelSpacingY() const + { + if (isValid_) + { + return pixelSpacingY_; + } + else + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_BadSequenceOfCalls); + } + } + + bool Intersect(double& x1, // Coordinates of the clipped line (out) + double& y1, + double& x2, + double& y2, + const FrameGeometry& other) const + { + if (this == &other) + { + return false; + } + + OrthancStone::Vector direction, origin; + + if (IsValid() && + other.IsValid() && + !extent_.IsEmpty() && + frameOfReferenceUid_ == other.frameOfReferenceUid_ && + OrthancStone::GeometryToolbox::IntersectTwoPlanes( + origin, direction, + coordinates_.GetOrigin(), coordinates_.GetNormal(), + other.coordinates_.GetOrigin(), other.coordinates_.GetNormal())) + { + double ax, ay, bx, by; + coordinates_.ProjectPoint(ax, ay, origin); + coordinates_.ProjectPoint(bx, by, origin + 100.0 * direction); + + return OrthancStone::GeometryToolbox::ClipLineToRectangle( + x1, y1, x2, y2, + ax, ay, bx, by, + extent_.GetX1(), extent_.GetY1(), extent_.GetX2(), extent_.GetY2()); + } + else + { + return false; + } + } +}; + + + +class ViewerViewport : public OrthancStone::ObserverBase +{ +public: + class IObserver : public boost::noncopyable + { + public: + virtual ~IObserver() + { + } + + virtual void SignalFrameUpdated(const ViewerViewport& viewport, + size_t currentFrame, + size_t countFrames, + DisplayedFrameQuality quality) = 0; + }; + +private: + static const int LAYER_TEXTURE = 0; + static const int LAYER_REFERENCE_LINES = 1; + + + class ICommand : public Orthanc::IDynamicObject + { + private: + boost::shared_ptr viewport_; + + public: + ICommand(boost::shared_ptr viewport) : + viewport_(viewport) + { + if (viewport == NULL) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer); + } + } + + virtual ~ICommand() + { + } + + ViewerViewport& GetViewport() const + { + assert(viewport_ != NULL); + return *viewport_; + } + + virtual void Handle(const OrthancStone::DicomResourcesLoader::SuccessMessage& message) const + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented); + } + + virtual void Handle(const OrthancStone::HttpCommand::SuccessMessage& message) const + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented); + } + + virtual void Handle(const OrthancStone::ParseDicomSuccessMessage& message) const + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented); + } + }; + + class SetDefaultWindowingCommand : public ICommand + { + public: + SetDefaultWindowingCommand(boost::shared_ptr viewport) : + ICommand(viewport) + { + } + + virtual void Handle(const OrthancStone::DicomResourcesLoader::SuccessMessage& message) const ORTHANC_OVERRIDE + { + if (message.GetResources()->GetSize() != 1) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol); + } + + const Orthanc::DicomMap& dicom = message.GetResources()->GetResource(0); + + { + OrthancStone::DicomInstanceParameters params(dicom); + + if (params.HasDefaultWindowing()) + { + GetViewport().defaultWindowingCenter_ = params.GetDefaultWindowingCenter(); + GetViewport().defaultWindowingWidth_ = params.GetDefaultWindowingWidth(); + LOG(INFO) << "Default windowing: " << params.GetDefaultWindowingCenter() + << "," << params.GetDefaultWindowingWidth(); + + GetViewport().windowingCenter_ = params.GetDefaultWindowingCenter(); + GetViewport().windowingWidth_ = params.GetDefaultWindowingWidth(); + } + else + { + LOG(INFO) << "No default windowing"; + GetViewport().ResetDefaultWindowing(); + } + } + + GetViewport().DisplayCurrentFrame(); + } + }; + + class SetLowQualityFrame : public ICommand + { + private: + std::string sopInstanceUid_; + unsigned int frameIndex_; + float windowCenter_; + float windowWidth_; + bool isMonochrome1_; + bool isPrefetch_; + + public: + SetLowQualityFrame(boost::shared_ptr viewport, + const std::string& sopInstanceUid, + unsigned int frameIndex, + float windowCenter, + float windowWidth, + bool isMonochrome1, + bool isPrefetch) : + ICommand(viewport), + sopInstanceUid_(sopInstanceUid), + frameIndex_(frameIndex), + windowCenter_(windowCenter), + windowWidth_(windowWidth), + isMonochrome1_(isMonochrome1), + isPrefetch_(isPrefetch) + { + } + + virtual void Handle(const OrthancStone::HttpCommand::SuccessMessage& message) const ORTHANC_OVERRIDE + { + std::unique_ptr jpeg(new Orthanc::JpegReader); + jpeg->ReadFromMemory(message.GetAnswer()); + + bool updatedCache; + + switch (jpeg->GetFormat()) + { + case Orthanc::PixelFormat_RGB24: + updatedCache = GetViewport().cache_->Acquire( + sopInstanceUid_, frameIndex_, jpeg.release(), QUALITY_JPEG); + break; + + case Orthanc::PixelFormat_Grayscale8: + { + if (isMonochrome1_) + { + Orthanc::ImageProcessing::Invert(*jpeg); + } + + std::unique_ptr converted( + new Orthanc::Image(Orthanc::PixelFormat_Float32, jpeg->GetWidth(), + jpeg->GetHeight(), false)); + + Orthanc::ImageProcessing::Convert(*converted, *jpeg); + + /** + + Orthanc::ImageProcessing::ShiftScale() computes "(x + offset) * scaling". + The system to solve is thus: + + (0 + offset) * scaling = windowingCenter - windowingWidth / 2 [a] + (255 + offset) * scaling = windowingCenter + windowingWidth / 2 [b] + + Resolution: + + [b - a] => 255 * scaling = windowingWidth + [a] => offset = (windowingCenter - windowingWidth / 2) / scaling + + **/ + + const float scaling = windowWidth_ / 255.0f; + const float offset = (OrthancStone::LinearAlgebra::IsCloseToZero(scaling) ? 0 : + (windowCenter_ - windowWidth_ / 2.0f) / scaling); + + Orthanc::ImageProcessing::ShiftScale(*converted, offset, scaling, false); + updatedCache = GetViewport().cache_->Acquire( + sopInstanceUid_, frameIndex_, converted.release(), QUALITY_JPEG); + break; + } + + default: + throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented); + } + + if (updatedCache) + { + GetViewport().SignalUpdatedFrame(sopInstanceUid_, frameIndex_); + } + + if (isPrefetch_) + { + GetViewport().ScheduleNextPrefetch(); + } + } + }; + + + class SetFullDicomFrame : public ICommand + { + private: + std::string sopInstanceUid_; + unsigned int frameIndex_; + bool isPrefetch_; + + public: + SetFullDicomFrame(boost::shared_ptr viewport, + const std::string& sopInstanceUid, + unsigned int frameIndex, + bool isPrefetch) : + ICommand(viewport), + sopInstanceUid_(sopInstanceUid), + frameIndex_(frameIndex), + isPrefetch_(isPrefetch) + { + } + + virtual void Handle(const OrthancStone::ParseDicomSuccessMessage& message) const ORTHANC_OVERRIDE + { + Orthanc::DicomMap tags; + message.GetDicom().ExtractDicomSummary(tags); + + std::string s; + if (!tags.LookupStringValue(s, Orthanc::DICOM_TAG_SOP_INSTANCE_UID, false)) + { + // Safety check + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError); + } + + std::unique_ptr frame( + Orthanc::DicomImageDecoder::Decode(message.GetDicom(), frameIndex_)); + + if (frame.get() == NULL) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_InternalError); + } + + bool updatedCache; + + if (frame->GetFormat() == Orthanc::PixelFormat_RGB24) + { + updatedCache = GetViewport().cache_->Acquire( + sopInstanceUid_, frameIndex_, frame.release(), QUALITY_FULL); + } + else + { + double a = 1; + double b = 0; + + double doseScaling; + if (tags.ParseDouble(doseScaling, Orthanc::DICOM_TAG_DOSE_GRID_SCALING)) + { + a = doseScaling; + } + + double rescaleIntercept, rescaleSlope; + if (tags.ParseDouble(rescaleIntercept, Orthanc::DICOM_TAG_RESCALE_INTERCEPT) && + tags.ParseDouble(rescaleSlope, Orthanc::DICOM_TAG_RESCALE_SLOPE)) + { + a *= rescaleSlope; + b = rescaleIntercept; + } + + std::unique_ptr converted( + new Orthanc::Image(Orthanc::PixelFormat_Float32, frame->GetWidth(), frame->GetHeight(), false)); + Orthanc::ImageProcessing::Convert(*converted, *frame); + Orthanc::ImageProcessing::ShiftScale2(*converted, b, a, false); + + updatedCache = GetViewport().cache_->Acquire( + sopInstanceUid_, frameIndex_, converted.release(), QUALITY_FULL); + } + + if (updatedCache) + { + GetViewport().SignalUpdatedFrame(sopInstanceUid_, frameIndex_); + } + + if (isPrefetch_) + { + GetViewport().ScheduleNextPrefetch(); + } + } + }; + + + class PrefetchItem + { + private: + size_t frameIndex_; + bool isFull_; + + public: + PrefetchItem(size_t frameIndex, + bool isFull) : + frameIndex_(frameIndex), + isFull_(isFull) + { + } + + size_t GetFrameIndex() const + { + return frameIndex_; + } + + bool IsFull() const + { + return isFull_; + } + }; + + + std::unique_ptr observer_; + OrthancStone::ILoadersContext& context_; + boost::shared_ptr viewport_; + boost::shared_ptr loader_; + OrthancStone::DicomSource source_; + boost::shared_ptr cache_; + std::unique_ptr frames_; + std::unique_ptr cursor_; + float windowingCenter_; + float windowingWidth_; + float defaultWindowingCenter_; + float defaultWindowingWidth_; + bool inverted_; + bool fitNextContent_; + bool isCtrlDown_; + FrameGeometry currentFrameGeometry_; + std::list prefetchQueue_; + + void ScheduleNextPrefetch() + { + while (!prefetchQueue_.empty()) + { + size_t index = prefetchQueue_.front().GetFrameIndex(); + bool isFull = prefetchQueue_.front().IsFull(); + prefetchQueue_.pop_front(); + + const std::string sopInstanceUid = frames_->GetFrameSopInstanceUid(index); + unsigned int frame = frames_->GetFrameIndex(index); + + { + FramesCache::Accessor accessor(*cache_, sopInstanceUid, frame); + if (!accessor.IsValid() || + (isFull && accessor.GetQuality() == 0)) + { + if (isFull) + { + ScheduleLoadFullDicomFrame(index, PRIORITY_NORMAL, true); + } + else + { + ScheduleLoadRenderedFrame(index, PRIORITY_NORMAL, true); + } + return; + } + } + } + } + + + void ResetDefaultWindowing() + { + defaultWindowingCenter_ = 128; + defaultWindowingWidth_ = 256; + + windowingCenter_ = defaultWindowingCenter_; + windowingWidth_ = defaultWindowingWidth_; + + inverted_ = false; + } + + void SignalUpdatedFrame(const std::string& sopInstanceUid, + unsigned int frameIndex) + { + if (cursor_.get() != NULL && + frames_.get() != NULL) + { + size_t index = cursor_->GetCurrentIndex(); + + if (frames_->GetFrameSopInstanceUid(index) == sopInstanceUid && + frames_->GetFrameIndex(index) == frameIndex) + { + DisplayCurrentFrame(); + } + } + } + + void DisplayCurrentFrame() + { + DisplayedFrameQuality quality = DisplayedFrameQuality_None; + + if (cursor_.get() != NULL && + frames_.get() != NULL) + { + const size_t index = cursor_->GetCurrentIndex(); + + unsigned int cachedQuality; + if (!DisplayFrame(cachedQuality, index)) + { + // This frame is not cached yet: Load it + if (source_.HasDicomWebRendered()) + { + ScheduleLoadRenderedFrame(index, PRIORITY_HIGH, false /* not a prefetch */); + } + else + { + ScheduleLoadFullDicomFrame(index, PRIORITY_HIGH, false /* not a prefetch */); + } + } + else if (cachedQuality < QUALITY_FULL) + { + // This frame is only available in low-res: Download the full DICOM + ScheduleLoadFullDicomFrame(index, PRIORITY_HIGH, false /* not a prefetch */); + quality = DisplayedFrameQuality_Low; + } + else + { + quality = DisplayedFrameQuality_High; + } + + currentFrameGeometry_ = FrameGeometry(frames_->GetFrameTags(index)); + + { + // Prepare prefetching + prefetchQueue_.clear(); + for (size_t i = 0; i < cursor_->GetPrefetchSize() && i < 16; i++) + { + size_t a = cursor_->GetPrefetchFrameIndex(i); + if (a != index) + { + prefetchQueue_.push_back(PrefetchItem(a, i < 2)); + } + } + + ScheduleNextPrefetch(); + } + + if (observer_.get() != NULL) + { + observer_->SignalFrameUpdated(*this, cursor_->GetCurrentIndex(), + frames_->GetFramesCount(), quality); + } + } + else + { + currentFrameGeometry_ = FrameGeometry(); + } + } + + void ClearViewport() + { + { + std::unique_ptr lock(viewport_->Lock()); + lock->GetController().GetScene().DeleteLayer(LAYER_TEXTURE); + //lock->GetCompositor().Refresh(lock->GetController().GetScene()); + lock->Invalidate(); + } + } + + bool DisplayFrame(unsigned int& quality, + size_t index) + { + if (frames_.get() == NULL) + { + return false; + } + + const std::string sopInstanceUid = frames_->GetFrameSopInstanceUid(index); + unsigned int frame = frames_->GetFrameIndex(index); + + FramesCache::Accessor accessor(*cache_, sopInstanceUid, frame); + if (accessor.IsValid()) + { + quality = accessor.GetQuality(); + + std::unique_ptr layer; + + switch (accessor.GetImage().GetFormat()) + { + case Orthanc::PixelFormat_RGB24: + layer.reset(new OrthancStone::ColorTextureSceneLayer(accessor.GetImage())); + break; + + case Orthanc::PixelFormat_Float32: + { + std::unique_ptr tmp( + new OrthancStone::FloatTextureSceneLayer(accessor.GetImage())); + tmp->SetCustomWindowing(windowingCenter_, windowingWidth_); + tmp->SetInverted(inverted_ ^ frames_->IsFrameMonochrome1(index)); + layer.reset(tmp.release()); + break; + } + + default: + throw Orthanc::OrthancException(Orthanc::ErrorCode_IncompatibleImageFormat); + } + + layer->SetLinearInterpolation(true); + + double pixelSpacingX, pixelSpacingY; + OrthancStone::GeometryToolbox::GetPixelSpacing( + pixelSpacingX, pixelSpacingY, frames_->GetFrameTags(index)); + layer->SetPixelSpacing(pixelSpacingX, pixelSpacingY); + + if (layer.get() == NULL) + { + return false; + } + else + { + std::unique_ptr lock(viewport_->Lock()); + lock->GetController().GetScene().SetLayer(LAYER_TEXTURE, layer.release()); + + if (fitNextContent_) + { + lock->GetCompositor().RefreshCanvasSize(); + lock->GetCompositor().FitContent(lock->GetController().GetScene()); + fitNextContent_ = false; + } + + //lock->GetCompositor().Refresh(lock->GetController().GetScene()); + lock->Invalidate(); + return true; + } + } + else + { + return false; + } + } + + void ScheduleLoadFullDicomFrame(size_t index, + int priority, + bool isPrefetch) + { + if (frames_.get() != NULL) + { + std::string sopInstanceUid = frames_->GetFrameSopInstanceUid(index); + unsigned int frame = frames_->GetFrameIndex(index); + + { + std::unique_ptr lock(context_.Lock()); + lock->Schedule( + GetSharedObserver(), priority, OrthancStone::ParseDicomFromWadoCommand::Create( + source_, frames_->GetStudyInstanceUid(), frames_->GetSeriesInstanceUid(), + sopInstanceUid, false /* transcoding (TODO) */, + Orthanc::DicomTransferSyntax_LittleEndianExplicit /* TODO */, + new SetFullDicomFrame(GetSharedObserver(), sopInstanceUid, frame, isPrefetch))); + } + } + } + + void ScheduleLoadRenderedFrame(size_t index, + int priority, + bool isPrefetch) + { + if (!source_.HasDicomWebRendered()) + { + ScheduleLoadFullDicomFrame(index, priority, isPrefetch); + } + else if (frames_.get() != NULL) + { + std::string sopInstanceUid = frames_->GetFrameSopInstanceUid(index); + unsigned int frame = frames_->GetFrameIndex(index); + bool isMonochrome1 = frames_->IsFrameMonochrome1(index); + + const std::string uri = ("studies/" + frames_->GetStudyInstanceUid() + + "/series/" + frames_->GetSeriesInstanceUid() + + "/instances/" + sopInstanceUid + + "/frames/" + boost::lexical_cast(frame + 1) + "/rendered"); + + std::map headers, arguments; + arguments["window"] = ( + boost::lexical_cast(defaultWindowingCenter_) + "," + + boost::lexical_cast(defaultWindowingWidth_) + ",linear"); + + std::unique_ptr command( + source_.CreateDicomWebCommand( + uri, arguments, headers, new SetLowQualityFrame( + GetSharedObserver(), sopInstanceUid, frame, + defaultWindowingCenter_, defaultWindowingWidth_, isMonochrome1, isPrefetch))); + + { + std::unique_ptr lock(context_.Lock()); + lock->Schedule(GetSharedObserver(), priority, command.release()); + } + } + } + + ViewerViewport(OrthancStone::ILoadersContext& context, + const OrthancStone::DicomSource& source, + const std::string& canvas, + boost::shared_ptr cache) : + context_(context), + source_(source), + viewport_(OrthancStone::WebGLViewport::Create(canvas)), + cache_(cache), + fitNextContent_(true), + isCtrlDown_(false) + { + if (!cache_) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer); + } + + emscripten_set_wheel_callback(viewport_->GetCanvasCssSelector().c_str(), this, true, OnWheel); + emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, this, false, OnKey); + emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, this, false, OnKey); + + ResetDefaultWindowing(); + } + + static EM_BOOL OnKey(int eventType, + const EmscriptenKeyboardEvent *event, + void *userData) + { + /** + * WARNING: There is a problem with Firefox 71 that seems to mess + * the "ctrlKey" value. + **/ + + ViewerViewport& that = *reinterpret_cast(userData); + that.isCtrlDown_ = event->ctrlKey; + return false; + } + + + static EM_BOOL OnWheel(int eventType, + const EmscriptenWheelEvent *wheelEvent, + void *userData) + { + ViewerViewport& that = *reinterpret_cast(userData); + + if (that.cursor_.get() != NULL) + { + if (wheelEvent->deltaY < 0) + { + that.ChangeFrame(that.isCtrlDown_ ? SeriesCursor::Action_FastMinus : SeriesCursor::Action_Minus); + } + else if (wheelEvent->deltaY > 0) + { + that.ChangeFrame(that.isCtrlDown_ ? SeriesCursor::Action_FastPlus : SeriesCursor::Action_Plus); + } + } + + return true; + } + + void Handle(const OrthancStone::DicomResourcesLoader::SuccessMessage& message) + { + dynamic_cast(message.GetUserPayload()).Handle(message); + } + + void Handle(const OrthancStone::HttpCommand::SuccessMessage& message) + { + dynamic_cast(message.GetOrigin().GetPayload()).Handle(message); + } + + void Handle(const OrthancStone::ParseDicomSuccessMessage& message) + { + dynamic_cast(message.GetOrigin().GetPayload()).Handle(message); + } + +public: + static boost::shared_ptr Create(OrthancStone::ILoadersContext::ILock& lock, + const OrthancStone::DicomSource& source, + const std::string& canvas, + boost::shared_ptr cache) + { + boost::shared_ptr viewport( + new ViewerViewport(lock.GetContext(), source, canvas, cache)); + + viewport->loader_ = OrthancStone::DicomResourcesLoader::Create(lock); + viewport->Register( + *viewport->loader_, &ViewerViewport::Handle); + + viewport->Register( + lock.GetOracleObservable(), &ViewerViewport::Handle); + + viewport->Register( + lock.GetOracleObservable(), &ViewerViewport::Handle); + + return viewport; + } + + void SetFrames(OrthancStone::SortedFrames* frames) + { + if (frames == NULL) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_NullPointer); + } + + fitNextContent_ = true; + + frames_.reset(frames); + cursor_.reset(new SeriesCursor(frames_->GetFramesCount())); + + LOG(INFO) << "Number of frames in series: " << frames_->GetFramesCount(); + + ResetDefaultWindowing(); + ClearViewport(); + prefetchQueue_.clear(); + currentFrameGeometry_ = FrameGeometry(); + + if (observer_.get() != NULL) + { + observer_->SignalFrameUpdated(*this, cursor_->GetCurrentIndex(), + frames_->GetFramesCount(), DisplayedFrameQuality_None); + } + + if (frames_->GetFramesCount() != 0) + { + const std::string& sopInstanceUid = frames_->GetFrameSopInstanceUid(cursor_->GetCurrentIndex()); + + { + // Fetch the default windowing for the central instance + const std::string uri = ("studies/" + frames_->GetStudyInstanceUid() + + "/series/" + frames_->GetSeriesInstanceUid() + + "/instances/" + sopInstanceUid + "/metadata"); + + loader_->ScheduleGetDicomWeb( + boost::make_shared(Orthanc::DICOM_TAG_SOP_INSTANCE_UID), + 0, source_, uri, new SetDefaultWindowingCommand(GetSharedObserver())); + } + } + } + + // This method is used when the layout of the HTML page changes, + // which does not trigger the "emscripten_set_resize_callback()" + void UpdateSize(bool fitContent) + { + std::unique_ptr lock(viewport_->Lock()); + lock->GetCompositor().RefreshCanvasSize(); + + if (fitContent) + { + lock->GetCompositor().FitContent(lock->GetController().GetScene()); + } + + lock->Invalidate(); + } + + void AcquireObserver(IObserver* observer) + { + observer_.reset(observer); + } + + const std::string& GetCanvasId() const + { + assert(viewport_); + return viewport_->GetCanvasId(); + } + + void ChangeFrame(SeriesCursor::Action action) + { + if (cursor_.get() != NULL) + { + size_t previous = cursor_->GetCurrentIndex(); + + cursor_->Apply(action); + + size_t current = cursor_->GetCurrentIndex(); + if (previous != current) + { + DisplayCurrentFrame(); + } + } + } + + const FrameGeometry& GetCurrentFrameGeometry() const + { + return currentFrameGeometry_; + } + + void UpdateReferenceLines(const std::list& planes) + { + std::unique_ptr layer(new OrthancStone::PolylineSceneLayer); + + if (GetCurrentFrameGeometry().IsValid()) + { + for (std::list::const_iterator + it = planes.begin(); it != planes.end(); ++it) + { + assert(*it != NULL); + + double x1, y1, x2, y2; + if (GetCurrentFrameGeometry().Intersect(x1, y1, x2, y2, **it)) + { + OrthancStone::PolylineSceneLayer::Chain chain; + chain.push_back(OrthancStone::ScenePoint2D(x1, y1)); + chain.push_back(OrthancStone::ScenePoint2D(x2, y2)); + layer->AddChain(chain, false, 0, 255, 0); + } + } + } + + { + std::unique_ptr lock(viewport_->Lock()); + + if (layer->GetChainsCount() == 0) + { + lock->GetController().GetScene().DeleteLayer(LAYER_REFERENCE_LINES); + } + else + { + lock->GetController().GetScene().SetLayer(LAYER_REFERENCE_LINES, layer.release()); + } + + //lock->GetCompositor().Refresh(lock->GetController().GetScene()); + lock->Invalidate(); + } + } + + + void ClearReferenceLines() + { + { + std::unique_ptr lock(viewport_->Lock()); + lock->GetController().GetScene().DeleteLayer(LAYER_REFERENCE_LINES); + lock->Invalidate(); + } + } + + + void SetDefaultWindowing() + { + SetWindowing(defaultWindowingCenter_, defaultWindowingWidth_); + } + + void SetWindowing(float windowingCenter, + float windowingWidth) + { + windowingCenter_ = windowingCenter; + windowingWidth_ = windowingWidth; + + { + std::unique_ptr lock(viewport_->Lock()); + + if (lock->GetController().GetScene().HasLayer(LAYER_TEXTURE) && + lock->GetController().GetScene().GetLayer(LAYER_TEXTURE).GetType() == + OrthancStone::ISceneLayer::Type_FloatTexture) + { + dynamic_cast( + lock->GetController().GetScene().GetLayer(LAYER_TEXTURE)). + SetCustomWindowing(windowingCenter_, windowingWidth_); + lock->Invalidate(); + } + } + } + + void Invert() + { + inverted_ = !inverted_; + + { + std::unique_ptr lock(viewport_->Lock()); + + if (lock->GetController().GetScene().HasLayer(LAYER_TEXTURE) && + lock->GetController().GetScene().GetLayer(LAYER_TEXTURE).GetType() == + OrthancStone::ISceneLayer::Type_FloatTexture) + { + OrthancStone::FloatTextureSceneLayer& layer = + dynamic_cast( + lock->GetController().GetScene().GetLayer(LAYER_TEXTURE)); + + // NB: Using "IsInverted()" instead of "inverted_" is for + // compatibility with MONOCHROME1 images + layer.SetInverted(!layer.IsInverted()); + lock->Invalidate(); + } + } + } +}; + + + + + +typedef std::map > Viewports; +static Viewports allViewports_; +static bool showReferenceLines_ = true; + + +static void UpdateReferenceLines() +{ + if (showReferenceLines_) + { + std::list planes; + + for (Viewports::const_iterator it = allViewports_.begin(); it != allViewports_.end(); ++it) + { + assert(it->second != NULL); + planes.push_back(&it->second->GetCurrentFrameGeometry()); + } + + for (Viewports::iterator it = allViewports_.begin(); it != allViewports_.end(); ++it) + { + assert(it->second != NULL); + it->second->UpdateReferenceLines(planes); + } + } + else + { + for (Viewports::iterator it = allViewports_.begin(); it != allViewports_.end(); ++it) + { + assert(it->second != NULL); + it->second->ClearReferenceLines(); + } + } +} + + +class WebAssemblyObserver : public ResourcesLoader::IObserver, + public ViewerViewport::IObserver +{ +public: + virtual void SignalResourcesLoaded() ORTHANC_OVERRIDE + { + DISPATCH_JAVASCRIPT_EVENT("ResourcesLoaded"); + } + + virtual void SignalSeriesThumbnailLoaded(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) ORTHANC_OVERRIDE + { + EM_ASM({ + const customEvent = document.createEvent("CustomEvent"); + customEvent.initCustomEvent("ThumbnailLoaded", false, false, + { "studyInstanceUid" : UTF8ToString($0), + "seriesInstanceUid" : UTF8ToString($1) }); + window.dispatchEvent(customEvent); + }, + studyInstanceUid.c_str(), + seriesInstanceUid.c_str()); + } + + virtual void SignalSeriesMetadataLoaded(const std::string& studyInstanceUid, + const std::string& seriesInstanceUid) ORTHANC_OVERRIDE + { + EM_ASM({ + const customEvent = document.createEvent("CustomEvent"); + customEvent.initCustomEvent("MetadataLoaded", false, false, + { "studyInstanceUid" : UTF8ToString($0), + "seriesInstanceUid" : UTF8ToString($1) }); + window.dispatchEvent(customEvent); + }, + studyInstanceUid.c_str(), + seriesInstanceUid.c_str()); + } + + virtual void SignalFrameUpdated(const ViewerViewport& viewport, + size_t currentFrame, + size_t countFrames, + DisplayedFrameQuality quality) ORTHANC_OVERRIDE + { + EM_ASM({ + const customEvent = document.createEvent("CustomEvent"); + customEvent.initCustomEvent("FrameUpdated", false, false, + { "canvasId" : UTF8ToString($0), + "currentFrame" : $1, + "framesCount" : $2, + "quality" : $3 }); + window.dispatchEvent(customEvent); + }, + viewport.GetCanvasId().c_str(), + static_cast(currentFrame), + static_cast(countFrames), + quality); + + + UpdateReferenceLines(); + }; +}; + + + +static OrthancStone::DicomSource source_; +static boost::shared_ptr cache_; +static boost::shared_ptr context_; +static std::string stringBuffer_; + + + +static void FormatTags(std::string& target, + const Orthanc::DicomMap& tags) +{ + Orthanc::DicomArray arr(tags); + Json::Value v = Json::objectValue; + + for (size_t i = 0; i < arr.GetSize(); i++) + { + const Orthanc::DicomElement& element = arr.GetElement(i); + if (!element.GetValue().IsBinary() && + !element.GetValue().IsNull()) + { + v[element.GetTag().Format()] = element.GetValue().GetContent(); + } + } + + target = v.toStyledString(); +} + + +static ResourcesLoader& GetResourcesLoader() +{ + static boost::shared_ptr resourcesLoader_; + + if (!resourcesLoader_) + { + std::unique_ptr lock(context_->Lock()); + resourcesLoader_ = ResourcesLoader::Create(*lock, source_); + resourcesLoader_->AcquireObserver(new WebAssemblyObserver); + } + + return *resourcesLoader_; +} + + +static boost::shared_ptr GetViewport(const std::string& canvas) +{ + Viewports::iterator found = allViewports_.find(canvas); + if (found == allViewports_.end()) + { + std::unique_ptr lock(context_->Lock()); + boost::shared_ptr viewport(ViewerViewport::Create(*lock, source_, canvas, cache_)); + viewport->AcquireObserver(new WebAssemblyObserver); + allViewports_[canvas] = viewport; + return viewport; + } + else + { + return found->second; + } +} + + +extern "C" +{ + int main(int argc, char const *argv[]) + { + printf("OK\n"); + Orthanc::InitializeFramework("", true); + Orthanc::Logging::EnableInfoLevel(true); + //Orthanc::Logging::EnableTraceLevel(true); + + context_.reset(new OrthancStone::WebAssemblyLoadersContext(1, 4, 1)); + cache_.reset(new FramesCache); + + DISPATCH_JAVASCRIPT_EVENT("StoneInitialized"); + } + + + EMSCRIPTEN_KEEPALIVE + void SetOrthancRoot(const char* uri, + int useRendered) + { + try + { + context_->SetLocalOrthanc(uri); // For "source_.SetDicomWebThroughOrthancSource()" + source_.SetDicomWebSource(std::string(uri) + "/dicom-web"); + source_.SetDicomWebRendered(useRendered != 0); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void SetDicomWebServer(const char* serverName, + int hasRendered) + { + try + { + source_.SetDicomWebThroughOrthancSource(serverName); + source_.SetDicomWebRendered(hasRendered != 0); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void FetchAllStudies() + { + try + { + GetResourcesLoader().FetchAllStudies(); + } + EXTERN_CATCH_EXCEPTIONS; + } + + EMSCRIPTEN_KEEPALIVE + void FetchStudy(const char* studyInstanceUid) + { + try + { + GetResourcesLoader().FetchStudy(studyInstanceUid); + } + EXTERN_CATCH_EXCEPTIONS; + } + + EMSCRIPTEN_KEEPALIVE + void FetchSeries(const char* studyInstanceUid, + const char* seriesInstanceUid) + { + try + { + GetResourcesLoader().FetchSeries(studyInstanceUid, seriesInstanceUid); + } + EXTERN_CATCH_EXCEPTIONS; + } + + EMSCRIPTEN_KEEPALIVE + int GetStudiesCount() + { + try + { + return GetResourcesLoader().GetStudiesCount(); + } + EXTERN_CATCH_EXCEPTIONS; + return 0; // on exception + } + + EMSCRIPTEN_KEEPALIVE + int GetSeriesCount() + { + try + { + return GetResourcesLoader().GetSeriesCount(); + } + EXTERN_CATCH_EXCEPTIONS; + return 0; // on exception + } + + + EMSCRIPTEN_KEEPALIVE + const char* GetStringBuffer() + { + return stringBuffer_.c_str(); + } + + + EMSCRIPTEN_KEEPALIVE + void LoadStudyTags(int i) + { + try + { + if (i < 0) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + + Orthanc::DicomMap dicom; + GetResourcesLoader().GetStudy(dicom, i); + FormatTags(stringBuffer_, dicom); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void LoadSeriesTags(int i) + { + try + { + if (i < 0) + { + throw Orthanc::OrthancException(Orthanc::ErrorCode_ParameterOutOfRange); + } + + Orthanc::DicomMap dicom; + GetResourcesLoader().GetSeries(dicom, i); + FormatTags(stringBuffer_, dicom); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + int LoadSeriesThumbnail(const char* seriesInstanceUid) + { + try + { + std::string image, mime; + switch (GetResourcesLoader().GetSeriesThumbnail(image, mime, seriesInstanceUid)) + { + case OrthancStone::SeriesThumbnailType_Image: + Orthanc::Toolbox::EncodeDataUriScheme(stringBuffer_, mime, image); + return ThumbnailType_Image; + + case OrthancStone::SeriesThumbnailType_Pdf: + return ThumbnailType_Pdf; + + case OrthancStone::SeriesThumbnailType_Video: + return ThumbnailType_Video; + + case OrthancStone::SeriesThumbnailType_NotLoaded: + return ThumbnailType_Loading; + + case OrthancStone::SeriesThumbnailType_Unsupported: + return ThumbnailType_NoPreview; + + default: + return ThumbnailType_Unknown; + } + } + EXTERN_CATCH_EXCEPTIONS; + return ThumbnailType_Unknown; + } + + + EMSCRIPTEN_KEEPALIVE + void SpeedUpFetchSeriesMetadata(const char* studyInstanceUid, + const char* seriesInstanceUid) + { + try + { + GetResourcesLoader().FetchSeriesMetadata(PRIORITY_HIGH, studyInstanceUid, seriesInstanceUid); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + int IsSeriesComplete(const char* seriesInstanceUid) + { + try + { + return GetResourcesLoader().IsSeriesComplete(seriesInstanceUid) ? 1 : 0; + } + EXTERN_CATCH_EXCEPTIONS; + return 0; + } + + EMSCRIPTEN_KEEPALIVE + int LoadSeriesInViewport(const char* canvas, + const char* seriesInstanceUid) + { + try + { + std::unique_ptr frames(new OrthancStone::SortedFrames); + + if (GetResourcesLoader().SortSeriesFrames(*frames, seriesInstanceUid)) + { + GetViewport(canvas)->SetFrames(frames.release()); + return 1; + } + else + { + return 0; + } + } + EXTERN_CATCH_EXCEPTIONS; + return 0; + } + + + EMSCRIPTEN_KEEPALIVE + void AllViewportsUpdateSize(int fitContent) + { + try + { + for (Viewports::iterator it = allViewports_.begin(); it != allViewports_.end(); ++it) + { + assert(it->second != NULL); + it->second->UpdateSize(fitContent != 0); + } + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void DecrementFrame(const char* canvas, + int fitContent) + { + try + { + GetViewport(canvas)->ChangeFrame(SeriesCursor::Action_Minus); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void IncrementFrame(const char* canvas, + int fitContent) + { + try + { + GetViewport(canvas)->ChangeFrame(SeriesCursor::Action_Plus); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void ShowReferenceLines(int show) + { + try + { + showReferenceLines_ = (show != 0); + UpdateReferenceLines(); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void SetDefaultWindowing(const char* canvas) + { + try + { + GetViewport(canvas)->SetDefaultWindowing(); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void SetWindowing(const char* canvas, + int center, + int width) + { + try + { + GetViewport(canvas)->SetWindowing(center, width); + } + EXTERN_CATCH_EXCEPTIONS; + } + + + EMSCRIPTEN_KEEPALIVE + void InvertContrast(const char* canvas) + { + try + { + GetViewport(canvas)->Invert(); + } + EXTERN_CATCH_EXCEPTIONS; + } +} diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/docker-build.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/docker-build.sh Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,27 @@ +#!/bin/bash + +set -ex + +IMAGE=jodogne/wasm-builder:1.39.17-upstream + +if [ "$1" != "Debug" -a "$1" != "Release" ]; then + echo "Please provide build type: Debug or Release" + exit -1 +fi + +if [ -t 1 ]; then + # TTY is available => use interactive mode + DOCKER_FLAGS='-i' +fi + +ROOT_DIR=`dirname $(readlink -f $0)`/../.. + +mkdir -p ${ROOT_DIR}/wasm-binaries + +docker run -t ${DOCKER_FLAGS} --rm \ + --user $(id -u):$(id -g) \ + -v ${ROOT_DIR}:/source:ro \ + -v ${ROOT_DIR}/wasm-binaries:/target:rw ${IMAGE} \ + bash /source/StoneWebViewer/WebAssembly/docker-internal.sh $1 + +ls -lR ${ROOT_DIR}/wasm-binaries/ diff -r 5a3ef478deb6 -r fb74ed5d8c22 StoneWebViewer/WebAssembly/docker-internal.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/StoneWebViewer/WebAssembly/docker-internal.sh Thu Jun 25 16:51:10 2020 +0200 @@ -0,0 +1,30 @@ +#!/bin/bash +set -ex + +source /opt/emsdk/emsdk_env.sh + +# Use a folder that is writeable by non-root users for the Emscripten cache +export EM_CACHE=/tmp/emscripten-cache + +# Get the Orthanc framework +cd /tmp/ +hg clone https://hg.orthanc-server.com/orthanc/ + +# Make a copy of the read-only folder containing the source code into +# a writeable folder, because of "DownloadPackage.cmake" that writes +# to the "ThirdPartyDownloads" folder next to the "CMakeLists.txt" +cd /source +hg clone /source /tmp/source-writeable + +mkdir /tmp/build +cd /tmp/build + +cmake /tmp/source-writeable/StoneWebViewer/WebAssembly \ + -DCMAKE_BUILD_TYPE=$1 \ + -DCMAKE_INSTALL_PREFIX=/target/StoneWebViewer \ + -DCMAKE_TOOLCHAIN_FILE=${EMSDK}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake \ + -DORTHANC_FRAMEWORK_ROOT=/tmp/orthanc \ + -DSTATIC_BUILD=ON \ + -G Ninja + +ninja -j2 install