Initial commit based on GenericQtClient v0.3.0
10
.clang-format
Normal file
@ -0,0 +1,10 @@
|
||||
BasedOnStyle: Chromium
|
||||
ColumnLimit: 100
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: false
|
||||
BreakConstructorInitializersBeforeComma: true
|
||||
AlignConsecutiveAssignments: true
|
||||
AllowShortFunctionsOnASingleLine: true
|
||||
BraceWrapping:
|
||||
AfterControlStatement: Always
|
||||
InsertBraces: true
|
||||
84
.gitignore
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
# This file is used to ignore files which are generated
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
*~
|
||||
*.autosave
|
||||
*.a
|
||||
*.core
|
||||
*.moc
|
||||
*.o
|
||||
*.obj
|
||||
*.orig
|
||||
*.rej
|
||||
*.so
|
||||
*.so.*
|
||||
*_pch.h.cpp
|
||||
*_resource.rc
|
||||
*.qm
|
||||
.#*
|
||||
*.*#
|
||||
core
|
||||
!core/
|
||||
tags
|
||||
.DS_Store
|
||||
.directory
|
||||
*.debug
|
||||
Makefile*
|
||||
*.prl
|
||||
*.app
|
||||
moc_*.cpp
|
||||
ui_*.h
|
||||
qrc_*.cpp
|
||||
Thumbs.db
|
||||
*.res
|
||||
*.rc
|
||||
/.qmake.cache
|
||||
/.qmake.stash
|
||||
|
||||
# qtcreator generated files
|
||||
*.pro.user*
|
||||
*.qbs.user*
|
||||
CMakeLists.txt.user*
|
||||
|
||||
# xemacs temporary files
|
||||
*.flc
|
||||
|
||||
# Vim temporary files
|
||||
.*.swp
|
||||
|
||||
# Visual Studio generated files
|
||||
*.ib_pdb_index
|
||||
*.idb
|
||||
*.ilk
|
||||
*.pdb
|
||||
*.sln
|
||||
*.suo
|
||||
*.vcproj
|
||||
*vcproj.*.*.user
|
||||
*.ncb
|
||||
*.sdf
|
||||
*.opensdf
|
||||
*.vcxproj
|
||||
*vcxproj.*
|
||||
|
||||
# MinGW generated files
|
||||
*.Debug
|
||||
*.Release
|
||||
|
||||
# Python byte code
|
||||
*.pyc
|
||||
|
||||
# Binaries
|
||||
# --------
|
||||
*.dll
|
||||
*.exe
|
||||
|
||||
# Directories with generated files
|
||||
.moc/
|
||||
.obj/
|
||||
.pch/
|
||||
.rcc/
|
||||
.uic/
|
||||
/build*/
|
||||
_build*/
|
||||
_output/*
|
||||
2
ApplicationConfig.h.in
Normal file
@ -0,0 +1,2 @@
|
||||
#define APPLICATION_NAME "${PROJECT_NAME}"
|
||||
#define APPLICATION_VERSION "${PROJECT_VERSION}"
|
||||
32
CHANGELOG.md
Normal file
@ -0,0 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
## 0.3.0 - 2026-02-04
|
||||
|
||||
### Added
|
||||
|
||||
- Basic JSON RESTful client (compatible with the GenericRestServer)
|
||||
- No editing of existing items on the server yet
|
||||
|
||||
### Fixed
|
||||
|
||||
- Save changes when closing the EditItemDialog
|
||||
|
||||
## 0.2.1 - 2026-01-15
|
||||
|
||||
### Added
|
||||
|
||||
- Displaying QR code of current item in edit item dialog
|
||||
|
||||
## 0.2 - 2026-01-14
|
||||
|
||||
### Added
|
||||
|
||||
- Displaying editable table model (sortable by column)
|
||||
- Modifying model data can be un-/redone
|
||||
- Data is stored in JSON file and automatically loaded on application start
|
||||
- Data can be imported/exported from/into CSV file
|
||||
- Model rows containing specific data can be selected via "Find item(s)" dialog
|
||||
|
||||
## 0.1 - 2025-11-01
|
||||
|
||||
A simple Qt application separated into an UI frontend and backend core. With installer (for Linux for now) and option to trigger updater from within the application.
|
||||
55
CMakeLists.txt
Normal file
@ -0,0 +1,55 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
set(TARGET_APP "GenericQtClient")
|
||||
project(${TARGET_APP} VERSION 0.3.0 LANGUAGES CXX)
|
||||
|
||||
enable_testing()
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
add_subdirectory(libs/GenericCore)
|
||||
set (CORE_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/GenericCore)
|
||||
|
||||
### 3rd party libraries
|
||||
add_subdirectory(libs/3rdParty/Qt-QrCodeGenerator)
|
||||
set (QR_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/libs/3rdParty/Qt-QrCodeGenerator)
|
||||
|
||||
configure_file(ApplicationConfig.h.in ApplicationConfig.h)
|
||||
|
||||
#Frontend applications
|
||||
add_subdirectory(UIs/GenericWidgets)
|
||||
|
||||
### Tests
|
||||
add_subdirectory(tests/GenericCoreTests)
|
||||
|
||||
### Qt installer
|
||||
set(PACKAGE_FOLDER "genericQtClient")
|
||||
set(TARGET_PACKAGE "org.working_copy.${PACKAGE_FOLDER}")
|
||||
set(CONFIG_REPO_URL ".../${PACKAGE_FOLDER}")
|
||||
set(PUSH_REPO_URL ".../${PACKAGE_FOLDER}")
|
||||
string(TIMESTAMP CURRENT_DATE "%Y-%m-%d")
|
||||
set(PLATFORM "linux")
|
||||
|
||||
set(BASH_COMMAND)
|
||||
|
||||
### quick fix for config.xml.in and installscript.qs.in:
|
||||
set(ApplicationsDir @ApplicationsDir@)
|
||||
set(TargetDir @TargetDir@)
|
||||
set(DesktopDir @DesktopDir@)
|
||||
set(HomeDir @HomeDir@)
|
||||
### end of quick fix
|
||||
|
||||
configure_file(installer/config/config.xml.in installer/config/config.xml)
|
||||
configure_file(installer/packages/defaultPackage/meta/package.xml.in installer/packages/${TARGET_PACKAGE}/meta/package.xml)
|
||||
configure_file(installer/packages/defaultPackage/meta/installscript.qs.in installer/packages/${TARGET_PACKAGE}/meta/installscript.qs)
|
||||
# configure_file(installer/packages/defaultPackage/meta/license.txt.in installer/packages/${TARGET_PACKAGE}/meta/license.txt)
|
||||
|
||||
# add_custom_command(
|
||||
# OUTPUT installer/config/config.xml
|
||||
# COMMAND ${BASH_COMMAND} ${CMAKE_CURRENT_SOURCE_DIR}/installer/script.sh ${PROJECT_VERSION} linux ${TARGET_APP} ${TARGET_PACKAGE}
|
||||
# )
|
||||
|
||||
# add_custom_target(installer ALL
|
||||
# DEPENDS installer/config/config.xml
|
||||
# )
|
||||
232
LICENSE
Normal file
@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
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.
|
||||
|
||||
GenericQtClient
|
||||
Copyright (C) 2025 bent
|
||||
|
||||
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/>.
|
||||
|
||||
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:
|
||||
|
||||
GenericQtClient Copyright (C) 2025 bent
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
19
README.md
Normal file
@ -0,0 +1,19 @@
|
||||
# GenericQtClient
|
||||
|
||||
This is a Qt application which can be used as a starting point for new software projects.
|
||||
|
||||
Common features most Qt software clients need will be already implemented and can be easily configured for the specific needs.
|
||||
|
||||
## Implemented features:
|
||||
- Separated UI frontend and backend core (in its own git submodules)
|
||||
- Using Qt model/view framework with QT undo framework
|
||||
- Saving/Loading JSON files
|
||||
- CSV import/export
|
||||
- installable and updateable via Qt updater framework
|
||||
- only linux for now
|
||||
- Qt 6 libraries must be installed on the machine to run
|
||||
|
||||
## Coming features:
|
||||
- REST client
|
||||
- Extensive use of sorting and filtering models to display data in different ways
|
||||
- ...
|
||||
83
UIs/GenericWidgets/.gitignore
vendored
Normal file
@ -0,0 +1,83 @@
|
||||
# This file is used to ignore files which are generated
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
*~
|
||||
*.autosave
|
||||
*.a
|
||||
*.core
|
||||
*.moc
|
||||
*.o
|
||||
*.obj
|
||||
*.orig
|
||||
*.rej
|
||||
*.so
|
||||
*.so.*
|
||||
*_pch.h.cpp
|
||||
*_resource.rc
|
||||
*.qm
|
||||
.#*
|
||||
*.*#
|
||||
core
|
||||
!core/
|
||||
tags
|
||||
.DS_Store
|
||||
.directory
|
||||
*.debug
|
||||
Makefile*
|
||||
*.prl
|
||||
*.app
|
||||
moc_*.cpp
|
||||
ui_*.h
|
||||
qrc_*.cpp
|
||||
Thumbs.db
|
||||
*.res
|
||||
*.rc
|
||||
/.qmake.cache
|
||||
/.qmake.stash
|
||||
|
||||
# qtcreator generated files
|
||||
*.pro.user*
|
||||
*.qbs.user*
|
||||
CMakeLists.txt.user*
|
||||
|
||||
# xemacs temporary files
|
||||
*.flc
|
||||
|
||||
# Vim temporary files
|
||||
.*.swp
|
||||
|
||||
# Visual Studio generated files
|
||||
*.ib_pdb_index
|
||||
*.idb
|
||||
*.ilk
|
||||
*.pdb
|
||||
*.sln
|
||||
*.suo
|
||||
*.vcproj
|
||||
*vcproj.*.*.user
|
||||
*.ncb
|
||||
*.sdf
|
||||
*.opensdf
|
||||
*.vcxproj
|
||||
*vcxproj.*
|
||||
|
||||
# MinGW generated files
|
||||
*.Debug
|
||||
*.Release
|
||||
|
||||
# Python byte code
|
||||
*.pyc
|
||||
|
||||
# Binaries
|
||||
# --------
|
||||
*.dll
|
||||
*.exe
|
||||
|
||||
# Directories with generated files
|
||||
.moc/
|
||||
.obj/
|
||||
.pch/
|
||||
.rcc/
|
||||
.uic/
|
||||
/build*/
|
||||
_build*/
|
||||
94
UIs/GenericWidgets/CMakeLists.txt
Normal file
@ -0,0 +1,94 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
set(TARGET_APP "GenericQtClient-Widgets")
|
||||
project(${TARGET_APP} VERSION 0.3.0 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 Qt5 REQUIRED COMPONENTS Widgets LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets LinguistTools)
|
||||
|
||||
set(TS_FILES ${TARGET_APP}_en_US.ts)
|
||||
|
||||
set(PROJECT_SOURCES
|
||||
main.cpp
|
||||
mainwindow.cpp
|
||||
mainwindow.h
|
||||
mainwindow.ui
|
||||
${TS_FILES}
|
||||
)
|
||||
|
||||
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
|
||||
qt_add_executable(${TARGET_APP}
|
||||
MANUAL_FINALIZATION
|
||||
${PROJECT_SOURCES}
|
||||
utils/messagehandler.h
|
||||
assets/icons.qrc
|
||||
dialogs/abstractdialog.h dialogs/abstractdialog.cpp
|
||||
dialogs/newitemdialog.h dialogs/newitemdialog.cpp
|
||||
dialogs/edititemdialog.h dialogs/edititemdialog.cpp
|
||||
dialogs/settingsdialog.h dialogs/settingsdialog.cpp
|
||||
views/itemdetailmapper.h views/itemdetailmapper.cpp
|
||||
)
|
||||
# Define target properties for Android with Qt 6 as:
|
||||
# set_property(TARGET ${TARGET_APP} 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
|
||||
|
||||
# qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
|
||||
else()
|
||||
if(ANDROID)
|
||||
add_library(${TARGET_APP} 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(${TARGET_APP}
|
||||
${PROJECT_SOURCES}
|
||||
)
|
||||
endif()
|
||||
|
||||
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
endif()
|
||||
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Widgets)
|
||||
|
||||
target_include_directories(${TARGET_APP} PRIVATE ${CORE_LIB_DIR}/)
|
||||
target_link_libraries(${TARGET_APP} PRIVATE GenericCore)
|
||||
target_include_directories(${TARGET_APP} PRIVATE ${QR_LIB_DIR}/src)
|
||||
target_link_libraries(${TARGET_APP} PRIVATE qrcode)
|
||||
|
||||
|
||||
# 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.${TARGET_APP})
|
||||
endif()
|
||||
set_target_properties(${TARGET_APP} 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 ${TARGET_APP}
|
||||
BUNDLE DESTINATION .
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
|
||||
if(QT_VERSION_MAJOR EQUAL 6)
|
||||
qt_finalize_executable(${TARGET_APP})
|
||||
endif()
|
||||
3
UIs/GenericWidgets/GenericQtClient-Widgets_en_US.ts
Normal file
@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE TS>
|
||||
<TS version="2.1" language="en_US"></TS>
|
||||
BIN
UIs/GenericWidgets/assets/feature.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
7
UIs/GenericWidgets/assets/icons.qrc
Normal file
@ -0,0 +1,7 @@
|
||||
<RCC>
|
||||
<qresource prefix="/">
|
||||
<file>software-application.png</file>
|
||||
<file>feature.png</file>
|
||||
<file>no-picture-taking.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
BIN
UIs/GenericWidgets/assets/no-picture-taking.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
UIs/GenericWidgets/assets/software-application.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
5
UIs/GenericWidgets/assets/urls.txt
Normal file
@ -0,0 +1,5 @@
|
||||
software-application.png:
|
||||
https://www.flaticon.com/free-icon/software-application_5063917
|
||||
|
||||
feature.png:
|
||||
https://www.flaticon.com/free-icon/feature_1085784
|
||||
51
UIs/GenericWidgets/dialogs/abstractdialog.cpp
Normal file
@ -0,0 +1,51 @@
|
||||
#include "abstractdialog.h"
|
||||
|
||||
#include <QDialogButtonBox>
|
||||
#include <QGuiApplication>
|
||||
#include <QLabel>
|
||||
#include <QScreen>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
AbstractDialog::AbstractDialog(QDialogButtonBox::StandardButtons buttons, QWidget* parent)
|
||||
: QDialog(parent) {
|
||||
setWindowTitle(tr("Dialog does what?..."));
|
||||
setModal(true);
|
||||
|
||||
m_buttonBox = new QDialogButtonBox(buttons, this);
|
||||
connect(m_buttonBox, &QDialogButtonBox::accepted, this, &AbstractDialog::accept);
|
||||
connect(m_buttonBox, &QDialogButtonBox::rejected, this, &AbstractDialog::reject);
|
||||
|
||||
m_contentContainer = new QLabel("content", this);
|
||||
|
||||
m_outerLayout = new QVBoxLayout;
|
||||
m_outerLayout->addWidget(m_contentContainer);
|
||||
m_outerLayout->addWidget(m_buttonBox);
|
||||
|
||||
setLayout(m_outerLayout);
|
||||
}
|
||||
|
||||
void AbstractDialog::show() {
|
||||
centerInParent();
|
||||
QWidget::show();
|
||||
}
|
||||
|
||||
void AbstractDialog::accept() { QDialog::accept(); }
|
||||
|
||||
void AbstractDialog::reject() { QDialog::reject(); }
|
||||
|
||||
void AbstractDialog::centerInParent() {
|
||||
// BUG the centering in the parent doesn't work the first time (and the later ones seem off too)
|
||||
QWidget* parent = parentWidget();
|
||||
|
||||
if (parent) {
|
||||
auto parentRect = parent->geometry();
|
||||
move(parentRect.center() - rect().center());
|
||||
} else {
|
||||
QRect screenGeometry = QGuiApplication::screens().at(0)->geometry();
|
||||
int x = (screenGeometry.width() - width()) / 2;
|
||||
int y = (screenGeometry.height() - height()) / 2;
|
||||
move(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractDialog::closeEvent(QCloseEvent* event) { QWidget::closeEvent(event); }
|
||||
33
UIs/GenericWidgets/dialogs/abstractdialog.h
Normal file
@ -0,0 +1,33 @@
|
||||
#ifndef ABSTRACTDIALOG_H
|
||||
#define ABSTRACTDIALOG_H
|
||||
|
||||
#include <QDialog>
|
||||
#include <QDialogButtonBox>
|
||||
|
||||
class QGridLayout;
|
||||
class QVBoxLayout;
|
||||
|
||||
class AbstractDialog : public QDialog {
|
||||
Q_OBJECT
|
||||
public:
|
||||
AbstractDialog(QDialogButtonBox::StandardButtons buttons, QWidget* parent = nullptr);
|
||||
virtual void createContent() = 0;
|
||||
|
||||
/// QDialog interface
|
||||
public slots:
|
||||
void show();
|
||||
void accept() override;
|
||||
void reject() override;
|
||||
|
||||
protected:
|
||||
void centerInParent();
|
||||
|
||||
protected:
|
||||
QWidget* m_contentContainer;
|
||||
QVBoxLayout* m_outerLayout;
|
||||
QDialogButtonBox* m_buttonBox = nullptr;
|
||||
|
||||
void closeEvent(QCloseEvent* event) override;
|
||||
};
|
||||
|
||||
#endif // ABSTRACTDIALOG_H
|
||||
57
UIs/GenericWidgets/dialogs/edititemdialog.cpp
Normal file
@ -0,0 +1,57 @@
|
||||
#include "edititemdialog.h"
|
||||
|
||||
#include <QDialogButtonBox>
|
||||
#include <QLabel>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
#include "../views/itemdetailmapper.h"
|
||||
|
||||
EditItemDialog::EditItemDialog(QTableView* tableView, QWidget* parent)
|
||||
: AbstractDialog(QDialogButtonBox::Ok, parent)
|
||||
, m_tableView(tableView)
|
||||
, m_qrCodeDisplay(new QLabel("QR Code")) {}
|
||||
|
||||
void EditItemDialog::createContent() {
|
||||
if (m_contentContainer) {
|
||||
delete m_contentContainer;
|
||||
}
|
||||
|
||||
setWindowTitle(tr("Edit item..."));
|
||||
|
||||
m_contentContainer = new QWidget(this);
|
||||
QHBoxLayout* innerLayout = new QHBoxLayout();
|
||||
m_contentContainer->setLayout(innerLayout);
|
||||
|
||||
m_detailMapper = new ItemDetailMapper(this);
|
||||
m_detailMapper->setModelMappings(m_tableView);
|
||||
innerLayout->addWidget(m_detailMapper);
|
||||
|
||||
updateQRCode();
|
||||
connect(m_detailMapper, &ItemDetailMapper::contentChanged, this, &EditItemDialog::updateQRCode);
|
||||
innerLayout->addWidget(m_qrCodeDisplay);
|
||||
|
||||
m_outerLayout->insertWidget(0, m_contentContainer);
|
||||
}
|
||||
|
||||
void EditItemDialog::accept() {
|
||||
m_detailMapper->submit();
|
||||
QDialog::accept();
|
||||
}
|
||||
|
||||
void EditItemDialog::reject() {
|
||||
m_detailMapper->revert();
|
||||
QDialog::reject();
|
||||
}
|
||||
|
||||
void EditItemDialog::updateQRCode(const QString text) {
|
||||
QImage unscaledImage;
|
||||
if (text.isEmpty()) {
|
||||
unscaledImage = QImage("://no-picture-taking.png");
|
||||
} else {
|
||||
unscaledImage = m_generator.generateQr(text);
|
||||
}
|
||||
QImage image = unscaledImage.scaled(250, 250);
|
||||
|
||||
m_qrCodeDisplay->setPixmap(QPixmap::fromImage(image));
|
||||
m_qrCodeDisplay->setToolTip(text);
|
||||
}
|
||||
53
UIs/GenericWidgets/dialogs/edititemdialog.h
Normal file
@ -0,0 +1,53 @@
|
||||
#ifndef EDITITEMDIALOG_H
|
||||
#define EDITITEMDIALOG_H
|
||||
|
||||
#include "QrCodeGenerator.h"
|
||||
#include "abstractdialog.h"
|
||||
|
||||
class QDoubleSpinBox;
|
||||
class QLineEdit;
|
||||
class QSpinBox;
|
||||
class QLabel;
|
||||
class QTableView;
|
||||
|
||||
class ItemDetailMapper;
|
||||
|
||||
class EditItemDialog : public AbstractDialog {
|
||||
Q_OBJECT
|
||||
public:
|
||||
EditItemDialog(QTableView* tableView, QWidget* parent = nullptr);
|
||||
|
||||
/// AbstractDialog interface
|
||||
void createContent() override;
|
||||
|
||||
public slots:
|
||||
void accept() override;
|
||||
void reject() override;
|
||||
|
||||
private slots:
|
||||
void updateQRCode(const QString text = "");
|
||||
|
||||
private:
|
||||
QTableView* m_tableView = nullptr;
|
||||
ItemDetailMapper* m_detailMapper;
|
||||
|
||||
QLabel* m_nameLabel = nullptr;
|
||||
QLineEdit* m_nameEdit = nullptr;
|
||||
|
||||
QLabel* m_descriptionLabel = nullptr;
|
||||
QLineEdit* m_descriptionEdit = nullptr;
|
||||
|
||||
QLabel* m_infoLabel = nullptr;
|
||||
QLineEdit* m_infoEdit = nullptr;
|
||||
|
||||
QLabel* m_amountLabel = nullptr;
|
||||
QSpinBox* m_amountBox = nullptr;
|
||||
|
||||
QLabel* m_factorLabel = nullptr;
|
||||
QDoubleSpinBox* m_factorBox = nullptr;
|
||||
|
||||
QLabel* m_qrCodeDisplay = nullptr;
|
||||
QrCodeGenerator m_generator;
|
||||
};
|
||||
|
||||
#endif // EDITITEMDIALOG_H
|
||||
81
UIs/GenericWidgets/dialogs/newitemdialog.cpp
Normal file
@ -0,0 +1,81 @@
|
||||
#include "newitemdialog.h"
|
||||
|
||||
#include <QGridLayout>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QSpinBox>
|
||||
#include "formats/jsonparser.h"
|
||||
#include "model/metadata.h"
|
||||
|
||||
NewItemDialog::NewItemDialog(QWidget* parent)
|
||||
: AbstractDialog(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, parent) {}
|
||||
|
||||
void NewItemDialog::createContent() {
|
||||
if (m_contentContainer) {
|
||||
delete m_contentContainer;
|
||||
}
|
||||
|
||||
setWindowTitle(tr("New item..."));
|
||||
|
||||
m_contentContainer = new QWidget(this);
|
||||
|
||||
// REFACTOR use a data structure for input widgets which can be iterated through
|
||||
// using a factory which iterates through the roles from metadata.h
|
||||
// and create the input widgets based on the data type of this role
|
||||
m_nameLabel = new QLabel("&Name");
|
||||
m_nameEdit = new QLineEdit();
|
||||
m_nameLabel->setBuddy(m_nameEdit);
|
||||
|
||||
m_descriptionLabel = new QLabel("&Description");
|
||||
m_descriptionEdit = new QLineEdit();
|
||||
m_descriptionLabel->setBuddy(m_descriptionEdit);
|
||||
|
||||
m_infoLabel = new QLabel("&Info");
|
||||
m_infoEdit = new QLineEdit();
|
||||
m_infoLabel->setBuddy(m_infoEdit);
|
||||
|
||||
m_amountLabel = new QLabel("&Amount");
|
||||
m_amountBox = new QSpinBox();
|
||||
m_amountBox->setMaximum(1000);
|
||||
m_amountLabel->setBuddy(m_amountBox);
|
||||
|
||||
m_factorLabel = new QLabel("&Factor");
|
||||
m_factorBox = new QDoubleSpinBox();
|
||||
m_factorBox->setMaximum(1000);
|
||||
m_factorLabel->setBuddy(m_factorBox);
|
||||
|
||||
QGridLayout* layout = new QGridLayout();
|
||||
layout->addWidget(m_nameLabel, 0, 0, 1, 1);
|
||||
layout->addWidget(m_nameEdit, 0, 1, 1, 1);
|
||||
layout->addWidget(m_descriptionLabel, 1, 0, 1, 1);
|
||||
layout->addWidget(m_descriptionEdit, 1, 1, 1, 1);
|
||||
layout->addWidget(m_infoLabel, 2, 0, 1, 1);
|
||||
layout->addWidget(m_infoEdit, 2, 1, 1, 1);
|
||||
layout->addWidget(m_amountLabel, 3, 0, 1, 1);
|
||||
layout->addWidget(m_amountBox, 3, 1, 1, 1);
|
||||
layout->addWidget(m_factorLabel, 4, 0, 1, 1);
|
||||
layout->addWidget(m_factorBox, 4, 1, 1, 1);
|
||||
|
||||
m_contentContainer->setLayout(layout);
|
||||
|
||||
m_outerLayout->insertWidget(0, m_contentContainer);
|
||||
}
|
||||
|
||||
void NewItemDialog::accept() {
|
||||
ModelItemValues itemValues;
|
||||
// TODO (after refactoring data structure for input widgets) use iteration through the relevant
|
||||
// roles and their input widgets
|
||||
itemValues.insert(NameRole, m_nameEdit->text());
|
||||
itemValues.insert(DescriptionRole, m_descriptionEdit->text());
|
||||
itemValues.insert(InfoRole, m_infoEdit->text());
|
||||
itemValues.insert(AmountRole, m_amountBox->value());
|
||||
itemValues.insert(FactorRole, m_factorBox->value());
|
||||
|
||||
const QByteArray jsonDoc = JsonParser::itemValuesListToJson({itemValues}, ITEMS_KEY_STRING);
|
||||
emit addItems(jsonDoc);
|
||||
|
||||
// resetContent();
|
||||
AbstractDialog::accept();
|
||||
}
|
||||
43
UIs/GenericWidgets/dialogs/newitemdialog.h
Normal file
@ -0,0 +1,43 @@
|
||||
#ifndef NEWITEMDIALOG_H
|
||||
#define NEWITEMDIALOG_H
|
||||
|
||||
#include "abstractdialog.h"
|
||||
|
||||
class QDoubleSpinBox;
|
||||
class QLineEdit;
|
||||
class QSpinBox;
|
||||
class QLabel;
|
||||
|
||||
class NewItemDialog : public AbstractDialog {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
NewItemDialog(QWidget* parent = nullptr);
|
||||
|
||||
void createContent() override;
|
||||
|
||||
signals:
|
||||
void addItems(const QByteArray& jsonDoc);
|
||||
|
||||
public slots:
|
||||
void accept() override;
|
||||
// void reject() override;
|
||||
|
||||
private:
|
||||
QLabel* m_nameLabel = nullptr;
|
||||
QLineEdit* m_nameEdit = nullptr;
|
||||
|
||||
QLabel* m_descriptionLabel = nullptr;
|
||||
QLineEdit* m_descriptionEdit = nullptr;
|
||||
|
||||
QLabel* m_infoLabel = nullptr;
|
||||
QLineEdit* m_infoEdit = nullptr;
|
||||
|
||||
QLabel* m_amountLabel = nullptr;
|
||||
QSpinBox* m_amountBox = nullptr;
|
||||
|
||||
QLabel* m_factorLabel = nullptr;
|
||||
QDoubleSpinBox* m_factorBox = nullptr;
|
||||
};
|
||||
|
||||
#endif // NEWITEMDIALOG_H
|
||||
63
UIs/GenericWidgets/dialogs/settingsdialog.cpp
Normal file
@ -0,0 +1,63 @@
|
||||
#include "settingsdialog.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QGridLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QTabWidget>
|
||||
|
||||
SettingsDialog::SettingsDialog(QWidget* parent)
|
||||
: AbstractDialog(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, parent) {}
|
||||
|
||||
void SettingsDialog::createContent() {
|
||||
if (m_contentContainer) {
|
||||
delete m_contentContainer;
|
||||
}
|
||||
|
||||
const QString dialogTitle = tr("Settings - ");
|
||||
const QString applicationName = QCoreApplication::applicationName();
|
||||
|
||||
setWindowTitle(dialogTitle + applicationName);
|
||||
setModal(true);
|
||||
setGeometry(0, 0, 350, 250);
|
||||
QGridLayout* serverLayout = new QGridLayout();
|
||||
QLabel* urlLabel = new QLabel("Server URL:");
|
||||
m_urlEdit = new QLineEdit();
|
||||
serverLayout->addWidget(urlLabel, 0, 0);
|
||||
serverLayout->addWidget(m_urlEdit, 0, 1);
|
||||
QLabel* emailLabel = new QLabel("Email:");
|
||||
m_emailEdit = new QLineEdit();
|
||||
m_emailEdit->setEnabled(false);
|
||||
serverLayout->addWidget(emailLabel, 1, 0);
|
||||
serverLayout->addWidget(m_emailEdit, 1, 1);
|
||||
QLabel* passwordLabel = new QLabel("Password:");
|
||||
m_passwordEdit = new QLineEdit();
|
||||
m_passwordEdit->setEnabled(false);
|
||||
m_passwordEdit->setEchoMode(QLineEdit::Password);
|
||||
serverLayout->addWidget(passwordLabel, 2, 0);
|
||||
serverLayout->addWidget(m_passwordEdit, 2, 1);
|
||||
|
||||
QWidget* serverTab = new QWidget();
|
||||
serverTab->setLayout(serverLayout);
|
||||
|
||||
QTabWidget* widget = new QTabWidget();
|
||||
widget->addTab(serverTab, "Server");
|
||||
|
||||
m_contentContainer = widget;
|
||||
m_outerLayout->insertWidget(0, m_contentContainer);
|
||||
}
|
||||
|
||||
void SettingsDialog::fillContent(const QVariantMap& settings) {
|
||||
m_urlEdit->setText(settings.value("url").toString());
|
||||
m_emailEdit->setText(settings.value("email").toString());
|
||||
m_passwordEdit->setText(settings.value("password").toString());
|
||||
}
|
||||
|
||||
QVariantMap SettingsDialog::getSettings() const {
|
||||
QVariantMap result;
|
||||
result.insert("url", m_urlEdit->text());
|
||||
result.insert("email", m_emailEdit->text());
|
||||
result.insert("password", m_passwordEdit->text());
|
||||
|
||||
return result;
|
||||
}
|
||||
23
UIs/GenericWidgets/dialogs/settingsdialog.h
Normal file
@ -0,0 +1,23 @@
|
||||
#ifndef SETTINGSDIALOG_H
|
||||
#define SETTINGSDIALOG_H
|
||||
|
||||
#include "abstractdialog.h"
|
||||
|
||||
class QLineEdit;
|
||||
|
||||
class SettingsDialog : public AbstractDialog {
|
||||
Q_OBJECT
|
||||
public:
|
||||
SettingsDialog(QWidget* parent = nullptr);
|
||||
|
||||
void createContent() override;
|
||||
void fillContent(const QVariantMap& settings);
|
||||
QVariantMap getSettings() const;
|
||||
|
||||
private:
|
||||
QLineEdit* m_urlEdit = nullptr;
|
||||
QLineEdit* m_emailEdit = nullptr;
|
||||
QLineEdit* m_passwordEdit = nullptr;
|
||||
};
|
||||
|
||||
#endif // SETTINGSDIALOG_H
|
||||
29
UIs/GenericWidgets/main.cpp
Normal file
@ -0,0 +1,29 @@
|
||||
#include "mainwindow.h"
|
||||
|
||||
#include <QApplication>
|
||||
#include <QLocale>
|
||||
#include <QTranslator>
|
||||
|
||||
#ifdef QT_DEBUG
|
||||
#include "utils/messagehandler.h"
|
||||
#endif
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
#ifdef QT_DEBUG
|
||||
qInstallMessageHandler(consoleHandlerColoredVerboseInDarkTheme);
|
||||
#endif
|
||||
QApplication a(argc, argv);
|
||||
|
||||
QTranslator translator;
|
||||
const QStringList uiLanguages = QLocale::system().uiLanguages();
|
||||
for (const QString& locale : uiLanguages) {
|
||||
const QString baseName = "GenericWidgets_" + QLocale(locale).name();
|
||||
if (translator.load(":/i18n/" + baseName)) {
|
||||
a.installTranslator(&translator);
|
||||
break;
|
||||
}
|
||||
}
|
||||
MainWindow w;
|
||||
w.show();
|
||||
return a.exec();
|
||||
}
|
||||
543
UIs/GenericWidgets/mainwindow.cpp
Normal file
@ -0,0 +1,543 @@
|
||||
#include "mainwindow.h"
|
||||
#include "./ui_mainwindow.h"
|
||||
|
||||
#include <QCloseEvent>
|
||||
#include <QFileDialog>
|
||||
#include <QInputDialog>
|
||||
#include <QMessageBox>
|
||||
#include <QStandardPaths>
|
||||
#include <QUndoStack>
|
||||
#include <QUndoView>
|
||||
|
||||
#include "../../ApplicationConfig.h"
|
||||
#include "dialogs/edititemdialog.h"
|
||||
#include "dialogs/newitemdialog.h"
|
||||
#include "dialogs/settingsdialog.h"
|
||||
#include "genericcore.h"
|
||||
#include "model/generalsortfiltermodel.h"
|
||||
#include "model/tablemodel.h"
|
||||
|
||||
static QStandardPaths::StandardLocation standardLocation = QStandardPaths::HomeLocation;
|
||||
static QString updateTextClean = "Do you want to update the application now?";
|
||||
static QString updateTextDirty = "Do you want to save the tasks & update the application now?";
|
||||
|
||||
MainWindow::MainWindow(QWidget* parent)
|
||||
: QMainWindow(parent)
|
||||
, ui(new Ui::MainWindow) {
|
||||
ui->setupUi(this);
|
||||
|
||||
m_core = std::make_unique<GenericCore>();
|
||||
|
||||
setWindowTitle(QCoreApplication::applicationName() + " [*]");
|
||||
|
||||
/// application icon
|
||||
const QString iconString = "://feature.png";
|
||||
#ifdef QT_DEBUG
|
||||
QPixmap pixmap = QPixmap(iconString);
|
||||
QTransform transform = QTransform();
|
||||
transform.rotate(180);
|
||||
QPixmap rotated = pixmap.transformed(transform);
|
||||
setWindowIcon(QIcon(rotated));
|
||||
#else
|
||||
setWindowIcon(QIcon(iconString));
|
||||
#endif
|
||||
|
||||
const QVariantMap settings = m_core->getSettings("GUI");
|
||||
restoreGeometry(settings.value("geometry").toByteArray());
|
||||
restoreState(settings.value("windowState").toByteArray());
|
||||
|
||||
// m_tableModel = m_core->getModel();
|
||||
// ui->tableView->setModel(m_tableModel.get());
|
||||
m_proxyModel = m_core->getSortFilterModel();
|
||||
ui->tableView->setModel((QAbstractItemModel*)m_proxyModel.get());
|
||||
ui->tableView->setSortingEnabled(true);
|
||||
|
||||
createActions();
|
||||
createHelpMenu();
|
||||
createGuiDialogs();
|
||||
|
||||
connect(m_core.get(), &GenericCore::displayStatusMessage, this,
|
||||
&MainWindow::displayStatusMessage);
|
||||
connect(this, &MainWindow::displayStatusMessage, this, &MainWindow::showStatusMessage);
|
||||
connect(this, &MainWindow::checkForUpdates, this,
|
||||
&MainWindow::on_actionCheck_for_update_triggered, Qt::QueuedConnection);
|
||||
|
||||
// connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this,
|
||||
// &MainWindow::onSelectionChanged);
|
||||
connect(ui->tableView->selectionModel(), &QItemSelectionModel::currentChanged, this,
|
||||
&MainWindow::onCurrentChanged);
|
||||
|
||||
onSelectionChanged(QItemSelection(), QItemSelection());
|
||||
onCurrentChanged(QModelIndex(), QModelIndex());
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow() { delete ui; }
|
||||
|
||||
void MainWindow::closeEvent(QCloseEvent* event) {
|
||||
if (isWindowModified()) {
|
||||
QMessageBox msgBox;
|
||||
msgBox.setWindowTitle(windowTitle() + " - Save dialog");
|
||||
msgBox.setText("The document has been modified.");
|
||||
msgBox.setInformativeText("Do you want to save your changes?");
|
||||
msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
|
||||
msgBox.setDefaultButton(QMessageBox::Save);
|
||||
int ret = msgBox.exec();
|
||||
|
||||
switch (ret) {
|
||||
case QMessageBox::Save:
|
||||
emit saveItems();
|
||||
event->accept();
|
||||
break;
|
||||
case QMessageBox::Discard:
|
||||
event->accept();
|
||||
break;
|
||||
case QMessageBox::Cancel:
|
||||
event->ignore();
|
||||
break;
|
||||
default:
|
||||
/// should never be reached
|
||||
qCritical() << "unexpected switch case in closeEvent:" << ret;
|
||||
event->ignore();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
event->accept();
|
||||
}
|
||||
|
||||
if (event->isAccepted()) {
|
||||
qInfo() << "Saving GUI settings...";
|
||||
m_core->applySettings({{"geometry", saveGeometry()}, {"windowState", saveState()}}, "GUI");
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::showStatusMessage(const QString text) {
|
||||
qInfo() << text;
|
||||
ui->statusbar->showMessage(text);
|
||||
}
|
||||
|
||||
void MainWindow::onCurrentChanged(const QModelIndex& current, const QModelIndex& previous) {
|
||||
// Q_UNUSED(current);
|
||||
Q_UNUSED(previous);
|
||||
|
||||
// QItemSelection localSelection = ui->tableView->selectionModel()->selection();
|
||||
if (current == QModelIndex()) {
|
||||
// qDebug() << "Nothing selected. Disabling delete action";
|
||||
m_deleteItemAct->setEnabled(false);
|
||||
} else {
|
||||
// qDebug() << "Something selected. Enabling delete action";
|
||||
m_deleteItemAct->setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onSelectionChanged(const QItemSelection& selected,
|
||||
const QItemSelection& deselected) {
|
||||
Q_UNUSED(selected);
|
||||
Q_UNUSED(deselected);
|
||||
|
||||
QItemSelection localSelection = ui->tableView->selectionModel()->selection();
|
||||
if (localSelection.empty()) {
|
||||
// qDebug() << "Nothing selected. Disabling delete action";
|
||||
m_deleteItemAct->setEnabled(false);
|
||||
} else {
|
||||
// qDebug() << "Something selected. Enabling delete action";
|
||||
m_deleteItemAct->setEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onAboutClicked() {
|
||||
const QString applicationName = APPLICATION_NAME;
|
||||
const QString titlePrefix = tr("About ");
|
||||
const QString aboutText =
|
||||
tr(QString("<b>%1 v%2</b> is a template for Qt applications."
|
||||
"<br><br><a href=\"https://working-copy.org/\">Working-Copy_Collective website</a>"
|
||||
"<br><br><a href=\"mailto:support@working-copy.org\">Mail to support</a>"
|
||||
"<br><br>It uses the <a href=\"https://qt.io\">Qt Framework</a>.")
|
||||
.arg(applicationName)
|
||||
.arg(APPLICATION_VERSION)
|
||||
.toLatin1());
|
||||
QMessageBox::about(this, titlePrefix + applicationName, aboutText);
|
||||
}
|
||||
|
||||
void MainWindow::on_actionCheck_for_update_triggered() {
|
||||
showStatusMessage("Checking for update...");
|
||||
const bool updateAvailable = m_core->isApplicationUpdateAvailable();
|
||||
if (updateAvailable) {
|
||||
const QString text = isWindowModified() ? updateTextDirty : updateTextClean;
|
||||
const QMessageBox::StandardButton clickedButton = QMessageBox::question(
|
||||
this, tr("Update available."), text, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
|
||||
if (clickedButton == QMessageBox::Yes) {
|
||||
m_core->triggerApplicationUpdate(true);
|
||||
close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::on_pushButton_clicked() {
|
||||
const QString prefix("Backend provided by: ");
|
||||
ui->label->setText(prefix + m_core->toString());
|
||||
}
|
||||
|
||||
void MainWindow::openNewItemDialog() {
|
||||
showStatusMessage(tr("Invoked 'Edit|New Item'"));
|
||||
m_newItemDialog->show();
|
||||
}
|
||||
|
||||
void MainWindow::openEditItemDialog() {
|
||||
showStatusMessage(tr("Invoked 'Edit|Edit Item'"));
|
||||
m_editItemDialog->show();
|
||||
}
|
||||
|
||||
void MainWindow::deleteCurrentItem() {
|
||||
showStatusMessage(tr("Invoked 'Edit|Delete Item'"));
|
||||
// QItemSelection localSelection = ui->tableView->selectionModel()->selection();
|
||||
const QModelIndex currentIndex = ui->tableView->selectionModel()->currentIndex();
|
||||
if (currentIndex == QModelIndex()) {
|
||||
qDebug() << "No current item. Nothing to remove.";
|
||||
} else {
|
||||
m_proxyModel->removeRows(currentIndex.row(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::deleteSelectedtItems() {
|
||||
showStatusMessage(tr("Invoked 'Edit|Delete Item'"));
|
||||
QItemSelection localSelection = ui->tableView->selectionModel()->selection();
|
||||
if (localSelection.empty()) {
|
||||
qDebug() << "No items selected. Nothing to remove.";
|
||||
} else {
|
||||
for (QList<QItemSelectionRange>::reverse_iterator iter = localSelection.rbegin(),
|
||||
rend = localSelection.rend();
|
||||
iter != rend; ++iter) {
|
||||
// qInfo() << "iter:" << *iter;
|
||||
// const QModelIndex parentIndex = iter->parent();
|
||||
const int topRow = iter->top();
|
||||
const int bottomRow = iter->bottom();
|
||||
const int nRows = bottomRow - topRow + 1;
|
||||
m_proxyModel->removeRows(topRow, nRows);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onCleanStateChanged(bool clean) {
|
||||
qInfo() << "Slot onCleanStateChanged triggered: clean:" << clean;
|
||||
setWindowModified(!clean);
|
||||
if (!clean) {
|
||||
ui->statusbar->clearMessage();
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onShowUndoViewToggled(bool checked) {
|
||||
// qInfo() << "Slot onShowUndoViewToggled toggled: checked:" << checked;
|
||||
// m_undoView->setVisible(checked);
|
||||
|
||||
/// workaround until m_showUndoViewAction is checkable
|
||||
qInfo() << "Slot onShowUndoViewToggled triggered, toggleing undo view...";
|
||||
Q_UNUSED(checked);
|
||||
if (m_modelUndoView->isVisible()) {
|
||||
m_modelUndoView->setVisible(false);
|
||||
|
||||
} else {
|
||||
m_modelUndoView->setVisible(true);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::saveItems() {
|
||||
showStatusMessage(tr("Invoked 'File|Save'"));
|
||||
m_core->saveItems();
|
||||
}
|
||||
|
||||
void MainWindow::importCSV() {
|
||||
showStatusMessage(tr("Invoked 'File|Import CSV'"));
|
||||
const QString csvFilePath = QFileDialog::getOpenFileName(
|
||||
this, tr("Import CSV"), QStandardPaths::standardLocations(standardLocation).first(),
|
||||
tr("CSV Files (*.csv)"));
|
||||
if (QFileInfo::exists(csvFilePath)) {
|
||||
m_core->importCSVFile(csvFilePath);
|
||||
showStatusMessage(tr("Imported CSV file."));
|
||||
} else {
|
||||
qWarning() << "Selected CSV file path doesn't exist. Doing nothing...";
|
||||
showStatusMessage(tr("Could't find CSV file!"));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::exportCSV() {
|
||||
showStatusMessage(tr("Invoked 'File|Export'"));
|
||||
const QString filter = tr("CSV Files (*.csv)");
|
||||
const QString location = QStandardPaths::standardLocations(standardLocation).first();
|
||||
QFileDialog dialog(this, "Export CSV File", location, "Comma-separated file (*.csv)");
|
||||
dialog.setDefaultSuffix(".csv");
|
||||
dialog.setAcceptMode(QFileDialog::AcceptSave);
|
||||
if (dialog.exec()) {
|
||||
const QString csvFilePath = dialog.selectedFiles().first();
|
||||
const bool successful = m_core->exportCSVFile(csvFilePath);
|
||||
if (successful) {
|
||||
const QString message = QString(tr("CSV exported to: %1")).arg(csvFilePath);
|
||||
showStatusMessage(message);
|
||||
}
|
||||
} else {
|
||||
qWarning() << "Selected CSV file path doesn't exist. Doing nothing...";
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::findItems() {
|
||||
showStatusMessage(tr("Invoked 'Edit|Find items'"));
|
||||
|
||||
bool ok;
|
||||
QString text = QInputDialog::getText(this, tr("Find items"), tr("Enter the text to search for:"),
|
||||
QLineEdit::Normal, "", &ok);
|
||||
if (ok && !text.isEmpty()) {
|
||||
const QItemSelection itemsToSelect = m_proxyModel->findItems(text);
|
||||
if (itemsToSelect.empty()) {
|
||||
ui->tableView->setCurrentIndex(QModelIndex());
|
||||
ui->tableView->selectionModel()->select(QModelIndex(), QItemSelectionModel::ClearAndSelect);
|
||||
} else {
|
||||
ui->tableView->setCurrentIndex(itemsToSelect.first().topLeft());
|
||||
ui->tableView->selectionModel()->select(itemsToSelect, QItemSelectionModel::ClearAndSelect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::fetchItems() {
|
||||
showStatusMessage(tr("Invoked 'Server|Fetch items'"));
|
||||
emit m_core->fetchItemsFromServer();
|
||||
}
|
||||
|
||||
void MainWindow::postItems() {
|
||||
showStatusMessage(tr("Invoked 'Server|Post items'"));
|
||||
const QModelIndex currentIndex = ui->tableView->currentIndex();
|
||||
const QByteArray jsonData = m_proxyModel->jsonDataForServer(currentIndex);
|
||||
emit m_core->postItemToServer(jsonData);
|
||||
}
|
||||
|
||||
void MainWindow::deleteItem() {
|
||||
showStatusMessage(tr("Invoked 'Server|Delete items'"));
|
||||
const QModelIndex currentIndex = ui->tableView->currentIndex();
|
||||
// const QByteArray jsonData = m_proxyModel->jsonDataForServer(currentIndex);
|
||||
const QString currentId = m_proxyModel->getUuid(currentIndex);
|
||||
emit m_core->deleteItemFromServer(currentId);
|
||||
}
|
||||
|
||||
void MainWindow::execSettingsDialog() {
|
||||
showStatusMessage(tr("Invoked 'Tools|Settings'"));
|
||||
QVariantMap oldSettings = m_core->getSettings("Server");
|
||||
// SettingsDialog* settingsDialog = new SettingsDialog(settingMap, this);
|
||||
SettingsDialog* settingsDialog = new SettingsDialog(this);
|
||||
settingsDialog->createContent();
|
||||
settingsDialog->fillContent(oldSettings);
|
||||
|
||||
int returnCode = settingsDialog->exec();
|
||||
if (returnCode == QDialog::Accepted) {
|
||||
qDebug() << "Settings dialog accepted, writing settings...";
|
||||
const QVariantMap settings = settingsDialog->getSettings();
|
||||
|
||||
m_core->applySettings(settings, "Server");
|
||||
// TODO use signal-slot connection Core::syncServerSetupChanged(bool enabled) ->
|
||||
// MainWindow::onSyncServerSetupChanged(bool enabled)
|
||||
|
||||
// enableDisableServerActions();
|
||||
} else {
|
||||
qDebug() << "Settings dialog rejected";
|
||||
}
|
||||
delete settingsDialog;
|
||||
}
|
||||
|
||||
void MainWindow::createActions() {
|
||||
// TODO add generic menu actions (file/new, edit/cut, ...)
|
||||
createFileActions();
|
||||
createUndoActions();
|
||||
createEditActions();
|
||||
createServerActions();
|
||||
createToolsActions();
|
||||
}
|
||||
|
||||
void MainWindow::createFileActions() {
|
||||
m_newFileAct = make_unique<QAction>(tr("&New File"), this);
|
||||
m_newFileAct->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));
|
||||
m_newFileAct->setStatusTip(tr("Create a new file"));
|
||||
// connect(m_newAct, &QAction::triggered, this, &MainWindow::newFile);
|
||||
m_newFileAct->setEnabled(false);
|
||||
ui->menu_File->addAction(m_newFileAct.get());
|
||||
|
||||
m_openAct = make_unique<QAction>(tr("&Open..."), this);
|
||||
m_openAct->setShortcuts(QKeySequence::Open);
|
||||
m_openAct->setStatusTip(tr("Open an existing file"));
|
||||
// connect(m_openAct, &QAction::triggered, this, &MainWindow::open);
|
||||
m_openAct->setEnabled(false);
|
||||
ui->menu_File->addAction(m_openAct.get());
|
||||
|
||||
m_saveAct = make_unique<QAction>(tr("&Save"), this);
|
||||
m_saveAct->setShortcuts(QKeySequence::Save);
|
||||
m_saveAct->setStatusTip(tr("Save the document to disk"));
|
||||
connect(m_saveAct.get(), &QAction::triggered, this, &MainWindow::saveItems);
|
||||
ui->menu_File->addAction(m_saveAct.get());
|
||||
|
||||
ui->menu_File->addSeparator();
|
||||
|
||||
m_importAct = make_unique<QAction>(tr("&Import CSV..."), this);
|
||||
m_importAct->setStatusTip(tr("Import an existing CSV file"));
|
||||
connect(m_importAct.get(), &QAction::triggered, this, &MainWindow::importCSV);
|
||||
ui->menu_File->addAction(m_importAct.get());
|
||||
|
||||
m_exportAct = make_unique<QAction>(tr("&Export CSV..."), this);
|
||||
m_exportAct->setStatusTip(tr("Export content to a CSV document to disk"));
|
||||
connect(m_exportAct.get(), &QAction::triggered, this, &MainWindow::exportCSV);
|
||||
ui->menu_File->addAction(m_exportAct.get());
|
||||
|
||||
ui->menu_File->addSeparator();
|
||||
|
||||
m_printAct = make_unique<QAction>(tr("&Print..."), this);
|
||||
m_printAct->setShortcuts(QKeySequence::Print);
|
||||
m_printAct->setStatusTip(tr("Print the document"));
|
||||
// connect(m_printAct, &QAction::triggered, this, &MainWindow::print);
|
||||
m_printAct->setEnabled(false);
|
||||
ui->menu_File->addAction(m_printAct.get());
|
||||
|
||||
ui->menu_File->addSeparator();
|
||||
|
||||
m_exitAct = make_unique<QAction>(tr("E&xit"), this);
|
||||
m_exitAct->setShortcuts(QKeySequence::Quit);
|
||||
m_exitAct->setStatusTip(tr("Exit the application"));
|
||||
connect(m_exitAct.get(), &QAction::triggered, this, &QWidget::close);
|
||||
ui->menu_File->addAction(m_exitAct.get());
|
||||
}
|
||||
|
||||
void MainWindow::createUndoActions() {
|
||||
if (!m_core) {
|
||||
qCritical() << "No core instance set, aborting...";
|
||||
return;
|
||||
}
|
||||
m_modelUndoStack = m_core->getModelUndoStack();
|
||||
|
||||
connect(m_modelUndoStack, &QUndoStack::cleanChanged, this, &MainWindow::onCleanStateChanged);
|
||||
|
||||
m_undoAct.reset(m_modelUndoStack->createUndoAction(this, tr("&Undo")));
|
||||
m_undoAct->setShortcuts(QKeySequence::Undo);
|
||||
m_undoAct->setStatusTip(tr("Undo the last operation"));
|
||||
ui->menu_Edit->addAction(m_undoAct.get());
|
||||
|
||||
m_redoAct.reset(m_modelUndoStack->createRedoAction(this, tr("&Redo")));
|
||||
m_redoAct->setShortcuts(QKeySequence::Redo);
|
||||
m_redoAct->setStatusTip(tr("Redo the last operation"));
|
||||
ui->menu_Edit->addAction(m_redoAct.get());
|
||||
|
||||
m_modelUndoView = make_unique<QUndoView>(m_modelUndoStack);
|
||||
m_modelUndoView->setWindowTitle(tr("Undo list"));
|
||||
m_modelUndoView->setAttribute(Qt::WA_QuitOnClose, false);
|
||||
m_modelUndoView->setMinimumSize(450, 600);
|
||||
m_showModelUndoViewAct = make_unique<QAction>(tr("Show undo/redo window"), this);
|
||||
m_showModelUndoViewAct->setStatusTip(tr("Opens a window displaying the items on the undo stack"));
|
||||
|
||||
// TODO showUndoViewAction should be checkable
|
||||
// m_showUndoViewAction->setCheckable(true);
|
||||
// connect(m_showUndoViewAction, &QAction::toggled, this, &MainWindow::onShowUndoViewToggled);
|
||||
connect(m_showModelUndoViewAct.get(), &QAction::triggered, this,
|
||||
&MainWindow::onShowUndoViewToggled);
|
||||
ui->menu_View->addAction(m_showModelUndoViewAct.get());
|
||||
}
|
||||
|
||||
void MainWindow::createEditActions() {
|
||||
m_cutAct = make_unique<QAction>(tr("Cu&t"), this);
|
||||
m_cutAct->setShortcuts(QKeySequence::Cut);
|
||||
m_cutAct->setStatusTip(
|
||||
tr("Cut the current selection's contents to the "
|
||||
"clipboard"));
|
||||
// connect(m_cutAct, &QAction::triggered, this, &MainWindow::cut);
|
||||
m_cutAct->setEnabled(false);
|
||||
ui->menu_Edit->addAction(m_cutAct.get());
|
||||
|
||||
m_copyAct = make_unique<QAction>(tr("&Copy"), this);
|
||||
m_copyAct->setShortcuts(QKeySequence::Copy);
|
||||
m_copyAct->setStatusTip(
|
||||
tr("Copy the current selection's contents to the "
|
||||
"clipboard"));
|
||||
// connect(m_copyAct, &QAction::triggered, this, &MainWindow::copy);
|
||||
m_copyAct->setEnabled(false);
|
||||
ui->menu_Edit->addAction(m_copyAct.get());
|
||||
|
||||
m_pasteAct = make_unique<QAction>(tr("&Paste"), this);
|
||||
m_pasteAct->setShortcuts(QKeySequence::Paste);
|
||||
m_pasteAct->setStatusTip(
|
||||
tr("Paste the clipboard's contents into the current "
|
||||
"selection"));
|
||||
// connect(m_pasteAct, &QAction::triggered, this, &MainWindow::paste);
|
||||
m_pasteAct->setEnabled(false);
|
||||
ui->menu_Edit->addAction(m_pasteAct.get());
|
||||
|
||||
ui->menu_Edit->addSeparator();
|
||||
|
||||
m_openNewItemDialogAct = make_unique<QAction>(tr("&New item"), this);
|
||||
m_openNewItemDialogAct->setShortcut(QKeySequence::New);
|
||||
m_openNewItemDialogAct->setStatusTip(tr("Opens a dialog to add a new item"));
|
||||
connect(m_openNewItemDialogAct.get(), &QAction::triggered, this, &MainWindow::openNewItemDialog);
|
||||
ui->menu_Edit->addAction(m_openNewItemDialogAct.get());
|
||||
|
||||
m_openEditItemDialogAct = make_unique<QAction>(tr("&Edit item"), this);
|
||||
m_openEditItemDialogAct->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_E));
|
||||
m_openEditItemDialogAct->setStatusTip(tr("Opens a edit dialog for the current item"));
|
||||
connect(m_openEditItemDialogAct.get(), &QAction::triggered, this,
|
||||
&MainWindow::openEditItemDialog);
|
||||
ui->menu_Edit->addAction(m_openEditItemDialogAct.get());
|
||||
|
||||
m_deleteItemAct = make_unique<QAction>(tr("&Delete item(s)"), this);
|
||||
m_deleteItemAct->setShortcut(QKeySequence::Delete);
|
||||
m_deleteItemAct->setStatusTip(tr("Delete currently selected item(s)"));
|
||||
// connect(m_deleteItemAct.get(), &QAction::triggered, this, &MainWindow::deleteSelectedtItems);
|
||||
connect(m_deleteItemAct.get(), &QAction::triggered, this, &MainWindow::deleteCurrentItem);
|
||||
ui->menu_Edit->addAction(m_deleteItemAct.get());
|
||||
|
||||
ui->menu_Edit->addSeparator();
|
||||
|
||||
m_findItemAct = make_unique<QAction>(tr("&Find item(s)"), this);
|
||||
m_findItemAct->setShortcuts(QKeySequence::Find);
|
||||
m_findItemAct->setStatusTip(tr("Opens a dialog to find item(s) by containing text"));
|
||||
connect(m_findItemAct.get(), &QAction::triggered, this, &MainWindow::findItems);
|
||||
ui->menu_Edit->addAction(m_findItemAct.get());
|
||||
}
|
||||
|
||||
void MainWindow::createServerActions() {
|
||||
m_fetchItemsAct = make_unique<QAction>(tr("&Fetch item(s)"), this);
|
||||
m_fetchItemsAct->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Down));
|
||||
m_fetchItemsAct->setStatusTip(tr("Fetches all item on configured server"));
|
||||
connect(m_fetchItemsAct.get(), &QAction::triggered, this, &MainWindow::fetchItems);
|
||||
ui->menu_Server->addAction(m_fetchItemsAct.get());
|
||||
|
||||
m_postItemsAct = make_unique<QAction>(tr("&Post item(s)"), this);
|
||||
m_postItemsAct->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Up));
|
||||
// m_postItemsAct->setStatusTip(tr("Posts the selected items on configured server"));
|
||||
m_postItemsAct->setStatusTip(tr("Posts the current item on configured server"));
|
||||
connect(m_postItemsAct.get(), &QAction::triggered, this, &MainWindow::postItems);
|
||||
ui->menu_Server->addAction(m_postItemsAct.get());
|
||||
|
||||
m_deleteItemsAct = make_unique<QAction>(tr("&Delete item"), this);
|
||||
m_deleteItemsAct->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Backspace));
|
||||
// m_deleteItemsAct->setStatusTip(tr("Deletes the selected items on configured server"));
|
||||
m_deleteItemsAct->setStatusTip(tr("Deletes the current item on configured server"));
|
||||
connect(m_deleteItemsAct.get(), &QAction::triggered, this, &MainWindow::deleteItem);
|
||||
ui->menu_Server->addAction(m_deleteItemsAct.get());
|
||||
}
|
||||
|
||||
void MainWindow::createToolsActions() {
|
||||
QMenu* menu = ui->menu_Tools;
|
||||
QAction* settingsAct = menu->addAction(tr("&Settings"), this, &MainWindow::execSettingsDialog);
|
||||
settingsAct->setStatusTip(tr("Opens a dialog to configure applications settings."));
|
||||
}
|
||||
|
||||
void MainWindow::createHelpMenu() {
|
||||
QMenu* helpMenu = ui->menu_Help;
|
||||
helpMenu->addSeparator();
|
||||
QAction* aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::onAboutClicked);
|
||||
aboutAct->setStatusTip(tr("Show the application's About box"));
|
||||
|
||||
QAction* aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
|
||||
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
|
||||
}
|
||||
|
||||
void MainWindow::createGuiDialogs() {
|
||||
/// new item dialog
|
||||
m_newItemDialog = make_unique<NewItemDialog>(this);
|
||||
m_newItemDialog->createContent();
|
||||
connect(m_newItemDialog.get(), &NewItemDialog::addItems, m_proxyModel.get(),
|
||||
&GeneralSortFilterModel::appendItems);
|
||||
/// edit item dialog
|
||||
m_editItemDialog = make_unique<EditItemDialog>(ui->tableView, this);
|
||||
m_editItemDialog->createContent();
|
||||
}
|
||||
122
UIs/GenericWidgets/mainwindow.h
Normal file
@ -0,0 +1,122 @@
|
||||
#ifndef MAINWINDOW_H
|
||||
#define MAINWINDOW_H
|
||||
|
||||
#include <QItemSelection>
|
||||
#include <QMainWindow>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
|
||||
class QUndoStack;
|
||||
|
||||
class QUndoView;
|
||||
namespace Ui {
|
||||
class MainWindow;
|
||||
}
|
||||
QT_END_NAMESPACE
|
||||
|
||||
class GenericCore;
|
||||
class TableModel;
|
||||
class GeneralSortFilterModel;
|
||||
class NewItemDialog;
|
||||
class EditItemDialog;
|
||||
|
||||
using namespace std;
|
||||
|
||||
class MainWindow : public QMainWindow {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
MainWindow(QWidget* parent = nullptr);
|
||||
~MainWindow();
|
||||
|
||||
signals:
|
||||
void displayStatusMessage(QString message);
|
||||
void checkForUpdates();
|
||||
|
||||
protected:
|
||||
void closeEvent(QCloseEvent* event) override;
|
||||
|
||||
private slots:
|
||||
void showStatusMessage(const QString text);
|
||||
void onCurrentChanged(const QModelIndex& current, const QModelIndex& previous);
|
||||
void onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
|
||||
|
||||
void onAboutClicked();
|
||||
void on_actionCheck_for_update_triggered();
|
||||
|
||||
void on_pushButton_clicked();
|
||||
|
||||
/// slots for menu actions
|
||||
void openNewItemDialog();
|
||||
void openEditItemDialog();
|
||||
void deleteCurrentItem();
|
||||
void deleteSelectedtItems();
|
||||
|
||||
void onCleanStateChanged(bool clean);
|
||||
void onShowUndoViewToggled(bool checked);
|
||||
|
||||
/// 'File' slots
|
||||
void saveItems();
|
||||
void importCSV();
|
||||
void exportCSV();
|
||||
|
||||
/// 'Edit' slots
|
||||
void findItems();
|
||||
|
||||
/// 'Server' slots
|
||||
void fetchItems();
|
||||
void postItems();
|
||||
void deleteItem();
|
||||
|
||||
/// 'Tools' slots
|
||||
void execSettingsDialog();
|
||||
|
||||
private:
|
||||
Ui::MainWindow* ui;
|
||||
|
||||
unique_ptr<GenericCore> m_core;
|
||||
shared_ptr<GeneralSortFilterModel> m_proxyModel;
|
||||
QUndoStack* m_modelUndoStack;
|
||||
unique_ptr<QUndoView> m_modelUndoView;
|
||||
|
||||
/// File actions
|
||||
unique_ptr<QAction> m_newFileAct;
|
||||
unique_ptr<QAction> m_openAct;
|
||||
unique_ptr<QAction> m_saveAct;
|
||||
unique_ptr<QAction> m_importAct;
|
||||
unique_ptr<QAction> m_exportAct;
|
||||
unique_ptr<QAction> m_printAct;
|
||||
unique_ptr<QAction> m_exitAct;
|
||||
/// Edit actions
|
||||
unique_ptr<QAction> m_undoAct;
|
||||
unique_ptr<QAction> m_redoAct;
|
||||
unique_ptr<QAction> m_cutAct;
|
||||
unique_ptr<QAction> m_copyAct;
|
||||
unique_ptr<QAction> m_pasteAct;
|
||||
unique_ptr<QAction> m_openNewItemDialogAct;
|
||||
unique_ptr<QAction> m_openEditItemDialogAct;
|
||||
unique_ptr<QAction> m_deleteItemAct;
|
||||
unique_ptr<QAction> m_findItemAct;
|
||||
/// Server actions
|
||||
unique_ptr<QAction> m_fetchItemsAct;
|
||||
unique_ptr<QAction> m_postItemsAct;
|
||||
unique_ptr<QAction> m_deleteItemsAct;
|
||||
|
||||
/// View actions
|
||||
unique_ptr<QAction> m_showModelUndoViewAct;
|
||||
|
||||
/// Dialogs
|
||||
unique_ptr<NewItemDialog> m_newItemDialog;
|
||||
unique_ptr<EditItemDialog> m_editItemDialog;
|
||||
|
||||
/// Setup functions
|
||||
void createActions();
|
||||
void createFileActions();
|
||||
void createUndoActions();
|
||||
void createEditActions();
|
||||
void createServerActions();
|
||||
void createToolsActions();
|
||||
void createHelpMenu();
|
||||
void createGuiDialogs();
|
||||
};
|
||||
#endif // MAINWINDOW_H
|
||||
96
UIs/GenericWidgets/mainwindow.ui
Normal file
@ -0,0 +1,96 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>MainWindow</class>
|
||||
<widget class="QMainWindow" name="MainWindow">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>600</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>GenericQtClient</string>
|
||||
</property>
|
||||
<widget class="QWidget" name="centralwidget">
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<item>
|
||||
<widget class="QTableView" name="tableView"/>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="text">
|
||||
<string>Push the button!</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="pushButton">
|
||||
<property name="text">
|
||||
<string>Button</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QMenuBar" name="menubar">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>22</height>
|
||||
</rect>
|
||||
</property>
|
||||
<widget class="QMenu" name="menu_File">
|
||||
<property name="title">
|
||||
<string>&File</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QMenu" name="menu_Edit">
|
||||
<property name="title">
|
||||
<string>&Edit</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QMenu" name="menu_View">
|
||||
<property name="title">
|
||||
<string>&View</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QMenu" name="menu_Help">
|
||||
<property name="title">
|
||||
<string>&Help</string>
|
||||
</property>
|
||||
<addaction name="actionCheck_for_update"/>
|
||||
</widget>
|
||||
<widget class="QMenu" name="menu_Server">
|
||||
<property name="title">
|
||||
<string>&Server</string>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QMenu" name="menu_Tools">
|
||||
<property name="title">
|
||||
<string>&Tools</string>
|
||||
</property>
|
||||
</widget>
|
||||
<addaction name="menu_File"/>
|
||||
<addaction name="menu_Edit"/>
|
||||
<addaction name="menu_View"/>
|
||||
<addaction name="menu_Server"/>
|
||||
<addaction name="menu_Tools"/>
|
||||
<addaction name="menu_Help"/>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusbar"/>
|
||||
<action name="actionCheck_for_update">
|
||||
<property name="text">
|
||||
<string>Check for &update</string>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
<slots>
|
||||
<slot>onPushButtonClicked()</slot>
|
||||
</slots>
|
||||
</ui>
|
||||
164
UIs/GenericWidgets/utils/messagehandler.h
Normal file
@ -0,0 +1,164 @@
|
||||
#ifndef MESSAGEHANDLER_H
|
||||
#define MESSAGEHANDLER_H
|
||||
/**
|
||||
* Color and formatting codes
|
||||
* @see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
|
||||
*/
|
||||
|
||||
#include <QObject>
|
||||
|
||||
// qSetMessagePattern("%{file}(%{line}): %{message}");
|
||||
// qSetMessagePattern("%{type}(%{line}):\t%{message}");
|
||||
// qSetMessagePattern("%{type}%{file}(%{line}):\t%{message}");
|
||||
|
||||
void consoleHandlerColoredVerbose(QtMsgType type,
|
||||
const QMessageLogContext& context,
|
||||
const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
|
||||
// context.line, context.function, localMsg.constData()); // bold
|
||||
fprintf(stderr, "\033[107;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void consoleHandlerColoredVerboseInDarkTheme(QtMsgType type,
|
||||
const QMessageLogContext& context,
|
||||
const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
|
||||
// context.line, context.function, localMsg.constData()); // bold
|
||||
fprintf(stderr, "\033[107;37mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void consoleHandlerColored(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
fprintf(stderr, "\033[1;30mDebug: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[0;30mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[1;33mWarning: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[31mCritical: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[31mFatal: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
|
||||
context.line, context.function);
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include <android/log.h>
|
||||
|
||||
const char* const applicationName = "Pensieve";
|
||||
void androidMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QString report = msg;
|
||||
if (context.file && !QString(context.file).isEmpty()) {
|
||||
report += " in file ";
|
||||
report += QString(context.file);
|
||||
report += " line ";
|
||||
report += QString::number(context.line);
|
||||
}
|
||||
if (context.function && !QString(context.function).isEmpty()) {
|
||||
report += +" function ";
|
||||
report += QString(context.function);
|
||||
}
|
||||
const char* const local = report.toLocal8Bit().constData();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
__android_log_write(ANDROID_LOG_DEBUG, applicationName, local);
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
__android_log_write(ANDROID_LOG_INFO, applicationName, local);
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
__android_log_write(ANDROID_LOG_WARN, applicationName, local);
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
__android_log_write(ANDROID_LOG_ERROR, applicationName, local);
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
default:
|
||||
__android_log_write(ANDROID_LOG_FATAL, applicationName, local);
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // MESSAGEHANDLER_H
|
||||
160
UIs/GenericWidgets/views/itemdetailmapper.cpp
Normal file
@ -0,0 +1,160 @@
|
||||
#include "itemdetailmapper.h"
|
||||
|
||||
#include <QAbstractItemModel>
|
||||
#include <QDataWidgetMapper>
|
||||
#include <QGridLayout>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QPushButton>
|
||||
#include <QSpinBox>
|
||||
#include <QTableView>
|
||||
#include "model/metadata.h"
|
||||
|
||||
ItemDetailMapper::ItemDetailMapper(QWidget* parent)
|
||||
: QWidget{parent} {
|
||||
/// model mapping
|
||||
m_mapper = std::make_unique<QDataWidgetMapper>(this);
|
||||
/// BUG: If multiple columns are changed not all changes are applied.
|
||||
/// Multiple changes are set individually by calling setData().
|
||||
/// Probably due to a conflicting dataChanged signal for too many roles&columns the data of
|
||||
/// the remaining columns is reset before setData is called.
|
||||
/// And a manual submit would also create multiple undo steps anyway.
|
||||
/// Workaround: ManualSubmit -> AutoSubmit
|
||||
// m_mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
|
||||
m_mapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
|
||||
|
||||
/// model mapping buttons
|
||||
m_nextButton = new QPushButton(tr("Ne&xt"));
|
||||
m_previousButton = new QPushButton(tr("&Previous"));
|
||||
|
||||
connect(m_previousButton, &QAbstractButton::clicked, this, &ItemDetailMapper::toPrevious);
|
||||
connect(m_nextButton, &QAbstractButton::clicked, this, &ItemDetailMapper::toNext);
|
||||
|
||||
/// the individual widgets
|
||||
// REFACTOR deduce label names and types from meta data & use a factory
|
||||
m_nameLabel = new QLabel("&Name");
|
||||
m_nameEdit = new QLineEdit();
|
||||
m_nameLabel->setBuddy(m_nameEdit);
|
||||
|
||||
m_descriptionLabel = new QLabel("&Description");
|
||||
m_descriptionEdit = new QLineEdit();
|
||||
m_descriptionLabel->setBuddy(m_descriptionEdit);
|
||||
|
||||
m_infoLabel = new QLabel("&Info");
|
||||
m_infoEdit = new QLineEdit();
|
||||
m_infoLabel->setBuddy(m_infoEdit);
|
||||
|
||||
m_amountLabel = new QLabel("&Amount");
|
||||
m_amountBox = new QSpinBox();
|
||||
m_amountBox->setMaximum(1000);
|
||||
m_amountLabel->setBuddy(m_amountBox);
|
||||
|
||||
m_factorLabel = new QLabel("&Factor");
|
||||
m_factorBox = new QDoubleSpinBox();
|
||||
m_factorBox->setMaximum(1000);
|
||||
m_factorLabel->setBuddy(m_factorBox);
|
||||
|
||||
QGridLayout* layout = new QGridLayout();
|
||||
layout->addWidget(m_nameLabel, 0, 0, 1, 1);
|
||||
layout->addWidget(m_nameEdit, 0, 1, 1, 1);
|
||||
layout->addWidget(m_descriptionLabel, 1, 0, 1, 1);
|
||||
layout->addWidget(m_descriptionEdit, 1, 1, 1, 1);
|
||||
layout->addWidget(m_infoLabel, 2, 0, 1, 1);
|
||||
layout->addWidget(m_infoEdit, 2, 1, 1, 1);
|
||||
layout->addWidget(m_amountLabel, 3, 0, 1, 1);
|
||||
layout->addWidget(m_amountBox, 3, 1, 1, 1);
|
||||
layout->addWidget(m_factorLabel, 4, 0, 1, 1);
|
||||
layout->addWidget(m_factorBox, 4, 1, 1, 1);
|
||||
|
||||
layout->addWidget(m_previousButton, 5, 0, 1, 1);
|
||||
layout->addWidget(m_nextButton, 5, 1, 1, 1);
|
||||
|
||||
setLayout(layout);
|
||||
}
|
||||
|
||||
void ItemDetailMapper::setModelMappings(QTableView* tableView) {
|
||||
qDebug() << "Setting model...";
|
||||
m_tableView = tableView;
|
||||
m_model = tableView->model();
|
||||
m_selectionModel = tableView->selectionModel();
|
||||
|
||||
m_mapper->setModel(m_model);
|
||||
m_mapper->addMapping(m_nameEdit, 0);
|
||||
m_mapper->addMapping(m_descriptionEdit, 1);
|
||||
m_mapper->addMapping(m_infoEdit, 2);
|
||||
m_mapper->addMapping(m_amountBox, 3);
|
||||
m_mapper->addMapping(m_factorBox, 4);
|
||||
|
||||
m_mapper->setCurrentIndex(m_selectionModel->currentIndex().row());
|
||||
|
||||
connect(m_model, &QAbstractItemModel::rowsInserted, this, &ItemDetailMapper::rowsInserted);
|
||||
connect(m_model, &QAbstractItemModel::rowsRemoved, this, &ItemDetailMapper::rowsRemoved);
|
||||
connect(m_selectionModel, &QItemSelectionModel::currentChanged, this,
|
||||
&ItemDetailMapper::onCurrentIndexChanged);
|
||||
|
||||
updateButtons(m_selectionModel->currentIndex().row());
|
||||
}
|
||||
|
||||
bool ItemDetailMapper::submit() { return m_mapper->submit(); }
|
||||
|
||||
void ItemDetailMapper::revert() { m_mapper->revert(); }
|
||||
|
||||
void ItemDetailMapper::onCurrentIndexChanged(const QModelIndex& current,
|
||||
const QModelIndex& /*previous*/) {
|
||||
if (!isEnabled()) {
|
||||
setEnabled(true);
|
||||
}
|
||||
m_mapper->setCurrentModelIndex(current);
|
||||
updateButtons(current.row());
|
||||
emitContentChanged(current);
|
||||
}
|
||||
|
||||
void ItemDetailMapper::rowsInserted(const QModelIndex& parent, int start, int end) {
|
||||
updateButtons(m_mapper->currentIndex());
|
||||
}
|
||||
|
||||
void ItemDetailMapper::rowsRemoved(const QModelIndex& parent, int start, int end) {
|
||||
if (m_model->rowCount() == 0) {
|
||||
setEnabled(false);
|
||||
|
||||
m_nameEdit->clear();
|
||||
m_descriptionEdit->clear();
|
||||
m_infoEdit->clear();
|
||||
m_amountBox->clear();
|
||||
m_factorBox->clear();
|
||||
}
|
||||
|
||||
updateButtons(m_mapper->currentIndex());
|
||||
}
|
||||
|
||||
void ItemDetailMapper::toPrevious() {
|
||||
int currentRow = m_selectionModel->currentIndex().row();
|
||||
QModelIndex previousIndex = m_selectionModel->currentIndex().siblingAtRow(currentRow - 1);
|
||||
if (previousIndex.isValid()) {
|
||||
m_selectionModel->setCurrentIndex(previousIndex, QItemSelectionModel::ClearAndSelect);
|
||||
}
|
||||
}
|
||||
|
||||
void ItemDetailMapper::toNext() {
|
||||
int currentRow = m_selectionModel->currentIndex().row();
|
||||
QModelIndex nextIndex = m_selectionModel->currentIndex().siblingAtRow(currentRow + 1);
|
||||
if (nextIndex.isValid()) {
|
||||
m_selectionModel->setCurrentIndex(nextIndex, QItemSelectionModel::ClearAndSelect);
|
||||
}
|
||||
}
|
||||
|
||||
void ItemDetailMapper::updateButtons(int row) {
|
||||
m_previousButton->setEnabled(row > 0);
|
||||
m_nextButton->setEnabled(row < m_model->rowCount() - 1);
|
||||
}
|
||||
|
||||
void ItemDetailMapper::emitContentChanged(const QModelIndex& currentIndex) {
|
||||
// BUG QR-Code isn't updated after changes through the ItemDetailMapper #18
|
||||
QString toStringText = "";
|
||||
if (currentIndex.isValid()) {
|
||||
toStringText = currentIndex.data(ToStringRole).toString();
|
||||
}
|
||||
emit contentChanged(toStringText);
|
||||
}
|
||||
67
UIs/GenericWidgets/views/itemdetailmapper.h
Normal file
@ -0,0 +1,67 @@
|
||||
#ifndef ITEMDETAILMAPPER_H
|
||||
#define ITEMDETAILMAPPER_H
|
||||
|
||||
#include <QDataWidgetMapper>
|
||||
#include <QWidget>
|
||||
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QDoubleSpinBox;
|
||||
class QSpinBox;
|
||||
class QPushButton;
|
||||
class QAbstractItemModel;
|
||||
class QItemSelectionModel;
|
||||
class QTableView;
|
||||
|
||||
class ItemDetailMapper : public QWidget {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ItemDetailMapper(QWidget* parent = nullptr);
|
||||
|
||||
void setModelMappings(QTableView* tableView);
|
||||
|
||||
bool submit();
|
||||
void revert();
|
||||
|
||||
signals:
|
||||
void contentChanged(const QString text);
|
||||
|
||||
private slots:
|
||||
void onCurrentIndexChanged(const QModelIndex& current, const QModelIndex& previous);
|
||||
void rowsInserted(const QModelIndex& parent, int start, int end);
|
||||
void rowsRemoved(const QModelIndex& parent, int start, int end);
|
||||
void toPrevious();
|
||||
void toNext();
|
||||
void updateButtons(int row);
|
||||
void emitContentChanged(const QModelIndex& currentIndex);
|
||||
|
||||
private:
|
||||
/// *** members ***
|
||||
/// Model stuff
|
||||
QTableView* m_tableView = nullptr;
|
||||
QAbstractItemModel* m_model = nullptr;
|
||||
QItemSelectionModel* m_selectionModel = nullptr;
|
||||
|
||||
std::unique_ptr<QDataWidgetMapper> m_mapper;
|
||||
|
||||
/// GUI elements
|
||||
QLabel* m_nameLabel = nullptr;
|
||||
QLineEdit* m_nameEdit = nullptr;
|
||||
|
||||
QLabel* m_descriptionLabel = nullptr;
|
||||
QLineEdit* m_descriptionEdit = nullptr;
|
||||
|
||||
QLabel* m_infoLabel = nullptr;
|
||||
QLineEdit* m_infoEdit = nullptr;
|
||||
|
||||
QLabel* m_amountLabel = nullptr;
|
||||
QSpinBox* m_amountBox = nullptr;
|
||||
|
||||
QLabel* m_factorLabel = nullptr;
|
||||
QDoubleSpinBox* m_factorBox = nullptr;
|
||||
|
||||
QPushButton* m_nextButton;
|
||||
QPushButton* m_previousButton;
|
||||
};
|
||||
|
||||
#endif // ITEMDETAILMAPPER_H
|
||||
BIN
assets/icons/GenericQtClient.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
assets/icons/feature.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
7
assets/icons/icons.qrc
Normal file
@ -0,0 +1,7 @@
|
||||
<RCC>
|
||||
<qresource prefix="/">
|
||||
<file>software-application.png</file>
|
||||
<file>feature.png</file>
|
||||
<file>no-picture-taking.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
BIN
assets/icons/no-picture-taking.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
assets/icons/software-application.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
5
assets/icons/urls.txt
Normal file
@ -0,0 +1,5 @@
|
||||
software-application.png:
|
||||
https://www.flaticon.com/free-icon/software-application_5063917
|
||||
|
||||
feature.png:
|
||||
https://www.flaticon.com/free-icon/feature_1085784
|
||||
4
installer/.env
Normal file
@ -0,0 +1,4 @@
|
||||
# ssh url of the packages directory of the repo
|
||||
PROJECT_FOLDER=""
|
||||
export CONFIG_REPO_URL="/${PROJECT_FOLDER}"
|
||||
export PUSH_REPO_URL="/${PROJECT_FOLDER}"
|
||||
52
installer/build.sh
Executable file
@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo amount of arguments: $#
|
||||
|
||||
if [[ $# -ne 4 ]]; then
|
||||
echo "Build script has to be called with exactly two arguments."
|
||||
echo "The version number (Major.Minor.Patch) as its first argument."
|
||||
echo "... and the OS (linux, windows or macos) as the second argument"
|
||||
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
|
||||
echo "Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$1
|
||||
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
|
||||
if [[ $VERSION =~ $regex ]]; then
|
||||
echo "Version accepted: $VERSION"
|
||||
else
|
||||
echo "Version '$VERSION' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PLATFORM=$2
|
||||
# TODO refactor this to use something like PLATFORMS.contains(PLATFORM)
|
||||
if [[ $PLATFORM == linux ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
elif [[ $PLATFORM == windows ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
elif [[ $PLATFORM == macos ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
else
|
||||
echo "Platform '$PLATFORM' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
#if [[ ! -e .env ]]; then
|
||||
# echo "File .env not found. Aborting..."
|
||||
# exit 1
|
||||
#fi
|
||||
#echo "Sourcing .env file..."
|
||||
#source .env
|
||||
|
||||
echo "calling the compile-executable.sh..."
|
||||
./compile-executable.sh $1 $2 $3 $4
|
||||
|
||||
echo "calling the create-installer.sh..."
|
||||
./create-installer.sh $1 $2 $3 $4
|
||||
|
||||
echo "calling the deployToRepo.sh..."
|
||||
./deployToRepo.sh $1 $2 $3 $4
|
||||
|
||||
cd ${OLD_PWD}
|
||||
59
installer/compile-executable.sh
Executable file
@ -0,0 +1,59 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo amount of arguments: $#
|
||||
|
||||
if [[ $# -ne 4 ]]; then
|
||||
echo "Build script has to be called with exactly two arguments."
|
||||
echo "The version number (Major.Minor.Patch) as its first argument."
|
||||
echo "... and the OS (linux, windows or macos) as the second argument"
|
||||
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
|
||||
echo "Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$1
|
||||
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
|
||||
if [[ $VERSION =~ $regex ]]; then
|
||||
echo "Version accepted: $VERSION"
|
||||
else
|
||||
echo "Version '$VERSION' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PLATFORM=$2
|
||||
# TODO refactor this to use something like PLATFORMS.contains(PLATFORM)
|
||||
if [[ $PLATFORM == linux ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
#QMAKE_EXE="qmake"
|
||||
COMPILER_EXE="make"
|
||||
elif [[ $PLATFORM == windows ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
#QMAKE_EXE="$QMAKE_LOCATION/qmake"
|
||||
#COMPILER_EXE="$MINGWROOT/bin/mingw32-make"
|
||||
elif [[ $PLATFORM == macos ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
#QMAKE_EXE="qmake"
|
||||
COMPILER_EXE="make"
|
||||
else
|
||||
echo "Platform '$PLATFORM' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Starting build ..."
|
||||
OLD_PWD=$(pwd)
|
||||
BUILD_DIR="_build"
|
||||
echo "starting in: ${OLD_PWD}"
|
||||
|
||||
# if [[ -e $BUILD_DIR/$TARGET ]]; then
|
||||
# echo "old build dir has old content, cleaning the build directory..."
|
||||
# rm -r $BUILD_DIR/*
|
||||
# fi
|
||||
cd $BUILD_DIR
|
||||
echo "Building in $(pwd) ..."
|
||||
|
||||
echo "Building whole project..."
|
||||
echo "Running CMake..."
|
||||
cmake -DCMAKE_BUILD_TYPE=Release ../../
|
||||
|
||||
echo "Compiling..."
|
||||
$COMPILER_EXE
|
||||
16
installer/config/config.xml.in
Normal file
@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Installer>
|
||||
<Name>${PROJECT_NAME}</Name>
|
||||
<Version>1.0.0</Version>
|
||||
<Title>${PROJECT_NAME} Installer</Title>
|
||||
<Publisher>Working-Copy Collective</Publisher>
|
||||
<StartMenuDir>Utilities</StartMenuDir>
|
||||
<TargetDir>@ApplicationsDir@/${PROJECT_NAME}</TargetDir>
|
||||
<RemoteRepositories>
|
||||
<Repository>
|
||||
<Url>${CONFIG_REPO_URL}/${PLATFORM}/packages</Url>
|
||||
<Enabled>1</Enabled>
|
||||
<DisplayName>The ${PROJECT_NAME} repository</DisplayName>
|
||||
</Repository>
|
||||
</RemoteRepositories>
|
||||
</Installer>
|
||||
112
installer/create-installer.sh
Executable file
@ -0,0 +1,112 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [[ $# -ne 4 ]]; then
|
||||
echo "Build script has to be called with exactly two arguments."
|
||||
echo "The version number (Major.Minor.Patch) as its first argument."
|
||||
echo "... and the OS (linux, windows or macos) as the second argument"
|
||||
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
|
||||
echo "Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$1
|
||||
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
|
||||
if [[ $VERSION =~ $regex ]]; then
|
||||
echo "Version accepted: $VERSION"
|
||||
else
|
||||
echo "Version '$VERSION' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PLATFORM=$2
|
||||
TARGET=$3
|
||||
EXECUTABLE="$TARGET-Widgets"
|
||||
BUILD_PREFIX="_build/UIs/GenericWidgets"
|
||||
# TODO refactor this to use PLATFORMS.contains(PLATFORM)
|
||||
if [[ $PLATFORM == linux ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
BUILD_DIR=$BUILD_PREFIX
|
||||
elif [[ $PLATFORM == windows ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
BUILD_DIR="$BUILD_PREFIX/release"
|
||||
elif [[ $PLATFORM == macos ]]; then
|
||||
echo "OS: $PLATFORM"
|
||||
BUILD_DIR=$BUILD_PREFIX
|
||||
else
|
||||
echo "Version '$PLATFORM' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
#if [[ ! -e .env ]]; then
|
||||
# echo "File .env not found. Aborting..."
|
||||
# exit 1
|
||||
#fi
|
||||
#echo "Sourcing .env file..."
|
||||
#source .env
|
||||
|
||||
PACKAGENAME=$4
|
||||
INSTALLER_DIR="_build/installer"
|
||||
PKG_DATA_DIR="$INSTALLER_DIR/packages/$PACKAGENAME/data"
|
||||
PKG_META_DIR="$INSTALLER_DIR/packages/$PACKAGENAME/meta"
|
||||
ASSET_DIR="../assets/icons"
|
||||
OUTPUT_DIR="../_output/installer"
|
||||
|
||||
if [[ -e $PKG_DATA_DIR/$TARGET ]]; then
|
||||
echo "old $TARGET exe exists, cleaning the package data directory..."
|
||||
rm -r $PKG_DATA_DIR/*
|
||||
fi
|
||||
|
||||
if [[ ! -d $PKG_DATA_DIR ]]; then
|
||||
echo "creating package data folder..."
|
||||
mkdir -p $PKG_DATA_DIR
|
||||
fi
|
||||
|
||||
mv $INSTALLER_DIR/packages/meta $PKG_META_DIR
|
||||
|
||||
echo "copying executable..."
|
||||
if [[ $PLATFORM == macos ]]; then
|
||||
cp -r $BUILD_DIR/$EXECUTABLE.app $PKG_DATA_DIR/$TARGET.app
|
||||
else
|
||||
cp $BUILD_DIR/$EXECUTABLE $PKG_DATA_DIR/$TARGET
|
||||
fi
|
||||
|
||||
echo "copying assets..."
|
||||
cp $ASSET_DIR/$TARGET.png $PKG_DATA_DIR/$TARGET.png
|
||||
|
||||
echo "copying license..."
|
||||
cp ../LICENSE $PKG_META_DIR/license.txt
|
||||
|
||||
### Platform dependencies
|
||||
echo "Applying platform dependencies..."
|
||||
INSTALLER_APPENDIX="installer"
|
||||
if [[ $PLATFORM == linux ]]; then
|
||||
echo "Linux..."
|
||||
# echo "Patching the config.xml"
|
||||
# sed -i "s/<PLATFORM>/$PLATFORM/g" config/config.xml
|
||||
elif [[ $PLATFORM == windows ]]; then
|
||||
echo "Windows..."
|
||||
cd $PKG_DATA_DIR
|
||||
echo "Copying OpenSSL dlls..."
|
||||
cp /c/Qt/Tools/OpenSSL/Win_x64/bin/libcrypto-1_1-x64.dll .
|
||||
cp /c/Qt/Tools/OpenSSL/Win_x64/bin/libssl-1_1-x64.dll .
|
||||
echo "Calling windeployqt..."
|
||||
$QMAKE_LOCATION/windeployqt $TARGET.exe
|
||||
cd -
|
||||
# echo "Patching the config.xml"
|
||||
# sed -i "s/<PLATFORM>/$PLATFORM/g" config/config.xml
|
||||
elif [[ $PLATFORM == macos ]]; then
|
||||
echo "MacOS..."
|
||||
echo "Calling macdeployqt..."
|
||||
INSTALLER_APPENDIX="installer.dmg"
|
||||
cd $PKG_DATA_DIR
|
||||
macdeployqt $TARGET.app
|
||||
cd -
|
||||
# echo "Patching the config.xml..."
|
||||
# sed -i '' "s/<PLATFORM>/$PLATFORM/g" config/config.xml
|
||||
fi
|
||||
|
||||
|
||||
echo "running binarycreator..."
|
||||
#echo "$QIF_LOCATION/binarycreator"
|
||||
binarycreator -n -c $INSTALLER_DIR/config/config.xml -p $INSTALLER_DIR/packages $OUTPUT_DIR/$TARGET-$PLATFORM-$VERSION-$INSTALLER_APPENDIX-online
|
||||
binarycreator -f -c $INSTALLER_DIR/config/config.xml -p $INSTALLER_DIR/packages $OUTPUT_DIR/$TARGET-$PLATFORM-$VERSION-$INSTALLER_APPENDIX-offline
|
||||
44
installer/deployToRepo.sh
Executable file
@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo amount of arguments: $#
|
||||
|
||||
if [[ $# -ne 4 ]]; then
|
||||
echo "Build script has to be called with exactly two arguments."
|
||||
echo "The version number (Major.Minor.Patch) as its first argument."
|
||||
echo "... and the OS (linux, windows or macos) as the second argument"
|
||||
echo "TODO: DOCUMENT ARGUMENTS 3 & 4!!!"
|
||||
echo "Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$1
|
||||
regex='^([0-9]+\.){0,2}(\*|[0-9]+)$'
|
||||
if [[ $VERSION =~ $regex ]]; then
|
||||
echo "Version accepted: $VERSION"
|
||||
else
|
||||
echo "Version '$VERSION' is not acceptable. Aborting..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -e .env ]]; then
|
||||
exit 1
|
||||
fi
|
||||
echo "Sourcing .env file..."
|
||||
source .env
|
||||
|
||||
PACKAGENAME=$4
|
||||
|
||||
PLATFORM=$2
|
||||
|
||||
PACKAGE_DIR="_build/installer/packages"
|
||||
OUTPUT_DIR="../_output/repository"
|
||||
echo "executing repo-gen..."
|
||||
repogen --update -p $PACKAGE_DIR $OUTPUT_DIR
|
||||
|
||||
if [[ $PUSH_REPO_URL != "" ]]; then
|
||||
echo "pushing package data to repo..."
|
||||
echo "PUSH_REPO_URL: $PUSH_REPO_URL"
|
||||
scp -r $OUTPUT_DIR/* $PUSH_REPO_URL/$PLATFORM/packages/
|
||||
fi
|
||||
|
||||
cd ${OLD_PWD}
|
||||
24
installer/packages/defaultPackage/meta/installscript.qs.in
Normal file
@ -0,0 +1,24 @@
|
||||
function Component() {}
|
||||
|
||||
Component.prototype.isDefault = function() {
|
||||
return true;
|
||||
}
|
||||
|
||||
Component.prototype.createOperations = function() {
|
||||
|
||||
try {
|
||||
component.createOperations();
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
|
||||
if (installer.value("os") === "win")
|
||||
{
|
||||
component.addOperation("CreateShortcut", "@TargetDir@/${PROJECT_NAME}.exe", "@DesktopDir@/${PROJECT_NAME}.lnk");
|
||||
}
|
||||
if (installer.value("os") === "x11")
|
||||
{
|
||||
component.addOperation("CreateDesktopEntry", "/usr/share/applications/${PROJECT_NAME}.desktop", "Version=1.0\nType=Application\nTerminal=false\nCategories=Utility\nExec=@TargetDir@/${PROJECT_NAME}\nName=${PROJECT_NAME}\nIcon=@TargetDir@/${PROJECT_NAME}.png\nName[en_US]=${PROJECT_NAME}");
|
||||
//component.addElevatedOperation("Copy", "/usr/share/applications/${PROJECT_NAME}.desktop", "@HomeDir@/Desktop/${PROJECT_NAME}.desktop");
|
||||
}
|
||||
}
|
||||
232
installer/packages/defaultPackage/meta/license.txt.in
Normal file
@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
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.
|
||||
|
||||
GenericQtClient
|
||||
Copyright (C) 2025 bent
|
||||
|
||||
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/>.
|
||||
|
||||
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:
|
||||
|
||||
GenericQtClient Copyright (C) 2025 bent
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
13
installer/packages/defaultPackage/meta/package.xml.in
Normal file
@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Package>
|
||||
<DisplayName>The application itself</DisplayName>
|
||||
<Description>Installs the ${PROJECT_NAME} executable.</Description>
|
||||
<Version>${PROJECT_VERSION}</Version>
|
||||
<ReleaseDate>${CURRENT_DATE}</ReleaseDate>
|
||||
<Licenses>
|
||||
<License name="GNU General Public License Agreement" file="license.txt" />
|
||||
</Licenses>
|
||||
<ForcedInstallation>true</ForcedInstallation>
|
||||
<Default>script</Default>
|
||||
<Script>installscript.qs</Script>
|
||||
</Package>
|
||||
55
libs/GenericCore/CMakeLists.txt
Normal file
@ -0,0 +1,55 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
set(TARGET_APP "GenericCore")
|
||||
project(${TARGET_APP} VERSION 0.3.0 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 LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools Gui)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Network)
|
||||
|
||||
configure_file(CoreConfig.h.in CoreConfig.h)
|
||||
|
||||
set(TS_FILES ${TARGET_APP}_en_US.ts)
|
||||
|
||||
add_library(${TARGET_APP} STATIC
|
||||
genericcore.cpp
|
||||
genericcore.h
|
||||
${TS_FILES}
|
||||
constants.h
|
||||
data/settingshandler.h data/settingshandler.cpp
|
||||
model/tablemodel.h model/tablemodel.cpp
|
||||
model/modelitem.h model/modelitem.cpp
|
||||
formats/jsonparser.h formats/jsonparser.cpp
|
||||
model/commands/insertrowscommand.h model/commands/insertrowscommand.cpp
|
||||
model/commands/removerowscommand.h model/commands/removerowscommand.cpp
|
||||
model/commands/edititemcommand.h model/commands/edititemcommand.cpp
|
||||
data/filehandler.h data/filehandler.cpp
|
||||
model/metadata.h
|
||||
formats/csvparser.h formats/csvparser.cpp
|
||||
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
|
||||
network/servercommunicator.h network/servercommunicator.cpp
|
||||
network/apiroutes.h
|
||||
# 3rd party libraries
|
||||
../3rdParty/rapidcsv/src/rapidcsv.h
|
||||
)
|
||||
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui)
|
||||
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Test)
|
||||
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Network)
|
||||
|
||||
target_compile_definitions(${TARGET_APP} PRIVATE ${TARGET_APP}_LIBRARY)
|
||||
|
||||
if(COMMAND qt_create_translation)
|
||||
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
else()
|
||||
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
|
||||
endif()
|
||||
2
libs/GenericCore/CoreConfig.h.in
Normal file
@ -0,0 +1,2 @@
|
||||
#define CORE_NAME "${PROJECT_NAME}"
|
||||
#define CORE_VERSION "${PROJECT_VERSION}"
|
||||
3
libs/GenericCore/GenericCore_en_US.ts
Normal file
@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!DOCTYPE TS>
|
||||
<TS version="2.1" language="en_US"></TS>
|
||||
15
libs/GenericCore/constants.h
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef CONSTANTS_H
|
||||
#define CONSTANTS_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
/// Platform dependent
|
||||
#ifdef Q_OS_LINUX
|
||||
static const QString UPDATER_EXE = "maintenancetool";
|
||||
#elif defined(Q_OS_MAC)
|
||||
static const QString UPDATER_EXE = "maintenancetool.app/Contents/MacOS/maintenancetool";
|
||||
#elif defined(Q_OS_WIN)
|
||||
static const QString UPDATER_EXE = "maintenancetool.exe";
|
||||
#endif
|
||||
|
||||
#endif // CONSTANTS_H
|
||||
89
libs/GenericCore/data/filehandler.cpp
Normal file
@ -0,0 +1,89 @@
|
||||
#include "filehandler.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QDir>
|
||||
#include <QJsonDocument>
|
||||
#include <QStandardPaths>
|
||||
|
||||
#include "../formats/csvparser.h"
|
||||
|
||||
bool FileHandler::saveToFile(const QJsonDocument& doc, const QString& fileName) {
|
||||
qDebug() << "saving file...";
|
||||
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
|
||||
qDebug() << path;
|
||||
|
||||
QDir dir;
|
||||
if (!dir.exists(path)) {
|
||||
dir.mkpath(path);
|
||||
}
|
||||
// qDebug() << path + fileName;
|
||||
const QString filePath = path + '/' + fileName;
|
||||
QFile file(filePath);
|
||||
|
||||
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
||||
qWarning() << "can't open file";
|
||||
return false;
|
||||
}
|
||||
QTextStream out(&file);
|
||||
out.setEncoding(QStringConverter::Utf8);
|
||||
out << doc.toJson(QJsonDocument::Indented);
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray FileHandler::loadJSONDataFromFile(const QString fileName) {
|
||||
QFile file;
|
||||
QString path = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).at(0);
|
||||
file.setFileName(path + "/" + fileName);
|
||||
|
||||
QPair<QString, QByteArray> fileContent = getFileContent(path + "/" + fileName);
|
||||
|
||||
return fileContent.second;
|
||||
}
|
||||
|
||||
QList<ModelItemValues> FileHandler::getItemValuesFromCSVFile(const QString& filePath) {
|
||||
QList<ModelItemValues> result;
|
||||
QFile file;
|
||||
file.setFileName(filePath);
|
||||
if (file.exists()) {
|
||||
result = CsvParser::getItemsFromCSVFile(filePath);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool FileHandler::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
|
||||
return CsvParser::exportToCSVFile(rows, filePath);
|
||||
}
|
||||
|
||||
FileHandler::FileHandler() {}
|
||||
|
||||
/** Tries to open the file specified by the file path & returns the content
|
||||
* @brief FileHandler::getFileContent
|
||||
* @param filePath
|
||||
* @return Returns an error string (empty if successful) and the file content
|
||||
*/
|
||||
QPair<QString, QByteArray> FileHandler::getFileContent(const QString& filePath) {
|
||||
QString errorString = "";
|
||||
|
||||
QByteArray fileContent;
|
||||
QFile file;
|
||||
file.setFileName(filePath);
|
||||
if (file.exists()) {
|
||||
qDebug() << "File found, reading content...";
|
||||
const bool successfulOpened = file.open(QIODevice::ReadOnly | QIODevice::Text);
|
||||
if (successfulOpened) {
|
||||
// TODO learn and decide on the differences between "readAll" and using
|
||||
// streams
|
||||
fileContent = file.readAll();
|
||||
file.close();
|
||||
} else {
|
||||
errorString = "File could not be opened!";
|
||||
qWarning() << errorString;
|
||||
}
|
||||
} else {
|
||||
errorString = "File not found. Returning empty result...";
|
||||
qInfo() << errorString;
|
||||
}
|
||||
|
||||
const QPair<QString, QByteArray> result(errorString, fileContent);
|
||||
return result;
|
||||
}
|
||||
28
libs/GenericCore/data/filehandler.h
Normal file
@ -0,0 +1,28 @@
|
||||
#ifndef FILEHANDLER_H
|
||||
#define FILEHANDLER_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class QJsonDocument;
|
||||
class QString;
|
||||
class QByteArray;
|
||||
|
||||
class FileHandler {
|
||||
public:
|
||||
/// JSON
|
||||
static bool saveToFile(const QJsonDocument& doc, const QString& fileName);
|
||||
static QByteArray loadJSONDataFromFile(const QString fileName);
|
||||
|
||||
/// CSV
|
||||
static QList<ModelItemValues> getItemValuesFromCSVFile(const QString& filePath);
|
||||
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
|
||||
|
||||
private:
|
||||
explicit FileHandler();
|
||||
|
||||
static QPair<QString, QByteArray> getFileContent(const QString& filePath);
|
||||
};
|
||||
|
||||
#endif // FILEHANDLER_H
|
||||
43
libs/GenericCore/data/settingshandler.cpp
Normal file
@ -0,0 +1,43 @@
|
||||
#include "settingshandler.h"
|
||||
|
||||
#include <QSettings>
|
||||
|
||||
QVariantMap SettingsHandler::getSettings(QString group) {
|
||||
QSettings settings;
|
||||
QVariantMap result;
|
||||
|
||||
if (!group.isEmpty()) {
|
||||
settings.beginGroup(group);
|
||||
}
|
||||
|
||||
foreach (QString key, settings.allKeys()) {
|
||||
result.insert(key, settings.value(key));
|
||||
}
|
||||
|
||||
if (!group.isEmpty()) {
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void SettingsHandler::saveSettings(QVariantMap settingMap, QString group) {
|
||||
qInfo() << "saving settings...";
|
||||
|
||||
QSettings settings;
|
||||
if (!group.isEmpty()) {
|
||||
settings.beginGroup(group);
|
||||
}
|
||||
|
||||
foreach (QString key, settingMap.keys()) {
|
||||
// qDebug() << "saving:" << key << "-" << settingMap.value(key);
|
||||
settings.setValue(key, settingMap.value(key));
|
||||
}
|
||||
if (!group.isEmpty()) {
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
settings.sync();
|
||||
}
|
||||
|
||||
SettingsHandler::SettingsHandler() {}
|
||||
15
libs/GenericCore/data/settingshandler.h
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef SETTINGSHANDLER_H
|
||||
#define SETTINGSHANDLER_H
|
||||
|
||||
#include <QVariantMap>
|
||||
|
||||
class SettingsHandler {
|
||||
public:
|
||||
static QVariantMap getSettings(QString group = "");
|
||||
static void saveSettings(QVariantMap settingMap, QString group = "");
|
||||
|
||||
private:
|
||||
SettingsHandler();
|
||||
};
|
||||
|
||||
#endif // SETTINGSHANDLER_H
|
||||
158
libs/GenericCore/formats/csvparser.cpp
Normal file
@ -0,0 +1,158 @@
|
||||
#include "csvparser.h"
|
||||
|
||||
#include <QHash>
|
||||
#include <QLocale>
|
||||
#include <QVariant>
|
||||
|
||||
#include "../../3rdParty/rapidcsv/src/rapidcsv.h"
|
||||
#include "../model/metadata.h"
|
||||
|
||||
using namespace rapidcsv;
|
||||
|
||||
QList<ModelItemValues> CsvParser::getItemsFromCSVFile(const QString& fileName) {
|
||||
Document doc(fileName.toStdString());
|
||||
|
||||
const bool isCompatible = isCsvCompatible(doc);
|
||||
if (isCompatible) {
|
||||
const QList<ModelItemValues> result = createListItemsFromCsvEntries(doc);
|
||||
return result;
|
||||
} else {
|
||||
return QList<ModelItemValues>();
|
||||
}
|
||||
}
|
||||
|
||||
bool CsvParser::exportToCSVFile(const QList<QStringList>& rows, const QString& filePath) {
|
||||
Document doc(std::string(), LabelParams(0, -1));
|
||||
const QList<QString> headerNames = GET_HEADER_NAMES();
|
||||
for (int column = 0; column < headerNames.size(); ++column) {
|
||||
doc.SetColumnName(column, headerNames.at(column).toStdString());
|
||||
}
|
||||
for (int row = 0; row < rows.size(); ++row) {
|
||||
QStringList rowValues = rows.at(row);
|
||||
std::vector<std::string> rowValueStrings;
|
||||
for (int column = 0; column < rowValues.size(); ++column) {
|
||||
rowValueStrings.push_back(rowValues.at(column).toStdString());
|
||||
}
|
||||
doc.InsertRow(row, rowValueStrings);
|
||||
}
|
||||
doc.Save(filePath.toStdString());
|
||||
return true;
|
||||
}
|
||||
|
||||
CsvParser::CsvParser() {}
|
||||
|
||||
/** A CSV file is compatible if the following is true:
|
||||
* - there is a CSV column for every column in the table model
|
||||
* (except there are optional columns defined in the model)
|
||||
* @brief CsvParser::isCsvCompatible
|
||||
* @param doc
|
||||
* @return
|
||||
*/
|
||||
bool CsvParser::isCsvCompatible(const rapidcsv::Document& doc) {
|
||||
qInfo() << "Checking CSV document for compatiblity...";
|
||||
const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
for (const QString& headerName : GET_HEADER_NAMES()) {
|
||||
bool isHeaderNameFound = false;
|
||||
if (std::find(columnNames.begin(), columnNames.end(), headerName) != columnNames.end()) {
|
||||
qDebug() << QString("Header found in column names: %1").arg(headerName);
|
||||
} else {
|
||||
const QString errorString =
|
||||
QString("Couldn't find header name '%1' in CSV file. Aborting...").arg(headerName);
|
||||
qWarning() << errorString;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
QList<ModelItemValues> CsvParser::createListItemsFromCsvEntries(const rapidcsv::Document& doc) {
|
||||
QList<ModelItemValues> result;
|
||||
const int rowCount = doc.GetRowCount();
|
||||
const QList<QString> headerNames = GET_HEADER_NAMES();
|
||||
|
||||
/// get the values for all columns
|
||||
QHash<QString, std::vector<std::string>> columnValueMap = extractColumnValues(headerNames, doc);
|
||||
|
||||
/// get item values for each row
|
||||
for (int row = 0; row < rowCount; ++row) {
|
||||
const ModelItemValues itemValues = getItemValuesForRow(headerNames, columnValueMap, row);
|
||||
result.append(itemValues);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QHash<QString, std::vector<std::string>> CsvParser::extractColumnValues(
|
||||
const QList<QString> headerNames,
|
||||
const rapidcsv::Document& doc) {
|
||||
QHash<QString, std::vector<std::string>> columnValueMap;
|
||||
for (const QString& columnName : headerNames) {
|
||||
// TODO add support for optional columns
|
||||
// if (optionalCsvHeaderNames.contains(columnName)) {
|
||||
// const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
// int columnIdx = doc.GetColumnIdx(columnName.toStdString());
|
||||
// if (columnIdx == -1) {
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
const std::vector<std::string> columnValues =
|
||||
doc.GetColumn<std::string>(columnName.toStdString());
|
||||
columnValueMap.insert(columnName, columnValues);
|
||||
}
|
||||
|
||||
return columnValueMap;
|
||||
}
|
||||
|
||||
ModelItemValues CsvParser::getItemValuesForRow(
|
||||
const QList<QString>& headerNames,
|
||||
const QHash<QString, std::vector<std::string>>& columnValueMap,
|
||||
const int row) {
|
||||
ModelItemValues result;
|
||||
for (const QString& columnName : headerNames) {
|
||||
if (!columnValueMap.contains(columnName)) {
|
||||
continue;
|
||||
}
|
||||
int role = ROLE_NAMES.key(columnName.toLatin1());
|
||||
std::string valueString = columnValueMap.value(columnName).at(row);
|
||||
|
||||
QVariant value = parseItemValue(role, valueString);
|
||||
if (value.isValid()) {
|
||||
result[role] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QVariant CsvParser::parseItemValue(const int role, const std::string& valueString) {
|
||||
QVariant result;
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
/// string values
|
||||
result = QString::fromStdString(valueString);
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
/// int values
|
||||
|
||||
/// GetColumn<int> crashed (probably because of the empty values)
|
||||
/// so the strings will be processed later
|
||||
const QString intAsString = QString::fromStdString(valueString);
|
||||
result = intAsString.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
/// double values
|
||||
const QString doubleAsString = QString::fromStdString(valueString);
|
||||
double doubleValue;
|
||||
if (doubleAsString.contains(',')) {
|
||||
QLocale german(QLocale::German);
|
||||
doubleValue = german.toDouble(doubleAsString);
|
||||
} else {
|
||||
doubleValue = doubleAsString.toDouble();
|
||||
}
|
||||
result = doubleValue;
|
||||
|
||||
// } else if (typeColumns.contains(columnName)) {
|
||||
// // TODO validate string is allowed
|
||||
// values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row));
|
||||
} else {
|
||||
/// no type recognized for column
|
||||
QString errorString = QString("Couldn't find value type for role '%1'").arg(role);
|
||||
qCritical() << errorString;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
32
libs/GenericCore/formats/csvparser.h
Normal file
@ -0,0 +1,32 @@
|
||||
#ifndef CSVPARSER_H
|
||||
#define CSVPARSER_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
namespace rapidcsv {
|
||||
class Document;
|
||||
}
|
||||
|
||||
class CsvParser {
|
||||
public:
|
||||
static QList<ModelItemValues> getItemsFromCSVFile(const QString& fileName);
|
||||
static bool exportToCSVFile(const QList<QStringList>& rows, const QString& filePath);
|
||||
|
||||
private:
|
||||
explicit CsvParser();
|
||||
|
||||
static bool isCsvCompatible(const rapidcsv::Document& doc);
|
||||
static QList<ModelItemValues> createListItemsFromCsvEntries(const rapidcsv::Document& doc);
|
||||
static QHash<QString, std::vector<std::string>> extractColumnValues(
|
||||
const QList<QString> headerNames,
|
||||
const rapidcsv::Document& doc);
|
||||
static ModelItemValues getItemValuesForRow(
|
||||
const QList<QString>& headerNames,
|
||||
const QHash<QString, std::vector<std::string>>& columnValueMap,
|
||||
const int row);
|
||||
static QVariant parseItemValue(const int role, const std::string& valueString);
|
||||
};
|
||||
|
||||
#endif // CSVPARSER_H
|
||||
119
libs/GenericCore/formats/jsonparser.cpp
Normal file
@ -0,0 +1,119 @@
|
||||
#include "jsonparser.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "../model/metadata.h"
|
||||
|
||||
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& rootValueName) {
|
||||
QList<ModelItemValues> result;
|
||||
|
||||
if (jsonData.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
// TODO tidy up the following code and encapsulate into functions;
|
||||
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
|
||||
/// case one: json value name in plural -> should contain an array of items
|
||||
if (rootValueName == ITEMS_KEY_STRING) {
|
||||
QJsonArray itemArray = extractItemArray(doc, rootValueName);
|
||||
|
||||
foreach (QJsonValue value, itemArray) {
|
||||
QJsonObject itemJsonObject = value.toObject();
|
||||
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
|
||||
result.append(values);
|
||||
}
|
||||
}
|
||||
/// case two: json value name in singular -> should contain an object of one item
|
||||
if (rootValueName == ITEM_KEY_STRING) {
|
||||
QJsonObject rootObject = doc.object();
|
||||
QJsonObject itemJsonObject = rootObject.value(rootValueName).toObject();
|
||||
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
|
||||
result.append(values);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
|
||||
const QString& objectName) {
|
||||
QJsonDocument jsonDoc;
|
||||
QJsonObject rootObject;
|
||||
QJsonArray itemArray;
|
||||
for (const ModelItemValues& itemValues : itemValuesList) {
|
||||
QJsonObject itemObject;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = itemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
|
||||
itemArray.append(itemObject);
|
||||
}
|
||||
|
||||
rootObject.insert(objectName, itemArray);
|
||||
jsonDoc.setObject(rootObject);
|
||||
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
JsonParser::JsonParser() {}
|
||||
|
||||
QJsonArray JsonParser::extractItemArray(const QJsonDocument& doc, const QString& objectName) {
|
||||
QJsonArray itemArray;
|
||||
if (objectName.isEmpty()) {
|
||||
itemArray = doc.array();
|
||||
} else {
|
||||
QJsonObject rootObject = doc.object();
|
||||
itemArray = rootObject.value(objectName).toArray();
|
||||
}
|
||||
return itemArray;
|
||||
}
|
||||
|
||||
ModelItemValues JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
|
||||
ModelItemValues values;
|
||||
|
||||
const UserRoles idRole = IdRole;
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
// QVariant idValue = data(idRole);
|
||||
if (itemJsonObject.contains(idRoleName)) {
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, idRole);
|
||||
values.insert(keyValuePair.first, keyValuePair.second);
|
||||
}
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, role);
|
||||
values.insert(keyValuePair.first, keyValuePair.second);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
pair<int, QVariant> JsonParser::getKeyValuePair(const QJsonObject& itemJsonObject, const int role) {
|
||||
QVariant result;
|
||||
const QJsonValue jsonValue = itemJsonObject[ROLE_NAMES.value(role)];
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
result = jsonValue.toString();
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
result = jsonValue.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
result = jsonValue.toDouble();
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
return pair<int, QVariant>(role, result);
|
||||
}
|
||||
31
libs/GenericCore/formats/jsonparser.h
Normal file
@ -0,0 +1,31 @@
|
||||
#ifndef JSONPARSER_H
|
||||
#define JSONPARSER_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
class QJsonObject;
|
||||
class QString;
|
||||
class QByteArray;
|
||||
class QJsonArray;
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
using namespace std;
|
||||
|
||||
class JsonParser {
|
||||
public:
|
||||
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& rootValueName = "");
|
||||
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
|
||||
const QString& objectName = "");
|
||||
|
||||
private:
|
||||
explicit JsonParser();
|
||||
|
||||
static QJsonArray extractItemArray(const QJsonDocument& doc, const QString& objectName);
|
||||
static ModelItemValues jsonObjectToItemValues(const QJsonObject& itemJsonObject);
|
||||
|
||||
static pair<int, QVariant> getKeyValuePair(const QJsonObject& itemJsonObject, const int role);
|
||||
};
|
||||
|
||||
#endif // JSONPARSER_H
|
||||
281
libs/GenericCore/genericcore.cpp
Normal file
@ -0,0 +1,281 @@
|
||||
#include "genericcore.h"
|
||||
|
||||
#include <QAbstractItemModelTester>
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QJsonDocument>
|
||||
#include <QProcess>
|
||||
#include <QSettings>
|
||||
#include <QString>
|
||||
|
||||
#include "../../ApplicationConfig.h"
|
||||
#include "CoreConfig.h"
|
||||
#include "constants.h"
|
||||
#include "data/filehandler.h"
|
||||
#include "data/settingshandler.h"
|
||||
#include "model/generalsortfiltermodel.h"
|
||||
#include "model/metadata.h"
|
||||
#include "model/tablemodel.h"
|
||||
#include "network/servercommunicator.h"
|
||||
|
||||
#include <QtGui/QUndoStack>
|
||||
|
||||
using namespace std;
|
||||
|
||||
GenericCore::GenericCore() {
|
||||
qDebug() << "Creating core...";
|
||||
|
||||
QCoreApplication::setOrganizationName("Working-Copy Collective");
|
||||
QCoreApplication::setOrganizationDomain("working-copy.org");
|
||||
|
||||
#ifdef QT_DEBUG
|
||||
QCoreApplication::setApplicationName(QString(APPLICATION_NAME) + "-dev");
|
||||
#else
|
||||
QCoreApplication::setApplicationName(QString(APPLICATION_NAME));
|
||||
#endif
|
||||
|
||||
// TODO let the model own its undo stack (& use TableModel::getUndoStack() if necessary)
|
||||
m_modelUndoStack = new QUndoStack(this);
|
||||
|
||||
setupModels();
|
||||
setupServerConfiguration();
|
||||
}
|
||||
|
||||
GenericCore::~GenericCore() { qDebug() << "Destroying core..."; }
|
||||
|
||||
QString GenericCore::toString() const {
|
||||
return QString("%1 (Version %2)").arg(CORE_NAME).arg(CORE_VERSION);
|
||||
}
|
||||
|
||||
void GenericCore::sayHello() const { qDebug() << "Hello from the core!"; }
|
||||
|
||||
bool GenericCore::isApplicationUpdateAvailable() {
|
||||
QProcess process;
|
||||
const QString programmString = getMaintenanceToolFilePath();
|
||||
const QStringList checkArgs("--checkupdates");
|
||||
process.start(programmString, checkArgs);
|
||||
process.waitForFinished();
|
||||
|
||||
const int exitCode = process.exitCode();
|
||||
if (process.error() != QProcess::UnknownError) {
|
||||
qDebug() << "Error checking for updates";
|
||||
emit displayStatusMessage("Error checking for updates");
|
||||
return false;
|
||||
}
|
||||
|
||||
QByteArray data = process.readAllStandardOutput();
|
||||
|
||||
QSettings settings;
|
||||
settings.beginGroup("Application");
|
||||
settings.setValue("lastCheckForUpdate", QDateTime::currentDateTimeUtc());
|
||||
settings.endGroup();
|
||||
settings.sync();
|
||||
|
||||
if (data.isEmpty() || data.contains("currently no updates")) {
|
||||
qInfo() << "No updates available";
|
||||
emit displayStatusMessage("No updates available.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void GenericCore::triggerApplicationUpdate(const bool saveChanges) {
|
||||
if (saveChanges && !m_modelUndoStack->isClean()) {
|
||||
saveItems();
|
||||
}
|
||||
QStringList args("--start-updater");
|
||||
QString toolFilePath = getMaintenanceToolFilePath();
|
||||
QProcess::startDetached(toolFilePath, args);
|
||||
}
|
||||
|
||||
QUndoStack* GenericCore::getModelUndoStack() const { return m_modelUndoStack; }
|
||||
|
||||
std::shared_ptr<TableModel> GenericCore::getModel() const { return m_mainModel; }
|
||||
|
||||
std::shared_ptr<GeneralSortFilterModel> GenericCore::getSortFilterModel() const {
|
||||
return m_sortFilterModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save items to default file (in standard location).
|
||||
* @brief GenericCore::saveItems Saves item fo file.
|
||||
*/
|
||||
void GenericCore::saveItems() {
|
||||
qDebug() << "saving items...";
|
||||
|
||||
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
|
||||
const bool successfulSave = FileHandler::saveToFile(doc, ITEMS_FILE_NAME);
|
||||
if (successfulSave) {
|
||||
m_modelUndoStack->setClean();
|
||||
emit displayStatusMessage(QString("Items saved."));
|
||||
} else {
|
||||
emit displayStatusMessage(QString("Error: Items couldn't be saved."));
|
||||
}
|
||||
}
|
||||
|
||||
void GenericCore::importCSVFile(const QString& filePath) {
|
||||
qInfo() << "importing items from CSV...";
|
||||
qDebug() << "filePath:" << filePath;
|
||||
const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath);
|
||||
// TODO inform UI on errors
|
||||
if (itemValuesList.isEmpty()) {
|
||||
qDebug() << "No items found. Doing nothing...";
|
||||
return;
|
||||
}
|
||||
// qDebug() << "CSV file content:" << itemValuesList;
|
||||
m_mainModel->insertItems(m_mainModel->rowCount(), itemValuesList);
|
||||
}
|
||||
|
||||
bool GenericCore::exportCSVFile(const QString& filePath) {
|
||||
qInfo() << "exporting items to CSV...";
|
||||
qDebug() << "filePath:" << filePath;
|
||||
const QList<QStringList> itemsAsStringLists = m_mainModel->getItemsAsStringLists();
|
||||
return FileHandler::exportToCSVFile(itemsAsStringLists, filePath);
|
||||
}
|
||||
|
||||
QVariantMap GenericCore::getSettings(QString group) const {
|
||||
return SettingsHandler::getSettings(group);
|
||||
}
|
||||
|
||||
void GenericCore::applySettings(QVariantMap settingMap, QString group) {
|
||||
SettingsHandler::saveSettings(settingMap, group);
|
||||
|
||||
if (group == "Server") {
|
||||
setupServerConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
bool GenericCore::isSyncServerSetup() const {
|
||||
if (m_serverCommunicator) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void GenericCore::onSendItemTriggered(const QByteArray& jsonData) {
|
||||
m_serverCommunicator->postItems(jsonData);
|
||||
}
|
||||
|
||||
void GenericCore::onItemsFetched(const QByteArray jsonData) {
|
||||
emit displayStatusMessage("New items fetched.");
|
||||
// TODO ? check compability of JSON structure beforehand?
|
||||
// NEXT check if item already exists and apply changes (UUID,...) ? ;
|
||||
m_mainModel->appendItems(jsonData);
|
||||
}
|
||||
|
||||
void GenericCore::onItemsFetchFailure(const QString errorString) {
|
||||
emit displayStatusMessage(QString("Error: %1").arg(errorString));
|
||||
}
|
||||
|
||||
void GenericCore::onPostRequestSuccessful(const QByteArray responseData) {
|
||||
const QString message = m_mainModel->updateItemsFromJson(responseData);
|
||||
emit displayStatusMessage(message);
|
||||
}
|
||||
|
||||
void GenericCore::onPostRequestFailure(const QString errorString) {
|
||||
emit displayStatusMessage(QString("Error: %1").arg(errorString));
|
||||
}
|
||||
|
||||
void GenericCore::onDeleteRequestSuccessful(const QByteArray responseData) {
|
||||
qWarning() << "TODO: Process success response!!!";
|
||||
}
|
||||
|
||||
void GenericCore::onDeleteRequestFailure(const QString errorString) {
|
||||
qWarning() << "TODO: Process error response!!!";
|
||||
}
|
||||
|
||||
void GenericCore::setupModels() {
|
||||
m_mainModel = make_shared<TableModel>(m_modelUndoStack, this);
|
||||
m_sortFilterModel = make_shared<GeneralSortFilterModel>(m_mainModel);
|
||||
|
||||
/// QAbstractItemModelTester
|
||||
#ifdef QT_DEBUG
|
||||
m_mainModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
|
||||
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
|
||||
#else
|
||||
m_mainModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
|
||||
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
|
||||
#endif
|
||||
|
||||
initModelData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializing model with data. Tries to read items from default file. Generating example items as
|
||||
* fallback.
|
||||
* @brief GenericCore::initModelData
|
||||
*/
|
||||
void GenericCore::initModelData() {
|
||||
qInfo() << "Trying to read model data from file...";
|
||||
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEMS_FILE_NAME);
|
||||
// qDebug() << "jsonDoc:" << jsonDoc;
|
||||
// TODO decide on lack of file(s) (config, data) if example items should be generated
|
||||
// (see welcome wizard)
|
||||
if (jsonDoc.isEmpty()) {
|
||||
qDebug() << "No item content in file. Generating example items...";
|
||||
const QByteArray exampleItems = m_mainModel->generateExampleItems();
|
||||
m_mainModel->insertItems(0, exampleItems);
|
||||
} else {
|
||||
qDebug() << "Item in file found.";
|
||||
m_mainModel->insertItems(0, jsonDoc);
|
||||
}
|
||||
m_modelUndoStack->clear();
|
||||
}
|
||||
|
||||
QString GenericCore::getMaintenanceToolFilePath() const {
|
||||
QString applicationDirPath = QCoreApplication::applicationDirPath();
|
||||
|
||||
/// setting the applicationDirPath hard coded to test update feature from IDE
|
||||
#ifdef QT_DEBUG
|
||||
applicationDirPath = QString("/opt/%1").arg(APPLICATION_NAME);
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_MAC
|
||||
applicationDirPath.append("/../../..");
|
||||
#endif
|
||||
const QString filePath = applicationDirPath + "/" + UPDATER_EXE;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
void GenericCore::setupServerConfiguration() {
|
||||
m_serverCommunicator = make_unique<ServerCommunicator>(this);
|
||||
/// request connections
|
||||
connect(this, &GenericCore::fetchItemsFromServer, m_serverCommunicator.get(),
|
||||
&ServerCommunicator::fetchItems);
|
||||
connect(this, &GenericCore::postItemToServer, this, &GenericCore::onSendItemTriggered);
|
||||
connect(this, &GenericCore::deleteItemFromServer, m_serverCommunicator.get(),
|
||||
&ServerCommunicator::deleteItem);
|
||||
|
||||
/// response connections
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetched, this,
|
||||
&GenericCore::onItemsFetched);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetchFailure, this,
|
||||
&GenericCore::onItemsFetchFailure);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::postRequestSuccessful, this,
|
||||
&GenericCore::onPostRequestSuccessful);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::postRequestFailure, this,
|
||||
&GenericCore::onPostRequestFailure);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteRequestSuccessful, this,
|
||||
&GenericCore::onDeleteRequestSuccessful);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteRequestFailure, this,
|
||||
&GenericCore::onDeleteRequestFailure);
|
||||
|
||||
applyServerConfiguration();
|
||||
}
|
||||
|
||||
void GenericCore::applyServerConfiguration() {
|
||||
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
|
||||
const QString urlValue = serverSettings.value("url").toString();
|
||||
if (!urlValue.isEmpty()) {
|
||||
const QString emailValue = serverSettings.value("email").toString();
|
||||
const QString passwordValue = serverSettings.value("password").toString();
|
||||
m_serverCommunicator->setServerConfiguration(urlValue, emailValue, passwordValue);
|
||||
}
|
||||
}
|
||||
73
libs/GenericCore/genericcore.h
Normal file
@ -0,0 +1,73 @@
|
||||
#ifndef GENERICCORE_H
|
||||
#define GENERICCORE_H
|
||||
|
||||
#include <QObject>
|
||||
|
||||
class QUndoStack;
|
||||
class QAbstractItemModel;
|
||||
class QAbstractItemModelTester;
|
||||
class QString;
|
||||
|
||||
class TableModel;
|
||||
class GeneralSortFilterModel;
|
||||
class ServerCommunicator;
|
||||
|
||||
class GenericCore : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
GenericCore();
|
||||
~GenericCore();
|
||||
|
||||
QString toString() const;
|
||||
void sayHello() const;
|
||||
|
||||
bool isApplicationUpdateAvailable();
|
||||
void triggerApplicationUpdate(const bool saveChanges);
|
||||
|
||||
QUndoStack* getModelUndoStack() const;
|
||||
std::shared_ptr<TableModel> getModel() const;
|
||||
std::shared_ptr<GeneralSortFilterModel> getSortFilterModel() const;
|
||||
|
||||
void saveItems();
|
||||
void importCSVFile(const QString& filePath);
|
||||
bool exportCSVFile(const QString& filePath);
|
||||
|
||||
QVariantMap getSettings(QString group = "") const;
|
||||
void applySettings(QVariantMap settingMap, QString group = "");
|
||||
bool isSyncServerSetup() const;
|
||||
|
||||
public slots:
|
||||
void onSendItemTriggered(const QByteArray& jsonData);
|
||||
void onItemsFetched(const QByteArray jsonData);
|
||||
void onItemsFetchFailure(const QString errorString);
|
||||
void onPostRequestSuccessful(const QByteArray responseData);
|
||||
void onPostRequestFailure(const QString errorString);
|
||||
void onDeleteRequestSuccessful(const QByteArray responseData);
|
||||
void onDeleteRequestFailure(const QString errorString);
|
||||
|
||||
signals:
|
||||
void displayStatusMessage(QString message);
|
||||
void fetchItemsFromServer();
|
||||
void postItemToServer(const QByteArray& jsonData);
|
||||
void deleteItemFromServer(const QString& id);
|
||||
|
||||
private:
|
||||
QUndoStack* m_modelUndoStack;
|
||||
std::shared_ptr<TableModel> m_mainModel;
|
||||
std::shared_ptr<GeneralSortFilterModel> m_sortFilterModel;
|
||||
std::unique_ptr<QAbstractItemModelTester> m_mainModelTester;
|
||||
std::unique_ptr<QAbstractItemModelTester> m_proxyModelTester;
|
||||
|
||||
void setupModels();
|
||||
void initModelData();
|
||||
|
||||
QString getMaintenanceToolFilePath() const;
|
||||
|
||||
/// Network communication
|
||||
std::unique_ptr<ServerCommunicator> m_serverCommunicator;
|
||||
void setupServerConfiguration();
|
||||
void applyServerConfiguration();
|
||||
};
|
||||
|
||||
#endif // GENERICCORE_H
|
||||
80
libs/GenericCore/model/commands/edititemcommand.cpp
Normal file
@ -0,0 +1,80 @@
|
||||
#include "edititemcommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../metadata.h"
|
||||
#include "../tablemodel.h"
|
||||
|
||||
EditItemCommand::EditItemCommand(TableModel* model,
|
||||
const QModelIndex& index,
|
||||
QMap<int, QVariant>& changedValues,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_model(model)
|
||||
, m_row(index.row()) {
|
||||
qInfo() << "New EditCommand...";
|
||||
QString commandText;
|
||||
|
||||
if (changedValues.size() == 1) {
|
||||
qDebug() << "Only one value to change. Using more specific command text...";
|
||||
const int role = changedValues.firstKey();
|
||||
const QVariant value = changedValues.first();
|
||||
QString roleName = model->roleNames().value(role);
|
||||
|
||||
if (USER_FACING_ROLES.contains(role)) {
|
||||
commandText = QString("Setting '%1' of item '%2' to '%3'")
|
||||
.arg(roleName)
|
||||
.arg(index.data(DEFAULT_ROLE).toString())
|
||||
.arg(value.toString());
|
||||
} else if (role == IdRole) {
|
||||
commandText = QString("Setting '%1' of item '%2' to '%3'")
|
||||
.arg(roleName)
|
||||
.arg(index.data(DEFAULT_ROLE).toString())
|
||||
.arg(value.toString());
|
||||
} else {
|
||||
qWarning() << "Role didn't match! Using a generic command text...";
|
||||
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
|
||||
}
|
||||
} else {
|
||||
qDebug() << "More than one value to change. Using a generic command text...";
|
||||
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
|
||||
}
|
||||
setText(commandText);
|
||||
|
||||
m_newValues = changedValues;
|
||||
|
||||
/// storing old values for undo step
|
||||
m_oldValues = getOldValues(index, changedValues);
|
||||
}
|
||||
|
||||
void EditItemCommand::undo() {
|
||||
qDebug() << "Undoing the EditCommand...";
|
||||
m_model->execEditItemData(m_row, m_oldValues);
|
||||
}
|
||||
|
||||
void EditItemCommand::redo() {
|
||||
qDebug() << "(Re-)doing the EditCommand...";
|
||||
m_model->execEditItemData(m_row, m_newValues);
|
||||
}
|
||||
|
||||
const QMap<int, QVariant> EditItemCommand::getOldValues(
|
||||
const QModelIndex& index,
|
||||
const QMap<int, QVariant>& changedValues) const {
|
||||
QMap<int, QVariant> result;
|
||||
QMap<int, QVariant>::const_iterator i;
|
||||
for (i = changedValues.constBegin(); i != changedValues.constEnd(); ++i) {
|
||||
const int role = i.key();
|
||||
const QVariant newValue = i.value();
|
||||
const QVariant oldValue = index.data(role);
|
||||
// TODO check if role is a editable role?
|
||||
if (oldValue != newValue) {
|
||||
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
|
||||
result.insert(role, oldValue);
|
||||
} else {
|
||||
qInfo() << "oldValue is already the same as newValue:" << oldValue;
|
||||
}
|
||||
}
|
||||
// QVariant oldModifiedDate = index.data(ModifiedDateUTCRole);
|
||||
// result.insert(ModifiedDateUTCRole, oldModifiedDate);
|
||||
return result;
|
||||
}
|
||||
33
libs/GenericCore/model/commands/edititemcommand.h
Normal file
@ -0,0 +1,33 @@
|
||||
#ifndef EDITITEMCOMMAND_H
|
||||
#define EDITITEMCOMMAND_H
|
||||
|
||||
#include <QMap>
|
||||
#include <QUndoCommand>
|
||||
|
||||
class TableModel;
|
||||
|
||||
class EditItemCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
EditItemCommand(TableModel* model,
|
||||
const QModelIndex& index,
|
||||
QMap<int, QVariant>& changedValues,
|
||||
QUndoCommand* parent = nullptr);
|
||||
/// QUndoCommand interface
|
||||
void undo();
|
||||
void redo();
|
||||
|
||||
private:
|
||||
TableModel* m_model = nullptr;
|
||||
const int m_row;
|
||||
QMap<int, QVariant> m_oldValues;
|
||||
QMap<int, QVariant> m_newValues;
|
||||
|
||||
/// private functions
|
||||
const QMap<int, QVariant> getOldValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& changedValues) const;
|
||||
};
|
||||
|
||||
#endif // EDITITEMCOMMAND_H
|
||||
33
libs/GenericCore/model/commands/insertrowscommand.cpp
Normal file
@ -0,0 +1,33 @@
|
||||
#include "insertrowscommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../tablemodel.h"
|
||||
|
||||
InsertRowsCommand::InsertRowsCommand(TableModel* model,
|
||||
int startRow,
|
||||
QList<ModelItemValues> valueList,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_tableModel(model)
|
||||
, m_startRow(startRow)
|
||||
, m_valueList(valueList) {
|
||||
qInfo() << "New InsertCommand...";
|
||||
const QString commandText =
|
||||
QString("inserting %1 item(s) on row %2").arg(valueList.length()).arg(startRow);
|
||||
setText(commandText);
|
||||
}
|
||||
|
||||
void InsertRowsCommand::undo() {
|
||||
qDebug() << "Undoing the InsertCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
|
||||
}
|
||||
}
|
||||
|
||||
void InsertRowsCommand::redo() {
|
||||
qDebug() << "(Re-)doing the InsertCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execInsertItems(m_startRow, m_valueList);
|
||||
}
|
||||
}
|
||||
30
libs/GenericCore/model/commands/insertrowscommand.h
Normal file
@ -0,0 +1,30 @@
|
||||
#ifndef INSERTROWSCOMMAND_H
|
||||
#define INSERTROWSCOMMAND_H
|
||||
|
||||
#include <QUndoCommand>
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel;
|
||||
|
||||
class InsertRowsCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
InsertRowsCommand(TableModel* model,
|
||||
int startRow,
|
||||
QList<ModelItemValues> valueList,
|
||||
QUndoCommand* parent = nullptr);
|
||||
|
||||
/// QUndoCommand interface
|
||||
void undo() override;
|
||||
void redo() override;
|
||||
|
||||
private:
|
||||
TableModel* m_tableModel;
|
||||
const int m_startRow;
|
||||
const QList<ModelItemValues> m_valueList;
|
||||
};
|
||||
|
||||
#endif // INSERTROWSCOMMAND_H
|
||||
41
libs/GenericCore/model/commands/removerowscommand.cpp
Normal file
@ -0,0 +1,41 @@
|
||||
#include "removerowscommand.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
#include "../tablemodel.h"
|
||||
|
||||
RemoveRowsCommand::RemoveRowsCommand(TableModel* model,
|
||||
const int startRow,
|
||||
const int nRows,
|
||||
QUndoCommand* parent)
|
||||
: QUndoCommand(parent)
|
||||
, m_tableModel(model)
|
||||
, m_startRow(startRow) {
|
||||
qInfo() << "New RemoveCommand...";
|
||||
const QString commandText =
|
||||
QString("removing %1 item(s) on position %2").arg(nRows).arg(startRow);
|
||||
setText(commandText);
|
||||
|
||||
for (int row = 0; row < nRows; ++row) {
|
||||
const int rowPosition = startRow + row;
|
||||
QModelIndex index = m_tableModel->index(rowPosition, 0);
|
||||
|
||||
ModelItemValues values = m_tableModel->getItemValues(index);
|
||||
|
||||
m_valueList.append(values);
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveRowsCommand::undo() {
|
||||
qDebug() << "Undoing the RemoveCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execInsertItems(m_startRow, m_valueList);
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveRowsCommand::redo() {
|
||||
qDebug() << "(Re-)doing the RemoveCommand...";
|
||||
if (m_tableModel) {
|
||||
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
|
||||
}
|
||||
}
|
||||
30
libs/GenericCore/model/commands/removerowscommand.h
Normal file
@ -0,0 +1,30 @@
|
||||
#ifndef REMOVEROWSCOMMAND_H
|
||||
#define REMOVEROWSCOMMAND_H
|
||||
|
||||
#include <QUndoCommand>
|
||||
|
||||
class TableModel;
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class RemoveRowsCommand : public QUndoCommand {
|
||||
public:
|
||||
// TODO don't use simple pointer to model
|
||||
/// Using simple pointer to model because there was a crash when closing the application with an
|
||||
/// unclean undo stack
|
||||
RemoveRowsCommand(TableModel* model,
|
||||
const int startRow,
|
||||
const int nRows,
|
||||
QUndoCommand* parent = nullptr);
|
||||
|
||||
/// QUndoCommand interface
|
||||
void undo() override;
|
||||
void redo() override;
|
||||
|
||||
private:
|
||||
TableModel* m_tableModel;
|
||||
const int m_startRow;
|
||||
QList<ModelItemValues> m_valueList;
|
||||
};
|
||||
|
||||
#endif // REMOVEROWSCOMMAND_H
|
||||
105
libs/GenericCore/model/generalsortfiltermodel.cpp
Normal file
@ -0,0 +1,105 @@
|
||||
#include "generalsortfiltermodel.h"
|
||||
#include "metadata.h"
|
||||
|
||||
#include <QItemSelection>
|
||||
|
||||
GeneralSortFilterModel::GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel)
|
||||
: QSortFilterProxyModel{sourceModel.get()}
|
||||
, m_tableModel(sourceModel) {
|
||||
setSourceModel(sourceModel.get());
|
||||
|
||||
m_collator.setNumericMode(true);
|
||||
}
|
||||
|
||||
QItemSelection GeneralSortFilterModel::findItems(const QString& text) const {
|
||||
QItemSelection result;
|
||||
|
||||
for (int i = 0; i < rowCount(); ++i) {
|
||||
const QModelIndex localIndex = index(i, 0);
|
||||
if (indexContainsText(localIndex, text)) {
|
||||
result.select(localIndex, index(i, columnCount() - 1)); /// select entire row
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QString GeneralSortFilterModel::getUuid(const QModelIndex& itemIndex) const {
|
||||
return data(itemIndex, IdRole).toString();
|
||||
}
|
||||
|
||||
QByteArray GeneralSortFilterModel::jsonDataForServer(const QModelIndex& proxyIndex) {
|
||||
const QModelIndex sourceIndex = mapToSource(proxyIndex);
|
||||
return m_tableModel->jsonDataForServer(sourceIndex);
|
||||
}
|
||||
|
||||
void GeneralSortFilterModel::appendItems(const QByteArray& jsonDoc) {
|
||||
m_tableModel->appendItems(jsonDoc);
|
||||
}
|
||||
|
||||
bool GeneralSortFilterModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
|
||||
const QModelIndex proxyIndex = index(firstRow, 0, parentIndex);
|
||||
const QModelIndex sourceIndex = mapToSource(proxyIndex);
|
||||
return m_tableModel->removeRows(sourceIndex.row(), nRows, sourceIndex.parent());
|
||||
}
|
||||
|
||||
bool GeneralSortFilterModel::lessThan(const QModelIndex& source_left,
|
||||
const QModelIndex& source_right) const {
|
||||
if (source_left.column() != source_right.column()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QAbstractItemModel* localSourceModel = sourceModel();
|
||||
const int role = GET_ROLE_FOR_COLUMN(source_left.column());
|
||||
const QVariant leftData = localSourceModel->data(source_left);
|
||||
const QVariant rightData = localSourceModel->data(source_right);
|
||||
|
||||
const bool isText = STRING_ROLES.contains(role);
|
||||
if (isText) {
|
||||
const QString leftString = leftData.toString();
|
||||
const QString rightString = rightData.toString();
|
||||
return m_collator.compare(leftString, rightString) > 0;
|
||||
}
|
||||
const bool isInt = INT_ROLES.contains(role);
|
||||
if (isInt) {
|
||||
const int leftInt = leftData.toInt();
|
||||
const int rightInt = rightData.toInt();
|
||||
return leftInt > rightInt;
|
||||
}
|
||||
const bool isDouble = DOUBLE_ROLES.contains(role);
|
||||
if (isDouble) {
|
||||
const int leftInt = leftData.toDouble();
|
||||
const int rightInt = rightData.toDouble();
|
||||
return leftInt > rightInt;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool GeneralSortFilterModel::indexContainsText(const QModelIndex& index,
|
||||
const QString& text) const {
|
||||
// iterate over USER_FACING_ROLES and call roleDataContainsText(...);
|
||||
// ...for each until text is found or no more roles to check;
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const bool isTextFound = roleDataContainsText(index, role, text);
|
||||
if (isTextFound) {
|
||||
// qInfo() << "Text is found in role:" << role;
|
||||
return true;
|
||||
// } else {
|
||||
// qDebug() << QString("Can't find text in role %1. Continuing search...").arg(role);
|
||||
}
|
||||
}
|
||||
// qWarning() << "Text not found in any role. Returning false...";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool GeneralSortFilterModel::roleDataContainsText(const QModelIndex& index,
|
||||
const int role,
|
||||
const QString& text) const {
|
||||
const QString dataString = index.data(role).toString();
|
||||
if (dataString.contains(text, Qt::CaseInsensitive)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
39
libs/GenericCore/model/generalsortfiltermodel.h
Normal file
@ -0,0 +1,39 @@
|
||||
#ifndef GENERALSORTFILTERMODEL_H
|
||||
#define GENERALSORTFILTERMODEL_H
|
||||
|
||||
#include <QCollator>
|
||||
#include <QSortFilterProxyModel>
|
||||
|
||||
#include "tablemodel.h"
|
||||
|
||||
class GeneralSortFilterModel : public QSortFilterProxyModel {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit GeneralSortFilterModel(std::shared_ptr<TableModel> sourceModel = nullptr);
|
||||
|
||||
/** Returns a QItemSelection with all ModelIndexes which contain the given text.
|
||||
* @brief Returns QItemSelection containing all successful ModelIndex results
|
||||
* @param text To search for
|
||||
* @return QItemSelection containing all successful ModelIndex results
|
||||
*/
|
||||
QItemSelection findItems(const QString& text) const;
|
||||
QString getUuid(const QModelIndex& itemIndex) const;
|
||||
|
||||
QByteArray jsonDataForServer(const QModelIndex& proxyIndex);
|
||||
|
||||
public slots:
|
||||
void appendItems(const QByteArray& jsonDoc);
|
||||
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
|
||||
/// QSortFilterProxyModel interface
|
||||
protected:
|
||||
bool lessThan(const QModelIndex& sourceLeft, const QModelIndex& sourceRight) const override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<TableModel> m_tableModel;
|
||||
QCollator m_collator; /// for sorting
|
||||
|
||||
bool indexContainsText(const QModelIndex& index, const QString& text) const;
|
||||
bool roleDataContainsText(const QModelIndex& index, const int role, const QString& text) const;
|
||||
};
|
||||
|
||||
#endif // GENERALSORTFILTERMODEL_H
|
||||
77
libs/GenericCore/model/metadata.h
Normal file
@ -0,0 +1,77 @@
|
||||
#ifndef METADATA_H
|
||||
#define METADATA_H
|
||||
|
||||
#include <QDebug>
|
||||
#include <QHash>
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
|
||||
// TODO add namespace
|
||||
|
||||
/// model data
|
||||
enum UserRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
DescriptionRole,
|
||||
InfoRole,
|
||||
AmountRole,
|
||||
FactorRole,
|
||||
/// Non user facing
|
||||
IdRole,
|
||||
/// read only roles
|
||||
ToStringRole,
|
||||
ToJsonRole
|
||||
};
|
||||
|
||||
static UserRoles DEFAULT_ROLE = NameRole;
|
||||
// TODO ?rename USER_FACING_ROLES -> MAIN_ROLES ?
|
||||
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, AmountRole,
|
||||
FactorRole};
|
||||
static QHash<int, QByteArray> ROLE_NAMES = {
|
||||
{NameRole, "name"}, {DescriptionRole, "description"}, {InfoRole, "info"},
|
||||
{AmountRole, "amount"}, {FactorRole, "factor"}, {ToStringRole, "ToString"},
|
||||
{IdRole, "id"}};
|
||||
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole, IdRole};
|
||||
static QList<UserRoles> INT_ROLES = {AmountRole};
|
||||
static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
|
||||
|
||||
/// JSON keys
|
||||
static const QString ITEMS_KEY_STRING = "items";
|
||||
static const QString ITEM_KEY_STRING = "item";
|
||||
|
||||
/// file naming
|
||||
static const QString ITEMS_FILE_NAME = ITEMS_KEY_STRING + ".json";
|
||||
|
||||
/// functions
|
||||
static int GET_ROLE_FOR_COLUMN(const int column) {
|
||||
switch (column) {
|
||||
case 0:
|
||||
return NameRole;
|
||||
break;
|
||||
case 1:
|
||||
return DescriptionRole;
|
||||
break;
|
||||
case 2:
|
||||
return InfoRole;
|
||||
break;
|
||||
case 3:
|
||||
return AmountRole;
|
||||
break;
|
||||
case 4:
|
||||
return FactorRole;
|
||||
break;
|
||||
default:
|
||||
qWarning() << QString("No role found for column %1! Returning 'NameRole'...").arg(column);
|
||||
return NameRole;
|
||||
break;
|
||||
}
|
||||
}
|
||||
static QList<QString> GET_HEADER_NAMES() {
|
||||
QList<QString> result;
|
||||
for (const UserRoles& role : USER_FACING_ROLES) {
|
||||
const QString headerName = ROLE_NAMES.value(role);
|
||||
result.append(headerName);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif // METADATA_H
|
||||
94
libs/GenericCore/model/modelitem.cpp
Normal file
@ -0,0 +1,94 @@
|
||||
#include "modelitem.h"
|
||||
|
||||
#include "metadata.h"
|
||||
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
|
||||
ModelItem::ModelItem(const ModelItemValues values)
|
||||
: m_values(values) {}
|
||||
|
||||
QVariant ModelItem::data(int role) const { return m_values.value(role); }
|
||||
|
||||
bool ModelItem::setData(const QVariant& value, int role) {
|
||||
bool valueChanged = false;
|
||||
if (m_values.contains(role)) {
|
||||
if (m_values.value(role) != value) {
|
||||
valueChanged = true;
|
||||
}
|
||||
}
|
||||
m_values[role] = value;
|
||||
|
||||
return valueChanged;
|
||||
}
|
||||
|
||||
bool ModelItem::setItemData(const QMap<int, QVariant>& changedValues) {
|
||||
bool valueChanged = false;
|
||||
|
||||
QMap<int, QVariant>::const_iterator citer = changedValues.constBegin();
|
||||
|
||||
while (citer != changedValues.constEnd()) {
|
||||
const int role = citer.key();
|
||||
const QVariant value = citer.value();
|
||||
|
||||
if (m_values.contains(role)) {
|
||||
if (m_values.value(role) != value) {
|
||||
valueChanged = true;
|
||||
}
|
||||
}
|
||||
m_values[role] = value;
|
||||
|
||||
citer++;
|
||||
}
|
||||
|
||||
return valueChanged;
|
||||
}
|
||||
|
||||
QString ModelItem::toString() const {
|
||||
QString result;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = data(role);
|
||||
// result.append(value.toString());
|
||||
result.append(QString("%1: %2\n").arg(roleName, data(role).toString()));
|
||||
}
|
||||
|
||||
const UserRoles idRole = IdRole;
|
||||
QVariant idValue = data(idRole);
|
||||
if (!idValue.isNull()) {
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
result.append(QString("%1: %2\n").arg(idRoleName, idValue.toString()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject ModelItem::toJsonObject() const {
|
||||
QJsonObject itemObject;
|
||||
// TODO add UUID and dates (entry, modification, end)
|
||||
const UserRoles idRole = IdRole;
|
||||
QVariant idValue = data(idRole);
|
||||
if (!idValue.isNull()) {
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
itemObject.insert(idRoleName, idValue.toString());
|
||||
}
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = data(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
return itemObject;
|
||||
}
|
||||
24
libs/GenericCore/model/modelitem.h
Normal file
@ -0,0 +1,24 @@
|
||||
#ifndef MODELITEM_H
|
||||
#define MODELITEM_H
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class ModelItem {
|
||||
public:
|
||||
ModelItem(const ModelItemValues values);
|
||||
|
||||
QVariant data(int role) const;
|
||||
bool setData(const QVariant& value, int role);
|
||||
// TODO change return value to list of changed roles
|
||||
bool setItemData(const QMap<int, QVariant>& changedValues);
|
||||
|
||||
QString toString() const;
|
||||
QJsonObject toJsonObject() const;
|
||||
|
||||
private:
|
||||
ModelItemValues m_values;
|
||||
};
|
||||
|
||||
#endif // MODELITEM_H
|
||||
390
libs/GenericCore/model/tablemodel.cpp
Normal file
@ -0,0 +1,390 @@
|
||||
#include "tablemodel.h"
|
||||
|
||||
#include "../formats/jsonparser.h"
|
||||
#include "commands/edititemcommand.h"
|
||||
#include "commands/insertrowscommand.h"
|
||||
#include "commands/removerowscommand.h"
|
||||
#include "metadata.h"
|
||||
#include "modelitem.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
QByteArray TableModel::generateExampleItems() {
|
||||
QJsonDocument doc = QJsonDocument();
|
||||
QJsonObject rootObject;
|
||||
QJsonArray array;
|
||||
|
||||
// TODO use JsonParser for the item generation
|
||||
for (int row = 0; row < 5; ++row) {
|
||||
QJsonObject itemObject;
|
||||
// itemObject.insert("uuid", m_uuid.toString());
|
||||
// itemObject.insert("entryDateUTC", m_entryDateUTC.toString(Qt::ISODate));
|
||||
itemObject.insert(ROLE_NAMES.value(NameRole), QString("Item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(DescriptionRole), QString("This is item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(InfoRole), QString("Info of item %1").arg(row));
|
||||
itemObject.insert(ROLE_NAMES.value(AmountRole), row);
|
||||
itemObject.insert(ROLE_NAMES.value(FactorRole), row * 1.1);
|
||||
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEMS_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc.toJson();
|
||||
}
|
||||
|
||||
TableModel::TableModel(QUndoStack* undoStack, QObject* parent)
|
||||
: QAbstractTableModel{parent}
|
||||
, m_undoStack(undoStack) {}
|
||||
|
||||
Qt::ItemFlags TableModel::flags(const QModelIndex& index) const {
|
||||
if (!index.isValid()) {
|
||||
return QAbstractTableModel::flags(index);
|
||||
}
|
||||
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
|
||||
|
||||
int TableModel::rowCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid()) {
|
||||
return 0; /// no children
|
||||
}
|
||||
return m_items.size();
|
||||
}
|
||||
|
||||
int TableModel::columnCount(const QModelIndex& parent) const {
|
||||
if (parent.isValid()) {
|
||||
return 0; /// no children
|
||||
}
|
||||
return USER_FACING_ROLES.size();
|
||||
}
|
||||
|
||||
QVariant TableModel::data(const QModelIndex& index, int role) const {
|
||||
const int row = index.row();
|
||||
const int column = index.column();
|
||||
|
||||
if (!index.isValid()) {
|
||||
return QVariant();
|
||||
}
|
||||
if (row >= rowCount(QModelIndex()) || column >= columnCount(QModelIndex())) {
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
return m_items.at(row)->data(roleForColumn);
|
||||
case NameRole:
|
||||
case DescriptionRole:
|
||||
case InfoRole:
|
||||
case AmountRole:
|
||||
case FactorRole:
|
||||
case IdRole:
|
||||
return m_items.at(row)->data(role);
|
||||
case ToStringRole:
|
||||
return m_items.at(row)->toString();
|
||||
case ToJsonRole:
|
||||
return m_items.at(row)->toJsonObject();
|
||||
}
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
|
||||
if (role == Qt::DisplayRole) {
|
||||
if (orientation == Qt::Horizontal) {
|
||||
const int columnRole = GET_ROLE_FOR_COLUMN(section);
|
||||
const QString headerName = ROLE_NAMES.value(columnRole);
|
||||
return QString("%1").arg(headerName);
|
||||
} else {
|
||||
return QString("%1").arg(section);
|
||||
}
|
||||
}
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) {
|
||||
if (role == Qt::EditRole && checkIndex(index)) {
|
||||
const int column = index.column();
|
||||
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
return setItemData(index, {{roleForColumn, value}});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TableModel::setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) {
|
||||
if (!checkIndex(index)) {
|
||||
return false;
|
||||
}
|
||||
// if (isRoleReadOnly(roleForColumn)) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
QMap<int, QVariant> changedValues = onlyChangedValues(index, roles);
|
||||
if (changedValues.size() > 0) {
|
||||
EditItemCommand* editCommand = new EditItemCommand(this, index, changedValues);
|
||||
m_undoStack->push(editCommand);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ModelItemValues TableModel::getItemValues(const QModelIndex& index) const {
|
||||
ModelItemValues values;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
values.insert(role, data(index, role));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
QJsonDocument TableModel::getAllItemsAsJsonDoc() const {
|
||||
QJsonDocument doc = QJsonDocument();
|
||||
QJsonObject rootObject;
|
||||
QJsonArray array;
|
||||
|
||||
foreach (shared_ptr<ModelItem> item, m_items) {
|
||||
QJsonObject itemObject = item->toJsonObject();
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEMS_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc;
|
||||
}
|
||||
|
||||
QList<QStringList> TableModel::getItemsAsStringLists() const {
|
||||
QList<QStringList> result;
|
||||
foreach (shared_ptr<ModelItem> item, m_items) {
|
||||
QStringList valueList;
|
||||
for (int column = 0; column < columnCount(); ++column) {
|
||||
QString value = item->data(GET_ROLE_FOR_COLUMN(column)).toString();
|
||||
valueList.append(value);
|
||||
}
|
||||
result.append(valueList);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// TODO use item selection as parameter to wrap multiple items into JSON data structure
|
||||
QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const {
|
||||
const QJsonObject itemObject = data(currentIndex, ToJsonRole).toJsonObject();
|
||||
QJsonObject rootObject;
|
||||
rootObject.insert(ITEM_KEY_STRING, itemObject);
|
||||
const QJsonDocument jsonDoc(rootObject);
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
QString TableModel::updateItemsFromJson(const QByteArray& jsonData) {
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonData, ITEM_KEY_STRING);
|
||||
int nChangedItems = 0;
|
||||
for (const ModelItemValues& itemValues : valueList) {
|
||||
bool updateHappened = updateItem(itemValues);
|
||||
if (updateHappened) {
|
||||
nChangedItems++;
|
||||
}
|
||||
}
|
||||
return QString("Found and updated %1 item(s).").arg(nChangedItems);
|
||||
}
|
||||
|
||||
bool TableModel::updateItem(const ModelItemValues& itemValues) {
|
||||
QModelIndex foundIndex = searchItemIndex(itemValues);
|
||||
|
||||
qDebug() << "Search done!";
|
||||
if (foundIndex == QModelIndex()) {
|
||||
const QString errorMessage = "No matching item found!";
|
||||
qWarning() << errorMessage;
|
||||
return false;
|
||||
} else {
|
||||
qInfo() << "Item found!";
|
||||
/// update existing item
|
||||
setItemData(foundIndex, itemValues);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
|
||||
if (parentIndex != QModelIndex()) {
|
||||
qWarning() << "Removing of child rows is not supported yet!";
|
||||
return false;
|
||||
}
|
||||
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
if (firstRow < 0 || lastRow >= m_items.size()) {
|
||||
qWarning() << "Trying to remove rows is out of bounds!";
|
||||
return false;
|
||||
}
|
||||
|
||||
RemoveRowsCommand* removeCommand = new RemoveRowsCommand(this, firstRow, nRows);
|
||||
m_undoStack->push(removeCommand);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDoc, QModelIndex()); }
|
||||
|
||||
void TableModel::insertItems(int startPosition,
|
||||
const QByteArray& jsonDoc,
|
||||
const QModelIndex& parentIndex) {
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEMS_KEY_STRING);
|
||||
|
||||
if (valueList.empty()) {
|
||||
/// don't try inserting if no values to insert
|
||||
qDebug() << "No items found in JSON document. Not adding anything...";
|
||||
return;
|
||||
}
|
||||
|
||||
insertItems(startPosition, valueList, parentIndex);
|
||||
}
|
||||
|
||||
void TableModel::insertItems(int startPosition,
|
||||
const QList<ModelItemValues>& itemValuesList,
|
||||
const QModelIndex& parentIndex) {
|
||||
qInfo() << "Inserting item(s) into model...";
|
||||
if (parentIndex != QModelIndex()) {
|
||||
qWarning()
|
||||
<< "Using invalid parent index (no child support for now)! Using root index as parent...";
|
||||
}
|
||||
if (startPosition == -1 || startPosition > m_items.size()) {
|
||||
/// Appending item(s)
|
||||
startPosition = m_items.size();
|
||||
}
|
||||
|
||||
InsertRowsCommand* insertCommand = new InsertRowsCommand(this, startPosition, itemValuesList);
|
||||
m_undoStack->push(insertCommand);
|
||||
}
|
||||
|
||||
void TableModel::execInsertItems(const int firstRow, const QList<ModelItemValues> valueList) {
|
||||
const int nRows = valueList.size();
|
||||
qDebug() << "Inserting" << nRows << "items...";
|
||||
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
beginInsertRows(QModelIndex(), firstRow, lastRow);
|
||||
for (int row = 0; row < nRows; ++row) {
|
||||
const int rowPosition = firstRow + row;
|
||||
shared_ptr<ModelItem> item = make_unique<ModelItem>(valueList.at(row));
|
||||
m_items.insert(rowPosition, std::move(item));
|
||||
}
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
void TableModel::execRemoveItems(const int firstRow, const int nRows) {
|
||||
const int lastRow = firstRow + nRows - 1;
|
||||
beginRemoveRows(QModelIndex(), firstRow, lastRow);
|
||||
m_items.remove(firstRow, nRows);
|
||||
endRemoveRows();
|
||||
}
|
||||
|
||||
void TableModel::execEditItemData(const int row, const QMap<int, QVariant>& changedValues) {
|
||||
shared_ptr<ModelItem> item = m_items.at(row);
|
||||
bool isDataChanged = item->setItemData(changedValues);
|
||||
|
||||
if (isDataChanged) {
|
||||
/// FIXME due to the mapping from roles to the DisplayRole of different columns the complete row
|
||||
/// is getting notified about (potential) data changes; dataChanged should be called only for
|
||||
/// the affected columns
|
||||
const QModelIndex firstIndex = this->index(row, 0);
|
||||
const QModelIndex lastIndex = this->index(row, USER_FACING_ROLES.size() - 1);
|
||||
QList<int> roles = changedValues.keys();
|
||||
roles.insert(0, Qt::DisplayRole);
|
||||
emit dataChanged(firstIndex, lastIndex, roles.toVector());
|
||||
}
|
||||
}
|
||||
|
||||
QMap<int, QVariant> TableModel::onlyChangedValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& roleValueMap) const {
|
||||
QMap<int, QVariant> result;
|
||||
QMap<int, QVariant>::const_iterator i;
|
||||
for (i = roleValueMap.constBegin(); i != roleValueMap.constEnd(); ++i) {
|
||||
const int role = i.key();
|
||||
const QVariant newValue = i.value();
|
||||
const QVariant oldValue = index.data(role);
|
||||
// TODO check if role is a editable role?
|
||||
if (oldValue != newValue) {
|
||||
bool emptyValueIsEqualToZero = isEmptyValueEqualToZero(role);
|
||||
if (emptyValueIsEqualToZero && oldValue == QVariant() && newValue == 0) {
|
||||
qDebug() << "oldValue:" << oldValue << "& newValue:" << newValue
|
||||
<< "mean the same. Ignoring...";
|
||||
continue;
|
||||
}
|
||||
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
|
||||
result.insert(role, newValue);
|
||||
} else {
|
||||
qInfo() << "oldValue is already the same as newValue:" << oldValue << "-> ignoring...";
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool TableModel::isEmptyValueEqualToZero(const int role) const {
|
||||
if (INT_ROLES.contains(role)) {
|
||||
return true;
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
|
||||
// iterate over indexes to search item : see searchItem(...);
|
||||
// for (const shared_ptr<ModelItem>& item : m_items) {
|
||||
for (int row = 0; row < rowCount(); ++row) {
|
||||
qDebug() << "Processing item at row" << row << "...";
|
||||
QModelIndex itemIndex = index(row, 0);
|
||||
if (isItemEqualToItemValues(itemIndex, givenItemValues)) {
|
||||
qInfo() << "Found item at row" << row << "! Returning its index...";
|
||||
return itemIndex;
|
||||
}
|
||||
}
|
||||
qDebug() << "No matching item found. Returning empty pointer...";
|
||||
return {};
|
||||
}
|
||||
|
||||
bool TableModel::isItemEqualToItemValues(const QModelIndex& itemIndex,
|
||||
const ModelItemValues givenItemValues) const {
|
||||
/// do both have a UUID?
|
||||
QVariant idOfItem = data(itemIndex, IdRole);
|
||||
QVariant given = givenItemValues.value(IdRole);
|
||||
if (idOfItem.isValid() && given.isValid()) {
|
||||
/// are the UUIDs the same?
|
||||
if (idOfItem.toString() == given.toString()) {
|
||||
qInfo() << "UUIDs are the same.";
|
||||
return true;
|
||||
} else {
|
||||
qDebug() << "UUIDs are NOT the same.";
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
/// are all other values the same? (for now only USER_FACING_ROLES are checked)
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant valueOfItem = data(itemIndex, role);
|
||||
const QVariant givenValue = givenItemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
if (valueOfItem.toString() != givenValue.toString()) {
|
||||
return false;
|
||||
}
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
if (valueOfItem.toInt() != givenValue.toInt()) {
|
||||
return false;
|
||||
}
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
if (valueOfItem.toDouble() != givenValue.toDouble()) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
79
libs/GenericCore/model/tablemodel.h
Normal file
@ -0,0 +1,79 @@
|
||||
#ifndef TABLEMODEL_H
|
||||
#define TABLEMODEL_H
|
||||
|
||||
#include <QAbstractTableModel>
|
||||
|
||||
class QUndoStack;
|
||||
class ModelItem;
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel : public QAbstractTableModel {
|
||||
Q_OBJECT
|
||||
|
||||
friend class InsertRowsCommand;
|
||||
friend class RemoveRowsCommand;
|
||||
friend class EditItemCommand;
|
||||
|
||||
public:
|
||||
static QByteArray generateExampleItems();
|
||||
|
||||
explicit TableModel(QUndoStack* undoStack, QObject* parent = nullptr);
|
||||
|
||||
/// QAbstractItemModel interface
|
||||
Qt::ItemFlags flags(const QModelIndex& index) const override;
|
||||
QHash<int, QByteArray> roleNames() const override;
|
||||
|
||||
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
|
||||
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
|
||||
QVariant data(const QModelIndex& index, int role) const override;
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
|
||||
|
||||
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
|
||||
bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) override;
|
||||
|
||||
ModelItemValues getItemValues(const QModelIndex& index) const;
|
||||
QJsonDocument getAllItemsAsJsonDoc() const;
|
||||
QList<QStringList> getItemsAsStringLists() const;
|
||||
|
||||
QByteArray jsonDataForServer(const QModelIndex& currentIndex) const;
|
||||
|
||||
QString updateItemsFromJson(const QByteArray& jsonData);
|
||||
bool updateItem(const ModelItemValues& itemValues);
|
||||
|
||||
public slots:
|
||||
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
|
||||
// override;
|
||||
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
|
||||
void appendItems(const QByteArray& jsonDoc);
|
||||
void insertItems(int startPosition,
|
||||
const QByteArray& jsonDoc,
|
||||
const QModelIndex& parentIndex = QModelIndex());
|
||||
void insertItems(int startPosition,
|
||||
const QList<ModelItemValues>& itemValuesList,
|
||||
const QModelIndex& parentIndex = QModelIndex());
|
||||
|
||||
private:
|
||||
/// *** members ***
|
||||
// TODO shared_ptr -> unique_ptr
|
||||
QList<shared_ptr<ModelItem>> m_items;
|
||||
QUndoStack* m_undoStack;
|
||||
|
||||
/// *** functions ***
|
||||
/// undo/redo functions
|
||||
void execInsertItems(const int firstRow, const QList<ModelItemValues> valueList);
|
||||
void execRemoveItems(const int firstRow, const int nRows);
|
||||
void execEditItemData(const int row, const QMap<int, QVariant>& changedValues);
|
||||
|
||||
/// misc functions
|
||||
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& roleValueMap) const;
|
||||
bool isEmptyValueEqualToZero(const int role) const;
|
||||
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
|
||||
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
|
||||
const ModelItemValues givenItemValues) const;
|
||||
};
|
||||
|
||||
#endif // TABLEMODEL_H
|
||||
12
libs/GenericCore/network/apiroutes.h
Normal file
@ -0,0 +1,12 @@
|
||||
#ifndef APIROUTES_H
|
||||
#define APIROUTES_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
// TODO add namespace
|
||||
|
||||
static const QString apiPrefix = "/api/";
|
||||
|
||||
static const QString ROUTE_ITEMS = apiPrefix + "items";
|
||||
|
||||
#endif // APIROUTES_H
|
||||
106
libs/GenericCore/network/servercommunicator.cpp
Normal file
@ -0,0 +1,106 @@
|
||||
#include "servercommunicator.h"
|
||||
#include "apiroutes.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QRestReply>
|
||||
|
||||
using namespace Qt::StringLiterals;
|
||||
|
||||
ServerCommunicator::ServerCommunicator(QObject* parent)
|
||||
: QObject{parent} {
|
||||
m_netManager.setAutoDeleteReplies(true);
|
||||
m_restManager = std::make_shared<QRestAccessManager>(&m_netManager);
|
||||
m_serviceApi = std::make_shared<QNetworkRequestFactory>();
|
||||
}
|
||||
|
||||
bool ServerCommunicator::sslSupported() {
|
||||
#if QT_CONFIG(ssl)
|
||||
return QSslSocket::supportsSsl();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
QUrl ServerCommunicator::url() const { return m_serviceApi->baseUrl(); }
|
||||
|
||||
void ServerCommunicator::setUrl(const QUrl& url) {
|
||||
if (m_serviceApi->baseUrl() == url) {
|
||||
return;
|
||||
}
|
||||
m_serviceApi->setBaseUrl(url);
|
||||
QHttpHeaders authenticationHeaders;
|
||||
authenticationHeaders.append(QHttpHeaders::WellKnownHeader::ContentType, "application/json");
|
||||
m_serviceApi->setCommonHeaders(authenticationHeaders);
|
||||
emit urlChanged();
|
||||
}
|
||||
|
||||
void ServerCommunicator::fetchItems() {
|
||||
/// Set up a GET request
|
||||
m_restManager->get(m_serviceApi->createRequest(ROUTE_ITEMS), this, [this](QRestReply& reply) {
|
||||
if (reply.isSuccess()) {
|
||||
qInfo() << "Fetching items successful.";
|
||||
const QJsonDocument doc = reply.readJson().value();
|
||||
emit itemsFetched(doc.toJson());
|
||||
|
||||
} else {
|
||||
if (reply.hasError()) {
|
||||
const QString errorString = reply.errorString();
|
||||
qCritical() << "ERROR:" << errorString;
|
||||
emit itemsFetchFailure(errorString);
|
||||
} else {
|
||||
int statusCode = reply.httpStatus();
|
||||
qCritical() << "ERROR:" << statusCode;
|
||||
emit itemsFetchFailure(QString::number(statusCode));
|
||||
emit itemsFetchFailure(QString("HTTP status code: %1").arg(statusCode));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::postItems(const QByteArray& jsonData) {
|
||||
QNetworkReply* reply = m_restManager->post(m_serviceApi->createRequest(ROUTE_ITEMS), jsonData);
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::finished, [=]() {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray responseData = reply->readAll();
|
||||
const QString message = QString("POST successful! Response: %1").arg(responseData);
|
||||
qInfo() << message;
|
||||
emit postRequestSuccessful(responseData);
|
||||
} else {
|
||||
const QString message = QString("Error: %1").arg(reply->errorString());
|
||||
qDebug() << message;
|
||||
emit postRequestFailure(message);
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::deleteItem(const QString& id) {
|
||||
const QString deleteRoute = QString("%1/%2").arg(ROUTE_ITEMS, id);
|
||||
QNetworkReply* reply = m_restManager->deleteResource(m_serviceApi->createRequest(deleteRoute));
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::finished, [=]() {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray responseData = reply->readAll();
|
||||
const QString message = QString("DELETE successful! Response: %1").arg(responseData);
|
||||
qInfo() << message;
|
||||
emit deleteRequestSuccessful(responseData);
|
||||
} else {
|
||||
const QString message = QString("Error: %1").arg(reply->errorString());
|
||||
qDebug() << message;
|
||||
emit deleteRequestFailure(message);
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::setServerConfiguration(const QString url,
|
||||
const QString email,
|
||||
const QString password) {
|
||||
setUrl(url);
|
||||
|
||||
m_email = email;
|
||||
m_password = password;
|
||||
}
|
||||
46
libs/GenericCore/network/servercommunicator.h
Normal file
@ -0,0 +1,46 @@
|
||||
#ifndef SERVERCOMMUNICATOR_H
|
||||
#define SERVERCOMMUNICATOR_H
|
||||
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkRequestFactory>
|
||||
#include <QObject>
|
||||
#include <QRestAccessManager>
|
||||
|
||||
class ServerCommunicator : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ServerCommunicator(QObject* parent = nullptr);
|
||||
|
||||
bool sslSupported();
|
||||
|
||||
QUrl url() const;
|
||||
void setUrl(const QUrl& url);
|
||||
|
||||
void setServerConfiguration(const QString url, const QString email, const QString password);
|
||||
|
||||
public slots:
|
||||
void fetchItems();
|
||||
void postItems(const QByteArray& jsonData);
|
||||
void deleteItem(const QString& id);
|
||||
|
||||
signals:
|
||||
void urlChanged();
|
||||
|
||||
void itemsFetched(const QByteArray jsonDoc);
|
||||
void itemsFetchFailure(const QString errorString);
|
||||
void postRequestSuccessful(const QByteArray responseData);
|
||||
void postRequestFailure(const QString errorString);
|
||||
void deleteRequestSuccessful(const QByteArray responseData);
|
||||
void deleteRequestFailure(const QString errorString);
|
||||
|
||||
private:
|
||||
QNetworkAccessManager m_netManager;
|
||||
std::shared_ptr<QRestAccessManager> m_restManager;
|
||||
std::shared_ptr<QNetworkRequestFactory> m_serviceApi;
|
||||
|
||||
QString m_email;
|
||||
QString m_password;
|
||||
// QString m_authToken;
|
||||
};
|
||||
|
||||
#endif // SERVERCOMMUNICATOR_H
|
||||
30
tests/GenericCoreTests/CMakeLists.txt
Normal file
@ -0,0 +1,30 @@
|
||||
include(FetchContent)
|
||||
|
||||
set(TARGET_APP "core_test")
|
||||
|
||||
FetchContent_Declare(
|
||||
googletest
|
||||
GIT_REPOSITORY https://github.com/google/googletest.git
|
||||
GIT_TAG v1.17.0
|
||||
)
|
||||
FetchContent_MakeAvailable(googletest)
|
||||
add_library(GTest::GTest INTERFACE IMPORTED)
|
||||
target_link_libraries(GTest::GTest INTERFACE gtest_main)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools)
|
||||
|
||||
add_executable(${TARGET_APP} core_test.cpp)
|
||||
|
||||
target_include_directories(${TARGET_APP} PRIVATE ${CORE_LIB_DIR}/include)
|
||||
|
||||
target_link_libraries(${TARGET_APP}
|
||||
PRIVATE
|
||||
GTest::GTest
|
||||
GenericCore)
|
||||
target_link_libraries(${TARGET_APP} PUBLIC Qt${QT_VERSION_MAJOR}::Core)
|
||||
|
||||
add_test(core_gtests ${TARGET_APP})
|
||||
26
tests/GenericCoreTests/core_test.cpp
Normal file
@ -0,0 +1,26 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <QString>
|
||||
|
||||
#include "../../libs/GenericCore/genericcore.h"
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
inline void PrintTo(const QString& qString, ::std::ostream* os) { *os << qUtf8Printable(qString); }
|
||||
QT_END_NAMESPACE
|
||||
|
||||
TEST(CoreTests, TestEqualString) {
|
||||
const QString coreName("GenericCore");
|
||||
const QString coreVersion("0.2.0");
|
||||
const auto expected = QString("%1 (Version %2)").arg(coreName).arg(coreVersion);
|
||||
auto core = std::make_unique<GenericCore>();
|
||||
const auto actual = core->toString();
|
||||
// const auto actual = multiply(1, 1);
|
||||
ASSERT_EQ(expected, actual);
|
||||
}
|
||||
|
||||
TEST(CoreTests, TestNotEqualString) {
|
||||
const QString expected = QString("Hello from the Core!");
|
||||
auto core = std::make_unique<GenericCore>();
|
||||
const QString actual = core->toString();
|
||||
ASSERT_NE(expected, actual);
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
Name,Description,Info,Factor
|
||||
Item 0,This is item 0,Info of item 0,0
|
||||
Item 1,This is item 1,Info of item 1,1
|
||||
Item 2,This is item 2,Info of item 2,2
|
||||
Item 3,This is item 3,Info of item 3,3
|
||||
Item 4,This is item 4,Info of item 4,4
|
||||
Item 5,This is item 5,Info of item 5,5
|
||||
Item 6,This is item 6,Info of item 6,6
|
||||
|
@ -0,0 +1,8 @@
|
||||
Name,Description,Info,Amount,Factor
|
||||
Item 0,This is item 0,Info of item 0,0,0
|
||||
Item 1,This is item 1,Info of item 1,1,1
|
||||
Item 2,This is item 2,Info of item 2,2,2
|
||||
Item 3,This is item 3,Info of item 3,3,3
|
||||
Item 4,This is item 4,Info of item 4,4,4
|
||||
Item 5,This is item 5,Info of item 5,5,5
|
||||
Item 6,This is item 6,Info of item 6,6,6
|
||||
|