diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c215532 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,85 @@ +cmake_minimum_required(VERSION 3.5) + +project(ChemCalc VERSION 0.1 LANGUAGES CXX) + +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core Widgets PrintSupport Sql Gui Network Xml KF6Config) +find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Widgets PrintSupport Sql Gui Network Xml) + +set(PROJECT_SOURCES + main.cpp + mainwindow.cpp + mainwindow.h + mainwindow.ui +) + +if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) + qt_add_executable(ChemCalc + MANUAL_FINALIZATION + ${PROJECT_SOURCES} + mprintdialog.h mprintdialog.cpp mprintdialog.ui + edit_dialog.h edit_dialog.cpp edit_dialog.ui + resources.qrc + select_dialog.h select_dialog.cpp select_dialog.ui + about_dialog.h about_dialog.cpp about_dialog.ui + COPYING.txt + ) +# Define target properties for Android with Qt 6 as: +# set_property(TARGET ChemCalc APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR +# ${CMAKE_CURRENT_SOURCE_DIR}/android) +# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation +else() + if(ANDROID) + add_library(ChemCalc SHARED + ${PROJECT_SOURCES} + ) +# Define properties for Android with Qt 5 after find_package() calls as: +# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android") + else() + add_executable(ChemCalc + ${PROJECT_SOURCES} + ) + endif() +endif() + +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Widgets) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::PrintSupport) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Core) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Sql) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Gui) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Network) +target_link_libraries(ChemCalc PRIVATE Qt${QT_VERSION_MAJOR}::Xml) + +# target_link_libraries(ChemCalc KF6::ConfigCore KF6::ConfigGui) // Doesn't work. + + +# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1. +# If you are developing for iOS or macOS you should consider setting an +# explicit, fixed bundle identifier manually though. +if(${QT_VERSION} VERSION_LESS 6.1.0) + set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.ChemCalc) +endif() +set_target_properties(ChemCalc PROPERTIES + ${BUNDLE_ID_OPTION} + MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} + MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} + MACOSX_BUNDLE TRUE + WIN32_EXECUTABLE TRUE +) + +include(GNUInstallDirs) +install(TARGETS ChemCalc + BUNDLE DESTINATION . + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(QT_VERSION_MAJOR EQUAL 6) + qt_finalize_executable(ChemCalc) +endif() diff --git a/CMakeLists.txt.user b/CMakeLists.txt.user new file mode 100644 index 0000000..761a190 --- /dev/null +++ b/CMakeLists.txt.user @@ -0,0 +1,421 @@ + + + + + + EnvironmentId + {60d062fe-61a0-4943-8a65-b2bab33ae0ef} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + 1 + UTF-8 + false + 4 + false + 80 + true + true + 1 + 0 + false + true + false + 0 + true + true + 0 + 8 + true + false + 1 + true + true + true + *.md, *.MD, Makefile + false + true + true + + + + ProjectExplorer.Project.PluginSettings + + + true + false + true + true + true + true + + false + + + 0 + true + + true + true + Builtin.DefaultTidyAndClazy + 2 + true + + + + true + + + false + true + + + + + ProjectExplorer.Project.Target.0 + + Desktop + Desktop + Desktop + {7e436c1d-b84c-4b08-8ee2-21b66cd3c4c1} + 1 + 0 + 0 + + Debug + 2 + false + + -DCMAKE_CXX_FLAGS_INIT:STRING=%{Qt:QML_DEBUG_FLAG} +-DCMAKE_GENERATOR:STRING=Ninja +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} +-DCMAKE_BUILD_TYPE:STRING=Debug +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtc/package-manager/auto-setup.cmake +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} + 0 + /home/chris/Cpp-Projects/Lessons/build-Test3-noQt5-Desktop-Debug + + + + + all + + false + + true + Build + CMakeProjectManager.MakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + Build + CMakeProjectManager.MakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Debug + CMakeProjectManager.CMakeBuildConfiguration + + + Release + 2 + false + + -DCMAKE_CXX_FLAGS_INIT:STRING=%{Qt:QML_DEBUG_FLAG} +-DCMAKE_GENERATOR:STRING=Ninja +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} +-DCMAKE_BUILD_TYPE:STRING=Release +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtc/package-manager/auto-setup.cmake +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} + /home/chris/Cpp-Projects/ChemCalc/build + + + + + all + + false + + true + Build + CMakeProjectManager.MakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + Build + CMakeProjectManager.MakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Release + CMakeProjectManager.CMakeBuildConfiguration + + + RelWithDebInfo + 2 + false + + -DCMAKE_CXX_FLAGS_INIT:STRING=%{Qt:QML_DEBUG_FLAG} +-DCMAKE_GENERATOR:STRING=Ninja +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} +-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtc/package-manager/auto-setup.cmake +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} + /home/chris/Cpp-Projects/Lessons/build-Test3-noQt5-Desktop-RelWithDebInfo + + + + + all + + false + + true + CMakeProjectManager.MakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + CMakeProjectManager.MakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Release with Debug Information + CMakeProjectManager.CMakeBuildConfiguration + + + RelWithDebInfo + 2 + false + + -DCMAKE_CXX_FLAGS_INIT:STRING=%{Qt:QML_DEBUG_FLAG} +-DCMAKE_GENERATOR:STRING=Ninja +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} +-DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtc/package-manager/auto-setup.cmake +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} + 0 + /home/chris/Cpp-Projects/Lessons/build-Test3-noQt5-Desktop-Profile + + + + + all + + false + + true + CMakeProjectManager.MakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + CMakeProjectManager.MakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Profile + CMakeProjectManager.CMakeBuildConfiguration + + + MinSizeRel + 2 + false + + -DCMAKE_CXX_FLAGS_INIT:STRING=%{Qt:QML_DEBUG_FLAG} +-DCMAKE_GENERATOR:STRING=Ninja +-DCMAKE_C_COMPILER:FILEPATH=%{Compiler:Executable:C} +-DQT_QMAKE_EXECUTABLE:FILEPATH=%{Qt:qmakeExecutable} +-DCMAKE_BUILD_TYPE:STRING=MinSizeRel +-DCMAKE_PROJECT_INCLUDE_BEFORE:FILEPATH=%{BuildConfig:BuildDirectory:NativeFilePath}/.qtc/package-manager/auto-setup.cmake +-DCMAKE_CXX_COMPILER:FILEPATH=%{Compiler:Executable:Cxx} +-DCMAKE_PREFIX_PATH:PATH=%{Qt:QT_INSTALL_PREFIX} + /home/chris/Cpp-Projects/Lessons/build-Test3-noQt5-Desktop-MinSizeRel + + + + + all + + false + + true + CMakeProjectManager.MakeStep + + 1 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + + + clean + + false + + true + CMakeProjectManager.MakeStep + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Minimum Size Release + CMakeProjectManager.CMakeBuildConfiguration + + 5 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + true + 0 + true + + 2 + + false + -e cpu-cycles --call-graph dwarf,4096 -F 250 + ChemCalc + CMakeProjectManager.CMakeRunConfiguration.ChemCalc + ChemCalc + false + true + true + true + /home/chris/Cpp-Projects/ChemCalc/build + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/COPYING.txt b/COPYING.txt new file mode 100644 index 0000000..a28fa47 --- /dev/null +++ b/COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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 General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ChemCalc.conf b/ChemCalc.conf new file mode 100644 index 0000000..ba9ede1 --- /dev/null +++ b/ChemCalc.conf @@ -0,0 +1,29 @@ +## ChemCalc.conf +## +## This is the Chemical Calculator configuration file. +## It is not used at this time but is reserved for future use. +## +## Lines starting with a pound sign (#) are ignored comments. +## If you change this and break it simply delete this file and +## restart Chemical Calulator to reinstall the default file. + +##---------------------------- +## These two comboboxes contain the same items (suffixes).: +## comboBox_StartingSolutionSuffix (= QStrings of maps A2 and A3) +## comboBox_DesiredSolutionSuffix (= QStrings of maps A2 and A3) + +suffix_molar_map_A2 = {{"M",1}, {"mM",1e3}, {"uM",1e6}, {"nM",1e9}, {"pM",1e12}, {"fM",1e15}}; + +suffix_weight_per_liter_map_A3 = {{"%",100},{"g/L",1e3},{"mg/L",1e6},{"ug/L",1e9},{"ng/L",1e12},{"pg/L",1e15},{"fg/L",1e18}}; +##----------------------------- + +volume_suffix_map_B2 = {{"ml",1e3}, {"L",1}, {"ul",1e6}}; +##----------------------------- + +## comboBox_TotalAmountSuffix (= next 2) +total_amount_suffix_map_moles_C2 = {{"moles",1}, {"millimoles",1e3}, {"micromoles",1e6}}; + +total_amount_suffix_map_weight_C3 = {{"g",1}, {"mg",1e3}, {"ug",1e6}}; +##----------------------------- + + diff --git a/ChemCalc_Screen_Capture.png b/ChemCalc_Screen_Capture.png new file mode 100644 index 0000000..985cfb5 Binary files /dev/null and b/ChemCalc_Screen_Capture.png differ diff --git a/ChemCalc_data.db b/ChemCalc_data.db new file mode 100644 index 0000000..ca6d9a3 Binary files /dev/null and b/ChemCalc_data.db differ diff --git a/ChemCalc_data.sqbpro b/ChemCalc_data.sqbpro new file mode 100644 index 0000000..c4c896c --- /dev/null +++ b/ChemCalc_data.sqbpro @@ -0,0 +1 @@ +
diff --git a/ChemCalc_help1.md b/ChemCalc_help1.md new file mode 100644 index 0000000..6b01348 --- /dev/null +++ b/ChemCalc_help1.md @@ -0,0 +1,23 @@ +**Chemical Calculator Help** + +Quick Start + +The easiest way to learn how to use Chemical Calculator is to jump right in with some examples. HINT: Move this window to one side of Chemical Calculator so that you can read this and enter data at the same time. + +Fill in the information needed in box 1 and continue to box 4 and press the 'Calculate' button. + +Example 1) Calculate how much Sodium Chloride (1 Molar stock solution / MW = 58.443) is needed to make 250 ml of a 1 mM desired solution. + +> In box **1-Starting Reagent**, type in "Sodium Chloride" in the first text box and '58.443' in the 'Molecular Weight' box. +> +> In box **2-Starting Reagent Concentration** click on the *Solution* radio button and type in '1.0' and select 'M' (Molar). +> +> In Box **3-Desired Solution** click on the 'Solution Conc' radio button and type in '1.0' and select 'mM' (for milliMolar). Then enter '250 ml' for the 'Final Volume Wanted' boxes. +> +> In Box **4-Results**, click on 'Calculate' to get your answer. +> +> If your answer looks correct you should click on the **'Add To Print List'** button to save or print. + +![myImage](qrc:/ChemCalc_Screen_Capture.png) + +Continue with any other reagents you want to add and click **'Add To Print List'** after each one is calculated. Then click on the **'Show, Print, or Save Print List'** button to view all of your results. diff --git a/ChemCalc_icon_120.png b/ChemCalc_icon_120.png new file mode 100644 index 0000000..059af96 Binary files /dev/null and b/ChemCalc_icon_120.png differ diff --git a/ChemCalc_icon_120.svg b/ChemCalc_icon_120.svg new file mode 100644 index 0000000..da98b54 --- /dev/null +++ b/ChemCalc_icon_120.svg @@ -0,0 +1,482 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/about_dialog.cpp b/about_dialog.cpp new file mode 100644 index 0000000..0220ddc --- /dev/null +++ b/about_dialog.cpp @@ -0,0 +1,16 @@ +#include + +#include "about_dialog.h" +#include "ui_about_dialog.h" + +about_Dialog::about_Dialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::about_Dialog) +{ + ui->setupUi(this); +} + +about_Dialog::~about_Dialog() +{ + delete ui; +} diff --git a/about_dialog.h b/about_dialog.h new file mode 100644 index 0000000..b26b6e4 --- /dev/null +++ b/about_dialog.h @@ -0,0 +1,23 @@ +#ifndef ABOUT_DIALOG_H +#define ABOUT_DIALOG_H + +#include + +namespace Ui { +class about_Dialog; +} + +class about_Dialog : public QDialog +{ + Q_OBJECT + +public: + explicit about_Dialog(QWidget *parent = nullptr); + ~about_Dialog(); + Ui::about_Dialog *ui; + +private: + +}; + +#endif // ABOUT_DIALOG_H diff --git a/about_dialog.ui b/about_dialog.ui new file mode 100644 index 0000000..327792d --- /dev/null +++ b/about_dialog.ui @@ -0,0 +1,274 @@ + + + about_Dialog + + + Qt::WindowModality::ApplicationModal + + + + 0 + 0 + 727 + 575 + + + + About Chemical Calculator + + + true + + + + + 10 + 10 + 701 + 541 + + + + 1 + + + + About Chemical Calculator + + + + + 10 + 20 + 161 + 181 + + + + + + + :/Icons/ChemCalc_icon_120.svg + + + + + + 200 + 20 + 361 + 61 + + + + + 16 + true + + + + About Chemical Calculator + + + false + + + + + + 40 + 440 + 97 + 30 + + + + + 14 + + + + OK + + + + + + 190 + 100 + 471 + 381 + + + + + 12 + + + + false + + + false + + + true + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> +p, li { white-space: pre-wrap; } +hr { height: 1px; border-width: 0; } +li.unchecked::marker { content: "\2610"; } +li.checked::marker { content: "\2612"; } +</style></head><body style=" font-family:'Noto Sans'; font-size:12pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Chemical Calculator is an application that calculates the amount of reagents to use when mixing up chemical solutions. It is intended for use by chemists and other scientists who have enough knowledge and experience to use it safely.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&quot;Chemical Calculator&quot; was written and copyrighted by Chris Baba in 2024. It is open source software licensed under GPLv3 or later. See next tab for the GPL License Info.</p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + Qt::TextInteractionFlag::LinksAccessibleByKeyboard|Qt::TextInteractionFlag::LinksAccessibleByMouse|Qt::TextInteractionFlag::TextBrowserInteraction|Qt::TextInteractionFlag::TextSelectableByKeyboard|Qt::TextInteractionFlag::TextSelectableByMouse + + + + + + + 14 + + + + GPL License Info + + + + + 10 + 20 + 161 + 181 + + + + + + + :/Icons/ChemCalc_icon_120.svg + + + + + + 190 + 20 + 361 + 61 + + + + + 13 + true + + + + GPL License Information + + + false + + + + + + 20 + 450 + 97 + 30 + + + + OK + + + + + + 180 + 100 + 481 + 381 + + + + + 12 + + + + false + + + true + + + Chemical Calculator is an application that calculates the amount of reagents to use when mixing up chemical solutions. Copyright (C) 2024 Chris Baba + +This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. + +Chris Baba (the author and copyright holder) can be reached by the following methods: + 1) by email (preferred method) at cbaba001@comcast.net, + 2) at my home phone at 301-698-0381 (leave a message), or + 3) by mail at the following address: + Chris Baba + 489 Hobnail Ct. + Frederick, MD 21703 (USA) + + + + + + + + + + + + pushButtonOK + clicked() + about_Dialog + close() + + + 533 + 408 + + + 613 + 412 + + + + + pushButtonOK_2 + clicked() + about_Dialog + close() + + + 556 + 424 + + + 623 + 424 + + + + + diff --git a/edit_database.cpp b/edit_database.cpp new file mode 100644 index 0000000..9f7a157 --- /dev/null +++ b/edit_database.cpp @@ -0,0 +1,115 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "edit_database.h" +#include "ui_edit_database.h" + + + //QDialog *edb = new Edit_DataBase(this); + //edb->open(); + + + + +Edit_DataBase::Edit_DataBase(QWidget *parent) + : QWidget(parent) + , ui3(new Ui::Edit_DataBase) +{ + ui3->setupUi(Ui::Edit_DataBase()) + //ui3->setupUi(this); +} + +Edit_DataBase::~Edit_DataBase() +{ + delete ui3; +} + +/* +void edit_database() // This function is usually called from another class "Ui_MainWindow". +{ + /* qDebug() << "edit_database function called"; + //This (below) is not the database name, it's the DRIVER name. + db = QtSql.QSqlDatabase.addDatabase("QSQLITE"); + // This (below) is the database file name. + // set Database Name to ~.local/share/ChemCalc/ChemCalc_data.db" (in linux). + db.setDatabaseName(g_user_data_file_path); + if not db.open(): + ui.cc_msgBox("Unable to connect to the database") + if g_debug_on: print("Unable to connect to the database") + sys.exit(-1) + + self.model = QtSql.QSqlTableModel() + self.model.setTable("USER") + self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) + + ## The sql syntax is different (truncated) from other times. +# sql = ("SELECT * FROM USER WHERE reagent LIKE '" + reagent_fragment +"%'") +# sql = ("reagent LIKE '" + reagent_fragment +"%'") +# model.setFilter(sql) + self.model.select() + if g_debug_on: print("edit_database function-after line model.select") + + ## Changed "view" to "tableView" in next group of lines.-------------------- + ## See https://realpython.com/python-pyqt-database/ + self.tableView.setModel(self.model) + self.tableView.setColumnWidth(0, 510) + self.tableView.setColumnWidth(1,75) + self.tableView.setWordWrap(True) + ## This was moved to end to give time to process previous comands. +# self.tableView.resizeRowsToContents() +# self.tableView.resizeColumnToContents(1) + self.tableView.setSortingEnabled(True) + self.label.setText("Double-Click On Data To Edit Items In DataBase.") +# button_OK = self.buttonBox.button.Ok +# button_OK.setEnabled(False) + +# Edit_Dialog.show() ## Shows Edit_Dialog Window. Use next line (.exec) instead. + ## 'Show' returns execution to main window immwdiately, while + ## 'exec' waits until 'OK' or 'Cancel' are clicked. + Edit_Dialog.exec() +# Keep next line after 'Edit_Dialog.exec()' so it works due to timing issues. +# If the tableView is not fully loaded it won't resize correctly. + self.tableView.resizeRowsToContents() + +} + + +void Edit_DataBase::accept() // <----Slot----- +{ + /* // Handles "OK' button click on Edit_Dialog box. + qDebug() << "In Ui_Edit_Database class, def 'accept' called from Ok button"; + model.submitAll() + //Close dialog box and continue from where 'Edit_Dialog.exec()' was called. + // (Either 'edit_database' or 'select_from_database'.) + //(Returns '1' which can be used in 'OK_clicked' variable.) + Edit_Dialog.done(1); // (0 = Cancel / 1 = OK) + +} + + +void Edit_DataBase::reject() // <----Slot----- +{ + /* qDebug() << "In Ui_Edit_Database class, def 'reject' called from Cancel button"; + //Handles "Cancel' button click on Edit_Dialog box. + model.revertAll(); + // Close dialog box and continue from where 'Edit_Dialog.exec()' was called. + // (Either 'edit_database' or 'select_from_database'.) + // (Returns '0' which can be used in 'OK_clicked' (=false) variable.) + Edit_Dialog.done(0); // (0 = Cancel / 1 = OK) + +} +*/ + + diff --git a/edit_database.h b/edit_database.h new file mode 100644 index 0000000..719c710 --- /dev/null +++ b/edit_database.h @@ -0,0 +1,41 @@ +#ifndef EDIT_DATABASE_H +#define EDIT_DATABASE_H + +#include +#include +#include +#include "ui_edit_database.h" + +// namespace Qsl { +namespace Ui { +class Edit_DataBase; +} + +class Edit_DataBase : public QWidget +{ + Q_OBJECT + +public: + //explicit Edit_DataBase(QWidget *parent = nullptr); + explicit Edit_DataBase(QWidget *parent); + //explicit Edit_DataBase(const QString &tableName, QDialog *parent = nullptr); + ~Edit_DataBase(); + +private: + Ui::Edit_DataBase *ui3; + QPushButton *submitButton; + QPushButton *revertButton; + QPushButton *quitButton; + QDialogButtonBox *buttonBox; + QSqlTableModel *model; + +private slots: + + void accept(); + void reject(); + void submit(); + + +}; + +#endif // EDIT_DATABASE_H diff --git a/edit_database.ui b/edit_database.ui new file mode 100644 index 0000000..1c1a133 --- /dev/null +++ b/edit_database.ui @@ -0,0 +1,132 @@ + + + Edit_DataBase + + + + 0 + 0 + 680 + 540 + + + + Dialog + + + + + 40 + 470 + 141 + 34 + + + + Add Row + + + + + + 30 + 110 + 611 + 341 + + + + + 12 + + + + + + + 50 + 20 + 571 + 61 + + + + + 12 + + + + Double-Click On Data To Edit Items In DataBase. + + + + + + 280 + 470 + 341 + 32 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + 190 + 470 + 141 + 34 + + + + + 10 + + + + Delete Row + + + + + + + buttonBox + accepted() + Edit_DataBase + accept() + + + 578 + 487 + + + 583 + 519 + + + + + buttonBox + rejected() + Edit_DataBase + reject() + + + 410 + 481 + + + 410 + 511 + + + + + diff --git a/edit_dialog.cpp b/edit_dialog.cpp new file mode 100644 index 0000000..a4ff19f --- /dev/null +++ b/edit_dialog.cpp @@ -0,0 +1,171 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include //REMOVE? +#include //REMOVE? +#include //REMOVE? +#include +#include +#include + +#include "edit_dialog.h" +#include "ui_edit_dialog.h" +#include "mainwindow.h" + +// Define these public STATIC (class?) variables that were declared in header file. +// They must defined outside of any functions?? +// Example 'Edit_Dialog::g_mw' to access from anywhere. +QString Edit_Dialog::g_reagent = "BLANK"; +double Edit_Dialog::g_mw = 0.0; +QString Edit_Dialog::g_mw_string = "0.0"; +QSqlTableModel* Edit_Dialog::model = NULL; +int Edit_Dialog::g_selected_row = 0; +int Edit_Dialog::g_selected_column = 0; +//-------------------------------------- + +Edit_Dialog::Edit_Dialog(QWidget *parent) + : QDialog(parent) + , ui3(new Ui::Edit_Dialog) +{ + ui3->setupUi(this); //This is QtCreator code to make GUI. + + qDebug() << "Edit_Dialog::Edit_Dialog Constructor - STARTED"; + setWindowTitle("Edit Database"); + // QSqlDatabase db; + g_db = QSqlDatabase::addDatabase("QSQLITE"); + // QString 'g_dataBaseFilePath' is static class scope, declared in MainWindow header file. + g_db.setDatabaseName(MainWindow::g_dataBaseFilePath); + qDebug() << "In Edit_Dialog, g_dataBaseFilePath = " << MainWindow::g_dataBaseFilePath; + + bool DB_opened_OK = g_db.open(); + qDebug() << "DB_opend_OK = " << DB_opened_OK; + if (DB_opened_OK == false) { + qDebug() << "Unable to connect to the database"; + MainWindow myObj; + myObj.cc_msgBox("Unable to connect to the local database"); + return; + } + model = new QSqlTableModel(this); + model->setTable("USER"); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); + + // QTableView *view = new QTableView; + view = ui3->tableView; + view->setModel(model); + view->setColumnWidth(0, 510); + view->setColumnWidth(1,75); + view->setWordWrap(true); + view->setSortingEnabled(true); + view->resizeRowsToContents(); + //------------------------------- + qDebug() << "Edit_Dialog Constructor - ENDED"; +} + +Edit_Dialog::~Edit_Dialog() +{ + delete ui3; +} + +void Edit_Dialog::on_pushButton_Cancel_clicked() +{ + qDebug() << "Edit_Dialog CANCEL clicked."; + // This works just like this. Changed data rolls back if not submitted. + close(); +} + +void Edit_Dialog::on_pushButton_OK_clicked() +{ + qDebug() << "Edit_Dialog OK clicked-1."; + model->submitAll(); + model->select(); + close(); +} + +void Edit_Dialog::on_pushButton_AddRow_clicked() +{ + qDebug() << "Edit_Dialog ADD ROW clicked-1."; + + model->insertRecord(-1, model->record()); + model->submitAll(); + if (model->lastError().isValid()) + qDebug() << "Last Error = " << model->lastError(); + model->select(); +} + +void Edit_Dialog::on_pushButton_DeleteRow_clicked() +{ + qDebug() << "Edit_Dialog DELETE ROW clicked."; + qDebug() << "In 'delete_row', 'g_selected_row' = " << Edit_Dialog::g_selected_row; + model->removeRows(g_selected_row, 1); + model->submitAll(); + model->select(); +} + +void Edit_Dialog::user_selected_index(QModelIndex selected_index) // <--SLOT +{ + // This function is a slot called whenever a user clicks on (selects) + // a table item from any instance of an Edit_Dialog box (signal) of + // reagents and molecular weights. It sets 4 class-wide variables + // (g_selected_row, g_selected_column g_reagent, g_mw) Which are declared + // in header for class scope, for use in other functions. + // It can also derive selected_index_model, but I use previousely defined 'model'. + + // Start setting 3 class-wide variables. + Edit_Dialog::g_selected_row = selected_index.row(); + qDebug() << "g_selected_row = " << Edit_Dialog::g_selected_row; + + Edit_Dialog::g_selected_column = selected_index.column(); + qDebug() << "g_selected_column = " << Edit_Dialog::g_selected_column; + + // Don't use next form of model. + qDebug() << "selected_index_model() = " << selected_index.model(); + // Use next line instead (the class scope form, QSqlTableModel *model;). + qDebug() << "Edit_Dialog::model = " << Edit_Dialog::model; + + Edit_Dialog::g_reagent = model->record(g_selected_row).value("Reagent").toString(); // ("Reagent"); + qDebug() << "Edit_Dialog::g_reagent = " << Edit_Dialog::g_reagent; + + Edit_Dialog::g_mw_string = model->record(g_selected_row).value("MW").toString(); // ("MW"); + Edit_Dialog::g_mw = model->record(g_selected_row).value("MW").toDouble(); // ("MW"); + qDebug() << "Edit_Dialog::g_mw = " << Edit_Dialog::g_mw; + qDebug() << "Edit_Dialog::g_mw_string = " << Edit_Dialog::g_mw_string; +} + + +void Edit_Dialog::on_tableView_clicked(const QModelIndex &index) +{ + qDebug() << "Edit_Dialog::on_tableView_clicked(const QModelIndex &index)--index = " << index; + Edit_Dialog::user_selected_index(index); + qDebug() << "End of on_tableview_clicked()"; +} + + diff --git a/edit_dialog.h b/edit_dialog.h new file mode 100644 index 0000000..3496570 --- /dev/null +++ b/edit_dialog.h @@ -0,0 +1,61 @@ +#ifndef EDIT_DIALOG_H +#define EDIT_DIALOG_H + +#include +#include +#include +#include +#include +#include + + +namespace Ui { +class Edit_Dialog; +} + +class Edit_Dialog : public QDialog +{ + Q_OBJECT + +public: + friend class MainWindow; + + explicit Edit_Dialog(QWidget *parent = nullptr); + ~Edit_Dialog(); + Ui::Edit_Dialog *ui3; + // void chem_db_read(QString reagent_fragment); + + //------------------------------------------------ + //These declarations have class(?) scope, + // Use scope resolution operator (::) to use these public variables. + // For example: "Edit_Dialog::g_selected_row". + QSqlDatabase g_db; + static int g_selected_row; + static int g_selected_column; + static QString g_reagent; + static double g_mw; + static QString g_mw_string; + int g_OK_clicked; + static QSqlTableModel *model; + QTableView *view; + //------------------------------------------------ + +public slots: + + +private slots: + void on_pushButton_Cancel_clicked(); + // void on_pushButton_OK_clicked(const QModelIndex &index); + void on_pushButton_DeleteRow_clicked(); + void on_pushButton_AddRow_clicked(); + void user_selected_index(QModelIndex selected_index); + // void select_from_database(QString reagent_fragment); + void on_tableView_clicked(const QModelIndex &index); + void on_pushButton_OK_clicked(); + +private: + // Ui::Edit_Dialog *ui3; + +}; + +#endif // EDIT_DIALOG_H diff --git a/edit_dialog.ui b/edit_dialog.ui new file mode 100644 index 0000000..b9cd0b0 --- /dev/null +++ b/edit_dialog.ui @@ -0,0 +1,122 @@ + + + Edit_Dialog + + + + 0 + 0 + 704 + 542 + + + + Edit Database + + + + :/Icons/ChemCalc_icon_120.svg:/Icons/ChemCalc_icon_120.svg + + + + + 30 + 20 + 591 + 51 + + + + + 12 + true + + + + Double-Click On Data To Edit Items In DataBase. + + + + + + 10 + 90 + 641 + 341 + + + + + 12 + + + + + + + 20 + 460 + 601 + 41 + + + + + + + Add Row + + + + + + + + 12 + + + + Delete Row + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Cancel + + + + + + + OK + + + + + + + + + + + + signal1() + tempCB1() + pushButton_OK_clicked(QSqlTableModel) + + diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..fd3e533 --- /dev/null +++ b/main.cpp @@ -0,0 +1,11 @@ +#include "mainwindow.h" + +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + MainWindow w; + w.show(); + return a.exec(); +} diff --git a/mainwindow.cpp b/mainwindow.cpp new file mode 100644 index 0000000..d5c48d1 --- /dev/null +++ b/mainwindow.cpp @@ -0,0 +1,1660 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include //?? +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include //REMOVE? +#include //REMOVE? +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "mainwindow.h" +#include "./ui_mainwindow.h" +#include "about_dialog.h" +#include "mprintdialog.h" +#include "edit_dialog.h" +#include "select_dialog.h" +#include "ui_about_dialog.h" +#include "ui_select_dialog.h" + +// #include +// #include +// #include + +//-----------DELETE?----------------------------- +// Initial definitions for static variables. +// Title only, for now // initial definition, (initial declaration is in header file (MainWindow.h)). +// QString MainWindow::g_print_text = "Chemical Calculator Results: \n"; +// QString mPrintDialog::g_print_text = "Chemical Calculator Results: \n"; + +QString MainWindow::g_dataBaseFilePath = ""; +QString MainWindow::g_configFilePath = ""; +//--------------------------------------- + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) +{ + ui->setupUi(this); + + setWindowTitle("Chemical Calculator"); + // No errors below, but it doesn't work (set window icon). + // QIcon myIcon; + // QIcon myIcon = QIcon(":/Icons/ChemCalc_icon_120.svg"); + // setWindowIcon(myIcon); + // MainWindow::setWindowIcon(QIcon(":/Icons/ChemCalc_icon_120.png")); + // setIcon(QIcon(":/Icons/ChemCalc_icon_120.png")); + + // Runs once at start, to setup file locations, database, config files etc. + runAtStart(); +} + +MainWindow::~MainWindow() +{ + delete ui; +} + +void MainWindow::runAtStart() +{ + // Runs once at start, to setup file locations, database, config files etc. + qDebug() << "runAtStart STARTED."; + + // 1) check for database.------ + bool dbOK = checkForDataBase(); + qDebug() << "dbOK = " << dbOK; + if (!dbOK){ + // Add error code here. + } + + // 2) check for configuration file.------ + // FOR FUTURE USE! + // + // bool configOK = checkForConfigurationFile(); + // qDebug() << "configOK = " << configOK; + // if (!configOK){ + // Add error code here. + // } +} + +bool MainWindow::checkForDataBase() +{ + // Checks for existence of ChemCalc_data.db and paths to it. + // If they don't exist it tries to create any needed paths/files. + // Returns false if it couldn't be created. true= OK to use. + + //--Returns 1 directory (as QString) OR an empty string. Use for DATA and DATABASE. + // See Qt QStandardPaths Class docs. + // Returns 1 directory OR an empty string, but is writable if returned. + // ("/home/chris/.local/share/ChemCalc" on my computer.) + // It may need to be created, but is writable. + QString myAppDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + qDebug() << "myAppDataLocation (writableLocation) = " << myAppDataLocation; + // If data directories don't exist, create them. + if (!QDir(myAppDataLocation).exists()){ + bool dirOK = QDir().mkpath(myAppDataLocation); + if (!dirOK){ + qDebug() << "Could not create DATA DIRECTORY PATH!"; + // Add error code here? + return false; + } + } + + // QString 'g_dataBaseFilePath' is static class scope, declared in header file. + g_dataBaseFilePath = myAppDataLocation + "/ChemCalc_data.db"; + QFile myDB = QFile(g_dataBaseFilePath); + // If database doesn't exist in users file system, create by copying resource db. + if (!myDB.exists()){ + // Copy nearly empty database in resource file to user's file system. + // resource file = :/CC/DB1/ChemCalc_data.db (notice ":" at start). + QFile resourceFileDB; + resourceFileDB.setFileName(":/CC/DB1/ChemCalc_data.db"); + bool fileCopyOK = resourceFileDB.copy(g_dataBaseFilePath); + if (fileCopyOK){ + // Set permissions. + int myPermissions = (QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadUser | QFileDevice::WriteUser); + bool permissionsSetOK = myDB.setPermissions(QFileDevice::Permissions(myPermissions)); + return true; + } + if (!fileCopyOK){ + qDebug() << "Database file could not be created."; + // Maybe add error code here. + return false; + } + } + return true; +} + +bool MainWindow::checkForConfigurationFile() // For future use! +{ + // Checks for existence of ChemCalc.conf and paths to it. + // ("$HOME/.config/ChemCalc" on my linux computer.) + // If they don't exist it tries to create any needed paths/files. + // Returns false if it couldn't be created. true= OK to use. + + //--Returns 1 directory (as QString) OR an empty string. Use for CONFIG. + // See Qt QStandardPaths Class docs. + // Returns 1 directory OR an empty string, but is writable if returned. + // It may need to be created, but is writable. + QString myConfigLocation = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); + qDebug() << "myConfigLocation (writableLocation) = " << myConfigLocation; + + // If config directories don't exist, create them. + if (!QDir(myConfigLocation).exists()){ + bool dirOK = QDir().mkpath(myConfigLocation); + if (!dirOK){ + qDebug() << "Could not create CONFIGURATION DIRECTORY PATH!"; + // Add error code here? + return false; + } + } + + // QString 'g_configFilePath' is static class scope, declared in header file. + g_configFilePath = myConfigLocation + "/ChemCalc.conf"; + QFile myConfig = QFile(g_configFilePath); + // If configuration file doesn't exist in users file system, create by copying resource configuration. + if (!myConfig.exists()){ + // Copy configuration in resource file to user's file system. + // resource file = :/ChemCalc.conf (notice ":" at start). + QFile resourceFileConfig; + resourceFileConfig.setFileName(":/ChemCalc.conf"); + bool fileCopyOK = resourceFileConfig.copy(g_configFilePath); + if (fileCopyOK){ + // Set permissions. + int myPermissions = (QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadUser | QFileDevice::WriteUser); + bool permissionsSetOK = myConfig.setPermissions(QFileDevice::Permissions(myPermissions)); + + // Don't use QSettings as it mangles (deletes) comments. + // Also set g_ccSettings (to use QSettings methods). + // QSettings g_ccSettings(g_configFilePath, QSettings::IniFormat); + // testing-------------<<--------FINISH HERE-------------------------- + // g_ccSettings.beginGroup("MyGroup"); + // g_ccSettings.setValue("myQString1", "Molar"); + // g_ccSettings.setValue("myQString2", "Micro-Molar"); + // g_ccSettings.endGroup(); + //--end testing.---------- + return true; + } + if (!fileCopyOK){ + qDebug() << "Configuration file could not be created."; + // Maybe add error code here. + return false; + } + } + return true; +} + +void MainWindow::on_pushButton_Quit_clicked() +{ + QApplication::quit(); +} + +void MainWindow::on_actionQuit_triggered() +{ + QApplication::quit(); +} + +void MainWindow::on_actionChemCalc_Help_triggered() +{ + // Display ChemCalc Help - Quick Start. + qDebug() << "MainWindow Menu ChemCalc HELP triggered."; + QTextBrowser *ccHelp = new QTextBrowser(this); + ccHelp->setWindowFlag(Qt::Window); + ccHelp->setWindowModality(Qt::NonModal); + ccHelp->setSource(QUrl("qrc:/ChemCalc_help1.md")); + ccHelp->resize(740,700); // WxH adjust W for width of images + 40. + ccHelp->show(); +} + +void MainWindow::on_actionAbout_ChemCalc_triggered() +{ + qDebug() << "MainWindow Menu ABOUT-ChemCalc triggered."; + + about_Dialog *myDialog = new about_Dialog(this); + // Set first tab as current tab when opening. + myDialog->ui->tabWidget->setCurrentWidget(myDialog->ui->tab); + myDialog->open(); +} + +void MainWindow::cc_msgBox(QString msgText, QString msgText2, QString msgText3, MainWindow *parent) +{ + //This creates a modal message box with a message and OK button. + QMessageBox msgBox; + + qDebug() << "cc_msgBox called"; + qDebug() << "This = " << this; + qDebug() << "Parent = " << parent; + + if (msgText == "") msgText = "ERROR-No text in message box."; + msgBox.setText(msgText); + msgBox.setInformativeText(msgText2); + msgBox.setDetailedText(msgText3); + msgBox.setParent(parent); + msgBox.setIcon(QMessageBox::Information); + msgBox.setWindowModality(Qt::WindowModal); + msgBox.setWindowTitle("ChemCalc"); + msgBox.exec(); +} + +int MainWindow::db_Save(QString reagent_name , QString mw_string, bool skipConfirmationMessage) +{ + // This is mostly used for 'Save MW' button. + // If no matches in db, insert new row of data. + // If 1 or more matches in db, notify and return with db unchanged. + + qDebug() << "db_query::db_connect - STARTED"; + QSqlDatabase db; + db = QSqlDatabase::addDatabase("QSQLITE"); + // db.setDatabaseName(":/CC/DB1/ChemCalc_data.db"); //FIX HERE----------- + // db.setDatabaseName("/home/chris/Cpp-Projects/ChemCalc/ChemCalc_data.db"); + db.setDatabaseName(g_dataBaseFilePath); + + bool DB_opened_OK = db.open(); + qDebug() << "DB_opend_OK = " << DB_opened_OK; + if (DB_opened_OK == false) { + MainWindow::cc_msgBox("Unable to connect to the database","","",this); + qDebug() << "Unable to connect to the database"; + return -2; //An error condition. + } + + // Correct short version for sqlite and Qt. + QString sql = ("reagent LIKE '" + reagent_name + "'"); // Query needs an exact match. + qDebug() << "sql = " << sql; + QSqlTableModel *model; + model = new QSqlTableModel; + model->setTable("USER"); + model->setFilter(sql); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); + int myNumRows = model->rowCount(); + qDebug() << "myNumRows = " << myNumRows; + + // If no matches in db, insert new row of data. + if (myNumRows==0){ + // Correct syntax example: + // query.exec("INSERT INTO USER ('reagent', 'mw') VALUES ('newreagent2', '333.33')"); //THIS WORKS!!! + QString sql2 = ("INSERT INTO USER ('reagent', 'mw') VALUES ('" + reagent_name + "', '" + mw_string + "')"); + QSqlQuery query; + query.exec(sql2); + // Confirmation of row addition, skip if 'skipConfirmationMessage' == true, default is 'false'. + if (skipConfirmationMessage == false){ + cc_msgBox("Reagent and molecular weight were saved to database.", + "Use Edit-Database (in Menu) to edit.", + "", this); + } + // Maybe add a cancel procedure? + } + // If 1 or more matches in db, notify and return with db unchanged. + if (myNumRows>=1){ + // Notification that (at least one) exact matching reagent exists in databaseb. + if (skipConfirmationMessage == false){ + cc_msgBox("There is already an exact match for this reagent in the database.", + "No changes were made to the databse.", + "Use Edit-Database (in Menu) to edit this reagent.", + this); + } + } + return myNumRows; +} + +void MainWindow::on_pushButton_Show_clicked() +{ + // Shows 'print list' (Dialog Box). + + // mPrintDialog *pd is declared in header file (MainWindow.h). + pd->show(); +} + +QString MainWindow::read_starting_radioButtons() +{ + /*Reads the 3 Starting Reagent radioButtons and returns + a string; either "solution", solid" or "liquid".*/ + + bool starting_solution_checked = ui->radioButton_StartingSolution->isChecked(); + bool starting_solid_checked = ui->radioButton_Solid->isChecked(); + bool starting_liquid_checked = ui->radioButton_Liquid->isChecked(); + + if (starting_solution_checked) return ("solution"); + if (starting_solid_checked) return ("solid"); + if (starting_liquid_checked)return ("liquid"); + else return ("Error in 'read_starting_radiobuttons function."); +} + +QString MainWindow::read_desired_radioButtons() +{ + /*Reads the 2 Desired Reagent radioButtons and returns + a string; either "solution", or "total_amount".*/ + + bool desired_solution_checked = ui->radioButton_DesiredSolution->isChecked(); + bool desired_total_amount_checked = ui->radioButton_TotalAmount->isChecked(); + + if (desired_solution_checked) return ("solution"); + if (desired_total_amount_checked) return ("total_amount"); + else return ("Error in 'read_starting_radiobuttons function."); +} + +double MainWindow::validate_raw_number(QString raw_num) +{ + //This function converts text input to double numbers, + //and checks for >= 0. Function returm a positive float or -1 on error. + + qDebug() << "Running 'validate_raw_number' function with raw_num = " << raw_num; + QDoubleValidator val; + val.setDecimals(3); + val.setLocale(QLocale::C); + val.setNotation(QDoubleValidator::StandardNotation); + val.fixup(raw_num); // input is a QString, out is double + bool ok; //return if conversion is ok in next line. + double validated_num = raw_num.toDouble(&ok); + qDebug() << "Running 'validate_raw_number' bool VAL OK = " << ok; + qDebug() << "Running 'validate_raw_number' function RETURNED double = " << validated_num; + if(ok and (validated_num >= 0.0)) {return validated_num;} + else { + cc_msgBox("Number validation error."); + return -1;} +} + +double MainWindow::read_starting_conc() +{ + QString raw_starting_solution = ui->lineEdit_StartingSolution->text(); + double validated_num = validate_raw_number(raw_starting_solution); + return(validated_num); +} + +QString MainWindow::read_starting_suffix() +{ + QString starting_solution_suffix = ui->comboBox_StartingSolutionSuffix->currentText(); + return(starting_solution_suffix); +} + +double MainWindow::read_desired_conc() +{ + QString raw_desired_solution = ui->lineEdit_DesiredSolution->text(); + double validated_num = validate_raw_number(raw_desired_solution); + return(validated_num); +} + +QString MainWindow::read_desired_suffix() +{ + QString desired_solution_suffix = ui->comboBox_DesiredSolutionSuffix->currentText(); + return(desired_solution_suffix); +} + +double MainWindow::calc_solution_molarity(double starting_conc, QString starting_conc_suffix) +{ + //This function combines input molarity (NO BY WEIGHT) and suffix and returns a double. + QMap suffix_molar_map_A2 = {{"M",1}, {"mM",1e3}, {"uM",1e6}, {"nM",1e9}, {"pM",1e12}, {"fM",1e15}}; + //double suffix_conversion_factor = suffix_molar_map_A2[starting_conc_suffix]; + double molarity = starting_conc / suffix_molar_map_A2[starting_conc_suffix]; + qDebug() << "calc_solution_molarity returns: " << molarity; + return molarity; +} + +double MainWindow::g_per_L(double starting_conc, QString starting_conc_suffix) +{ + // This Function takes raw conentrations and conc suffix, + // and returns the (by weight) concentration in g/L. + + QMap suffix_weight_per_liter_map_A3 = {{"%",100},{"g/L",1e3},{"mg/L",1e6},{"ug/L",1e9},{"ng/L",1e12},{"pg/L",1e15},{"fg/L",1e18}}; + double final_conc = ((starting_conc / suffix_weight_per_liter_map_A3[starting_conc_suffix]) * 1000); + qDebug() << "conc, in g_per_L = " << final_conc; + return final_conc; +} + +double MainWindow::read_MW() +{ + QString raw_mw = ui->lineEdit_MW->text(); + double mw = validate_raw_number(raw_mw); + qDebug() << "raw_mw, (validated) mw = " << raw_mw << mw; + return (mw); +} + +double MainWindow::read_density() +{ + QString raw_density = ui->lineEdit_Density->text(); + double density = validate_raw_number(raw_density); + qDebug() << "raw_density, density = " << raw_density << density; + return (density); +} + +double MainWindow::sol_is_molar(QString str) +{ + //This returns 0 if NOT molar, or the conversion factor if found. + // Remember (0=false, 1=true, any non-zero=true?) + QMap g_suffix_molar_map_A2 = {{"M",1}, {"mM",1e3}, {"uM",1e6}, {"nM",1e9}, {"pM",1e12}, {"fM",1e15}}; + QString myStr = str; + double retVal; + if (g_suffix_molar_map_A2.contains(myStr)) + return g_suffix_molar_map_A2.value(myStr); + else return (0.0); +} + +double MainWindow::read_total_amount() +{ + // This returns a double of the total amount box. + if (ui->radioButton_TotalAmount->isChecked()){ + QString raw_total_amount = ui->lineEdit_TotalAmount->text(); + double total_amount = validate_raw_number(raw_total_amount); + return total_amount; + } + else { + qDebug() << "ERROR-read_total_amount was called but the Total Amount RadioButton is not checked."; + return 0; //An ERROR condition + } +} + +QString MainWindow::read_total_amount_suffix() +{ + // This returns a QString of the total amount suffix comboBox. + if (ui->radioButton_TotalAmount->isChecked()){ + QString total_amount_suffix = ui->comboBox_TotalAmountSuffix->currentText(); + return total_amount_suffix; + } + else { + qDebug() << "ERROR-read_total_amount_SUFFIX was called but the Total Amount RadioButton is not checked."; + return 0; //An ERROR condition + } +} + +bool MainWindow::is_desired_reagent_total_by_moles() +{ + // This return bool (true or false) if desired reagent is total by moles. + + QMap total_amount_suffix_map_moles_C2 = {{"moles",1}, {"millimoles",1e3}, {"micromoles",1e6}}; + //QMap total_amount_suffix_map_weight_C3 = {{"g",1}, {"mg",1e3}, {"ug",1e6}}; + if (ui->radioButton_TotalAmount->isChecked()){ + QString total_amount_suffix = ui->comboBox_TotalAmountSuffix->currentText(); + qDebug() << "In is_desired_reagent_total_by_moles()" << "Total_amount_suffix = " << total_amount_suffix; + if (total_amount_suffix_map_moles_C2.contains(total_amount_suffix)) return true; //TODO FIX HERE + else return false; + } + else { + qDebug() << "ERROR-read_total_amount_SUFFIX was called but the Total Amount RadioButton is not checked."; + return false; //An ERROR condition + } +} + +bool MainWindow::is_desired_reagent_total_by_weight() +{ + // This return bool (true or false) if desired reagent is total by WEIGHT. + + QMap total_amount_suffix_map_weight_C3 = {{"g",1}, {"mg",1e3}, {"ug",1e6}}; + if (ui->radioButton_TotalAmount->isChecked()){ + QString total_amount_suffix = ui->comboBox_TotalAmountSuffix->currentText(); + qDebug() << "In is_desired_reagent_total_by_weight()" << "Total_amount_suffix = " << total_amount_suffix; + if (total_amount_suffix_map_weight_C3.contains(total_amount_suffix)) return true; //TODO FIX HERE + else return false; + } + else { + qDebug() << "ERROR-read_total_amount_SUFFIX was called but the Total Amount RadioButton is not checked."; + return false; //An ERROR condition + } +} + +double MainWindow::calc_moles(double input_num, QString suffix) +{ //This function combines input moles and suffix and returns a double. + + QMap total_amount_suffix_map_moles_C2 = {{"moles",1}, {"millimoles",1e3}, {"micromoles",1e6}}; + double suffix_conversion_factor = total_amount_suffix_map_moles_C2[suffix]; + double moles = (input_num / suffix_conversion_factor); + return moles; +} + +double MainWindow::calc_grams(double input_num, QString suffix) +{ //This function combines input grams and suffix and returns a double. + + QMap total_amount_suffix_map_weight_C3 = {{"g",1}, {"mg",1e3}, {"ug",1e6}}; + double suffix_conversion_factor = total_amount_suffix_map_weight_C3[suffix]; + double grams = (input_num / suffix_conversion_factor); + return grams; +} + +double MainWindow::read_desired_volume() +{ + //This reads the desired volume and returns (a double) desired volume in liters. + QMap volume_suffix_map_B2 = {{"ml",1e3}, {"L",1}, {"ul",1e6}}; + + QString raw_desired_volume = ui->lineEdit_DesiredVolume->text(); + double desired_volume = validate_raw_number(raw_desired_volume); + QString desired_volume_suffix = ui->comboBox_DesiredVolumeSuffix->currentText(); + // Convert desired volume to liters. + + qDebug() << "volume_suffix_map_B2[desired_volume_suffix] = " << volume_suffix_map_B2[desired_volume_suffix]; + qDebug() << "desired_volume = " << desired_volume; + qDebug() << "desired_volume_suffix = " << desired_volume_suffix; + + double desired_volume_liters = (desired_volume / volume_suffix_map_B2[desired_volume_suffix]); + qDebug() << "raw_desired_volume = " << raw_desired_volume; + qDebug() << "final_desired_volume (in L) = " << desired_volume_liters; + return desired_volume_liters; +} + +void MainWindow::format_gram_answer(double grams_needed) +{ + // This checks and formats the answer, and sends it to write_answer function. + + // Initialize some variables. + double amt_needed = 0.0; + QString amt_suffix; + QString formatted_answer; + QString str; + + qDebug() << "Started: format_gram_answer"; + if (grams_needed >= 1000){ // use kilograms (kg) in final answer. + amt_needed = (grams_needed / 1000); + amt_suffix = "kg"; + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 kg").arg(amt_needed, 0, 'F', 3); + + } + if ((grams_needed < 1000) and (grams_needed >=1)){ // use grams (g) in final answer. + amt_needed = (grams_needed); + amt_suffix = "g"; + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 g").arg(amt_needed, 0, 'F', 3); + + } + if (grams_needed < 1) { // use milligram (mg) in final answer. + amt_needed = (grams_needed * 1000); + amt_suffix = "mg"; + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 mg").arg(amt_needed, 0, 'F', 3); + } + //formatted_answer = ("Use " + str(amt_needed) + " " + amt_suffix); + formatted_answer = str; // ("Use " << amt_needed << " " << amt_suffix); + qDebug() << "formatted_answer = " << formatted_answer; + write_answer(formatted_answer); +} + +void MainWindow::format_ml_answer(double ml_needed) +{ + // This checks and formats the answer, and sends it to write_answer function. + + // Declare some variables. + double desired_volume_liters; + double amt_needed; + QString amt_suffix; + QString formatted_answer; + QString str; + + qDebug() << "Started: format_ml_answer. input ml_needed = " << ml_needed; + // Check if answer is larger than desired volume. + desired_volume_liters = read_desired_volume(); + if (ml_needed > (desired_volume_liters * 1000) and (desired_volume_liters > 0.0)) + { + cc_msgBox("ERROR \n Calculated Volume needed is MORE than Desired Volume.", + "Your Desired Solution concentration may be more than your Starting Solution concentration.", + "", + this); + } + // use liters in final answer. + if (ml_needed >= 1000) + { + amt_needed = (ml_needed / 1000); + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 L").arg(amt_needed, 0, 'F', 3); + amt_suffix = "L"; + } + // use ml in final answer. + if ((ml_needed < 1000) and (ml_needed >=1)) + { + amt_needed = (ml_needed); + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 ml").arg(amt_needed, 0, 'F', 3); + amt_suffix = "ml"; + } + // use ul in final answer. + if (ml_needed < 1) + { + amt_needed = (ml_needed) * 1000; + // Last digit below (3) sets the number of digits to the right of the decimal point. + str = QString("Use %1 ul").arg(amt_needed, 0, 'F', 3); + amt_suffix = "ul"; + } + formatted_answer = str; //("Use " + amt_needed + " " + amt_suffix); + qDebug() << "formatted_answer = " << formatted_answer; + write_answer(formatted_answer); +} + +void MainWindow::write_answer(QString text) +{ + ui->textEdit_Results->clear(); + ui->textEdit_Results->setText(text); +} + +QString MainWindow::read_result() +{ + QString result = ui->textEdit_Results->toPlainText(); + qDebug() << "read_result = " << result; + return result; +} + +QString MainWindow::read_starting_reagent() +{ + //Read Starting Reagent text and do some (minimal) processing. + QString raw_starting_reagent = ui->textEdit_StartingReagent->toPlainText(); + qDebug() << "raw_starting_reagent = " << raw_starting_reagent; + + // On first click of 'Starting Reagent' text box, clear original text. + qDebug() << "Clearing Starting Reagent defauilt text."; + if (raw_starting_reagent == "Enter reagent name here."){ + ui->textEdit_StartingReagent->setPlainText(""); //Clear text box. + return "Unnamed Reagent"; + } return raw_starting_reagent; +} + + +QString MainWindow::on_pushButton_AddToPrintList_clicked() +{ + /* This creates a text answer formated like: + partA = "Use 32 grams of " or "Use 5 ml of 1 molar " + partB = starting reagent + partC = "(MW = 123)" (only if needed) + partD = "to get " + partE = "250 ml " or total amount + suffix + partF = "of 10 mM " + starting reagent. + */ + + qDebug() << "'onPushButton_add_to_printList_clicked' called."; + //Declare some variables upfront to avoid double declarations: + QString partA = ""; + QString starting_reagent_text = ""; + QString partB =""; + QString mw = ""; + QString partC = ""; + QString partD = ""; + QString desired_radioButton = ""; + QString raw_desired_volume = ""; + QString desired_volume_suffix = ""; + QString partE = ""; + QString desired_conc = ""; + QString desired_conc_suffix = ""; + QString partF = ""; + QString starting_radioButton =""; + QString t_amount_num = ""; + QString t_amount_suffix = ""; + QString solution_A = ""; + QString solution_B = ""; + + //------------------------ + //Call 'calculate_clicked' to recalculate current answer. + qDebug() << "'calculate_clicked' called from 'onPushButton_add_to_printList_clicked' function"; + qDebug() << "Existing g_print_text = " << mPrintDialog::g_print_text; + MainWindow::on_pushButton_Calculate_clicked(); + //------------- + partA = MainWindow::read_result(); + starting_reagent_text = read_starting_reagent(); + if (starting_reagent_text == ""){ + starting_reagent_text = "reagent"; + }; + starting_reagent_text.truncate(80); + partB = starting_reagent_text; + mw = ui->lineEdit_MW->text(); + //Maybe setup a validator to check for empty MW text box. TODO. + partC += " (MW = "; partC += mw; partC += ") "; + partD = "to get "; + desired_radioButton = MainWindow::read_desired_radioButtons(); // either "solution" or "total_amount". + if (desired_radioButton == "solution") { + raw_desired_volume = ui->lineEdit_DesiredVolume->text(); + desired_volume_suffix = ui->comboBox_DesiredVolumeSuffix->currentText(); + partE = raw_desired_volume + " " + desired_volume_suffix + " "; + desired_conc = ui->lineEdit_DesiredSolution->text(); + desired_conc_suffix = MainWindow::read_desired_suffix(); + partF = "of " + desired_conc + " " + desired_conc_suffix + " " + partB; + } + if (desired_radioButton == "total_amount") { + t_amount_num = ui->lineEdit_TotalAmount->text(); //a QString. + t_amount_suffix = MainWindow::read_total_amount_suffix(); //a QString + partE += t_amount_num; partE += " "; partE += t_amount_suffix; partE += " "; + partF = "of " + partB; + } + //Next line returns either "solution", solid" or "liquid". + starting_radioButton = MainWindow::read_starting_radioButtons(); + if (starting_radioButton == "solution") { + solution_A = ui->lineEdit_StartingSolution->text(); // QString of molar number + solution_B = MainWindow::read_starting_suffix(); // molar suffix + partA += " of "; partA += solution_A; partA += " "; partA += solution_B; partA += " "; + } + if (starting_radioButton == "solid") { + //append " of " to partA via QString append command. + partA += " of "; + } + if (starting_radioButton == "liquid") { + partA += " of "; + } + QString answer_text_string = (partA + partB + partC + partD + partE + partF + ".\n\n"); + qDebug() << "In on_pushButton_AddToPrintList_clicked, answer_text_string = " << answer_text_string; + mPrintDialog::g_print_text += answer_text_string; + qDebug() << "In on_pushButton_AddToPrintList_clicked, FINAL mPrintDialog::g_print_text = " << mPrintDialog::g_print_text; //answer_text_string; + //---------------------- + pd = new mPrintDialog(this); //Works but may not be correct. + pd->open(); + + MainWindow::pd->show_printList(mPrintDialog::g_print_text); + return ("Returned Text Goes Here"); // returned_text; +} + +void MainWindow::on_pushButton_Calculate_clicked() +{ + //Start calculating chemical amounts, etc. + // This function runs every time the "Calculate" button is clicked. + + //Clear results area. + ui->textEdit_Results->clear(); + + //Initalize these variables. + //bool sol_is_molar; //This is a function. + bool starting_solution_is_weight = false; + bool starting_solution_is_molar= false; + bool starting_reagent_is_solid= false; + bool starting_reagent_is_liquid= false; + bool desired_solution_is_molar= false; + bool desired_solution_is_weight= false; + bool desired_reagent_is_total_by_moles= false; + bool desired_reagent_is_total_by_weight= false; + bool skipMW= false; + double total_amount = 0.0; + QString total_amount_suffix = "CB-error"; + double desired_volume_liters = 0.0; + double calculated_desired_moles = 0.0; + double desired_molarity = 0.0; + double desired_conc = 0.0; + double starting_conc = 0.0; + double ml_needed = 0.0; + double grams_needed = 0.0; + double starting_molarity = 0.0; + double desired_moles = 0.0; + double desired_grams = 0.0; + double desired_g_per_L = 0.0; + double mw = 0.0; + double calculated_starting_molarity = 0.0; + double starting_g_per_L = 0.0; + //double liquid_g_per_L = 0.0; // Use density instead. -DELETE? + double density = 0.0; + QString starting_radio_button_selected = "NONE"; + QString desired_radio_button_selected = "NONE"; + QString starting_conc_suffix = "NONE"; + QString desired_conc_suffix = "NONE"; + + + + // Read starting reagent radio buttons. + starting_radio_button_selected = MainWindow::read_starting_radioButtons(); + qDebug() << "starting_radio_button_selected = " << starting_radio_button_selected; + // Read desired reagent radio buttons. + desired_radio_button_selected = MainWindow::read_desired_radioButtons(); + qDebug() << "desired_radio_button_selected = " << desired_radio_button_selected; + + /*Sets the following variables: -------------------------------- + + (Starting Reagents-sets 1): (Desired Reagents-sets 1): + 1) starting_solution_is_molar* A) desired_solution_is_molar* + 2) starting_solution_is_weight B) desired_solution_is_weight + 3) starting_reagent_is_solid (by weight) C) desired_reagent_is_total_by_moles* + 4) starting_reagent_is_liquid (by weight) D) desired_reagent_is_total_by_weight + + -This means 16 different combinations are needed (labeled 1A to 4D). + -The following 8 are molar-molar combinations, no MW needed: + 1A, 1C, 2B, 2D, 3B, 3D, 4B, 4D + -----------------------------------------------------------------*/ + + // Starting Reagent 1 and 2 above. + // STARTING reagent is a SOLUTION. + if (starting_radio_button_selected == "solution") { + starting_conc = read_starting_conc(); + starting_conc_suffix = read_starting_suffix(); + + //This returns the conversion factor or 0 if not found --NO ???. + if (sol_is_molar(starting_conc_suffix)!=0) { + starting_molarity = calc_solution_molarity(starting_conc, starting_conc_suffix); + starting_solution_is_molar = true; + starting_solution_is_weight = false; + qDebug() << "The starting Solution is Molar. " << "The start suffix = " << starting_conc_suffix; + qDebug() << "The starting molarity = " << starting_molarity; + } + + else { + qDebug() << "The starting Solution is by weight. "; + starting_solution_is_weight = true; + starting_solution_is_molar = false; + starting_g_per_L = g_per_L(starting_conc, starting_conc_suffix); + qDebug() << "starting_g_per_L = " << starting_g_per_L; + mw = read_MW(); + starting_molarity = (starting_g_per_L / mw); + qDebug() << "starting_molarity via g/L = " << starting_molarity; + qDebug() << "starting_conc and suffix = " << starting_conc << starting_conc_suffix; + } + } + // Starting Reagent 3 above. + //Starting is a solid. No other info needed here (ex. MW). + if (read_starting_radioButtons() == "solid"){ + starting_reagent_is_solid = true; + qDebug() << "Starting reagent is a SOLID."; + } + // Starting Reagent 4 above. + // If STARTING reagent is a LIQUID. + if (read_starting_radioButtons() == "liquid"){ + density = read_density(); + starting_reagent_is_liquid = true; + qDebug() << "Starting reagent is a LIQUID. density =" << density; + } + //-------------------------------------------- + // Desired Reagent A and B above. + if (desired_radio_button_selected == "solution") { // if DESIRED is a SOLUTION. + desired_conc = read_desired_conc(); + desired_conc_suffix = read_desired_suffix(); + qDebug() << "desired_conc and suffix = " << desired_conc << desired_conc_suffix; + //This returns the conversion factor or 0 if not found --NO ???. + // If DESIRED SOLUTION is MOLAR. + if (sol_is_molar(desired_conc_suffix)!=0) { + desired_solution_is_molar = true; + desired_molarity = calc_solution_molarity(desired_conc, desired_conc_suffix); + qDebug() << "The DESIRED Solution is Molar. " << "The DESIRED suffix = " << desired_conc_suffix; + qDebug() << "The DESIRED molarity = " << desired_molarity; + } + else { + desired_solution_is_weight = true; + desired_solution_is_molar = false; + desired_g_per_L = g_per_L(desired_conc, desired_conc_suffix); + qDebug() << "The DESIRED Solution is by WEIGHT. " << "The DESIRED suffix = " << desired_conc_suffix; + qDebug() << "The DESIRED g_per_L = " << desired_g_per_L; + } + } + //----------------------------- + // Desired Reagent C and D above. + // If DESIRED solution is a TOTAL AMOUNT. + if (desired_radio_button_selected == "total_amount") { + total_amount = read_total_amount(); + total_amount_suffix = read_total_amount_suffix(); + qDebug() << "Total amount and suffix = " << total_amount << total_amount_suffix; + desired_reagent_is_total_by_moles = is_desired_reagent_total_by_moles(); + desired_reagent_is_total_by_weight = is_desired_reagent_total_by_weight(); + + qDebug() << "desired_reagent_is_total_by_moles = " << desired_reagent_is_total_by_moles; + qDebug() << "desired_reagent_is_total_by_weight = " << desired_reagent_is_total_by_weight; + + if (desired_reagent_is_total_by_moles){ + desired_moles = calc_moles(total_amount, total_amount_suffix); + } + if (desired_reagent_is_total_by_weight){ + desired_grams = calc_grams(total_amount, total_amount_suffix); + } + } // This is the curly bracket for the end of "Desired reagent C and D" code. + + /*--------------------Repeated Note ----------------------------------------- + (Starting Reagents-sets 1): (Desired Reagents-sets 1): + 1) starting_solution_is_molar* A) desired_solution_is_molar* + 2) starting_solution_is_weight B) desired_solution_is_weight + 3) starting_reagent_is_solid (by weight) C) desired_reagent_is_total_by_moles* + 4) starting_reagent_is_liquid (by weight) D) desired_reagent_is_total_by_weight + + -This means 16 different combinations are needed (labeled 1A to 4D). + -The following 8 are molar-molar combinations, no MW needed: + 1A, 1C, 2B, 2D, 3B, 3D, 4B, 4D + -----------------------------------------------------------------------""" + Start the 16 different reagent combinations. Order changed from above.----- */ + + // The first two don't need mw (nolecular weight) so skip getting it. + if (starting_solution_is_molar and desired_solution_is_molar) skipMW = true; + if (starting_solution_is_molar and desired_reagent_is_total_by_moles) skipMW = true; + qDebug() << "(Before step 1A) starting_solution_is_molar = " << starting_solution_is_molar; + qDebug() << "(Before step 1A) desired_solution_is_molar = " << desired_solution_is_molar; + qDebug() << "(Before step 1A) desired_reagent_is_total_by_moles = " << desired_reagent_is_total_by_moles; + qDebug() << "(Before step 1A) desired_reagent_is_total_by_weight = " << desired_reagent_is_total_by_weight; + qDebug() << "(Before step 1A) skipMW = " << skipMW; + //Get mw (molecular weight) for other 14 combinations. + if (skipMW == false) mw = read_MW(); + + // -- 1A -- no mw needed. + if (starting_solution_is_molar and desired_solution_is_molar){ + // Use starting_molarity and desired_molarity. (NO mw needed) + qDebug() << "Entered calculate step 1A. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + calculated_desired_moles = desired_molarity * desired_volume_liters; + ml_needed = ((calculated_desired_moles / starting_molarity) * 1000); // for ml answer. + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "calculated_desired_moles = " << calculated_desired_moles; + qDebug() << "ml_needed = " << ml_needed; + } + + // -- 1C -- No mw needed. + if (starting_solution_is_molar and desired_reagent_is_total_by_moles) { + // Use starting_molarity and desired_moles (NO mw needed). + qDebug() << "Entered calculate step 1C. "; + ml_needed = ((desired_moles / starting_molarity) * 1000); // desired_moles from above.. + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_moles = " << desired_moles; + qDebug() <<"ml_needed = " << ml_needed; + } + + // The last 14 need to use the mw (molecular weight).--------------- + // -- 1B -- + if (starting_solution_is_molar and desired_solution_is_weight){ + // Use starting_molarity and desired_g_per_L with mw. + qDebug() << "Entered calculate step 1B. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + calculated_desired_moles = (desired_g_per_L / mw) * desired_volume_liters; + ml_needed = ((calculated_desired_moles / starting_molarity) * 1000); // for ml answer. + format_ml_answer(ml_needed); // Format and post answer to box. + + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "calculated_desired_moles = " << calculated_desired_moles; + qDebug() << "ml_needed = " << ml_needed; + } + + // -- 1D -- + if (starting_solution_is_molar and desired_reagent_is_total_by_weight) { + // Use starting_molarity and desired_grams with mw. + qDebug() << "Entered calculate step 1D. "; + calculated_desired_moles = (desired_grams / mw); + ml_needed = ((calculated_desired_moles / starting_molarity) * 1000); // for ml answer. + // No error checking needed for starting volume > desired volume + // because there is no final volume. + format_ml_answer(ml_needed); // Format and post answer to box. + } + + //------------------------------------------ + // -- 2A -- + if (starting_solution_is_weight and desired_solution_is_molar){ + // Use starting_g_per_L and desired_molarity. + qDebug() << "Entered calculate step 2A. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + calculated_desired_moles = desired_molarity * desired_volume_liters; + calculated_starting_molarity = (starting_g_per_L / mw); + ml_needed = ((calculated_desired_moles / calculated_starting_molarity) * 1000); // for ml answer. + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "calculated_desired_moles = " << calculated_desired_moles; + qDebug() << "ml_needed = " << ml_needed; + } + + // -- 2B -- no mw needed + if (starting_solution_is_weight and desired_solution_is_weight) { + // Use starting_g_per_L and desired_g_per_L. + qDebug() << "Entered calculate step 2B. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + desired_grams = (desired_g_per_L * desired_volume_liters); + ml_needed = (desired_grams / starting_g_per_L) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "ml_needed = " << ml_needed; + } + + // -- 2C -- + if (starting_solution_is_weight and desired_reagent_is_total_by_moles) { + //Use starting_g_per_L and desired_moles. + qDebug() << "Entered calculate step 2C. "; + desired_grams = (desired_moles * mw); + ml_needed = (desired_grams / starting_g_per_L) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_grams = " << desired_grams; + qDebug() << "ml_needed = " << ml_needed; + } + // -- 2D -- no mw needed + if (starting_solution_is_weight and desired_reagent_is_total_by_weight) { + // Use starting_g_per_L and desired_grams. + qDebug() << "Entered calculate step 2D. "; + ml_needed = (desired_grams / starting_g_per_L) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "desired_grams = " << desired_grams; + qDebug() << "ml_needed = " << ml_needed; + } + + //--------------------------------------- + // -- 3A -- + if (starting_reagent_is_solid and desired_solution_is_molar) { + // Use desired_molarity. + qDebug() << "Entered calculate step 3A. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + calculated_desired_moles = desired_molarity * desired_volume_liters; + grams_needed = (calculated_desired_moles * mw); + format_gram_answer(grams_needed); // Format and post answer to box. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "calculated_desired_moles = " << calculated_desired_moles; + qDebug() << "grams_needed = " << grams_needed; + } + + // -- 3B -- no mw needed + if (starting_reagent_is_solid and desired_solution_is_weight) { + // Use desired_g_per_L. + qDebug() << "Entered calculate step 3B. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + desired_grams = (desired_g_per_L * desired_volume_liters); + grams_needed = desired_grams; + format_gram_answer(grams_needed); // Format and post answer to box. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + qDebug() << "grams_needed = " << grams_needed; + } + + // -- 3C -- + if (starting_reagent_is_solid and desired_reagent_is_total_by_moles) { + // Use desired_moles + qDebug() << "Entered calculate step 3C. "; + grams_needed = (mw * desired_moles); + format_gram_answer(grams_needed); // Format and post answer to box. + qDebug() << "grams_needed = " << grams_needed; + } + + // -- 3D -- no mw needed + if (starting_reagent_is_solid and desired_reagent_is_total_by_weight) { + //Use desired_grams. + qDebug() << "Entered calculate step 3D. "; + grams_needed = desired_grams; + format_gram_answer(grams_needed); // Format and post answer to box. + qDebug() << "grams_needed = " << grams_needed; + } + + //--------------------------------------- + // -- 4A -- + if (starting_reagent_is_liquid and desired_solution_is_molar) { + // Use density and desired_molarity. + qDebug() << "Entered calculate step 4A. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + qDebug() << "desired_volume_liters = " << desired_volume_liters; + calculated_desired_moles = desired_molarity * desired_volume_liters; + qDebug() << "calculated_desired_moles = " << calculated_desired_moles; + grams_needed = (calculated_desired_moles * mw); + qDebug() << "grams_needed = " << grams_needed; + ml_needed = (grams_needed / density); + qDebug() << "ml_needed = " << ml_needed; + format_ml_answer(ml_needed); // Format and post answer to box. + } + // -- 4B -- no mw needed + if (starting_reagent_is_liquid and desired_solution_is_weight) { + // Use density and desired_g_per_L. + qDebug() << "Entered calculate step 4B. "; + desired_volume_liters = read_desired_volume(); // Get desired volume. + desired_grams = desired_g_per_L * desired_volume_liters; + grams_needed = desired_grams; + ml_needed = (grams_needed / density) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "ml_needed = " << ml_needed; + } + // -- 4C -- + if (starting_reagent_is_liquid and desired_reagent_is_total_by_moles) { + // Use desired_g_per_L and desired_moles. + qDebug() << "Entered calculate step 4C. "; + grams_needed = (mw * desired_moles); + ml_needed = (grams_needed / density) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "ml_needed = " << ml_needed; + } + // -- 4D -- no mw needed + if (starting_reagent_is_liquid and desired_reagent_is_total_by_weight) { + // Use density and desired_grams. + qDebug() << "Entered calculate step 4D. "; + grams_needed = desired_grams; + ml_needed = (grams_needed / density) * 1000; + format_ml_answer(ml_needed); // Format and post answer to box. + qDebug() << "ml_needed = " << ml_needed; + } +} // This is the curly bracket for the end of "calculate pushbutton clicked". +//--------------------------------------------------------------------------- + +void MainWindow::on_pushButton_FindMW_clicked() +{ + // Looks up MW in database. + + qDebug() << "MainWindow FindMW clicked - Part 1."; + // Create new Select_Dialog object, BUT don't display it yet. + Select_Dialog *mySD = new Select_Dialog(this); // Don't make two copies. + + //QString reagent_fragment = ui->textEdit_StartingReagent->toPlainText(); + QString reagent_fragment = read_starting_reagent(); + qDebug() << "In find_MW... of reagent_fragment = " << reagent_fragment; + + mySD->ui4->label->setText("Pick One Reagent In DataBase (Or Cancel)."); + int rowCount = mySD->chem_db_read(reagent_fragment); + qDebug() << "MainWindow FindMW clicked - Part 2- ROWCOUNT = " << rowCount; + + if (rowCount <=0){ + // No local results, do a PubChem (Enterez) search <-----------FINISH ME----- + on_actionEnterez_Search_triggered(true); + // Line above returns BEFORE search is fully completed. + // NOTE: A race condition exists here if code continues! <---------- + // Follow code at end of query (processReturnedText2()) to continue. + return; // End now to prevent race condition. + } + if (rowCount >20){ + // Too many results. + cc_msgBox("Too many matching reagents were found.", + "Please narrow you search by typing a longer reagent name", + "", + this); + } + if (rowCount >0 and rowCount <=20){ + // Display SELECT dialog box. Returns '1' for OK // '0' for canceled. + int dialogCode = mySD->exec(); + if (dialogCode == 1){ + ui->textEdit_StartingReagent->setText(Edit_Dialog::g_reagent); + ui->lineEdit_MW->setText(Edit_Dialog::g_mw_string); + } + } + qDebug() << "MainWindow FindMW clicked - Part 3-END."; +} + +void MainWindow::on_pushButton_SaveMW_clicked() +{ + // Saves MW in the database. + qDebug() << "MainWindow SaveMW clicked."; + + QString reagent_name = read_starting_reagent(); + qDebug() << "save_MW of " << reagent_name; + if (reagent_name == "Unknown Reagent"){ + // Error message and DON'T SAVE. + cc_msgBox("Please enter a reagent name."); + return; + } + + // Note: Changed to mw as a string (mw_string). + // Read, validate, and return mw (molecular weight) as a double. + // double mw = read_MW(); + // qDebug() << "In SaveMW...MW = " << mw; + + QString mw_string = ui->lineEdit_MW->text(); + // Add error checking here for mw = empty etc.. + qDebug() << "In SaveMW...MW = " << mw_string; + + // db_query my_db_query; + // int myNum = my_db_query.db_Save(reagent_name, mw_string); + + int myNum = db_Save(reagent_name, mw_string); + qDebug() << "myNum = " << myNum; +} + +void MainWindow::on_actionDatabase_triggered() +{ + // Display and edit the ChemCalc chemical database. + qDebug() << "MainWindow Menu Edit-Database triggered-STARTED."; + Edit_Dialog *myED = new Edit_Dialog(this); + myED->open(); + qDebug() << "MainWindow Menu Edit-Database triggered-ENDED."; +} + +void MainWindow::on_textEdit_StartingReagent_cursorPositionChanged() +{ + // On first click of 'Starting Reagent' text box, clear original text. + qDebug() << "Clearing Starting Reagent defauilt text-2."; + if (ui->textEdit_StartingReagent->toPlainText() == "Enter reagent name here."){ + ui->textEdit_StartingReagent->setPlainText(""); + }; +} + +//-------------TEST AREA------------------------- + +//------Start of PubChem Search Code------------------------------------ +// The many functions called (in order) are: +// 1) on_actionEnterez_Search_triggered() +// 1B) which includes---> manager->get(QNetworkRequest(QUrl(entrezURL))); +// 2) replyFinished1() +// 3) processReturnedText1() +// ----------------------- +// 4) entrezQuery2() +// 4B) which includes---> manager2->get(QNetworkRequest(QUrl(entrezURL2))) +// 5) replyFinished2() +// 6) processReturnedText2() +// 7) askToUseAndSave() +//------------------------------------------- + +void MainWindow::on_actionEnterez_Search_triggered(bool strictSearch = true) +{ + // This slot is called when the "entrez search" menu item is clicked, + // or when 'Find_MW()' calls it due to reagent not in local database. + // For strictSearch: true (default) = strict search, false = not strict (loose) search. + // + // This function queries a PubChem chemical database + // in order to obtain the molecular Weight (mw). + // This is the FIRST SEARCH that gets UID's only. + // Later 'entrezQuery2()' is called to get Docsums of compounds. + // Ref for e-searches: https://www.ncbi.nlm.nih.gov/books/NBK25497/ + // Start with "strictSearch" = true (default/optional) but if no results change to false. + + QString myReagentText = read_starting_reagent(); + qDebug() << "Starting on_actionEntrez_Search_triggered. myReagentText = " << myReagentText; + + // g_strictSearch is class scope, declared in header file. (vs local strictSearch). + g_strictSearch = strictSearch; // Used at end of search if needed to run a loose search. + qDebug() << "strictSearch = " << strictSearch; + + // From https://doc.qt.io/qt-6/qnetworkaccessmanager.html#details + // Note there are some new functions in Qt6.7 that may work better (less slots). + // See https://doc.qt.io/qt-6/qnetworkaccessmanager.html#get-2 + QNetworkAccessManager *manager = new QNetworkAccessManager(this); + connect(manager, &QNetworkAccessManager::finished, this, + &MainWindow::replyFinished1); + + QString pubMedDB = "pccompound"; // "PubChem-Compound" There are many other databases, but this one is good. + QString query = myReagentText; + // Replace spaces with "+". + query.replace(" ", "+"); + + // assemble the esearch URL + QString urlA1 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db="; + QString urlA2 = pubMedDB; + QString urlA3 = "&term="; + QString urlA4; // Must be declared outside of if loop. + // (%22=1 double quote) query search terms has double quotes around it. + if (strictSearch==true){urlA4 = "%22" + query + "%22";} + if (strictSearch==false){urlA4 = query;} // (query search terms do NOT have any quotes around it. + QString urlA5 = "&usehistory=y"; + // Returns only one value. Works great with just the best search return. + QString urlA6 = "&retmax=1"; + QString urlA7 = "&sort=relevance"; + QString urlAComplete = urlA1 + urlA2 + urlA3 + urlA4 + urlA5 + urlA6 + urlA7; + qDebug() << "urlAComplete = " << urlAComplete; + + QUrl entrezURL(urlAComplete); + // If no internet connection. + if (!entrezURL.isValid()){ + cc_msgBox("Could not establish an internet connection to PubChem databases."); + qDebug() << "entrezURL is NOT valid. = " << entrezURL; + entrezURL.clear(); // You need to clear QUrl on failure. + return; // End entire function. + } + qDebug() << "entrezURL is valid. = " << entrezURL; + qDebug() << "Encoded entrezURL = " << entrezURL.toEncoded(); + + // Leads to (slot) MainWindow::replyFinished1(QNetworkReply *reply1). + manager->get(QNetworkRequest(QUrl(entrezURL))); + qDebug() << "End of on_actionEnterez_Search_triggered."; +} + +void MainWindow::replyFinished1(QNetworkReply *reply1) +{ + // The web reply for FIRST SEARCH ends up here. + qDebug() << "replyFinshed1 started. " << "reply 1 = " << reply1; + QByteArray myByteArray1 = reply1->readAll(); //WORKS but includesheader etc. + qDebug() << "myByteArray1 = " << myByteArray1; // LONG! Uncomment to debug. + entrezData myEntrezDataStruct = processReturnedText1(myByteArray1); + qDebug() << "myEnterezDataStruct.WebEnv = " << myEntrezDataStruct.WebEnv; + qDebug() << "myEnterezDataStruct.QueryKey = " << myEntrezDataStruct.QueryKey; + qDebug() << "myEnterezDataStruct.UIDString = " << myEntrezDataStruct.UIDString; + // Start SECOND entrez search, for DocSums. + entrezQuery2(myEntrezDataStruct); +} + +// ******************************************************* +// Note: The following items are declared at top for CLASS SCOPE. +// 1) QString UIDString(); +// +// And in mainwindow.h: +// 2) struct entrezData{ +// QString WebEnv; +// QString QueryKey; +// QString UIDString;} +// ******************************************************* + +MainWindow::entrezData MainWindow::processReturnedText1(QByteArray myByteArray1) +{ + //This returns a 'entrezData' struct of 2 data items and 1 Qlist obtained from the network response mByteArray. + qDebug() << "processReturnedText1 called"; + auto toUtf16 = QStringDecoder(QStringDecoder::Utf8); + QString myString = toUtf16(myByteArray1); + qDebug() << "\nmyString = " << myString; + + QXmlStreamReader xml(myByteArray1); + QString chemUIDHeader = "Id"; //These need to be declared outside of if/while loops below. + QString chemUIDNumber = ""; + QString webEnvHeader = "WebEnv"; + QString webEnvNumber = ""; + QString queryKeyHeader = "QueryKey"; + QString queryKeyNumber = ""; + + while (!xml.atEnd()) { + xml.readNext(); + // 1) Look for 1 "" element and put into UIDString. + if(xml.name()== chemUIDHeader){ + chemUIDNumber = xml.readElementText(); // This is the chemical ID number. + qDebug() << "chemUIDNumber = " << chemUIDNumber; + // UIDList.append(chemUIDNumber); //DELETE + UIDString = chemUIDNumber; + } //end of FIRST if loop. -------------------------------------- + + // 2) Look for (one) "" element and put into QString 'webEnvNumber'.----- + if(xml.name()== webEnvHeader){ + qDebug() << "webEnvHeader = " << xml.name(); + webEnvNumber = xml.readElementText(); // This is the web Envelope number. + qDebug() << "webEnvNumber = " << webEnvNumber; + } //end of SECOND if loop. ---------------------------------------------------- + + // 3) Look for (one) "" element and put into QString 'query'.----- + if(xml.name()== queryKeyHeader){ + qDebug() << "queryKeyHeader = " << xml.name(); + queryKeyNumber = xml.readElementText(); // This is the web Envelope number. + qDebug() << "queryKeyNumber = " << queryKeyNumber; + } //end of THIRD if loop. ---------------------------------------------------- + } //end of while loop. + + // do error handling + if (xml.hasError()) { + qDebug() << "Error in processReturnText() function. "; + // Add more here. // <----------------- + } //end of if loop (error processor). + qDebug() << "UIDString = " << UIDString; + // return entrezData structure; + return entrezData{webEnvNumber, queryKeyNumber, UIDString}; +} + +void MainWindow::entrezQuery2(entrezData myEntrezDataStruct) +{ + // This function queries a PubChem chemical database + // in order to obtain the molecular Weight (mw). + // This is the SECOND SEARCH that gets Docsums of compounds. + // Ref for e-searches: https://www.ncbi.nlm.nih.gov/books/NBK25497/ + // ESummary Output: XML Document Summaries + + //------Notes from book------------ + // Downloading Data From a Previous Search + // esearch.fcgi?db=&term=&usehistory=y // <------entrezQery1----- + // # esearch produces WebEnv value ($web1) and QueryKey value ($key1) + // esummary.fcgi?db=&query_key=$key1&WebEnv=$web1 // <-------entrezQuery2----- + // Input: Web environment (&WebEnv) and query key (&query_key) representing a set + // of Entrez UIDs on the Entrez history server + //---------------------------------- + + // From https://doc.qt.io/qt-6/qnetworkaccessmanager.html#details + // Only one QNetworkManager needed for the whole Qt app, but I used 2. + + QString myWebEnv = myEntrezDataStruct.WebEnv; + QString myQueryKey = myEntrezDataStruct.QueryKey; + qDebug() << "myWebEnv = " << myWebEnv << " and " << "myQueryKey = " << myQueryKey; + + QNetworkAccessManager *manager2 = new QNetworkAccessManager(this); + connect(manager2, &QNetworkAccessManager::finished, + this, &MainWindow::replyFinished2); + + // assemble the 2nd URL. + QString urlB1 = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db="; + QString urlB2 = "pccompound"; // "PubChem-Compound" There are many other databases, but this one is good. + QString urlB3 = "&query_key="; + QString urlB4 = myQueryKey; + QString urlB5 = "&WebEnv="; + QString urlB6 = myWebEnv; + // Returns only one value. Works great with just the best search return. + QString urlB7 = "&retmax=1"; + QString urlBComplete = urlB1 + urlB2 + urlB3 + urlB4 + urlB5 + urlB6 + urlB7; + QUrl entrezURL2(urlBComplete); + + // If no internet connection. + if (!entrezURL2.isValid()){ + cc_msgBox("Could not establish an internet connection to PubChem databases."); + qDebug() << "entrezURL2 is NOT valid. = " << entrezURL2; + entrezURL2.clear(); // You need to clear QUrl on failure. + return; // End entire function. + } + + qDebug() << "entrezURL2 is valid. = " << entrezURL2; + qDebug() << "Encoded entrezURL2 = " << entrezURL2.toEncoded(); + // Leads to replyFinished2() via Signals and Slots. + manager2->get(QNetworkRequest(QUrl(entrezURL2))); +} + +void MainWindow::replyFinished2(QNetworkReply *reply2) +{ + // The web reply for SECOND SEARCH ends up here via Signals and Slots. + qDebug() << "replyFinshed2 started. " << "reply 2 = " << reply2; + QByteArray myByteArray2 = reply2->readAll(); //WORKS but includesheader etc. + myByteArray2 = myByteArray2.simplified(); //Removes excess whitespace (/n,/t, etc). + qDebug() << "myByteArray2 = " << myByteArray2; + processReturnedText2(myByteArray2); +} + +void MainWindow::processReturnedText2(QByteArray myByteArray2) +{ + // This gets chemName and molecular weight(mw) + // obtained from the network response mByteArray2. + // Example: returned text from 'Sodium Chloride': 58.440 + qDebug() << "processReturnedText2 called \n"; + + QDomNodeList myNodeList; + QDomNode myDomNode; + QString molecularWeight, chemNameReturned; + QDomDocument myDomDoc; + myDomDoc.setContent(myByteArray2); + + // Uncomment this for debugging (lots of output). + // QString myString = myDomDoc.toString(); + // qDebug() << "\n myString = " << myString; + + // Clear default molecular weight. + ui->lineEdit_MW->setText(""); + + myNodeList = myDomDoc.elementsByTagName("Item"); + for (int i=1; i<=myNodeList.count(); i++){ + myDomNode = myNodeList.item(i); + QDomElement myElement = myDomNode.toElement(); + QDomAttr myAttribute = myElement.attributeNode("Name"); + QString myAttributValue = qPrintable(myAttribute.value()); + QString myElementText = myElement.text(); + // Uncomment for debugging. + // qDebug() << "Name = " << myAttributValue << "myText = " << myText; + + // Get Molecular Weight (MW). + if (myAttributValue == "MolecularWeight"){ + molecularWeight = myElementText; + qDebug() << "myText (MW) = " << molecularWeight; + } + // Get chemical name "MeSHTermList" (chemNameReturned). + if (myAttributValue == "MeSHHeadingList"){ //This is NOT my typo: "MeSHHeadingList"; + chemNameReturned = myElementText; + qDebug() << "chemNameReturned = " << chemNameReturned; + } + } + + if (chemNameReturned.isEmpty() or molecularWeight.isEmpty()){ + qDebug() << "In processReturnedText2, either chemName or MW are EMPTY!"; + if (g_strictSearch == true){ + // Start a LOOSE SEARCH. Watch for infinite loop with no results! + // NOTE: Insert a time delay to prevent being banned from database. (3 queries/sec max) + QObject().thread()->msleep(1000); //Sleep for 1000 milliseconds (1 sec). + on_actionEnterez_Search_triggered(false); + return; // Nothing is written to GUI (MW and chemical name) on early return. + } + if (g_strictSearch == false){ + // If LOOSE SEARCH failed too. + qDebug() << "No results were found in both PubChem and Local databases."; + // If no valid results from entrezQuery, ask to open PubChem website. + //This creates a modal message box with a message and OK button. + QMessageBox msgBox2; + msgBox2.setText("No results were found in both PubChem and Local databases."); + msgBox2.setInformativeText("Do you want open the PubChem website in your browser?"); + msgBox2.setParent(this); + msgBox2.setIcon(QMessageBox::Question); + msgBox2.setWindowModality(Qt::WindowModal); + msgBox2.setWindowTitle("ChemCalc"); + msgBox2.setStandardButtons(QMessageBox::Open | QMessageBox::No | QMessageBox::Cancel); + msgBox2.setDefaultButton(QMessageBox::Cancel); + int ret2 = msgBox2.exec(); + if (ret2 == QMessageBox::Open){ + // Open PubChem website. + on_actionOpen_PubChem_Website_triggered(); + return; // Nothing is written to GUI (MW and chemical name) on early return. + } + if (ret2 == (QMessageBox::No | QMessageBox::Cancel)){ + qDebug() << "No or Cancel button selected."; + return; // Nothing is written to GUI (MW and chemical name) on early return. + } + } + } + askToUseAndSave(chemNameReturned, molecularWeight); +} // End of processReturnedText2. + +void MainWindow::askToUseAndSave(QString chemNameReturned, QString molecularWeight) +{ + // Only valid data continues from here. (Has 'chemNameReturned', + // and 'molecularWeight', but it might not be the correct chemical you want.) + + // Get typed Reagent Name in GUI. + QString typedReagentName = ui->textEdit_StartingReagent->toPlainText(); + + qDebug() << "MW = " << molecularWeight << " reagent = " << chemNameReturned; + QString chemNameToGui; // This chem name is the one added to Gui and used for calculations. + //------------------------------- + // Ask to use molecular weight in the GUI (for calculation). + QMessageBox msgBox5; + msgBox5.setText("PubChem found: MW = " + molecularWeight + " for " + chemNameReturned ); + msgBox5.setInformativeText("Do you want to use this MOLECULAR WEIGHT for the calculation?"); + msgBox5.setParent(this); + msgBox5.setIcon(QMessageBox::Question); + msgBox5.setWindowModality(Qt::WindowModal); + msgBox5.setWindowTitle("ChemCalc"); + msgBox5.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); + msgBox5.setDefaultButton(QMessageBox::Cancel); + int ret5 = msgBox5.exec(); + if (ret5 == (QMessageBox::No | QMessageBox::Cancel)){ + qDebug() << "In ask to use MW, No or Cancel button selected."; + return; // Nothing is written to GUI or saved (MW and chemical name) on early return. + } + if (ret5 == QMessageBox::Yes){ + qDebug() << "In ask to use MW, YES BUTTON selected."; + ui->lineEdit_MW->setText(molecularWeight); + } + + + //-------------------------------- + // Ask to save chemical name in the local database. + QMessageBox msgBox; + msgBox.setText("PubChem found: (MW = " + molecularWeight + ") " + chemNameReturned ); + msgBox.setInformativeText("Do you want to save this in the database?"); + msgBox.setParent(this); + msgBox.setIcon(QMessageBox::Question); + msgBox.setWindowModality(Qt::WindowModal); + msgBox.setWindowTitle("ChemCalc"); + msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + msgBox.setDefaultButton(QMessageBox::Cancel); + int ret = msgBox.exec(); + if (ret == (QMessageBox::Discard | QMessageBox::Cancel)){ + qDebug() << "Discard or Cancel button selected."; + return; // Nothing is written to GUI (MW and chemical name) on early return. + } + if (ret == (QMessageBox::Save)){ + // Save (to local database) and insert data (to GUI). + + // Added code here to select which reagent name (e.g. EDTA vs Edetic Acid) + // If typed reagent name is not exactly the same as returned name, choose a name to save. + if (typedReagentName != chemNameReturned){ + qDebug() << "Choosing a reagent name to save."; + // ------------ + //This creates a modal message box with a message and OK button. + QMessageBox msgBox3; + msgBox3.setText("Returned reagent name is different than your typed reagent name."); + msgBox3.setInformativeText("Do you want to save under both names"); + msgBox3.setParent(this); + msgBox3.setIcon(QMessageBox::Question); + msgBox3.setWindowModality(Qt::WindowModal); + msgBox3.setWindowTitle("ChemCalc"); + msgBox3.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); + msgBox3.setDefaultButton(QMessageBox::Cancel); + int ret3 = msgBox3.exec(); + if (ret3 == QMessageBox::Yes){ + // Save (twice) under both reagent names. + qDebug() << "Writing chemname and MW to LOCAL database."; + // Add (returned Reagent Name) data to localdatabase. (skipping confirmation) + db_Save(chemNameReturned, molecularWeight, true); + qDebug() << "New reagent and MW added to LOCAL database."; + chemNameToGui = typedReagentName; + } + if (ret3 == QMessageBox::Cancel){ + qDebug() << "Cancel button selected."; + return; // Nothing is written to GUI (MW and chemical name) on early return. + } + if (ret3 == QMessageBox::No){ + qDebug() << "No button selected."; + // Code to choose (saving) either typed or returned reagent name + //This creates a modal message box. + QMessageBox msgBox4; + msgBox4.setText("Which reagent name do you want to save."); + QString namesText = "1) = " + typedReagentName + ".\n" + "2) = " + chemNameReturned + "."; + msgBox4.setInformativeText(namesText); + msgBox4.setParent(this); + msgBox4.setIcon(QMessageBox::Question); + msgBox4.setWindowModality(Qt::WindowModal); + msgBox4.setWindowTitle("ChemCalc"); + msgBox4.setStandardButtons(QMessageBox::Cancel); + msgBox4.setDefaultButton(QMessageBox::Cancel); + QPushButton *use1Button = msgBox4.addButton("Use 1", QMessageBox::ActionRole); + QPushButton *use2Button = msgBox4.addButton("Use 2", QMessageBox::ActionRole); + int ret4 = msgBox4.exec(); + + if (msgBox4.clickedButton() == use1Button) { + // Add (TYPED Reagent Name) data to localdatabase. + qDebug() << "use1Button clicked. Saving TYPED reagent to local database."; + chemNameToGui = typedReagentName; + } + if (msgBox4.clickedButton() == use2Button) { + chemNameToGui = chemNameReturned; + } + if (ret4 == QMessageBox::Cancel){ + qDebug() << "Cancel button selected."; + return; // Nothing is saved or written to GUI (MW and chemical name) on early return. + } + } + } + + qDebug() << "Writing chemname to GUI."; + ui->textEdit_StartingReagent->setPlainText(chemNameToGui); + // Add data to localdatabase. + db_Save(chemNameToGui, molecularWeight, true); // Skip confirmation message. + qDebug() << "chemNameReturned and MW added to LOCAL database."; + } +} + +void MainWindow::on_actionOpen_PubChem_Website_triggered() +{ + // Open PubChem website in users browser. + bool OK = QDesktopServices::openUrl(QUrl("https://pubchem.ncbi.nlm.nih.gov/")); + if (!OK){ + cc_msgBox("Unknown internet or web browser error."); + } +} + + diff --git a/mainwindow.h b/mainwindow.h new file mode 100644 index 0000000..0a94957 --- /dev/null +++ b/mainwindow.h @@ -0,0 +1,119 @@ +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include +#include + +#include "mprintdialog.h" +#include "edit_dialog.h" +#include "qnetworkreply.h" +#include "qsqltablemodel.h" +#include "qtableview.h" + +QT_BEGIN_NAMESPACE +namespace Ui { +class MainWindow; +} +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + Ui::MainWindow *ui; + + friend class Select_Dialog; + friend class Edit_Dialog; + + void cc_msgBox(QString msgText, QString msgText2 ="", QString msgText3="", MainWindow *parent = nullptr); + void on_pushButton_DeleteRow_clicked(); + QString read_starting_reagent(); + int db_Save(QString reagent_name, QString mw, bool skipConfirmationMessage=false); + + QString UIDString; + struct entrezData{ + QString WebEnv; + QString QueryKey; + QString UIDString; + }; + + bool g_strictSearch; + static QString g_dataBaseFilePath; + static QString g_configFilePath; + static QSettings g_ccSettings; + + void entrezQuery1(QString myReagentText, bool strictSearch); + void entrezQuery2(entrezData myEntrezDataStruct); + +public slots: + +signals: + +private slots: + + void on_pushButton_Quit_clicked(); + void on_actionQuit_triggered(); + void on_pushButton_Show_clicked(); + void on_pushButton_Calculate_clicked(); + QString read_starting_radioButtons(); + + QString read_desired_radioButtons(); + double read_density(); + double validate_raw_number(QString raw_num); + double read_starting_conc(); + + QString read_starting_suffix(); + double read_desired_conc(); + QString read_desired_suffix(); + QString read_total_amount_suffix(); + double read_total_amount(); + + double read_MW(); + double sol_is_molar(QString str); + bool is_desired_reagent_total_by_moles(); + bool is_desired_reagent_total_by_weight(); + double calc_solution_molarity(double starting_conc, QString starting_conc_suffix); + + double g_per_L(double starting_conc, QString starting_conc_suffix); + double calc_moles(double input_num, QString suffix); + double calc_grams(double input_num, QString suffix); + double read_desired_volume(); + void format_ml_answer(double ml_needed); + + void format_gram_answer(double grams_needed); + void write_answer(QString text); + QString on_pushButton_AddToPrintList_clicked(); + QString read_result(); + + void on_pushButton_FindMW_clicked(); + void on_pushButton_SaveMW_clicked(); + void on_actionDatabase_triggered(); + void on_actionChemCalc_Help_triggered(); + void on_actionAbout_ChemCalc_triggered(); + + void on_textEdit_StartingReagent_cursorPositionChanged(); + void replyFinished1(QNetworkReply *reply1); + void replyFinished2(QNetworkReply *reply2); + entrezData processReturnedText1(QByteArray returnedText1); + void processReturnedText2(QByteArray returnedText2); + void on_actionEnterez_Search_triggered(bool strictSearch); + + void askToUseAndSave(QString chemNameReturned, QString molecularWeight); + void on_actionOpen_PubChem_Website_triggered(); + void runAtStart(); + bool checkForDataBase(); + bool checkForConfigurationFile(); + +private: + + mPrintDialog *pd; + QSqlTableModel *model; + QTableView *view; + +}; +#endif // MAINWINDOW_H diff --git a/mainwindow.ui b/mainwindow.ui new file mode 100644 index 0000000..cdb115f --- /dev/null +++ b/mainwindow.ui @@ -0,0 +1,715 @@ + + + MainWindow + + + + 0 + 0 + 683 + 570 + + + + MainWindow + + + + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg + :/Icons/ChemCalc_icon_120.svg:/Icons/ChemCalc_icon_120.svg + + + + + + 0 + 10 + 291 + 221 + + + + 1 - Starting Reagent + + + + + 10 + 40 + 241 + 71 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> +p, li { white-space: pre-wrap; } +hr { height: 1px; border-width: 0; } +li.unchecked::marker { content: "\2610"; } +li.checked::marker { content: "\2612"; } +</style></head><body style=" font-family:'Noto Sans'; font-size:12pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Enter reagent name here.</p></body></html> + + + + + + + + + 10 + 130 + 241 + 32 + + + + + + + Molecular Weight: + + + lineEdit_MW + + + + + + + 111.111 + + + Qt::AlignmentFlag::AlignCenter + + + + + + + + + 30 + 170 + 168 + 32 + + + + + + + Find MW + + + + + + + Save MW + + + + + + + + + + 10 + 250 + 401 + 181 + + + + 3 - Desired Solution + + + + + 10 + 30 + 361 + 147 + + + + + + + + + Solution Conc. + + + true + + + + + + + 1.0 + + + Qt::AlignmentFlag::AlignCenter + + + + + + + + M + + + + + mM + + + + + uM + + + + + nM + + + + + pM + + + + + fM + + + + + % + + + + + g/L + + + + + mg/L + + + + + ug/L + + + + + ng/L + + + + + pg/L + + + + + fg/L + + + + + + + + + + Or + + + + + + + + + Total Amount + + + + + + + 111.111 + + + Qt::AlignmentFlag::AlignCenter + + + + + + + + g + + + + + mg + + + + + ug + + + + + moles + + + + + millimoles + + + + + micromoles + + + + + + + + + + Qt::Orientation::Horizontal + + + + + + + + + Final Volume Wanted: + + + + + + + 250 + + + Qt::AlignmentFlag::AlignCenter + + + + + + + ml + + + + ml + + + + + L + + + + + ul + + + + + + + + + + + + + 440 + 250 + 231 + 181 + + + + 4 - Results + + + + + 20 + 30 + 181 + 141 + + + + + + + + + + Calculate + + + + + + + + + + 20 + 460 + 591 + 41 + + + + + + + Show, Print, or Save Print List + + + + + + + Add To Print List + + + + + + + Quit + + + + + + + Qt::Orientation::Horizontal + + + + 98 + 20 + + + + + + + + + + 300 + 10 + 381 + 221 + + + + 2 - Starting Reagent Concentration + + + + + 20 + 50 + 331 + 131 + + + + + + + + + Solution + + + true + + + + + + + 1.0 + + + 32767 + + + + + + + + + + + M + + + + + mM + + + + + uM + + + + + nM + + + + + pM + + + + + fM + + + + + % + + + + + g/L + + + + + mg/L + + + + + ug/L + + + + + ng/L + + + + + pg/L + + + + + fg/L + + + + + + + + + + Solid + + + + + + + + + Li&quid: Density + + + false + + + + + + + 1.0 + + + + + + + g/ml + + + + + + + + + groupBox_3_DesiredSolution + groupBox_4_Results + layoutWidget + groupBox_1_StartingReagent + groupBox_2_StartingReagent + + + + + 0 + 0 + 683 + 27 + + + + + File + + + + + + Edit + + + + + + Help + + + + + + + Search + + + + + + + + + + + + &Database + + + Edit Database + + + + + &Preferences + + + + + Close + + + File Close + + + + + &ChemCalc Help + + + + + &About ChemCalc + + + + + &Quit + + + QAction::MenuRole::TextHeuristicRole + + + + + &Search Local Database + + + + + &Open PubChem Website + + + + + &Enterez Search + + + + + + + + + actionClose + triggered() + MainWindow + close() + + + -1 + -1 + + + 319 + 280 + + + + + + signal1_CB() + slot1() + + diff --git a/mprintdialog.cpp b/mprintdialog.cpp new file mode 100644 index 0000000..c4c0b4a --- /dev/null +++ b/mprintdialog.cpp @@ -0,0 +1,94 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mprintdialog.h" +#include "ui_mprintdialog.h" + +QString mPrintDialog::g_print_text = "Chemical Calculator Results: \n\n"; + +mPrintDialog::mPrintDialog(QWidget *parent) + : QDialog(parent) + , ui2(new Ui::mPrintDialog) +{ + ui2->setupUi(this); + setWindowTitle("Print List - ChemCalc"); +} + +mPrintDialog::~mPrintDialog() +{ + delete ui2; +} + +void mPrintDialog::on_pushButton_Cancel_clicked() +{ + close(); +} + +void mPrintDialog::on_pushButton_Print_clicked() +{ + //Note: This produces a pdf file if file is saved via print dialog. + QPrinter my_printer = QPrinter(); + QPrintDialog printDialog(&my_printer, this); + if (printDialog.exec() == QDialog::Accepted) { + ui2->textEdit->document()->print(printDialog.printer()); + } +} + +void mPrintDialog::on_pushButton_Save_clicked() +{ + //Put file SAVE code here. This is called from the printlist save pushbutton. + qDebug("pushButton_Save called."); + //Code to be able to select file name and path. + //TODO - Add suggested default filename (ChemCalcSave.txt ??). + //QString fileNameHint = "ChemCalc_Output.txt"; + QString print_save_path_filename = QFileDialog::getSaveFileName(this, tr("Save File"),"~/ChemCalcResults.txt"); + qDebug() << "print_save_path_filename= " << print_save_path_filename; + + //Try to create and open the file for writing. + //Return on no file name error, and skip rest of code. + if (print_save_path_filename.isEmpty()){ + return; + } + QFile mfile(print_save_path_filename); + if(!mfile.open(QFile::WriteOnly | QFile::Text)){ + qDebug() << "Could not open file for text writing."; + return; + } + QString final_text = ui2->textEdit->toPlainText(); + QTextStream out(&mfile); + out << final_text; + qDebug() << "Final text= " << final_text; + mfile.flush(); + mfile.close(); //Close file - IMPORTANT! +} + + +//QString mPrintDialog::show_printList(QString print_list_text) +void mPrintDialog::show_printList(QString print_list_text) +{ + qDebug() << "'show_printList' called (in mprintdialog.cpp)."; + ui2->textEdit->setPlainText(print_list_text); + qDebug() << "'In mPrintDialog::show_printList' After 'ui2->textEdit->setPlainText(print_list_text)' " ; +} + +void mPrintDialog::on_mPrintDialog_finished(int result) +{ + //This is called automatically when the mPrintDialog dialog is closed by user. + + qDebug() << "In 'mPrintDialog_finished' STARTED."; + QString final_text = ui2->textEdit->toPlainText(); + //Add a 'newline (\n)' at end of previous text. + final_text.append( "\n"); + qDebug() << "In 'mPrintDialog_finished', 'final_text = " << final_text; + mPrintDialog::g_print_text = final_text; +} + + diff --git a/mprintdialog.h b/mprintdialog.h new file mode 100644 index 0000000..9949982 --- /dev/null +++ b/mprintdialog.h @@ -0,0 +1,35 @@ +#ifndef mPRINTDIALOG_H +#define mPRINTDIALOG_H + +#include +#include +#include +#include + +namespace Ui { +class mPrintDialog; +} + +class mPrintDialog : public QDialog +{ + Q_OBJECT + +public: + explicit mPrintDialog(QWidget *parent = nullptr); + ~mPrintDialog(); + + // see https://stackoverflow.com/questions/23922319/global-variables-in-qt-5-3 + static QString g_print_text; // initial declaration + void show_printList(QString print_list_text); + +private slots: + void on_pushButton_Cancel_clicked(); + void on_pushButton_Print_clicked(); + void on_pushButton_Save_clicked(); + void on_mPrintDialog_finished(int result); + +private: + Ui::mPrintDialog *ui2; +}; + +#endif // mPRINTDIALOG_H diff --git a/mprintdialog.ui b/mprintdialog.ui new file mode 100644 index 0000000..806df7d --- /dev/null +++ b/mprintdialog.ui @@ -0,0 +1,110 @@ + + + mPrintDialog + + + + 0 + 0 + 675 + 843 + + + + Dialog + + + true + + + + + 10 + 60 + 652 + 691 + + + + + + + + + + 16 + + + + This text file can be edited before saving or printing. + + + + + + + Qt::Orientation::Horizontal + + + + 128 + 20 + + + + + + + + + + + 12 + + + + + + + + + + Qt::Orientation::Horizontal + + + + 378 + 20 + + + + + + + + Print + + + + + + + Save + + + + + + + Cancel + + + + + + + + + + + diff --git a/resources.qrc b/resources.qrc new file mode 100644 index 0000000..b7858f0 --- /dev/null +++ b/resources.qrc @@ -0,0 +1,14 @@ + + + ChemCalc_data.db + + + ChemCalc_help1.md + ChemCalc_Screen_Capture.png + ChemCalc.conf + + + ChemCalc_icon_120.svg + ChemCalc_icon_120.png + + diff --git a/select_dialog.cpp b/select_dialog.cpp new file mode 100644 index 0000000..13edc4f --- /dev/null +++ b/select_dialog.cpp @@ -0,0 +1,149 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include //REMOVE? +#include //REMOVE? +#include //REMOVE? +#include +#include +#include + +#include "mainwindow.h" +#include "select_dialog.h" +#include "ui_select_dialog.h" + +Select_Dialog::Select_Dialog(QWidget *parent) + : QDialog(parent) + , ui4(new Ui::Select_Dialog) +{ + ui4->setupUi(this); + + qDebug() << "Select_Dialog::Select_Dialog Constructor - STARTED"; + setWindowTitle("Select From Database - ChemCalc"); + + Select_Dialog::g_db = QSqlDatabase::addDatabase("QSQLITE"); + g_db.setDatabaseName(MainWindow::g_dataBaseFilePath); + + bool DB_opened_OK = g_db.open(); + qDebug() << "DB_opend_OK = " << DB_opened_OK; + if (DB_opened_OK == false) { + MainWindow myObj; + myObj.cc_msgBox("Unable to connect to the local database"); + qDebug() << "Unable to connect to the database"; + return; + } + model = new QSqlTableModel(this); + model->setTable("USER"); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->select(); + + view = ui4->tableView; + view->setModel(model); + view->setColumnWidth(0, 510); + view->setColumnWidth(1,75); + view->setWordWrap(true); + view->setSortingEnabled(true); + view->resizeRowsToContents(); + //------------------------------- + qDebug() << "Select_Dialog Constructor - PARENT = " << parent; + qDebug() << "Select_Dialog Constructor - THIS = " << this; + + qDebug() << "Select_Dialog Constructor - ENDED"; +} + +Select_Dialog::~Select_Dialog() +{ + delete ui4; +} + +void Select_Dialog::on_pushButton_Cancel_clicked() +{ + qDebug() << "Select_Dialog CANCEL clicked."; + // This works just like this. Changed data rolls back if not submitted. + close(); +} + +void Select_Dialog::on_pushButton_OK_clicked() +{ + close(); +} + +void Select_Dialog::on_tableView_clicked(const QModelIndex &index) +{ + // This function is a slot called whenever a user clicks on (selects) + // a table item from a Select_Dialog box (signal) of + // reagents and molecular weights. It sets LOCAL VARIABLES. + // It sets 2 (Edit_Dialog) global or class-wide variables. + + qDebug() << "Select_Dialog::on_tableView_clicked(const QModelIndex &index)--index = " << index; + + //Use local variables in this function. + int selected_row = index.row(); + qDebug() << "selected_row = " << selected_row; + + int selected_column = index.column(); + qDebug() << "selected_column = " << selected_column; + + QString mw = index.siblingAtColumn(1).data().toString(); + qDebug() << "mw = " << mw; //MW as a QSTRING, local variable only. + Edit_Dialog::g_mw = mw.toDouble(); //MW as a DOUBLE + Edit_Dialog::g_mw_string = mw; //MW as a String + qDebug() << "Edit_Dialog::g_mw = " << Edit_Dialog::g_mw; + qDebug() << "Edit_Dialog::g_mw_string = " << Edit_Dialog::g_mw_string; + + QString reagent = index.siblingAtColumn(0).data().toString(); + qDebug() << "Reagent = " << reagent; + Edit_Dialog::g_reagent = reagent; // ("Reagent"); + qDebug() << "Edit_Dialog::g_reagent = " << Edit_Dialog::g_reagent; + qDebug() << "End of on_tableview_clicked()"; +} + +int Select_Dialog::chem_db_read(QString reagent_fragment) +{ + // Finds and reads reagents and MW from database. + // Data is selected in QSqlTableModel (*model). + + qDebug() << "STARTED Select_Dialog::chem_db_read()"; + // The sql syntax is different (truncated) from other times. + // Don't use the long SQL syntax, use the short version below. + // sql = ("SELECT * FROM USER WHERE reagent LIKE '" + reagent_fragment +"%'") //Long, incorrect version. + QString sql = ("reagent LIKE '" + reagent_fragment +"%'"); // Correct short version for sqlite and Qt. + qDebug() << "sql = " << sql; + model->setFilter(sql); + model->select(); // Selects all data left after filter above. + int mySize = model->rowCount(); + qDebug() << "Select_Dialog::chem_db_read()-MYSIZE = " << mySize; + qDebug() << "ENDED Select_Dialog::chem_db_read()"; + //Do cc_msgBox info upon return to MainWindow (using int 'MySize'). + return mySize; +} + diff --git a/select_dialog.h b/select_dialog.h new file mode 100644 index 0000000..449cf1a --- /dev/null +++ b/select_dialog.h @@ -0,0 +1,57 @@ +#ifndef SELECT_DIALOG_H +#define SELECT_DIALOG_H + +// #include "qmainwindow.h" +#include +#include +#include +#include +#include +#include + +namespace Ui { +class Select_Dialog; +} + +class Select_Dialog : public QDialog +{ + Q_OBJECT + +public: + Select_Dialog(QWidget *parent = nullptr); + ~Select_Dialog(); + Ui::Select_Dialog *ui4; + void select_from_database(QString reagent_fragment); + void chem_db_insert(QString reagent, double mw); + int chem_db_read(QString reagent_fragment); + + friend class MainWindow; //Allows access to MainWindow functions/ + + //------------------------------------------------ + //These declarations have class(?) scope, + // Use scope resolution operator (::) to use these public variables. + // For example: "Edit_Dialog::g_selected_row". + QSqlDatabase g_db; + int g_selected_row; + int g_selected_column; + // QString g_reagent; + // double g_mw; + int g_OK_clicked; + QSqlTableModel *model; + QTableView *view; + + //------------------------------------------------ +public slots: + +signals: + +private slots: + void on_pushButton_Cancel_clicked(); + void on_tableView_clicked(const QModelIndex &index); + void on_pushButton_OK_clicked(); + +private: + +}; + +#endif // SELECT_DIALOG_H diff --git a/select_dialog.ui b/select_dialog.ui new file mode 100644 index 0000000..397b2f9 --- /dev/null +++ b/select_dialog.ui @@ -0,0 +1,85 @@ + + + Select_Dialog + + + + 0 + 0 + 732 + 508 + + + + Dialog + + + + + 20 + 80 + 671 + 341 + + + + + + + 20 + 20 + 561 + 41 + + + + Select the Reagent to Use, or Click Cancel. + + + + + + 580 + 440 + 97 + 30 + + + + OK + + + + + + 470 + 440 + 97 + 30 + + + + Cancel + + + + + + + pushButton_OK + clicked() + Select_Dialog + accept() + + + 531 + 458 + + + 527 + 500 + + + + +