File j4-dmenu-desktop-2.18~git20230912.obscpio of Package j4-dmenu-desktop

07070100000000000081A40000000000000000000000016500A7F00000018D000000000000000000000000000000000000003000000000j4-dmenu-desktop-2.18~git20230912/.clang-format---
# This clang format file is custom crafted to match enkore's coding style.
BasedOnStyle: LLVM
AccessModifierOffset: -4
IndentWidth: 4
AllowShortFunctionsOnASingleLine: Empty
AlignArrayOfStructures: Left
BreakBeforeBraces: Custom
SeparateDefinitionBlocks: Always
BraceWrapping:
  AfterClass: true
  AfterControlStatement: Never
  AfterFunction: false
  AfterNamespace: true
  AfterStruct: true
07070100000001000081A40000000000000000000000016500A7F0000000C7000000000000000000000000000000000000002D00000000j4-dmenu-desktop-2.18~git20230912/.gitignorebuild/*

catch/*
CMakeCache.txt
CMakeFiles/*
CMakeScripts/*
Makefile
cmake_install.cmake
CTestTestfile.cmake
install_manifest.txt

*~
debug/*
release/*
test/*
tests/*

j4-dmenu-desktop
j4-dmenu-tests07070100000002000081A40000000000000000000000016500A7F000000A87000000000000000000000000000000000000002C00000000j4-dmenu-desktop-2.18~git20230912/CHANGELOG
r2.5 released 2013-11-02
	+ add --display-binary option

r2.6 released 2013-11-28
	+ fixed quoting
	+ different output formats
	+ misc. bug fixes and improvements

r2.7 released 2013-12-04
	+ removed i3 dependency
	+ fixed memory leak
	+ fixed wrong usage of getopt_long()
	+ fixed GCC 4.7 compatibility
	+ misc. bug fixes and improvements

r2.8 released 2013-12-09
	+ various performance improvements
	+ better error messages
	+ added debugging messages
	+ fixed mixup of malloc/new[]
	+ fixed wrong usage of getline()

r2.9 released 2014-01-25
	+ added test suite, travis integration
	+ fixed $XDG_DATA_HOME being ignored
	+ fixed wrong ordering of default search paths
	+ support shell aliases

r2.10 released 2014-04-17
	+ minor changes regarding quoting
	+ change to application path if specified as per XDG spec

r2.11 released 2014-04-20
	+ fixed unhidden desktop files being regarded as hidden

r2.12 released 2014-12-14
	+ fixed quoting issue with localized names
	+ fixed CMakeLists for multithreaded builds
	+ fixed overriding files with Hidden and/or NoDisplay keys
	+ whitespace after "=" is now ignored
	+ implemented desktop file ID concept of the XDG specification
	  (supersedes old "override-by-name" semantics)
	+ added support for OnlyShowIn and NotShowIn tags
	+ added --use-xdg-de flag to interpret $XDG_CURRENT_DESKTOP
	  (for OnlyShowIn/NotShowIn)
	+ temporary files are now created with mkstemp

r2.13 released 2015-06-22
	+ GenericName fields are added to the menu, too
	+ Added manpage j4-dmenu-desktop(1)
	+ Menu is now sorted by names

r2.14 released 2016-03-31
	+ Added --usage-log feature to sort by usage frequency
	+ Added --no-generic option to exclude GenericName fields

r2.15 released 2017-03-19
	+ fixed bug where using some shells could use a lot of CPU for nothing
	+ fixed issue when locale setup is completely broken (fall back to "C" locale)
	+ fixed build on FreeBSD

r2.16 released 2018-01-11
	+ updated CMakeLists to use Catch 1.x (instead of 2.x)

r2.17 released 2019-02-26
	+ fixed compilation error on FreeBSD 11
	+ fixed specifying `--no-generic` after `--usage-log=` breaking usage log
	+ improved build speed
	+ added --wait-on feature to daemonize for better responsiveness

r2.18 released 2020-10-02
	+ Re-add support for %k in .desktopfiles (location of the file)
	+ --wait-on: child processes detach now, parent does not wait
	+ use POSIX printf instead of echo (see 2e6308783 for detailed explanation)
	  (fix for dash/Debian)
	+ .desktop files are read sorted by inode now, improving performance on
	  traditional hard drives
	+ added --no-exec option
	+ added --wrapper option (e.g. for i3 exec)
	+ removed last usage of C/C++ locales
07070100000003000081A40000000000000000000000016500A7F000000A8E000000000000000000000000000000000000003100000000j4-dmenu-desktop-2.18~git20230912/CMakeLists.txtcmake_minimum_required(VERSION 2.8.12)

project(j4-dmenu)

option(WITH_TESTS "Build and run tests" ON)
option(WITH_GIT_CATCH "Use a Git checkout of Catch to build the tests" ON)

if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7")
  set(CXX_OPT "-std=c++0x")
else()
  set(CXX_OPT "-std=c++11")
endif()

# _WITH_GETLINE for FreeBSD
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_OPT} -Wall -Wextra -pedantic -Wno-missing-field-initializers -O2 -D_WITH_GETLINE")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")

if (CMAKE_HOST_SYSTEM_NAME STREQUAL FreeBSD)
    option(USE_KQUEUE "Use the kqueue event notification mechanism instead of Inotify" ON)
else()
    option(USE_KQUEUE "Use the kqueue event notification mechanism instead of Inotify" OFF)
endif()

if (USE_KQUEUE)
    find_package(Threads REQUIRED)
endif()

configure_file(src/Notify.hh.in Notify.hh)
include_directories("${PROJECT_BINARY_DIR}")

if(WITH_TESTS)
  enable_testing(true)
  add_test(
          NAME j4-dmenu-tests
          COMMAND j4-dmenu-tests
  )
  add_executable(
          j4-dmenu-tests
          src/Test.cc
  )
  add_definitions(-DTEST_FILES="${CMAKE_CURRENT_SOURCE_DIR}/test_files/")

  if(WITH_GIT_CATCH)
    include(ExternalProject)
    ExternalProject_Add(
      catch
      PREFIX ${CMAKE_BINARY_DIR}/catch
      GIT_TAG Catch1.x
      GIT_REPOSITORY https://github.com/catchorg/Catch2
      TIMEOUT 10
      UPDATE_COMMAND git pull
      CONFIGURE_COMMAND ""
      BUILD_COMMAND ""
      INSTALL_COMMAND ""
      LOG_DOWNLOAD ON
    )
    add_dependencies(j4-dmenu-tests catch)

    # Expose required variable (CATCH_INCLUDE_DIR) to parent scope
    ExternalProject_Get_Property(catch source_dir)
    set(CATCH_INCLUDE_DIR ${source_dir}/include CACHE INTERNAL "Path to include folder for Catch")
  else()
    # Use system-installed version of Catch
    find_path(CATCH_INCLUDE_DIR catch.hpp PATH_SUFFIXES catch)
    if(NOT CATCH_INCLUDE_DIR)
      message(FATAL_ERROR "Catch include directory not found")
    endif()
  endif(WITH_GIT_CATCH)

  # Include Catch in the project
  include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES})
endif(WITH_TESTS)

add_executable(
    j4-dmenu-desktop
    src/main.cc
)

if (USE_KQUEUE)
    if(THREADS_HAVE_PTHREAD_ARG)
      target_compile_options(j4-dmenu-desktop PUBLIC "-pthread")
      target_compile_options(j4-dmenu-tests PUBLIC "-pthread")
    endif()
    if(CMAKE_THREAD_LIBS_INIT)
      target_link_libraries(j4-dmenu-desktop "${CMAKE_THREAD_LIBS_INIT}")
      target_link_libraries(j4-dmenu-tests "${CMAKE_THREAD_LIBS_INIT}")
    endif()
endif()

install (
    TARGETS j4-dmenu-desktop
        RUNTIME DESTINATION bin
    )

07070100000004000081A40000000000000000000000016500A7F000000158000000000000000000000000000000000000003100000000j4-dmenu-desktop-2.18~git20230912/HOW-TO-RELEASE- Compile and commit CHANGELOG
- Commit message follows the pattern "rX.Y released ISO8601DATE"
- Tag:
  git tag -a -m '<CHANGELOG ENTRY>' rX.Y --sign
- Use GPG key A1774C1B37DC1DCEDB65EE469B8450B91D1362C1
- git push --tags
- Create GitHub release
- Download .tar.gz
- Compare to repo
- gpg --detach-sign .tar.gz
- Upload .tar.gz.sig to GitHub
07070100000005000081A40000000000000000000000016500A7F00000894B000000000000000000000000000000000000002A00000000j4-dmenu-desktop-2.18~git20230912/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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 <http://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:

    <program>  Copyright (C) <year>  <name of author>
    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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
07070100000006000081A40000000000000000000000016500A7F000001304000000000000000000000000000000000000002C00000000j4-dmenu-desktop-2.18~git20230912/README.md# j4-dmenu-desktop

j4-dmenu-desktop is a replacement for i3-dmenu-desktop. It's purpose
is to find .desktop files and offer you a menu to start an application
using dmenu. Since r2.7 j4-dmenu-desktop doesn't require i3wm anymore
and should work just fine on about any desktop environment.

You can also execute shell commands using it.

## Build requirements

* Compiler with basic C++11 support (GCC 4.77 or later required, Clang works, too)
* CMake

Building is the usual cmake/make thingy:

    cmake .
    make
    sudo make install

## Distribution packages

### Archlinux <a href="https://repology.org/project/j4-dmenu-desktop/versions"><img src="https://repology.org/badge/vertical-allrepos/j4-dmenu-desktop.svg" alt="Packaging status" align="right"></a>


The package is provided by the AUR. You can install it with an AUR helper of your choice: `j4-dmenu-desktop-git` or `j4-dmenu-desktop`. Else, you may install it manually by invoking the following commands as a regular user. (to build packages from the AUR, the `base-devel` package group is assumed to be installed)

    git clone https://aur.archlinux.org/j4-dmenu-desktop.git    
    cd j4-dmenu-desktop
    makepkg -si

or for the latest:

    git clone https://aur.archlinux.org/j4-dmenu-desktop-git.git
    cd j4-dmenu-desktop-git
    makepkg -si

### FreeBSD

j4-dmenu-desktop is now available in the FreeBSD Ports Collection. A prebuilt package can be installed via

    pkg install j4-dmenu-desktop

### Gentoo

j4-dmenu-desktop is available in Portage for the `amd64` and `x86` architectures. You can install it via

    echo "x11-misc/j4-dmenu-desktop ~amd64 ~x86" >> /etc/portage/package.accept_keywords
    emerge --ask x11-misc/j4-dmenu-desktop

The package is also provided by the `gentoo-el` overlay. You can install it with the following commands as root. (you need to have `layman` installed and configured)

    layman -a gentoo-el
    echo "=x11-misc/j4-dmenu-desktop-9999 **" >> /etc/portage/package.accept_keywords
    emerge x11-misc/j4-dmenu-desktop
    
### Ubuntu

The package is now in the apt repository. You can install it via

    sudo apt-get install j4-dmenu-desktop

### Debian

j4-dmenu-desktop is in Debian stable:

    sudo apt install j4-dmenu-desktop

### Nix / NixOS

j4-dmenu-desktop is in [nixpkgs](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/j4-dmenu-desktop/default.nix):

    nix-env --install j4-dmenu-desktop
    # Or use pkgs attribute of the same name in NixOS configuration 


## Invocation

Usage:

    j4-dmenu-desktop [--dmenu="dmenu -i"] [--term="i3-sensible-terminal"]
    j4-dmenu-desktop --help

Options:

    --dmenu=<command>
        Determines the command used to invoke dmenu
        Executed with your shell ($SHELL) or /bin/sh
    --use-xdg-de
        Enables reading $XDG_CURRENT_DESKTOP to determine the desktop environment
    --display-binary
        Display binary name after each entry (off by default)
    --no-generic
        Do not include the generic name of desktop entries
    --wrapper=<wrapper>
        A wrapper binary. Useful in case you want to wrap into 'i3 exec'
    --term=<command>
        Sets the terminal emulator used to start terminal apps
    --usage-log=<file>
        Must point to a read-writeable file (will create if not exists).
        In this mode entries are sorted by usage frequency.
    --wait-on=<path>
        Must point to a path where a file can be created.
        In this mode no menu will be shown. Instead the program waits for <path>
        to be written to (use echo > path). Every time this happens a menu will be shown.
        Desktop files are parsed ahead of time.
        Perfoming 'echo -n q > path' will exit the program.
    --no-exec
        Do not execute selected command, send to stdout instead
    --help
        Display this help message

Environment variables

- $SHELL is respected, and if absent /bin/sh is used
- XDG-spec variables (XDG_CURRENT_DESKTOP, XDG_DATA_HOME, HOME) are respected

## FAQ / RAQ / RMR

### I want it to display normal binaries, too, yes?

You can put this in a script file and use it instead of calling j4dd directly:

    j4-dmenu-desktop --dmenu="(cat ; (stest -flx $(echo $PATH | tr : ' ') | sort -u)) | dmenu"

Exchanging the `cat` and `(stest ... sort -u)` parts will swap the two parts (j4dd's output and the list of binaries).

### Get the output into a pipe / launching a program by arbitrary user input

[GOTO](https://github.com/enkore/j4-dmenu-desktop/issues/39#issuecomment-177164865)

### How much faster is it?

    % time i3-dmenu-desktop --dmenu="cat"
    [{"success":true}]
    i3-dmenu-desktop --dmenu="cat"  0.37s user 0.02s system 96% cpu 0.404 total
    % time ./j4-dmenu-desktop --dmenu=cat
    ./j4-dmenu-desktop --dmenu=cat  0.01s user 0.01s system 107% cpu 0.015 total

More than 25 times faster :)

07070100000007000081ED0000000000000000000000016500A7F000000092000000000000000000000000000000000000002E00000000j4-dmenu-desktop-2.18~git20230912/iwyu-driver#!/bin/sh

IWYU_COMMAND=$(which include-what-you-use)
COMPILER_COMMAND=/usr/bin/g++

$COMPILER_COMMAND $@
STATUS=$?
$IWYU_COMMAND $@
exit $STATUS
07070100000008000081A40000000000000000000000016500A7F000000971000000000000000000000000000000000000003500000000j4-dmenu-desktop-2.18~git20230912/j4-dmenu-desktop.1.Dd $Mdocdate: July 18 2021$
.Dt J4-DMENU-DESKTOP 1
.Os
.Sh NAME
.Nm j4-dmenu-desktop
.Nd fast desktop menu
.Sh SYNOPSIS
.Nm
.Op OPTIONS
.Sh DESCRIPTION
.Nm
is a faster replacement for i3-dmenu-desktop.
.Pp
It's purpose is to find .desktop files and offer you a menu to start an application using dmenu.
.Pp
The arguments are as follows:
.Bl -tag -width indent
.It Fl b , Fl Fl display-binary
Display binary name after each entry (off by default).
.It Fl f , Fl Fl display-binary-base
Display basename of binary name after each entry (off by default).
.It Fl d , Fl Fl dmenu Ar command
Determines the command used to invoke dmenu. Executed with your shell ($SHELL) or
.Pa /bin/sh .
.It Fl Fl no-exec
Do not execute selected command, send to stdout instead.
.It Fl Fl no-generic
Do not include the generic name of desktop entries.
.It Fl t , Fl Fl term Ar command
Sets the terminal emulator used to start terminal apps.
.It Fl Fl usage-log Ar file
Must point to a read-writeable file (will create if not exists). In this mode entries are sorted by usage frequency.
.It Fl x , Fl Fl use-xdg-de
Enables reading $XDG_CURRENT_DESKTOP to determine the desktop environment.
.It Fl Fl wait-on Ar path
Must point to a path where a file can be created. In this mode no menu will be shown. Instead the program waits for
.Ar path
to be written to (use echo > path). Every time this happens a menu will be shown. Desktop files are parsed ahead of time. Performing 'echo -n q > path' will exit the program.
.It Fl Fl wrapper Ar wrapper
A wrapper binary. Useful in case you want to wrap into 'i3 exec'.
.It Fl h , Fl Fl help
Display help message.
.El
.Sh SEE ALSO
.Lk https://github.com/enkore/j4-dmenu-desktop
.Sh COPYRIGHT
Copyright (C) 2013 enkore
.Eo < Mt public+j4-dmenu-desktop@enkore.de Ec >
.Pp
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.
.Pp
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.
.Pp
You should have received a copy of the GNU General Public License along with this program. If not, see
.Eo < Lk http://www.gnu.org/licenses/ Ec > .
07070100000009000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000002600000000j4-dmenu-desktop-2.18~git20230912/src0707010000000A000081A40000000000000000000000016500A7F000002B93000000000000000000000000000000000000003500000000j4-dmenu-desktop-2.18~git20230912/src/Application.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef APPLICATION_DEF
#define APPLICATION_DEF

#include <algorithm>
#include <cstdint>
#include <cstring>
#include <limits.h>
#include <memory>
#include <stdexcept>
#include <unistd.h>

#include "LocaleSuffixes.hh"
#include "Utilities.hh"

struct disabled_error : public std::runtime_error
{
    using std::runtime_error::runtime_error;
};

struct escape_error : public std::runtime_error
{
    using std::runtime_error::runtime_error;
};

void close_file(FILE *f) {
    fclose(f);
}

class Application
{
    using application_formatter = std::string (*)(const Application &);

public:
    // Localized name
    std::string name;

    // Generic name
    std::string generic_name;

    // Command line
    std::string exec;

    // Path
    std::string path;

    // Path of .desktop file
    std::string location;

    // Terminal app
    bool terminal = false;

    // file id
    // It isn't set by Application, it is a helper variable managed by
    // Applications
    std::string id;

    bool operator==(const Application &other) const {
        return name == other.name && generic_name == other.generic_name &&
               exec == other.exec && path == other.path &&
               location == other.location && terminal == other.terminal &&
               id == other.id;
    }

    Application(const char *path, char **linep, size_t *linesz,
                application_formatter format,
                const LocaleSuffixes &locale_suffixes,
                const stringlist_t &desktopenvs) {
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // !!   The code below is extremely hacky. But fast.    !!
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //
        // Please don't try this at home.

        this->location = path;

        int locale_match = -1, locale_generic_match = -1;

        bool parse_key_values = false;
        ssize_t linelen;
        char *line;
        std::unique_ptr<FILE, decltype(&close_file)> file(fopen(path, "r"),
                                                          &close_file);
        if (!file)
            throw std::runtime_error(
                (std::string) "Couldn't open desktop file - " +
                strerror(errno));

#ifdef DEBUG
        fprintf(stderr, "%s -> ", pwd, filename);
#endif

        while ((linelen = getline(linep, linesz, file.get())) != -1) {
            line = *linep;
            line[--linelen] = 0; // Chop off \n

            // Blank line or comment
            if (!linelen || line[0] == '#')
                continue;

            if (parse_key_values) {
                // Desktop Entry section ended (b/c another section starts)
                if (line[0] == '[')
                    break;

                // Split that string in place
                char *key = line, *value = strpbrk(line, " =");
                if (!value || value == line)
                    throw std::runtime_error("Malformed file.");
                // Cut spaces before equal sign
                if (*value != '=') {
                    *value++ = '\0';
                    value = strchr(value, '=');
                    if (!value)
                        throw std::runtime_error("Malformed file.");
                } else
                    *value = '\0';
                value++;
                // Cut spaces after equal sign
                while (*value == ' ')
                    value++;

                try {
                    if (strncmp(key, "Name", 4) == 0)
                        parse_localestring(key, 4, locale_match, value,
                                           this->name, locale_suffixes);
                    else if (strncmp(key, "GenericName", 11) == 0)
                        parse_localestring(key, 11, locale_generic_match, value,
                                           this->generic_name, locale_suffixes);
                    else if (strcmp(key, "Exec") == 0)
                        this->exec = expand("Exec", value);
                    else if (strcmp(key, "Path") == 0)
                        this->path = expand("Path", value);
                    else if (strcmp(key, "OnlyShowIn") == 0) {
                        if (!desktopenvs.empty()) {
                            stringlist_t values =
                                expandlist("OnlyShowIn", value);
                            if (!have_equal_element(desktopenvs, values)) {
#ifdef DEBUG
                                fprintf(stderr,
                                        "OnlyShowIn: %s -> app is hidden\n",
                                        value);
#endif
                                throw disabled_error(
                                    "Refusing to parse desktop file whose "
                                    "OnlyShowIn field doesn't match current "
                                    "desktop.");
                            }
                        }
                    } else if (strcmp(key, "NotShowIn") == 0) {
                        if (!desktopenvs.empty()) {
                            stringlist_t values =
                                expandlist("NotShowIn", value);
                            if (have_equal_element(desktopenvs, values)) {
#ifdef DEBUG
                                fprintf(stderr,
                                        "NotShowIn: %s -> app is hidden\n",
                                        value);
#endif
                                throw disabled_error(
                                    "Refusing to parse desktop file whose "
                                    "NotShowIn field matches current desktop.");
                            }
                        }
                    } else if (strcmp(key, "Hidden") == 0 ||
                               strcmp(key, "NoDisplay") == 0) {
                        if (strcmp(value, "true") == 0) {
#ifdef DEBUG
                            fprintf(stderr, "NoDisplay/Hidden\n");
#endif
                            throw disabled_error("Refusing to parse Hidden or "
                                                 "NoDisplay desktop file.");
                        }
                    } else if (strcmp(key, "Terminal") == 0) {
                        this->terminal = strcmp(value, "true") == 0;
                    }
                } catch (const escape_error &e) {
                    fprintf(stderr, "%s: %s\n", location.c_str(), e.what());
                    throw;
                }
            } else if (!strcmp(line, "[Desktop Entry]"))
                parse_key_values = true;
        }

#ifdef DEBUG
        fprintf(stderr, "%s", this->name.c_str());
        fprintf(stderr, " (%s)\n", this->generic_name.c_str());
#endif
        this->name = format(*this);
    }

private:
    static char convert(char escape) {
        switch (escape) {
        case 's':
            return ' ';
        case 'n':
            return '\n';
        case 't':
            return '\t';
        case 'r':
            return '\r';
        case '\\':
            return '\\';
        }
        throw escape_error(
            (std::string) "Tried to interpret invalid escape sequence \\" +
            escape + ".");
    }

    std::string expand(const char *key, const char *value) {
        size_t len = strlen(value);
        std::string result;
        result.reserve(len);
        bool escape =
            false; // if true then the next character should be escaped
        try {
            for (size_t i = 0; i < len; i++) {
                if (escape) {
                    result += convert(value[i]);
                    escape = false;
                } else {
                    if (value[i] == '\\')
                        escape = true;
                    else
                        result += value[i];
                }
            }
            if (escape)
                throw escape_error("Invalid escape character at end of line.");
        } catch (const escape_error &e) {
            throw escape_error((std::string)key + ": " + e.what());
        }
        return result;
    }

    stringlist_t expandlist(const char *key, const char *value) {
        stringlist_t result;
        std::string curr;
        bool escape = false;
        try {
            do {
                if (escape) {
                    if (*value == ';') // lists also allow ; to be escaped
                                       // because it has special meaning in
                        curr += ';'; // lists, so this will handle the escaping
                                     // of it
                    else
                        curr += convert(*value);
                    escape = false;
                } else {
                    switch (*value) {
                    case '\\':
                        escape = true;
                        break;
                    case ';':
                        result.push_back(std::move(curr));
                        curr.clear();
                        break;
                    default:
                        curr += *value;
                        break;
                    }
                }
            } while (*++value != '\0');
            if (escape)
                throw escape_error("Invalid escape character at end of line.");
        } catch (const escape_error &e) {
            throw escape_error((std::string)key + ": " + e.what());
        }
        return result;
    }

    // Value is assigned to field if the new match is less or equal the current
    // match. Newer entries of same match override older ones.
    void parse_localestring(const char *key, int key_length, int &match,
                            const char *value, std::string &field,
                            const LocaleSuffixes &locale_suffixes) {
        if (key[key_length] == '[') {
            std::string locale(key + key_length + 1,
                               strlen(key + key_length + 1) - 1);

            int new_match = locale_suffixes.match(locale);
            if (new_match == -1)
                return;
            if (new_match <= match || match == -1) {
                match = new_match;
                field = expand(key, value);
            }
        } else if (match == -1 || match == 4) {
            match = 4; // The maximum match of LocaleSuffixes.match() is 3. 4
                       // means default value.
            field = expand(key, value);
        }
    }
};

#endif
0707010000000B000081A40000000000000000000000016500A7F000000C94000000000000000000000000000000000000003B00000000j4-dmenu-desktop-2.18~git20230912/src/ApplicationRunner.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef APPLICATIONRUNNER_DEF
#define APPLICATIONRUNNER_DEF

#include <iostream>
#include <string.h>
#include <unistd.h>

#include "Application.hh"
#include "Utilities.hh"

static std::string quote(const std::string &s) {
    if (s.empty())
        return {};
    std::string result = "\"";
    for (std::string::size_type i = 0; i < s.size(); i++) {
        switch (s[i]) {
        case '$':
        case '`':
        case '\\':
        case '"':
            result += '\\';
            break;
        }
        result += s[i];
    }
    result += '"';

    return result;
}

// This functions expands the field codes in Exec and prepares the arguments for
// the shell
const std::string application_command(const Application &app,
                                      const std::string &args) {
    const std::string &exec = app.exec;

    std::string result;

    bool field = false;
    for (std::string::size_type i = 0; i < exec.size(); i++) {
        if (field) {
            switch (exec[i]) {
            case '%':
                result += '%';
                break;
            case 'f': // this isn't exactly to the spec, we expect that the user
                      // specified correct arguments
            case 'F':
            case 'u':
            case 'U': {
                bool first = true;
                for (const std::string &i : split(args, ' ')) {
                    if (i.empty())
                        continue;
                    if (!first)
                        result += ' ';
                    result += quote(i);
                    first = false;
                }
            } break;
            case 'c':
                result += quote(app.name);
                break;
            case 'k':
                result += quote(app.location);
                break;
            case 'i': // icons aren't handled
            case 'd': // ignore despeaced entries
            case 'D':
            case 'n':
            case 'N':
            case 'v':
            case 'm':
                break;
            default:
                throw std::runtime_error((std::string) "Invalid field code %" +
                                         exec[i] + '.');
            }
            field = false;
        } else {
            if (exec[i] == '%')
                field = true;
            else
                result += exec[i];
        }
    }
    if (field)
        throw std::runtime_error("Invalid field code at the end of Exec.");

    return result;
}

#endif
0707010000000C000081A40000000000000000000000016500A7F00000527B000000000000000000000000000000000000003600000000j4-dmenu-desktop-2.18~git20230912/src/Applications.hh#ifndef APPLICATIONS_DEF
#define APPLICATIONS_DEF

#include "Application.hh"
#include "Formatters.hh"
#include <functional>
#include <list>
#include <map>
#include <set>
#include <string>
#include <type_traits>
#include <unordered_map>

// a container friendly version of const std::string &
struct string_ref : public std::reference_wrapper<const std::string>
{
    using std::reference_wrapper<const std::string>::reference_wrapper;

    bool operator<(const string_ref &other) const {
        return get() < other.get();
    }

    bool operator==(const string_ref &other) const {
        return get() == other.get();
    }
};

template <> struct std::hash<string_ref>
{
    std::size_t operator()(const string_ref &tohash) const noexcept {
        return std::hash<remove_const<string_ref::type>::type>{}(tohash.get());
    }
};

#include "Application.hh"

// a helper function that safely gets an iterator from container.insert() and
// container.emplace()
template <typename iterator>
iterator getiter(const std::pair<iterator, bool> &p) {
    if (!p.second) {
        fprintf(stderr, "Tried to insert an element when it was already "
                        "present, aborting...\n");
        abort();
    }
    return p.first;
}

class Applications
{
private:
    // This struct holds iterators to sortedentrymap members and a reference to
    // desktop file ID which is useful in update_log().
    struct histentry
    {
        // These iterators point to a valid element only if the name is
        // currently displayed i.e. isdisplayed() returns true.
        std::set<string_ref>::const_iterator iter;
        std::set<string_ref>::const_iterator generic_iter;
        const std::string &id;

        histentry(const std::string &s) : id(s) {}

        bool operator==(const histentry &other) const {
            return iter == other.iter && generic_iter == other.generic_iter &&
                   id == other.id;
        }
    };

    struct appcontainer;

    struct namelistentrytype
    {
        appcontainer *const app;
        bool isgeneric;

        namelistentrytype(appcontainer *a, bool i) : app(a), isgeneric(i) {}

        bool operator<(const namelistentrytype &other) const {
            return app->hist < other.app->hist;
        }

        bool operator==(const namelistentrytype &other) const {
            return app == other.app && isgeneric == other.isgeneric;
        }
    };

    // The primary struct.
    // All data about a desktop file is directly or indirectly accessible
    // through this.
    struct appcontainer
    {
        // Precedence of the desktop file based on the SearchPath order.
        // When two desktop files have the same ID, the one with lower rank
        // value has priority.
        int rank;
        Application app;

        struct
        {
            std::multiset<namelistentrytype>::const_iterator iter;
            std::multiset<namelistentrytype>::const_iterator generic_iter;
        } listcandidate;

        std::list<histentry>::iterator listed;
        unsigned hist = 0;
        bool display = true;

        appcontainer(int r, const Application &a) : rank(r), app(a) {}

        bool operator==(const appcontainer &other) const {
            return rank == other.rank && app == other.app &&
                   hist == other.hist && display == other.display;
        }
    };

    // None of these four containers shall have an empty container as their
    // value, because that would break things. Applications must take care to
    // remove the entire key value pair when it's removing the last entry from
    // value. For example when there are two names belonging to one desktop
    // entry in sortedentrymap with history 1, the sortedentrymap[1] must be
    // removed altogether when the desktop entry's history increases because
    // empty std::set<string_ref> would break sortediter.

    std::unordered_map<std::string /* ID */, appcontainer> idmap;

    // This map contains all Names and GenericNames of all programs as keys and
    // the desktop entries with that name as values. This prevents duplicate
    // names. Each name can have one or more namelistentrytypes attached to it,
    // but only the last one (the one for which isdisplayed() returns true) is
    // active.
    std::unordered_map<std::string, std::multiset<namelistentrytype>> namelist;

    std::map<unsigned, std::list<histentry>> sortedhistmap;
    // This map is used for sorted output into Dmenu.
    // Beware, a desktop entry doesn't have to have both Name and GenericName
    // displayed because there could be a desktop entry with higher history and
    // with the same Name or GenericName. Higher history has higher priority.
    // Both Name and GenericName can be shadowed.
    std::map<unsigned, std::set<string_ref>, std::greater<unsigned>>
        sortedentrymap;

    application_formatter format;
    char *linep = nullptr;
    size_t linesz = 0;
    LocaleSuffixes suffixes;
    stringlist_t desktopenvs;
    bool exclude_generic;
    bool use_history;

    bool isdisplayed(const std::multiset<namelistentrytype> &list,
                     const std::multiset<namelistentrytype>::const_iterator
                         &listiter) const {
        return std::prev(list.end()) == listiter;
    }

    bool isdisplayed(const appcontainer &app, bool isgeneric) const {
        if (isgeneric)
            return isdisplayed(namelist.at(app.app.generic_name),
                               app.listcandidate.generic_iter);
        else
            return isdisplayed(namelist.at(app.app.name),
                               app.listcandidate.iter);
    }

    void add_generic(appcontainer &appc, bool isgeneric) {
        const std::string &name =
            isgeneric ? appc.app.generic_name : appc.app.name;
        std::set<string_ref>::const_iterator &histiter =
            isgeneric ? appc.listed->generic_iter : appc.listed->iter;
        std::multiset<namelistentrytype>::const_iterator &namelistentry =
            isgeneric ? appc.listcandidate.generic_iter
                      : appc.listcandidate.iter;

        auto listentries = namelist.find(name);
        if (listentries == namelist.end()) {
            namelistentry = namelist[name].emplace(&appc, isgeneric);
            histiter = getiter(sortedentrymap[appc.hist].emplace(name));
        } else {
            namelistentry = listentries->second.emplace(&appc, isgeneric);
            if (isdisplayed(appc, isgeneric)) { // we are currently displayed,
                                                // undisplay the old entry
                auto &orig = *std::prev(namelistentry);
                if (orig.isgeneric)
                    sortedentrymap.at(orig.app->hist)
                        .erase(orig.app->listed->generic_iter);
                else
                    sortedentrymap.at(orig.app->hist)
                        .erase(orig.app->listed->iter);
                if (sortedentrymap.at(orig.app->hist).empty())
                    sortedentrymap.erase(orig.app->hist);
            }
            histiter = getiter(sortedentrymap[appc.hist].emplace(name));
        }
    }

    void deletename_generic(appcontainer &appc, bool isgeneric) {
        const std::string &name =
            isgeneric ? appc.app.generic_name : appc.app.name;
        std::set<string_ref>::const_iterator &sortediter =
            isgeneric ? appc.listed->generic_iter : appc.listed->iter;
        const std::multiset<namelistentrytype>::const_iterator &listiter =
            isgeneric ? appc.listcandidate.generic_iter
                      : appc.listcandidate.iter;

        if (namelist.at(name).size() == 1) {
            sortedentrymap.at(appc.hist).erase(sortediter);
            if (sortedentrymap.at(appc.hist).empty())
                sortedentrymap.erase(appc.hist);
            namelist.erase(name); // delete the entire namelist entry rather
                                  // than having it with an empty list
        } else if (isdisplayed(namelist.at(name), listiter)) {
            sortedentrymap.at(appc.hist).erase(
                sortediter); // delete listed entry of name
            if (sortedentrymap.at(appc.hist).empty())
                sortedentrymap.erase(appc.hist);
            namelist.at(name).erase(listiter);
            auto &newentry = *std::prev(
                namelist.at(name)
                    .end()); // replace it with the next suitable entry
            if (!exclude_generic && newentry.isgeneric)
                newentry.app->listed->generic_iter =
                    getiter(sortedentrymap[newentry.app->hist].insert(
                        newentry.app->app.generic_name));
            else
                newentry.app->listed->iter =
                    getiter(sortedentrymap[newentry.app->hist].insert(
                        newentry.app->app.name));
        } else
            namelist.at(name).erase(listiter);
    }

    void deletename(appcontainer &todelete) {
        deletename_generic(todelete, false);
        if (!exclude_generic && !todelete.app.generic_name.empty())
            deletename_generic(todelete, true);
        sortedhistmap.at(todelete.hist).erase(todelete.listed);
        if (sortedhistmap.at(todelete.hist).empty())
            sortedhistmap.erase(todelete.hist);
    }

    void sethistory_generic(appcontainer &appc, bool isgeneric) {
        std::set<string_ref>::const_iterator &sortediter =
            isgeneric ? appc.listed->generic_iter : appc.listed->iter;
        std::multiset<namelistentrytype>::const_iterator &nameiter =
            isgeneric ? appc.listcandidate.generic_iter
                      : appc.listcandidate.iter;
        const std::string &name =
            isgeneric ? appc.app.generic_name : appc.app.name;

        nameiter = namelist[name].emplace(&appc, isgeneric);
        if (isdisplayed(appc, isgeneric)) {
            if (namelist.at(name).size() != 1) {
                const namelistentrytype &undisplay = *std::prev(nameiter);
                if (!exclude_generic && undisplay.isgeneric)
                    sortedentrymap.at(undisplay.app->hist)
                        .erase(undisplay.app->listed->generic_iter);
                else
                    sortedentrymap.at(undisplay.app->hist)
                        .erase(undisplay.app->listed->iter);
                if (sortedentrymap.at(undisplay.app->hist).empty())
                    sortedentrymap.erase(undisplay.app->hist);
            }

            sortediter = getiter(sortedentrymap[appc.hist].emplace(name));
        }
    }

    void sethistory(appcontainer &appc, unsigned newval) {
        deletename(appc);

        appc.hist = newval;

        appc.listed = sortedhistmap[newval].insert(sortedhistmap[newval].end(),
                                                   appc.app.id);

        sethistory_generic(appc, false);
        if (!exclude_generic && !appc.app.generic_name.empty())
            sethistory_generic(appc, true);
    }

    // This iterator crawls through sortedentrymap and mapped_type and presents
    // it continuously.
    class sortediter
    {
    private:
        decltype(sortedentrymap)::const_iterator topiter;
        std::set<string_ref>::const_iterator nameiter;
        // When topiter is incremented, we can't just set nameiter to
        // topiter->second.begin() because the newly incremented topiter might
        // be the past-the-end iterator and therefore undeferencable. When
        // topiter is incremented, isunknown is set to true and the next time
        // someone deferences or increments sortediter, we assume that topiter
        // is deferencable and set nameiter.
        bool isunknown = false;

    public:
        typedef std::ptrdiff_t difference_type;
        typedef std::string value_type;
        typedef const std::string *pointer;
        typedef const std::string &reference;
        typedef std::forward_iterator_tag iterator_category;

        reference operator*() const {
            if (isunknown)
                return topiter->second.begin()->get();
            return nameiter->get();
        }

        sortediter &operator++() {
            if (isunknown) {
                isunknown = false;
                nameiter = topiter->second.begin();
            }
            ++nameiter;
            if (topiter->second.end() == nameiter) {
                ++topiter;
                isunknown = true;
            }
            return *this;
        }

        bool operator==(const sortediter &other) const {
            return topiter == other.topiter &&
                   (isunknown == other.isunknown &&
                    (isunknown || nameiter == other.nameiter));
        }

        bool operator!=(const sortediter &other) const {
            return !(*this == other);
        }

        pointer operator->() const {
            return &operator*();
        }

        sortediter operator++(int) {
            sortediter ret = *this;
            operator++();
            return ret;
        }

        sortediter() = default;

        sortediter(decltype(topiter) t, decltype(nameiter) n)
            : topiter(t), nameiter(n) {}

        // This is the constructor for the past-the-end iterator of sortediter
        sortediter(decltype(topiter) t) : topiter(t), isunknown(true) {}
    };

public:
    Applications(application_formatter f, const stringlist_t &denvs,
                 const LocaleSuffixes &suff, bool exclude, bool history)
        : format(f), suffixes(suff), desktopenvs(denvs),
          exclude_generic(exclude), use_history(history) {}

    /// These functions and operators don't have much use in j4dd, but are
    /// useful for tests.

    Applications(const Applications &other)
        : format(other.format), suffixes(other.suffixes),
          desktopenvs(other.desktopenvs),
          exclude_generic(other.exclude_generic),
          use_history(other.use_history) {
        for (const auto &i : other.idmap) {
            auto &curr = *getiter(idmap.emplace(i));
            auto &appc = curr.second;

            namelist[appc.app.name].emplace(&appc, false);
            appc.listed = sortedhistmap[appc.hist].insert(
                sortedhistmap[appc.hist].end(), curr.first);
            if (other.isdisplayed(i.second, false))
                appc.listed->iter =
                    getiter(sortedentrymap[appc.hist].insert(appc.app.name));
            if (!exclude_generic && !appc.app.generic_name.empty()) {
                namelist[appc.app.generic_name].emplace(&appc, true);
                if (other.isdisplayed(i.second, true))
                    appc.listed->generic_iter =
                        getiter(sortedentrymap[appc.hist].insert(
                            appc.app.generic_name));
            }
        }
    }

    friend void swap(Applications &a, Applications &b) {
        using std::swap;

        swap(a.format, b.format);
        swap(a.suffixes, b.suffixes);
        swap(a.desktopenvs, b.desktopenvs);
        swap(a.exclude_generic, b.exclude_generic);
        swap(a.use_history, b.use_history);
        swap(a.idmap, b.idmap);
        swap(a.namelist, b.namelist);
        swap(a.sortedhistmap, b.sortedhistmap);
        swap(a.sortedentrymap, b.sortedentrymap);
    }

    Applications &operator=(Applications other) {
        swap(*this, other);

        return *this;
    }

    bool operator==(const Applications &other) const {
        return format == other.format && suffixes == other.suffixes &&
               desktopenvs == other.desktopenvs &&
               exclude_generic == other.exclude_generic &&
               use_history == other.use_history && idmap == other.idmap &&
               sortedentrymap == other.sortedentrymap;
    }

    ///

    ~Applications() {
        if (linesz != 0)
            free(linep);
    }

    sortediter begin() const {
        if (sortedentrymap.empty())
            return end();
        else
            return sortediter(sortedentrymap.cbegin(),
                              sortedentrymap.cbegin()->second.cbegin());
    }

    sortediter end() const {
        return sortediter(sortedentrymap.cend());
    }

    using size_type = decltype(idmap)::size_type;

    size_type size() const {
        return idmap.size();
    }

    void remove(const std::string &filename, int rank) {
        std::string id;
        id.reserve(filename.size());
        std::replace_copy(filename.cbegin(), filename.cend(),
                          std::back_inserter(id), '/', '-');

        auto appiter = idmap.find(id);
        if (appiter == idmap.end())
            throw std::runtime_error("Couldn't remove nonexistent item.");
        auto &app = appiter->second;
        if (app.rank != rank)
            return;

        deletename(app);
        idmap.erase(appiter);
    }

    // add or overwrite the file filename
    // providing a path and a filename instead of the absolute path is done to
    // be able to distinguish the desktop file ID
    void add(const std::string &filename, int rank, const std::string &path) {
        std::string id;
        id.reserve(filename.size());
        std::replace_copy(filename.cbegin(), filename.cend(),
                          std::back_inserter(id), '/', '-');

        auto tryfind = idmap.find(id);
        try {
            if (tryfind != idmap.end()) // application already exists
            {
                if (rank > tryfind->second.rank)
                    return;

                deletename(tryfind->second);

                tryfind->second.rank = rank;
                tryfind->second.app =
                    Application((path + filename).c_str(), &linep, &linesz,
                                format, suffixes, desktopenvs);
            } else
                tryfind = getiter(idmap.emplace(
                    std::piecewise_construct, std::forward_as_tuple(id),
                    std::forward_as_tuple(rank,
                                          Application((path + filename).c_str(),
                                                      &linep, &linesz, format,
                                                      suffixes, desktopenvs))));
        } catch (
            disabled_error &) // if the desktop file is disabled, do nothing
        {
            return;
        } catch (escape_error &) {
            return;
        }

        auto &appc = tryfind->second;

        appc.app.id = id;
        appc.listed =
            sortedhistmap[0].insert(sortedhistmap[0].end(), appc.app.id);

        add_generic(appc, false);
        if (!exclude_generic && !appc.app.generic_name.empty())
            add_generic(appc, true);
    }

    std::pair<Application *, std::string> get(const std::string &choice) {
        appcontainer *app;
        size_t match_length = 0;

        // Find longest match amongst apps
        for (const auto &current_app : namelist) {
            const auto &name = current_app.first;
            auto &currapp = std::prev(current_app.second.end())->app;

            if (name.size() > match_length && startswith(choice, name)) {
                app = currapp;
                match_length = name.length();
            }
        }

        if (match_length) {
            if (use_history)
                sethistory(*app, app->hist + 1);
            // +1 b/c there must be whitespace we add back later...
            return std::make_pair(
                &app->app, choice.substr(match_length, choice.length() - 1));
        }

        // No matching app found, return user dmenu choice
        return std::make_pair(nullptr, choice);
    }

    // If the log doesn't exist, than do nothing. A next update_log() call
    // should create it.
    void load_log(const char *log) {
        if (!use_history)
            return;
        FILE *fp = fopen(log, "r");
        if (!fp)
            return;

        unsigned count;
        char name[256];
        while (fscanf(fp, "%u,%255[^\n]\n", &count, name) == 2) {
            auto appc = idmap.find(name);
            if (appc == idmap.end())
                continue;

            sethistory(appc->second, count);
        }

        fclose(fp);
    }

    void update_log(const char *log) {
        if (!use_history)
            return;
        std::stringstream write_file;
        write_file << log << "." << getpid();
        FILE *fp = fopen(write_file.str().c_str(), "w");
        if (!fp) {
            fprintf(stderr, "Can't write usage log '%s': %s\n", log,
                    strerror(errno));
            exit(EXIT_FAILURE);
        }

        for (auto x = sortedhistmap.crbegin();
             x != sortedhistmap.crend() && x->first != 0; ++x) {
            for (const auto &y : x->second) {
                if (fprintf(fp, "%u,%s\n", x->first, y.id.c_str()) < 0) {
                    perror("Write error");
                    fclose(fp);
                    return;
                }
            }
        }

        fclose(fp);

        if (rename(write_file.str().c_str(), log)) {
            perror("rename failed");
        }
    }
};

#endif
0707010000000D000081A40000000000000000000000016500A7F000000D86000000000000000000000000000000000000002F00000000j4-dmenu-desktop-2.18~git20230912/src/Dmenu.hh#ifndef DMENU_DEF
#define DMENU_DEF

#include <stdexcept>
#include <unistd.h>

#include <sys/stat.h>
#include <sys/wait.h>

static int write_proper(const int fd, const char *buf, size_t size) {
    while (size) {
        ssize_t written = write(fd, buf, size);
        if (written == -1) {
            if ((errno == EINTR) || (errno == EWOULDBLOCK) ||
                (errno == EAGAIN)) {
                continue;
            } else {
                break;
            }
        }

        buf += written;
        size -= written;
    }

    return size ? -1 : 0;
}

class Dmenu
{
public:
    Dmenu(const std::string &dmenu_command, const char *sh)
        : dmenu_command(dmenu_command), shell(sh) {}

    Dmenu(const Dmenu &dmenu) = delete;
    void operator=(const Dmenu &dmenu) = delete;

    void write(const std::string &what) {
        write_proper(this->outpipe[1], what.c_str(), what.size());
        write_proper(this->outpipe[1], "\n", 1);
    }

    void display() {
        // Closing the pipe produces EOF for dmenu, signalling
        // end of all options. dmenu shows now up on the screen
        // (if -f hasn't been used)
        close(this->outpipe[1]);
    }

    std::string read_choice() {
        int status;
        waitpid(this->pid, &status, 0);

        // If dmenu exited abnormally, than it is unlikely that the WIFEXITED ==
        // false handler will be executed because j4dd would receive SIGPIPE or
        // block when trying to call Dmenu::write().
        if (!WIFEXITED(status)) {
            close(inpipe[0]);
            fprintf(stderr, "ERROR: Dmenu exited abnormally.\n");
            exit(EXIT_FAILURE);
        }
        if (WEXITSTATUS(status) !=
            0) { // Dmenu returns 1 when the user exits dmenu with the Escape
                 // key, signaling that no choice was made.
            close(inpipe[0]);
            return {};
        }

        std::string choice;
        char buf[256];
        ssize_t len;
        while ((len = read(inpipe[0], buf, sizeof buf)) > 0)
            choice.append(buf, len);
        if (len == -1)
            perror("read");
        if (choice.back() == '\n')
            choice.pop_back();
        close(inpipe[0]);
        return choice;
    }

    void run() {
        // Create the dmenu as soon as we know the command,
        // this speeds up things a bit if the -f flag for dmenu is
        // used

        if (pipe(this->inpipe) == -1 || pipe(this->outpipe) == -1)
            throw std::runtime_error("Dmenu::create(): pipe() failed");

        this->pid = fork();
        switch (this->pid) {
        case -1:
            throw std::runtime_error("Dmenu::create(): fork() failed");
        case 0:
            close(this->inpipe[0]);
            close(this->outpipe[1]);

            dup2(this->inpipe[1], STDOUT_FILENO);
            dup2(this->outpipe[0], STDIN_FILENO);

            close(this->inpipe[1]);
            close(this->outpipe[0]);

            execl(
                shell, shell, "-c", this->dmenu_command.c_str(), 0,
                nullptr); // double nulls are needed because of
                          // https://github.com/enkore/j4-dmenu-desktop/pull/66#issuecomment-273126739
            _exit(EXIT_FAILURE);
        }

        close(this->inpipe[1]);
        close(this->outpipe[0]);
    }

private:
    const std::string &dmenu_command;
    const char *shell;

    int inpipe[2];
    int outpipe[2];
    int pid = 0;
};
#endif
0707010000000E000081A40000000000000000000000016500A7F0000008BA000000000000000000000000000000000000003400000000j4-dmenu-desktop-2.18~git20230912/src/FileFinder.hh#ifndef FILEFINDER_DEF
#define FILEFINDER_DEF

#include <cstddef>
#include <dirent.h>
#include <iterator>
#include <stack>
#include <stdexcept>
#include <vector>

#include "Utilities.hh"

class FileFinder
{
public:
    typedef std::input_iterator_tag iterator_category;

    FileFinder(const std::string &path) : done(false), dir(NULL) {
        dirstack.push(path);
    }

    operator bool() const {
        return !done;
    }

    const std::string &path() const {
        return curpath;
    }

    bool isdir() const {
        return curisdir;
    }

    FileFinder &operator++() {
        if (direntries.empty()) {
            dirent *entry;
            opendir();
            if (done)
                return *this;
            while ((entry = readdir(dir))) {
                if (entry->d_name[0] == '.') {
                    // Exclude ., .. and hidden files
                    continue;
                }
                direntries.emplace_back(entry);
            }
            closedir(dir);
            dir = NULL;
            std::sort(direntries.begin(), direntries.end(),
                      [](const _dirent &a, const _dirent &b) {
                          return a.d_ino > b.d_ino;
                      });
            return ++(*this);

        } else {
            curpath = curdir + direntries.back().d_name;
            curisdir = is_directory(curpath);
            direntries.pop_back();
            if (curisdir) {
                dirstack.push(curpath + "/");
            }
            return *this;
        }
    }

private:
    struct _dirent
    {
        _dirent(const dirent *ent) : d_ino(ent->d_ino), d_name(ent->d_name) {}

        ino_t d_ino;
        std::string d_name;
    };

    void opendir() {
        if (dirstack.empty()) {
            done = true;
            return;
        }

        curdir = dirstack.top();
        dirstack.pop();
        dir = ::opendir(curdir.c_str());
        if (!dir)
            throw std::runtime_error(curdir + ": opendir() failed");
        direntries.clear();
    }

    bool done;

    DIR *dir;
    std::stack<std::string> dirstack;
    std::vector<_dirent> direntries;

    std::string curpath;
    bool curisdir;
    std::string curdir;
};

#endif
0707010000000F000081A40000000000000000000000016500A7F000000698000000000000000000000000000000000000003400000000j4-dmenu-desktop-2.18~git20230912/src/Formatters.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef DESKTOP_DEF
#define DESKTOP_DEF

#include <string>

#include "Application.hh"

using application_formatter = std::string (*)(const Application &);

inline std::string appformatter_default(const Application &app) {
    return app.name;
}

inline std::string appformatter_with_binary_name(const Application &app) {
    // get name and the first part of exec
    return app.name + " (" + app.exec.substr(0, app.exec.find(' ')) + ")";
}

std::string appformatter_with_base_binary_name(const Application &app) {
    auto command_end = app.exec.find(' ');
    auto last_slash = app.exec.rfind('/', command_end);

    if (last_slash == std::string::npos)
        last_slash = 0; // exec is relative, it doesn't contain slashes in path
    else
        last_slash++;
    if (command_end != std::string::npos)
        command_end -= last_slash; // make command_end an offset from last_slash

    return app.name + " (" + app.exec.substr(last_slash, command_end) + ")";
}

#endif
07070100000010000081A40000000000000000000000016500A7F000000EF1000000000000000000000000000000000000003800000000j4-dmenu-desktop-2.18~git20230912/src/LocaleSuffixes.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef LOCALE_DEF
#define LOCALE_DEF

#include <set>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>

class LocaleSuffixes
{
public:
    LocaleSuffixes(std::string locale = set_locale()) {
        size_t uscorepos = 0, dotpos = 0, atpos = 0;

        for (size_t i = 0; i < locale.length(); i++) {
            switch (locale[i]) {
            case '_':
                uscorepos = i;
                break;
            case '.':
                dotpos = i;
                break;
            case '@':
                atpos = i;
                break;
            }
        }

        // Strip encoding
        if (dotpos != 0) {
            if (atpos == 0)
                locale.erase(dotpos);
            else {
                locale.erase(dotpos, atpos - dotpos);
                atpos = dotpos;
            }
        }

        this->suffixes[0] = locale;

        if (uscorepos == 0 && atpos == 0) {
            this->length = 1;
            return;
        }

        if (uscorepos != 0 && atpos != 0) {
            this->suffixes[1] = locale.substr(0, atpos);
            this->suffixes[2] =
                locale.substr(0, uscorepos) + locale.substr(atpos);
            this->suffixes[3] = locale.substr(0, uscorepos);
        } else {
            this->length = 2;
            this->suffixes[1] =
                locale.substr(0, (atpos == 0 ? uscorepos : atpos));
        }

#ifdef DEBUG
        for (int i = 0; this->length; i++)
            fprintf(stderr, "LocaleSuffix: %s\n", this->suffixes[i].c_str());
#endif
    }

    // this function tests if a given string is matched by the current locale
    // it returns an int that signifies how well it matches so that Application
    // can skip localized keys with locales which have lower priority than a
    // previously matched one
    int match(const std::string &str) const {
        for (int i = 0; i < this->length; i++) {
            if (suffixes[i] == str)
                return i;
        }
        return -1;
    }

    bool operator==(const LocaleSuffixes &other) const {
        return length == other.length &&
               std::equal(suffixes, suffixes + length, other.suffixes);
    }

private:
    std::string suffixes[4];
    // There are three possible values of length:
    // 1 - there is only a single variation of the current locale - lang
    // 2 - there are two variations - lang@MODIFIER and lang_COUNTRY
    // 4 - all four variations are valid - lang_COUNTRY@MODIFIER
    int length = 4;

    static std::string set_locale() {
        char *user_locale = setlocale(LC_MESSAGES, "");
        if (!user_locale) {
            fprintf(stderr, "Locale configuration invalid, check locale(1).\n"
                            "No translated menu entries will be available.\n");
            user_locale = setlocale(LC_MESSAGES, "C");
            if (!user_locale) {
                fprintf(stderr, "POSIX/C locale is not available, setlocale(3) "
                                "failed. Bailing.\n");
                abort();
            }
        }
        return user_locale;
    }
};

#endif
07070100000011000081A40000000000000000000000016500A7F000000018000000000000000000000000000000000000003300000000j4-dmenu-desktop-2.18~git20230912/src/Notify.hh.in#cmakedefine USE_KQUEUE
07070100000012000081A40000000000000000000000016500A7F0000002F3000000000000000000000000000000000000003400000000j4-dmenu-desktop-2.18~git20230912/src/NotifyBase.hh#ifndef NOTIFYBASE_DEF
#define NOTIFYBASE_DEF

#include <string>
#include <vector>

class NotifyBase
{
public:
    virtual ~NotifyBase() {}

    // getfd() returns a file descriptor that should become readable when
    // desktop entries have been modified.
    virtual int getfd() const = 0;

    // Applicaions doesn't see a difference between created and modified desktop
    // files so only a single flag is used for them.
    enum changetype { modified, deleted };

    struct filechange
    {
        int rank;
        std::string name;
        changetype status;

        filechange(int r, std::string n, changetype s)
            : rank(r), name(std::move(n)), status(s) {}
    };

    virtual std::vector<filechange> getchanges() = 0;
};
#endif
07070100000013000081A40000000000000000000000016500A7F000000B44000000000000000000000000000000000000003700000000j4-dmenu-desktop-2.18~git20230912/src/NotifyInotify.hh#ifndef NOTIFYINOTIFY_DEV
#define NOTIFYINOTIFY_DEV

#include <sys/inotify.h>
#include <unordered_map>

#include "FileFinder.hh"
#include "NotifyBase.hh"
#include "Utilities.hh"

class NotifyInotify : public NotifyBase
{
private:
    int inotifyfd;

    struct directory_entry
    {
        int rank;
        std::string path; // this is the intermediate path for subdirectories in
                          // searchpath directory

        directory_entry(int r, std::string p) : rank(r), path(std::move(p)) {}
    };

    std::unordered_map<int /* watch descriptor */, directory_entry> directories;

public:
    NotifyInotify(const stringlist_t &search_path) {
        inotifyfd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
        if (inotifyfd == -1)
            pfatale("inotify_init");

        for (int i = 0; i < (int)search_path.size();
             i++) // size() is converted to int to silent warnings about
                  // narrowing when adding i to directories
        {
            int wd = inotify_add_watch(inotifyfd, search_path[i].c_str(),
                                       IN_DELETE | IN_MODIFY);
            if (wd == -1)
                pfatale("inotify_add_watch");
            directories.insert({
                wd, {i, {}}
            });
            FileFinder find(search_path[i]);
            while (++find) {
                if (!find.isdir())
                    continue;
                wd = inotify_add_watch(inotifyfd, find.path().c_str(),
                                       IN_DELETE | IN_MODIFY);
                directories.insert({
                    wd,
                    {i, find.path().substr(search_path[i].length()) + '/'}
                });
            }
        }
    }

    NotifyInotify(const NotifyInotify &) = delete;
    void operator=(const NotifyInotify &) = delete;

    int getfd() const {
        return inotifyfd;
    }

    std::vector<filechange> getchanges() {
        char buffer alignas(inotify_event)[4096];
        ssize_t len;
        std::vector<filechange> result;

        while ((len = read(inotifyfd, buffer, sizeof buffer)) > 0) {
            const inotify_event *event;
            for (const char *ptr = buffer; ptr < buffer + len;
                 ptr += sizeof(inotify_event) + event->len) {
                event = reinterpret_cast<const inotify_event *>(ptr);

                const auto &dir = directories.at(event->wd);

                if (event->mask & IN_MODIFY)
                    result.push_back({dir.rank, dir.path + event->name,
                                      changetype::modified});
                else
                    result.push_back({dir.rank, dir.path + event->name,
                                      changetype::deleted});
            }
        }

        if (len == -1 && errno != EAGAIN)
            perror("read");

        return result;
    }
};
#endif
07070100000014000081A40000000000000000000000016500A7F00000193F000000000000000000000000000000000000003600000000j4-dmenu-desktop-2.18~git20230912/src/NotifyKqueue.hh#ifndef NOTIFYKQUEUE_DEF
#define NOTIFYKQUEUE_DEF

#include "NotifyBase.hh"
#include <mutex>
#include <sys/event.h>
#include <sys/time.h>
#include <sys/types.h>
#include <thread>

/*
 * This is the Notify implementation for systems using kqueue.
 * Unlike NotifyInotify, this implementation doesn't handle desktop file
 * modification. This could be implemented, but it would take up a bit more file
 * descriptors and desktop files aren't really modified often. The most typical
 * desktop file modifications are their creation on package install and their
 * removal on package uninstallation.
 */

class NotifyKqueue : public NotifyBase
{
private:
    int pipefd[2];

    struct directory_entry
    {
        int queue;
        int rank;
        // Files contains a list of processed desktop files. This list is then
        // compared to the current state to see whether files have been added or
        // removed.
        std::set<std::string> files;
        std::string path; // this is the intermediate path for subdirectories in
                          // searchpath directory

        directory_entry(int q, int r, std::string p)
            : queue(q), rank(r), path(std::move(p)) {}
    };

    std::vector<filechange> changes;
    std::mutex changes_mutex;

    static void process_kqueue(const stringlist_t &search_path,
                               std::vector<directory_entry> directories,
                               NotifyKqueue &instance) {
        struct kevent event;
        timespec timeout = {0};

        while (true) {
            for (auto &i : directories) {
                switch (kevent(i.queue, NULL, 0, &event, 1, &timeout)) {
                case 0:
                    continue;
                case 1:
                    break;
                default:
                    pfatale("kevent");
                }

                DIR *d = opendir((search_path[i.rank] + i.path).c_str());
                if (d == NULL)
                    pfatale("opendir");

                std::set<std::string> files;

                struct dirent *dir;
                while ((dir = readdir(d))) {
                    if (dir->d_name[0] == '.')
                        continue;
                    if (is_directory(search_path[i.rank] + i.path +
                                     dir->d_name))
                        continue;
                    files.insert(std::string(dir->d_name));
                }

                closedir(d);

                {
                    std::lock_guard<std::mutex> lock(instance.changes_mutex);

                    std::vector<std::string> diff;
                    std::set_difference(i.files.begin(), i.files.end(),
                                        files.begin(), files.end(),
                                        std::back_inserter(diff));
                    for (const auto &missing : diff) {
                        i.files.erase(missing);
                        instance.changes.push_back(
                            {i.rank, i.path + missing, changetype::deleted});
                    }

                    diff.clear();
                    std::set_difference(files.begin(), files.end(),
                                        i.files.begin(), i.files.end(),
                                        std::back_inserter(diff));
                    for (const auto &added : diff) {
                        i.files.insert(added);
                        instance.changes.push_back(
                            {i.rank, i.path + added, changetype::modified});
                    }
                }

                write(instance.pipefd[1], "", 1);
            }

            std::this_thread::sleep_for(std::chrono::minutes(1));
        }
    }

public:
    NotifyKqueue(const stringlist_t &search_path) {
        if (pipe2(pipefd, O_NONBLOCK | O_CLOEXEC) == -1)
            pfatale("pipe");

        std::vector<directory_entry> directories;

        // We reuse the event and only change the ident.
        struct kevent event;
        EV_SET(&event, 0, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL);

        for (int i = 0; i < (int)search_path.size();
             i++) // size() is converted to int to silent warnings about
                  // narrowing when adding i to directories
        {
            std::stack<std::string, std::vector<std::string>> dirstack;
            dirstack.push(search_path[i]);

            while (!dirstack.empty()) {
                std::string path = dirstack.top();
                dirstack.pop();

                int queue = kqueue();
                if (queue == -1)
                    pfatale("kqueue");
                if (fcntl(queue, F_SETFD, FD_CLOEXEC) == -1)
                    pfatale("fcntl");
                int fd = open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
                if (fd == -1)
                    pfatale("open");

                event.ident = fd;
                if (kevent(queue, &event, 1, NULL, 0, NULL) == -1)
                    pfatale("kevent");

                directories.push_back(
                    {queue, i, path.substr(search_path[i].length())});
                auto &files = directories.back().files;

                DIR *d = opendir(path.c_str());
                if (d == NULL)
                    pfatale("opendir");

                struct dirent *file;
                while ((file = readdir(d))) {
                    // Exclude ., .. and hidden files
                    if (file->d_name[0] == '.')
                        continue;

                    if (is_directory(path + file->d_name))
                        dirstack.push(path + file->d_name + '/');
                    else {
                        files.insert(std::string(file->d_name));
                    }
                }

                closedir(d);
            }
        }

        std::thread t(process_kqueue, search_path, std::move(directories),
                      std::ref(*this));
        t.detach();
    }

    int getfd() const {
        return pipefd[0];
    }

    std::vector<filechange> getchanges() {
        std::vector<filechange> result;
        {
            std::lock_guard<std::mutex> lock(changes_mutex);
            result = changes;
            changes.clear();
        }
        char dump;
        while (read(pipefd[0], &dump, 1) != -1)
            ;
        if (errno != EAGAIN)
            pfatale("read");
        return result;
    }
};

#endif
07070100000015000081A40000000000000000000000016500A7F0000006A1000000000000000000000000000000000000003400000000j4-dmenu-desktop-2.18~git20230912/src/SearchPath.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef SEARCHPATH_DEF
#define SEARCHPATH_DEF

#include "Utilities.hh"

void add_applications_dir(std::string &str) {
    if (str.back() == '/') // fix double slashes
        str.pop_back();
    if (!endswith(str, "/applications"))
        str += "/applications";
    str += '/';
}

stringlist_t get_search_path() {
    stringlist_t result;

    std::string xdg_data_home = get_variable("XDG_DATA_HOME");
    if (xdg_data_home.empty())
        xdg_data_home = get_variable("HOME") + "/.local/share/";

    add_applications_dir(xdg_data_home);
    if (is_directory(xdg_data_home))
        result.push_back(xdg_data_home);

    std::string xdg_data_dirs = get_variable("XDG_DATA_DIRS");
    if (xdg_data_dirs.empty())
        xdg_data_dirs = "/usr/share/:/usr/local/share/";

    auto dirs = split(xdg_data_dirs, ':');
    for (auto &path : dirs) {
        add_applications_dir(path);
        if (is_directory(path))
            result.push_back(path);
    }

    return result;
}

#endif
07070100000016000081A40000000000000000000000016500A7F000000140000000000000000000000000000000000000002E00000000j4-dmenu-desktop-2.18~git20230912/src/Test.cc// #include "Application.hh"

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "TestApplication.cc"
#include "TestApplicationRunner.cc"
#include "TestApplications.cc"
#include "TestFileFinder.cc"
#include "TestFormatters.cc"
#include "TestLocaleSuffixes.cc"
#include "TestNotify.cc"
#include "TestSearchPath.cc"
07070100000017000081A40000000000000000000000016500A7F0000015A9000000000000000000000000000000000000003900000000j4-dmenu-desktop-2.18~git20230912/src/TestApplication.cc#include <stddef.h>
#include <stdlib.h>
#include <string>

#include "Application.hh"
#include "Formatters.hh"
#include "LocaleSuffixes.hh"
#include "catch.hpp"

TEST_CASE("Application/invalid_file", "") {
    LocaleSuffixes ls("en_US");
    char *buffer = nullptr;
    size_t size;
    REQUIRE_THROWS(Application("some-file-that-doesnt-exist", &buffer, &size,
                               appformatter_default, ls, {}));
}

TEST_CASE("Application/valid/eagle",
          "Validates correct parsing of a simple file") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/eagle.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name == "Eagle");
    REQUIRE(app.exec == "eagle -style plastique");
    REQUIRE(!app.terminal);

    free(buffer);
}

TEST_CASE("Application/valid/htop",
          "Similar to Application/valid/eagle, just for a term app") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/htop.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name == "Htop");
    REQUIRE(app.exec == "htop");
    REQUIRE(app.terminal);

    free(buffer);
}

TEST_CASE("Application/valid/gimp",
          "Tests correct parsing of localization and stuff") {
    LocaleSuffixes ls("eo");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/gimp.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name ==
            "Bildmanipulilo (GIMP = GNU Image Manipulation Program)");
    REQUIRE(app.generic_name == "Bildredaktilo");
    REQUIRE(app.exec == "gimp-2.8 %U");
    REQUIRE(!app.terminal);

    free(buffer);
}

TEST_CASE("Application/valid/long_line",
          "Tests correct parsing of file with line longer than buffer") {
    LocaleSuffixes ls("eo");
    size_t size = 20;
    char *buffer = static_cast<char *>(malloc(20));
    Application app(TEST_FILES "applications/gimp.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name ==
            "Bildmanipulilo (GIMP = GNU Image Manipulation Program)");
    REQUIRE(app.exec == "gimp-2.8 %U");
    REQUIRE(!app.terminal);
    REQUIRE(size > 20);

    free(buffer);
}

TEST_CASE(
    "Application/flag/hidden=false",
    "Regression test for issue #17, Hidden=false was read as Hidden=true") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/visible.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name == "visibleApp");
    REQUIRE(app.exec == "visibleApp");

    free(buffer);
}

TEST_CASE("Application/flag/hidden=true",
          "Test for an issue where the name wasn't set correctly after reading "
          "a hidden file") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    REQUIRE_THROWS_AS(Application(TEST_FILES "applications/hidden.desktop",
                                  &buffer, &size, appformatter_default, ls, {}),
                      const disabled_error &);

    free(buffer);
}

TEST_CASE("Application/spaces_around_equals",
          "Test whether spaces around the equal sign are ignored") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/whitespaces.desktop", &buffer,
                    &size, appformatter_default, ls, {});

    // It should be "Htop", not "     Htop"
    REQUIRE(app.name == "Htop");
    REQUIRE(app.generic_name == "Process Viewer");

    free(buffer);
}

TEST_CASE("Application/onlyShowIn", "Test whether the OnlyShowIn tag works") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;

    // Case 1: The app should be shown in this environment
    Application app(TEST_FILES "applications/onlyShowIn.desktop", &buffer,
                    &size, appformatter_default, ls, {"i3", "Gnome"});
    REQUIRE(app.name == "Htop");
    REQUIRE(app.generic_name == "Process Viewer");

    // Case 2: The app should not be shown in this environment
    REQUIRE_THROWS_AS(Application(TEST_FILES "applications/onlyShowIn.desktop",
                                  &buffer, &size, appformatter_default, ls,
                                  {"Kde"}),
                      const disabled_error &);

    free(buffer);
}

TEST_CASE("Application/notShowIn", "Test whether the NotShowIn tag works") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;

    // Case 1: The app should be hidden
    REQUIRE_THROWS_AS(Application(TEST_FILES "applications/notShowIn.desktop",
                                  &buffer, &size, appformatter_default, ls,
                                  {"i3", "Gnome"}),
                      const disabled_error &);

    // Case 2: The app should be shown in this environment
    Application app2(TEST_FILES "applications/notShowIn.desktop", &buffer,
                     &size, appformatter_default, ls, {"Gnome"});
    REQUIRE(app2.name == "Htop");
    REQUIRE(app2.generic_name == "Process Viewer");

    free(buffer);
}
07070100000018000081A40000000000000000000000016500A7F000000B41000000000000000000000000000000000000003F00000000j4-dmenu-desktop-2.18~git20230912/src/TestApplicationRunner.cc#include <string>
#include <sys/wait.h>

#include "Application.hh"
#include "ApplicationRunner.hh"
#include "Formatters.hh"
#include "LocaleSuffixes.hh"
#include "catch.hpp"

// This function will pass the string to the shell, the shell will unquote and
// expand it and it will return the split arguments.
stringlist_t getshell(const std::string &args) {
    int pipefd[2];
    if (pipe(pipefd) == -1) {
        WARN("Unable to create pipe: " << strerror(errno));
        return {};
    }
    pid_t pid;
    switch (pid = fork()) {
    case -1:
        WARN("Unable to fork: " << strerror(errno));
        return {};
    case 0:
        dup2(pipefd[1], STDOUT_FILENO);
        close(pipefd[0]);
        close(pipefd[1]);
        close(STDIN_FILENO);
        execl("/bin/sh", "/bin/sh", "-c",
              ((std::string) "printf '%s\\0' " + args).c_str(), (char *)NULL);
        _exit(1);
    }
    close(pipefd[1]);
    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
        WARN("Couldn't execute shell.");
        close(pipefd[0]);
        return {};
    }

    char buf[512];
    ssize_t len;
    len = read(pipefd[0], buf, sizeof buf - 1);
    close(pipefd[0]);

    stringlist_t result = split(std::string(buf, len), '\0');
    if (result.back().empty())
        result.pop_back();
    return result;
}

TEST_CASE("ApplicationRunner/expand",
          "Tests proper handling of special characters") {
    LocaleSuffixes ls("en_US");
    char *data = nullptr;
    size_t size;
    Application app(TEST_FILES "applications/gimp.desktop", &data, &size,
                    appformatter_default, ls, {});

    auto result = getshell(application_command(app, R"--(@#$%^&*}{)(\)--"));

    stringlist_t cmp({"gimp-2.8", R"--(@#$%^&*}{)(\)--"});
    REQUIRE(result == cmp);

    free(data);
}

TEST_CASE("ApplicationRunner/field_codes", "") {
    LocaleSuffixes ls("en_US");
    char *data = nullptr;
    size_t size;
    Application app(TEST_FILES "applications/field_codes.desktop", &data, &size,
                    appformatter_default, ls, {});

    auto result = getshell(application_command(app, "arg1 arg2\\ arg3"));
    stringlist_t cmp({"true", "--name=%c", "--location",
                      TEST_FILES "applications/field_codes.desktop", "arg1",
                      "arg2\\", "arg3"});
    REQUIRE(result == cmp);

    free(data);
}

TEST_CASE("ApplicationRunner/escape",
          "Regression test for issue #18, %c was not escaped") {
    LocaleSuffixes ls("en_US");
    char *data = nullptr;
    size_t size;
    Application app(TEST_FILES "applications/caption.desktop", &data, &size,
                    appformatter_default, ls, {});

    auto result = getshell(application_command(app, ""));
    stringlist_t cmp({"1234", "--caption", "Regression Test 18"});
    REQUIRE(result == cmp);

    free(data);
}
07070100000019000081A40000000000000000000000016500A7F000003830000000000000000000000000000000000000003A00000000j4-dmenu-desktop-2.18~git20230912/src/TestApplications.cc#include "Applications.hh"
#include "Formatters.hh"
#include "SearchPath.hh"
#include "catch.hpp"
#include <fcntl.h>

TEST_CASE("Applications/empty", "Tests state of empty Applications") {
    Applications app(appformatter_default, {}, {}, false, false);
    REQUIRE(app.begin() == app.end());
}

TEST_CASE("Application/get", "") {
    Applications apps(appformatter_default, {}, {}, false, false);

    apps.add("web.desktop", 0, TEST_FILES "applications/");
    apps.add("web_browser.desktop", 0, TEST_FILES "applications/");

    auto query = apps.get(
        "true"); // requested direct executable instead of desktop entry
    REQUIRE(query.first == nullptr);
    REQUIRE(query.second == "true");

    query = apps.get("Web --help");
    REQUIRE(query.first->name == "Web");
    REQUIRE(query.second == " --help");

    // a incorrect implementation could assume that the requested desktop entry
    // is "Web" and the arguments are "browser --help". This verifies correct
    // behaviour.
    query = apps.get("Web browser --help");
    REQUIRE(query.first->name == "Web browser");
    REQUIRE(query.second == " --help");
}

TEST_CASE("Applications/comparison", "") {
    Applications apps(appformatter_default, {}, {}, false, false);

    apps.add("eagle.desktop", 0, TEST_FILES "applications/");
    apps.add("gimp.desktop", 0, TEST_FILES "applications/");

    Applications oldapps(apps);

    REQUIRE(apps == oldapps);

    apps.add("htop.desktop", 0, TEST_FILES "applications/");

    stringlist_t cmp({"Eagle", "GNU Image Manipulation Program", "Htop",
                      "Image Editor", "Process Viewer"});

    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    REQUIRE(apps == apps);
    REQUIRE(oldapps == oldapps);
    REQUIRE_FALSE(apps == oldapps);

    oldapps = apps;

    REQUIRE(apps == oldapps);
}

TEST_CASE("Applications/bad_remove",
          "Test removing nonexistent/invalid desktop entries") {
    Applications apps(appformatter_default, {}, {}, false, false);

    apps.add("eagle.desktop", 0, TEST_FILES "applications/");

    REQUIRE_THROWS(apps.remove("gimp.desktop", 0));

    Applications before(apps);

    // trying to remove eagle.desktop which is in a different SearchPath
    // directory than the current desktop entry
    apps.remove("eagle.desktop", 1);

    REQUIRE(before == apps);
}

TEST_CASE("Applications/basic_colision", "Test desktop ID precedence") {
    SECTION("the former overrides the latter") {
        // This simulates
        // $XDG_DATA_DIRS="TEST_FILESusr/share:TEST_FILESusr/local/share"
        Applications apps(appformatter_default, {}, {}, false, false);

        REQUIRE_NOTHROW(apps.add("collision.desktop", 0,
                                 TEST_FILES "usr/share/applications/"));
        REQUIRE(std::distance(apps.begin(), apps.end()) == 1);
        REQUIRE(*apps.begin() == "First");

        REQUIRE_NOTHROW(apps.add("collision.desktop", 1,
                                 TEST_FILES "usr/local/share/applications/"));
        REQUIRE(std::distance(apps.begin(), apps.end()) == 1);
        REQUIRE(*apps.begin() == "First");
    }
    SECTION("the latter overrides the former") {
        // This simulates
        // $XDG_DATA_DIRS="TEST_FILESusr/local/share:TEST_FILESusr/share"
        Applications apps(appformatter_default, {}, {}, false, false);

        REQUIRE_NOTHROW(apps.add("collision.desktop", 1,
                                 TEST_FILES "usr/share/applications/"));
        REQUIRE(std::distance(apps.begin(), apps.end()) == 1);
        REQUIRE(*apps.begin() == "First");

        REQUIRE_NOTHROW(apps.add("collision.desktop", 0,
                                 TEST_FILES "usr/local/share/applications/"));
        REQUIRE(std::distance(apps.begin(), apps.end()) == 1);
        REQUIRE(*apps.begin() == "Second");
    }
}

TEST_CASE("Applications/increment_history",
          "Verify that get()ing a Application increments its history") {
    Applications apps(appformatter_default, {}, {}, false, true);

    REQUIRE_NOTHROW(
        apps.add("firefox.desktop", 0, TEST_FILES "a/applications/"));

    REQUIRE_NOTHROW(
        apps.add("safari.desktop", 1, TEST_FILES "b/applications/"));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 3);

    std::pair<Application *, std::string> ret = apps.get("Web browser");
    REQUIRE(ret.first->name == "Safari");
    REQUIRE(ret.first->generic_name == "Web browser");
    REQUIRE(ret.second.empty());

    REQUIRE(std::distance(apps.begin(), apps.end()) == 3);

    stringlist_t cmp({"Safari", "Web browser", "Firefox"});
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
}

TEST_CASE("Applications/disable_increment_history",
          "Verify that get()ing a Application doens't have side effects when "
          "history is turned off") {
    Applications apps(appformatter_default, {}, {}, false, false);

    REQUIRE_NOTHROW(
        apps.add("firefox.desktop", 0, TEST_FILES "a/applications/"));

    REQUIRE_NOTHROW(
        apps.add("safari.desktop", 1, TEST_FILES "b/applications/"));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 3);

    std::pair<Application *, std::string> ret = apps.get("Web browser");
    REQUIRE(ret.first->name == "Safari");
    REQUIRE(ret.first->generic_name == "Web browser");
    REQUIRE(ret.second.empty());

    REQUIRE(std::distance(apps.begin(), apps.end()) == 3);

    stringlist_t cmp({"Firefox", "Safari", "Web browser"});
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
}

TEST_CASE("Applications/shadow",
          "Test correct handling of desktop files with overlapping names") {
    Applications apps(appformatter_default, {}, {}, false, true);

    apps.add("eagle.desktop", 0, TEST_FILES "applications/");
    apps.add("eagle_shadow.desktop", 0, TEST_FILES "applications/");

    REQUIRE(std::distance(apps.begin(), apps.end()) == 1);

    auto query = apps.get("Eagle");
    REQUIRE(query.first->id == "eagle_shadow.desktop");
    // getting "Eagle" twice tests correct history handling when the group of
    // desktop entries with history 1 gets completely moved to the "history
    // group" 2 (this tests that the histentries with hist value 1 get properly
    // deleted in favour of hist 2)
    apps.get("Eagle");
    REQUIRE(std::distance(apps.begin(), apps.end()) == 1);

    apps.remove("eagle_shadow.desktop", 0);

    REQUIRE(std::distance(apps.begin(), apps.end()) == 1);

    query = apps.get("Eagle");
    REQUIRE(query.first->id == "eagle.desktop");

    apps.remove("eagle.desktop", 0);

    REQUIRE(std::distance(apps.begin(), apps.end()) == 0);
}

TEST_CASE("Applications/exclude_generic", "") {
    Applications apps(appformatter_default, {}, {}, true, false);

    apps.add("eagle.desktop", 0, TEST_FILES "applications/");
    apps.add("gimp.desktop", 0, TEST_FILES "applications/");
    apps.add("htop.desktop", 0, TEST_FILES "applications/");
    apps.add("visible.desktop", 0, TEST_FILES "applications/");

    REQUIRE(std::distance(apps.begin(), apps.end()) == 4);

    stringlist_t cmp(
        {"Eagle", "GNU Image Manipulation Program", "Htop", "visibleApp"});
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
}

TEST_CASE("Applications/precedence", "") {
    // This behaves like $XDG_DATA_DIRS="TEST_FILESa:TEST_FILESb:TEST_FILESc"
    Applications apps(appformatter_default, {}, {}, false, false);

    REQUIRE_NOTHROW(
        apps.add("hidden.desktop", 0, TEST_FILES "a/applications/"));
    REQUIRE(std::distance(apps.begin(), apps.end()) == 0);

    REQUIRE_NOTHROW(
        apps.add("firefox.desktop", 0, TEST_FILES "a/applications/"));
    REQUIRE(std::distance(apps.begin(), apps.end()) == 2);
    REQUIRE(*apps.begin() == "Firefox");
    REQUIRE(*std::next(apps.begin()) == "Web browser");

    REQUIRE_NOTHROW(
        apps.add("chromium.desktop", 0, TEST_FILES "a/applications/"));
    REQUIRE(std::distance(apps.begin(), apps.end()) == 4);

    stringlist_t cmp(
        {"Chrome based browser", "Chromium", "Firefox", "Web browser"});
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    REQUIRE_NOTHROW(
        apps.add("safari.desktop", 1, TEST_FILES "b/applications/"));
    REQUIRE(std::distance(apps.begin(), apps.end()) == 5);

    cmp = {"Chrome based browser", "Chromium", "Firefox", "Safari",
           "Web browser"};
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    std::pair<Application *, std::string> bravesearch = apps.get("Web browser");
    REQUIRE(bravesearch.first->name == "Safari");
    REQUIRE(bravesearch.second.empty());

    std::pair<Application *, std::string> bravesearch2 = apps.get("Firefox");
    REQUIRE(bravesearch2.first->name == "Firefox");
    REQUIRE(bravesearch2.first->generic_name == "Web browser");
    REQUIRE(bravesearch2.second.empty());

    std::pair<Application *, std::string> bravesearch3 = apps.get("Safari");
    REQUIRE(bravesearch3.first->name == "Safari");
    REQUIRE(bravesearch3.first->generic_name == "Web browser");
    REQUIRE(bravesearch3.second.empty());

    REQUIRE_NOTHROW(
        apps.add("chrome.desktop", 1, TEST_FILES "b/applications/"));
    REQUIRE(std::distance(apps.begin(), apps.end()) == 6);

    cmp = {"Chrome", "Chrome based browser", "Chromium", "Firefox",
           "Safari", "Web browser"};
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    REQUIRE_NOTHROW(
        apps.add("vivaldi.desktop", 2, TEST_FILES "c/applications/"));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 7);

    cmp = {"Chrome",  "Chrome based browser", "Chromium", "Firefox", "Safari",
           "Vivaldi", "Web browser"};
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    std::pair<Application *, std::string> bravesearch4 =
        apps.get("Web browser");
    REQUIRE(bravesearch4.first->name == "Vivaldi");
    REQUIRE(bravesearch4.first->generic_name == "Web browser");
    REQUIRE(bravesearch4.second.empty());

    REQUIRE_NOTHROW(apps.remove("safari.desktop", 1));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 6);

    cmp = {"Chrome",  "Chrome based browser", "Chromium", "Firefox",
           "Vivaldi", "Web browser"};
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
    std::pair<Application *, std::string> bravesearch5 =
        apps.get("Web browser");
    REQUIRE(bravesearch5.first->name == "Vivaldi");
    REQUIRE(bravesearch5.first->generic_name == "Web browser");
    REQUIRE(bravesearch5.second.empty());

    REQUIRE_NOTHROW(apps.remove("vivaldi.desktop", 2));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 5);

    cmp = {"Chrome", "Chrome based browser", "Chromium", "Firefox",
           "Web browser"};
    std::pair<Application *, std::string> bravesearch6 =
        apps.get("Web browser");
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
    REQUIRE(bravesearch6.first->name == "Firefox");
    REQUIRE(bravesearch6.first->generic_name == "Web browser");
    REQUIRE(bravesearch6.second.empty());

    REQUIRE_NOTHROW(apps.remove("chromium.desktop", 0));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 4);

    cmp = {"Chrome", "Chrome based browser", "Firefox", "Web browser"};
    std::pair<Application *, std::string> bravesearch7 =
        apps.get("Chrome based browser");
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));
    REQUIRE(bravesearch7.first->name == "Chrome");
    REQUIRE(bravesearch7.first->generic_name == "Chrome based browser");
    REQUIRE(bravesearch7.second.empty());

    REQUIRE_NOTHROW(apps.remove("chrome.desktop", 1));

    REQUIRE(std::distance(apps.begin(), apps.end()) == 2);

    cmp = {"Firefox", "Web browser"};
}

TEST_CASE("Applications/history", "Test loading and saving log") {
    Applications apps(appformatter_default, {}, {}, false, true);

    REQUIRE_NOTHROW(apps.add("eagle.desktop", 0, TEST_FILES "applications/"));
    REQUIRE_NOTHROW(apps.add("gimp.desktop", 0, TEST_FILES "applications/"));

    stringlist_t cmp(
        {"Eagle", "GNU Image Manipulation Program", "Image Editor"});
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    REQUIRE_NOTHROW(apps.load_log(TEST_FILES "applications/history"));

    cmp = {"GNU Image Manipulation Program", "Image Editor", "Eagle"};
    REQUIRE(std::equal(apps.begin(), apps.end(), cmp.begin()));

    std::pair<Application *, std::string> search = apps.get("Eagle");
    REQUIRE(search.first->name == "Eagle");
    REQUIRE(search.first->generic_name.empty());
    REQUIRE(search.second.empty());

    apps.update_log(TEST_FILES "testhist");

    if (access(TEST_FILES "testhist", R_OK) == -1) {
        WARN("Couldn't create a test history file. This could be caused by "
             "programming error or by insuffitient permissions to "
             "create " TEST_FILES "/testhist.");
    } else {
        Applications histapps(appformatter_default, {}, {}, false, true);
        REQUIRE_NOTHROW(
            histapps.add("eagle.desktop", 0, TEST_FILES "applications/"));
        REQUIRE_NOTHROW(
            histapps.add("gimp.desktop", 0, TEST_FILES "applications/"));

        REQUIRE_NOTHROW(histapps.load_log(TEST_FILES "testhist"));

        cmp = {"Eagle", "GNU Image Manipulation Program", "Image Editor"};
        REQUIRE(std::equal(histapps.begin(), histapps.end(), cmp.begin()));

        if (unlink(TEST_FILES "/testhist") == -1)
            FAIL("Couldn't remove temporary history file " TEST_FILES
                 "/testhist: "
                 << strerror(errno));
    }
}

TEST_CASE("Applications/empty_log",
          "Test that handling a nonexistant log doesn't break Applications") {
    // This removes log if it wasn't removed by the test (this can happen if the
    // test would fail before calling the last unlink()).
    unlink(TEST_FILES "log");

    Applications apps(appformatter_default, {}, {}, false, true);
    apps.load_log(TEST_FILES "log");
    REQUIRE(access(TEST_FILES "log", F_OK) == -1);

    REQUIRE_NOTHROW(apps.add("eagle.desktop", 0, TEST_FILES "applications/"));
    auto query =
        apps.get("Eagle"); // Increase the history of eagle.desktop so that
                           // update_log() will have something to write.
    apps.update_log(TEST_FILES "log");
    REQUIRE(access(TEST_FILES "log", F_OK) == 0);

    unlink(TEST_FILES "log");
}
0707010000001A000081A40000000000000000000000016500A7F000000155000000000000000000000000000000000000003800000000j4-dmenu-desktop-2.18~git20230912/src/TestFileFinder.cc#include <list>
#include <string>
#include <vector>

#include "FileFinder.hh"
#include "catch.hpp"

TEST_CASE("FileFinder/find2", "") {
    FileFinder ff(TEST_FILES);
    bool found = false;
    while (++ff) {
        if (endswith(ff.path(), "other.ext")) {
            found = true;
            break;
        }
    }
    REQUIRE(found);
}
0707010000001B000081A40000000000000000000000016500A7F000000351000000000000000000000000000000000000003800000000j4-dmenu-desktop-2.18~git20230912/src/TestFormatters.cc#include <stddef.h>
#include <stdlib.h>
#include <string>

#include "catch.hpp"

#include "Application.hh"
#include "Formatters.hh"
#include "LocaleSuffixes.hh"

TEST_CASE("Formatters/standard", "") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/eagle.desktop", &buffer, &size,
                    appformatter_default, ls, {});

    REQUIRE(app.name == "Eagle");

    free(buffer);
}

TEST_CASE("Formatters/with_binary", "") {
    LocaleSuffixes ls("en_US");
    char *buffer = static_cast<char *>(malloc(4096));
    size_t size = 4096;
    Application app(TEST_FILES "applications/eagle.desktop", &buffer, &size,
                    appformatter_with_binary_name, ls, {});

    REQUIRE(app.name == "Eagle (eagle)");

    free(buffer);
}
0707010000001C000081A40000000000000000000000016500A7F0000003E7000000000000000000000000000000000000003C00000000j4-dmenu-desktop-2.18~git20230912/src/TestLocaleSuffixes.cc#include <string.h>

#include "LocaleSuffixes.hh"
#include "catch.hpp"

TEST_CASE("LocaleSuffixes/full", "") {
    LocaleSuffixes ls("en_US.UTF-8@mod");
    REQUIRE(ls.match("en_US@mod") == 0);
    REQUIRE(ls.match("en_US") == 1);
    REQUIRE(ls.match("en@mod") == 2);
    REQUIRE(ls.match("en") == 3);
}

TEST_CASE("LocaleSuffixes/full_no_encoding", "") {
    LocaleSuffixes ls("en_US@mod");
    REQUIRE(ls.match("en_US@mod") == 0);
    REQUIRE(ls.match("en_US") == 1);
    REQUIRE(ls.match("en@mod") == 2);
    REQUIRE(ls.match("en") == 3);
}

TEST_CASE("LocaleSuffixes/with_encoding", "") {
    LocaleSuffixes ls("en_US.UTF-8");
    REQUIRE(ls.match("en_US") == 0);
    REQUIRE(ls.match("en") == 1);
}

TEST_CASE("LocaleSuffixes/long", "") {
    LocaleSuffixes ls("en_US");
    REQUIRE(ls.match("en_US") == 0);
    REQUIRE(ls.match("en") == 1);
}

TEST_CASE("LocaleSuffixes/short", "") {
    LocaleSuffixes ls("en");
    REQUIRE(ls.match("en") == 0);
    REQUIRE_FALSE(ls.match("en_US") == 0);
}
0707010000001D000081A40000000000000000000000016500A7F00000091F000000000000000000000000000000000000003400000000j4-dmenu-desktop-2.18~git20230912/src/TestNotify.cc#include <poll.h>

#include "catch.hpp"

#include "Notify.hh"
#ifdef USE_KQUEUE
#include "NotifyKqueue.hh"
#else
#include "NotifyInotify.hh"
#endif

#define FILENAME TEST_FILES "usr/local/share/newfile"

TEST_CASE("Notify/create_delete",
          "Test detection of file creation and deletion of a subdirectory of "
          "watched directory") {
    stringlist_t search_path({TEST_FILES "usr/"});
#ifdef USE_KQUEUE
    NotifyKqueue notify(search_path);
#else
    NotifyInotify notify(search_path);
#endif

    // Try to delete FILENAME if it exists. A failed test might not have
    // properly deleted it, so this assures that it won't interfere with tests.
    if (unlink(FILENAME) == -1 && errno != ENOENT)
        FAIL("Couldn't remove " FILENAME ": " << strerror(errno));

    pollfd towait = {notify.getfd(), POLLIN, 0};

    FILE *file = fopen(FILENAME, "w");
    if (!file)
        FAIL("Couldn't create " FILENAME ": " << strerror(errno));
    fprintf(file, "DATA");
    fclose(file);

    // Timeout of 65 seconds is set because NotifyKqueue polls events in one
    // minute intervals. NotifyInotify should return immediately on these polls.
    if (poll(&towait, 1, 65000) != 1)
        FAIL("Notify didn't detect the creation of " FILENAME);
    bool found = false;
    for (const auto &i : notify.getchanges()) {
        // test if the newly created FILENAME is detected
        if (i.name == &FILENAME[strlen(TEST_FILES "usr/")]) {
            found = true;
            REQUIRE(i.rank == 0);
            REQUIRE(i.status == NotifyBase::modified);
            break;
        }
    }
    REQUIRE(found);

    // since the event was handled, there should be no other events available
    // therefore notify.getfd() shouldn't be readable
    REQUIRE(poll(&towait, 1, 0) == 0);

    if (unlink(FILENAME) == -1)
        FAIL("Couldn't remove " FILENAME ": " << strerror(errno));

    if (poll(&towait, 1, 65000) != 1)
        FAIL("Notify didn't detect the deletion of " FILENAME);
    found = false;
    for (const auto &i : notify.getchanges()) {
        if (i.name == &FILENAME[strlen(TEST_FILES "usr/")]) {
            found = true;
            REQUIRE(i.rank == 0);
            REQUIRE(i.status == NotifyBase::deleted);
            break;
        }
    }
    REQUIRE(found);
    REQUIRE(poll(&towait, 1, 0) == 0);
}
0707010000001E000081A40000000000000000000000016500A7F00000046F000000000000000000000000000000000000003800000000j4-dmenu-desktop-2.18~git20230912/src/TestSearchPath.cc#include <list>
#include <stdlib.h>
#include <string>
#include <vector>

#include "SearchPath.hh"
#include "catch.hpp"

TEST_CASE("SearchPath/XDG_DATA_HOME", "Check SearchPath honors XDG_DATA_HOME") {
    setenv("XDG_DATA_HOME", "/usr/share", 1);
    setenv("XDG_DATA_DIRS", " ", 1);

    std::vector<std::string> result = get_search_path();

    if (is_directory(
            "/usr/share/applications")) { // test if /usr/share/applications is
                                          // valid
        REQUIRE(result.size() == 1);
        REQUIRE(result.front() == "/usr/share/applications/");
    } else {
        REQUIRE(result.size() == 0);
    }
}

TEST_CASE("SearchPath/XDG_DATA_DIRS", "Check SearchPath honors XDG_DATA_DIRS") {
    unsetenv("XDG_DATA_HOME");
    setenv("HOME", "/home/testuser", 1);
    setenv("XDG_DATA_DIRS",
           TEST_FILES "usr/share/:" TEST_FILES "usr/local/share/", 1);

    std::vector<std::string> result = get_search_path();

    REQUIRE(result.size() == 2);
    REQUIRE(result[0] == TEST_FILES "usr/share/applications/");
    REQUIRE(result[1] == TEST_FILES "usr/local/share/applications/");
}
0707010000001F000081A40000000000000000000000016500A7F000000B23000000000000000000000000000000000000003300000000j4-dmenu-desktop-2.18~git20230912/src/Utilities.hh//
// This file is part of j4-dmenu-desktop.
//
// j4-dmenu-desktop 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.
//
// j4-dmenu-desktop 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 j4-dmenu-desktop.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef UTIL_DEF
#define UTIL_DEF

#include <algorithm>
#include <cstdlib>
#include <dirent.h>
#include <istream>
#include <map>
#include <set>
#include <sstream>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <utility>
#include <vector>

typedef std::vector<std::string> stringlist_t;

inline stringlist_t split(const std::string &str, char delimiter) {
    std::stringstream ss(str);
    std::string item;
    stringlist_t result;

    while (std::getline(ss, item, delimiter))
        result.push_back(item);

    return result;
}

inline bool have_equal_element(const stringlist_t &list1,
                               const stringlist_t &list2) {
    for (auto e1 : list1) {
        for (auto e2 : list2) {
            if (e1 == e2)
                return true;
        }
    }
    return false;
}

inline void replace(std::string &str, const std::string &substr,
                    const std::string &substitute) {
    if (substr.empty())
        return;
    size_t start_pos = 0;
    while ((start_pos = str.find(substr, start_pos)) != std::string::npos) {
        str.replace(start_pos, substr.length(), substitute);
        start_pos += substitute.length();
    }
}

inline bool endswith(const std::string &str, const std::string &suffix) {
    if (str.length() < suffix.length())
        return false;
    return str.compare(str.length() - suffix.length(), suffix.length(),
                       suffix) == 0;
}

inline bool startswith(const std::string &str, const std::string &prefix) {
    if (str.length() < prefix.length())
        return false;
    return str.compare(0, prefix.length(), prefix) == 0;
}

inline bool is_directory(const std::string &path) {
    int status;
    struct stat filestat;

    status = stat(path.c_str(), &filestat);
    if (status)
        return false;

    return S_ISDIR(filestat.st_mode);
}

inline std::string get_variable(const std::string &var) {
    const char *env = std::getenv(var.c_str());
    if (env) {
        return env;
    } else
        return "";
}

inline void pfatale(const char *msg) {
    perror(msg);
    abort();
}

#endif
07070100000020000081A40000000000000000000000016500A7F000003263000000000000000000000000000000000000002E00000000j4-dmenu-desktop-2.18~git20230912/src/main.cc#include <algorithm>
#include <cstring>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <unistd.h>
#include <vector>

#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "Application.hh"
#include "ApplicationRunner.hh"
#include "Applications.hh"
#include "Dmenu.hh"
#include "FileFinder.hh"
#include "Formatters.hh"
#include "SearchPath.hh"
#include "Utilities.hh"

#include "Notify.hh"
#ifdef USE_KQUEUE
#include "NotifyKqueue.hh"
#else
#include "NotifyInotify.hh"
#endif

void sigchld(int) {
    while (waitpid(-1, NULL, WNOHANG) > 0)
        ;
}

void print_usage(FILE *f) {
    fprintf(
        f,
        "j4-dmenu-desktop\n"
        "A faster replacement for i3-dmenu-desktop\n"
        "Copyright (c) 2013 Marian Beermann, GPLv3 license\n"
        "\nUsage:\n"
        "\tj4-dmenu-desktop [--dmenu=\"dmenu -i\"] "
        "[--term=\"i3-sensible-terminal\"]\n"
        "\tj4-dmenu-desktop --help\n"
        "\nOptions:\n"
        "\t-b, --display-binary\n"
        "\t\tDisplay binary name after each entry (off by default)\n"
        "\t-f, --display-binary-base\n"
        "\t\tDisplay basename of binary name after each entry (off by "
        "default)\n"
        "\t-d, --dmenu=<command>\n"
        "\t\tDetermines the command used to invoke dmenu\n"
        "\t\tExecuted with your shell ($SHELL) or /bin/sh\n"
        "\t--no-exec\n"
        "\t\tDo not execute selected command, send to stdout instead\n"
        "\t--no-generic\n"
        "\t\tDo not include the generic name of desktop entries\n"
        "\t-t, --term=<command>\n"
        "\t\tSets the terminal emulator used to start terminal apps\n"
        "\t--usage-log=<file>\n"
        "\t\tMust point to a read-writeable file (will create if not exists).\n"
        "\t\tIn this mode entries are sorted by usage frequency.\n"
        "\t-x, --use-xdg-de\n"
        "\t\tEnables reading $XDG_CURRENT_DESKTOP to determine the desktop "
        "environment\n"
        "\t--wait-on=<path>\n"
        "\t\tMust point to a path where a file can be created.\n"
        "\t\tIn this mode no menu will be shown. Instead the program waits for "
        "<path>\n"
        "\t\tto be written to (use echo > path). Every time this happens a "
        "menu will be shown.\n"
        "\t\tDesktop files are parsed ahead of time.\n"
        "\t\tPerforming 'echo -n q > path' will exit the program.\n"
        "\t--wrapper=<wrapper>\n"
        "\t\tA wrapper binary. Useful in case you want to wrap into 'i3 exec'\n"
        "\t-h, --help\n"
        "\t\tDisplay this help message\n\n"
        "j4-dmenu-desktop is compiled with "
#ifdef USE_KQUEUE
        "kqueue"
#else
        "inotify"
#endif
        " support.\n");
}

int collect_files(Applications &apps, const stringlist_t &search_path) {
    int parsed_files = 0;

    for (Applications::size_type i = 0; i < search_path.size(); i++) {
        FileFinder finder(search_path[i]);
        while (++finder) {
            if (finder.isdir() || !endswith(finder.path(), ".desktop"))
                continue;
            apps.add(finder.path().substr(search_path[i].length()), i,
                     search_path[i]);
            parsed_files++;
        }
    }

    return parsed_files;
}

struct CommandInfo
{
    std::string command;
    bool isterminal; // this indicated whether the program should be executed in
                     // a terminal
    /*
     * iscustom indicates whether a program was picked from a desktop file or if
     * it is a custom program that should be executed directly
     */
    bool iscustom;

    CommandInfo(std::string n, bool t, bool c)
        : command(std::move(n)), isterminal(t), iscustom(c) {}

    CommandInfo() = default;
};

CommandInfo get_command(int parsed_files, Applications &apps,
                        const std::string &choice, const std::string &wrapper,
                        const char *usage_log) {
    std::string args;
    Application *app;

    fprintf(stderr, "Read %d .desktop files, found %lu apps.\n", parsed_files,
            apps.size());

    if (choice.empty())
        return CommandInfo("", false, false);

    std::tie(app, args) = apps.get(choice);

    fprintf(stderr, "User input is: %s %s\n", choice.c_str(), args.c_str());

    if (!app) {
        if (wrapper.empty())
            return CommandInfo(args, false, true);
        else
            return CommandInfo(wrapper + " \"" + args + "\"", false, true);
    }

    apps.update_log(usage_log);

    if (!app->path.empty()) {
        if (chdir(app->path.c_str())) {
            perror("chdir into application path");
        }
    }

    std::string command = application_command(*app, args);
    if (wrapper.empty())
        return CommandInfo(command, app->terminal, false);
    else
        return CommandInfo(wrapper + " \"" + command + "\"", app->terminal,
                           false);
}

int do_dmenu(const char *shell, int parsed_files, Dmenu &dmenu,
             Applications &apps, std::string &terminal, std::string &wrapper,
             bool no_exec, const char *usage_log) {
    // Transfer the list to dmenu
    for (auto &name : apps)
        dmenu.write(name);

    dmenu.display();

    CommandInfo info;

    try {
        info = get_command(parsed_files, apps, dmenu.read_choice(), wrapper,
                           usage_log); // read_choice blocks
    } catch (const std::runtime_error
                 &e) { // invalid field code in Exec, the standard says that the
                       // implementation shall not process these
        fprintf(stderr, "%s\n", e.what());
        return 1;
    }

    if (!info.command.empty()) {
        if (no_exec) {
            printf("%s\n", info.command.c_str());
            return 0;
        }

        /*
         * Some shells automatically exec() the last command in the
         * command_string passed in by $SHELL -c but some do not. For example
         * bash does this but dash doesn't. Prepending "exec " to the command
         * ensures that the shell will get replaced. Custom commands might
         * contain complicated expressions so exec()ing them might not be a good
         * idea. Desktop files can contain only a single command in Exec so
         * using the exec shell builtin is safe.
         */
        if (!info.iscustom)
            info.command = "exec " + info.command;

        if (info.isterminal) {
            fprintf(stderr, "%s -e %s -c '%s'\n", terminal.c_str(), shell,
                    info.command.c_str());
            return execlp(terminal.c_str(), terminal.c_str(), "-e", shell, "-c",
                          info.command.c_str(), (char *)NULL);
        } else {
            fprintf(stderr, "%s -c '%s'\n", shell, info.command.c_str());
            return execl(shell, shell, "-c", info.command.c_str(),
                         (char *)NULL);
        }
    }
    return 0;
}

int do_wait_on(NotifyBase &notify, const char *shell, const char *wait_on,
               int parsed_files, Dmenu &dmenu, Applications &apps,
               std::string &terminal, std::string &wrapper, bool no_exec,
               const stringlist_t &search_path, const char *usage_log) {
    // Avoid zombie processes.
    struct sigaction act = {{0}}; // double curly braces fix a warning fixes
                                  // -Wmissing-braces on FreeBSD
    act.sa_handler = sigchld;
    if (sigaction(SIGCHLD, &act, NULL) == -1)
        pfatale("sigaction");

    int fd;
    if (mkfifo(wait_on, 0600) && errno != EEXIST) {
        perror("mkfifo");
        return 1;
    }
    fd = open(wait_on, O_RDWR);
    if (fd == -1) {
        perror("open(fifo)");
        return 1;
    }
    pollfd watch[] = {
        {fd,             POLLIN, 0},
        {notify.getfd(), POLLIN, 0},
    };
    while (1) {
        watch[0].revents = watch[1].revents = 0;
        int ret;
        while ((ret = poll(watch, 2, -1)) == -1 && errno == EINTR)
            ;
        if (ret == -1)
            pfatale("poll");
        if (watch[1].revents & POLLIN) {
            for (const auto &i : notify.getchanges()) {
                if (!endswith(i.name, ".desktop"))
                    continue;
                switch (i.status) {
                case NotifyBase::changetype::modified:
                    apps.add(i.name, i.rank, search_path[i.rank]);
                    break;
                case NotifyBase::changetype::deleted:
                    apps.remove(i.name, i.rank);
                    break;
                }
            }
        }
        if (watch[0].revents & POLLIN) {
            char data;
            if (read(fd, &data, sizeof(data)) < 1) {
                perror("read(fifo)");
                break;
            }
            if (data == 'q')
                return 0;
            pid_t pid = fork();
            switch (pid) {
            case -1:
                perror("fork");
                return 1;
            case 0:
                close(fd);
                setsid();
                dmenu.run();
                return do_dmenu(shell, parsed_files, dmenu, apps, terminal,
                                wrapper, no_exec, usage_log);
            }
        }
    }
    close(fd);
    return 0;
}

int main(int argc, char **argv) {
    std::string dmenu_command = "dmenu -i";
    std::string terminal = "i3-sensible-terminal";
    std::string wrapper;
    const char *wait_on = 0;

    const char *shell = getenv("SHELL");
    if (shell == NULL)
        shell = "/bin/sh";

    stringlist_t desktopenvs;
    bool use_xdg_de = false;
    bool exclude_generic = false;
    bool no_exec = false;

    stringlist_t search_path = get_search_path();

#ifdef DEBUG
    for (const std::string &path : search_path) {
        fprintf(stderr, "SearchPath: %s\n", path.c_str());
    }
#endif

    LocaleSuffixes suffixes;

    application_formatter appformatter = appformatter_default;

    const char *usage_log = 0;

    while (true) {
        int option_index = 0;
        static struct option long_options[] = {
            {"dmenu",               required_argument, 0, 'd'},
            {"use-xdg-de",          no_argument,       0, 'x'},
            {"term",                required_argument, 0, 't'},
            {"help",                no_argument,       0, 'h'},
            {"display-binary",      no_argument,       0, 'b'},
            {"display-binary-base", no_argument,       0, 'f'},
            {"no-generic",          no_argument,       0, 'n'},
            {"usage-log",           required_argument, 0, 'l'},
            {"wait-on",             required_argument, 0, 'w'},
            {"no-exec",             no_argument,       0, 'e'},
            {"wrapper",             required_argument, 0, 'W'},
            {0,                     0,                 0, 0  }
        };

        int c =
            getopt_long(argc, argv, "d:t:xhbf", long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
        case 'd':
            dmenu_command = optarg;
            break;
        case 'x':
            use_xdg_de = true;
            break;
        case 't':
            terminal = optarg;
            break;
        case 'h':
            print_usage(stderr);
            exit(0);
        case 'b':
            appformatter = appformatter_with_binary_name;
            break;
        case 'f':
            appformatter = appformatter_with_base_binary_name;
            break;
        case 'n':
            exclude_generic = true;
            break;
        case 'l':
            usage_log = optarg;
            break;
        case 'w':
            wait_on = optarg;
            break;
        case 'e':
            no_exec = true;
            break;
        case 'W':
            wrapper = optarg;
            break;
        default:
            exit(1);
        }
    }

    if (use_xdg_de) {
        desktopenvs = split(get_variable("XDG_CURRENT_DESKTOP"), ':');
    }

#ifdef DEBUG
    fprintf(stderr, "desktop environments:\n");
    for (auto s : desktopenvs)
        fprintf(stderr, "%s\n", s.c_str());
#endif

    Applications apps(appformatter, desktopenvs, suffixes, exclude_generic,
                      usage_log != NULL);

    Dmenu dmenu(dmenu_command, shell);

    if (!wait_on)
        dmenu.run();

    int parsed_files = collect_files(apps, search_path);

    apps.load_log(usage_log); // load the log if it's enabled

    if (wait_on) {
#ifdef USE_KQUEUE
        NotifyKqueue notify(search_path);
#else
        NotifyInotify notify(search_path);
#endif
        return do_wait_on(notify, shell, wait_on, parsed_files, dmenu, apps,
                          terminal, wrapper, no_exec, search_path, usage_log);
    } else {
        return do_dmenu(shell, parsed_files, dmenu, apps, terminal, wrapper,
                        no_exec, usage_log);
    }
}
07070100000021000041ED0000000000000000000000076500A7F000000000000000000000000000000000000000000000002D00000000j4-dmenu-desktop-2.18~git20230912/test_files07070100000022000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000002F00000000j4-dmenu-desktop-2.18~git20230912/test_files/a07070100000023000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000003C00000000j4-dmenu-desktop-2.18~git20230912/test_files/a/applications07070100000024000081A40000000000000000000000016500A7F000000089000000000000000000000000000000000000004D00000000j4-dmenu-desktop-2.18~git20230912/test_files/a/applications/chromium.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Chromium
GenericName=Chrome based browser
Comment=j4-dmenu-desktop test file
Exec=true
07070100000025000081A40000000000000000000000016500A7F00000007F000000000000000000000000000000000000004C00000000j4-dmenu-desktop-2.18~git20230912/test_files/a/applications/firefox.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Firefox
GenericName=Web browser
Comment=j4-dmenu-desktop test file
Exec=true
07070100000026000081A40000000000000000000000016500A7F000000075000000000000000000000000000000000000004B00000000j4-dmenu-desktop-2.18~git20230912/test_files/a/applications/hidden.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=errapp
Comment=j4-dmenu-desktop test file
NoDisplay=true
Exec=true
07070100000027000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000003A00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications07070100000028000081A40000000000000000000000016500A7F00000005C000000000000000000000000000000000000004A00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/caption.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Regression Test 18
Exec=1234 --caption %c
07070100000029000081A40000000000000000000000016500A7F0000000A7000000000000000000000000000000000000004800000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/eagle.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Eagle
TryExec=/usr/bin/eagle
Exec=eagle -style plastique
Icon=/opt/eagle/bin/eagleicon50.png
Categories=Development;
0707010000002A000081A40000000000000000000000016500A7F0000000A7000000000000000000000000000000000000004F00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/eagle_shadow.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Eagle
TryExec=/usr/bin/eagle
Exec=eagle -style plastique
Icon=/opt/eagle/bin/eagleicon50.png
Categories=Development;
0707010000002B000081A40000000000000000000000016500A7F00000005A000000000000000000000000000000000000004E00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/field_codes.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=%c
Exec=true --name=%c --location %k %u
0707010000002C000081A40000000000000000000000016500A7F000002A9C000000000000000000000000000000000000004700000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/gimp.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=GNU Image Manipulation Program
Name[ar]=برنامج جنو لمعالجة الصور
Name[ast]=Programa de manipulación d'Imaxe GNU
Name[be]=GIMP — праґрама праекту GNU для працы зь відарысамі
Name[bg]=Редактор на изображения (GIMP)
Name[br]=Goulev da zornata skeudennoù GNU
Name[ca]=Programa de retoc d'imatges de GNU
Name[ca@valencia]=Programa de retoc d'imatges de GNU
Name[cs]=GNU Image Manipulation Program
Name[csb]=Editora òbrôzów GIMP
Name[da]=GNU Image Manipulation Program
Name[de]=GNU Image Manipulation Program
Name[dz]=་་ཨི་མེཇི་་མ་ནུ་པུ་ལེ་ཤཱན་་པོརོ་གརམ།
Name[el]=Πρόγραμμα επεξεργασίας εικόνων GNU
Name[en_CA]=GNU Image Manipulation Program
Name[en_GB]=GNU Image Manipulation Program
Name[eo]=Bildmanipulilo (GIMP = GNU Image Manipulation Program)
Name[es]=Programa de manipulación de imágenes de GNU
Name[et]=GIMP - GNU pilditöötlusprogramm
Name[eu]=GNUren Irudiak Manipulatzeko Programa
Name[fa]=برنامهٔ روتوش تصاویر گنو
Name[fi]=GIMP-kuvankäsittely
Name[fr]=Éditeur d'image GIMP
Name[gl]=Programa de Manipulación de Imaxes de GNU
Name[gu]=GNU ચિત્ર જાળવણી કાર્યક્રમ
Name[he]=תוכנת עיבוד התמונה של GNU
Name[hu]=A GNU képszerkesztő program
Name[is]=GNU Myndvinnsluforrit
Name[it]=GNU Image Manipulation Program
Name[ja]=GIMP (GNU Image Manipulation Program)
Name[km]=កម្មវិធី​រៀបចំ​រូបភាពរបស់ GNU
Name[kn]=GNU ಇಮೇಜ್ ಮ್ಯಾನಿಪುಲೇಶನ್ ಪ್ರೊಗ್ರಾಮ್
Name[ko]=GNU Image Manipulation Program
Name[lt]=GNU paveikslėlių manipuliavimo programa
Name[lv]=GNU attēlu apstrādes programma
Name[mk]=ГНУ програма за манипулација со слики
Name[ml]=GNU Image Manipulation Program
Name[my]=GNU ရုပ်ပုံ စီမံကိုင်တွယ်ရေး ပရိုဂရမ်
Name[nb]=GNU bildebehandlingsprogram
Name[nds]=GNU Billbewarkenprogramm
Name[ne]=जी एन यू छवि परिचालन कार्यक्रम
Name[nl]=GNU Image Manipulation Program
Name[nn]=GNU biletbehandlingsprogram
Name[pa]=ਗਨੂ ਈਮੇਜ਼ ਮੈਨੂਪਲੇਸ਼ਨ ਪਰੋਗਰਾਮ
Name[pl]=Edytor obrazów GIMP
Name[pt]=Programa de Manipulação de Imagens GNU
Name[pt_BR]=Programa de manipulação de imagem do GNU
Name[ro]=GIMP
Name[ru]=GNU Image Manipulation Program
Name[si]=GNU Image Manipulation Program
Name[sk]=GNU program na manipuláciu s obrázkami
Name[sl]=GIMP - program GNU za obdelavo slik
Name[sr]=Гнуов програм за обраду слика
Name[sr@latin]=Gnuov program za obradu slika
Name[sv]=GNU:s bildmanipuleringsprogram
Name[ta]=க்னூ பட கையாளல் நிரல்
Name[te]=గ్నూ ఇమేజ్ మానిప్యులేషన్ ప్రోగ్రామ్
Name[th]=GNU Image Manipulation Program
Name[tr]=GNU Görüntü İşleme Programı
Name[tt]=Sürät Eşkärtüçe GNU-Yasılım
Name[uk]=GNU Image Manipulation Program
Name[vi]=Chương Trình Thao Tác Ảnh GNU
Name[zh_CN]=GNU 图像处理程序
Name[zh_HK]=GNU 圖片處理程式
Name[zh_TW]=GNU 圖片處理程式
GenericName=Image Editor
GenericName[ar]=محرر صور
GenericName[ast]=Editor d'imaxe
GenericName[be]=Рэдактар відарысаў
GenericName[bg]=Редактор на изображения
GenericName[br]=Embanner skeudennoù
GenericName[ca]=Editor d'imatges
GenericName[ca@valencia]=Editor d'imatges
GenericName[cs]=Editor obrázků
GenericName[da]=Billedredigering
GenericName[de]=Bildeditor
GenericName[dz]=གཟུགས་བརྙན་ ཞུན་དག་པ།
GenericName[el]=Επεξεργαστής εικόνων
GenericName[en_CA]=Image Editor
GenericName[en_GB]=Image Editor
GenericName[eo]=Bildredaktilo
GenericName[es]=Editor de imagen
GenericName[et]=Pildiredaktor
GenericName[eu]=Irudi-editorea
GenericName[fa]=ویرایشگر تصویر
GenericName[fi]=Kuvankäsittely
GenericName[fr]=Éditeur d'image
GenericName[gl]=Editor de imaxes
GenericName[gu]=ચિત્ર સંપાદક
GenericName[hu]=Képszerkesztő
GenericName[id]=Penyunting Gambar
GenericName[is]=Myndvinnsluforrit
GenericName[it]=Modifica immagine
GenericName[ja]=画像エディター
GenericName[ka]=გამოსახულებების რედაქტორი
GenericName[km]=កម្មវិធី​និពន្ធ​រូបភាព
GenericName[kn]=ಚಿತ್ರ ಸಂಪಾದಕ
GenericName[ko]=이미지 편집기
GenericName[lt]=Paveikslėlių rengyklė
GenericName[lv]=Attēla redaktors
GenericName[mk]=Уредник за слики
GenericName[my]=ရုပ်ပုံ တည်းဖြတ်ကိရိယာ
GenericName[nb]=Bildebehandler
GenericName[nds]=Billbewarker
GenericName[ne]=छवि सम्पादक
GenericName[nl]=Afbeeldingsbewerker
GenericName[nn]=Bilethandterar
GenericName[pa]=ਚਿੱਤਰ ਐਡੀਟਰ
GenericName[pl]=Edytor obrazów
GenericName[pt]=Editor de Imagens
GenericName[pt_BR]=Editor de imagens
GenericName[ro]=Editor de imagini
GenericName[ru]=Редактор изображений
GenericName[sk]=Editor obrázkov
GenericName[sl]=Urejevalnik slik
GenericName[sr]=Обрада слика
GenericName[sr@latin]=Obrada slika
GenericName[sv]=Bildredigerare
GenericName[ta]=பிம்ப திருத்தி
GenericName[te]=బొమ్మ కూర్పకము
GenericName[th]=เครื่องมือแก้ไขภาพ
GenericName[tr]=Görüntü Düzenleyici
GenericName[tt]=Sürät Tözätkeç
GenericName[uk]=Редактор зображень
GenericName[vi]=Bộ biên soạn ảnh
GenericName[xh]=UmHleli woMfanekiso
GenericName[zh_CN]=图像编辑器
GenericName[zh_HK]=圖片編輯器
GenericName[zh_TW]=圖片編輯器
Comment=Create images and edit photographs
Comment[ar]=أنشئ صورا وحرّر لقطات
Comment[ast]=Cree imáxenes y edite semeyes
Comment[be]=Стварэньне відарысаў і праўленьне фатаздымкаў
Comment[bg]=Създаване на изображения и редакция на снимки
Comment[br]=Krouiñ hag embann skeudennoù pe luc'hskeudennoù
Comment[ca]=Creeu imatges i editeu fotografies
Comment[ca@valencia]=Creeu imatges i editeu fotografies
Comment[cs]=Vytvářet obrázky a upravovat fotografie
Comment[da]=Opret billeder og redigér fotografier
Comment[de]=Bilder erstellen und Fotografien bearbeiten
Comment[dz]=གཟུགས་བརྙན་ཚུ་ གསར་བསྐྲུན་འབད་ནི་དང་ དཔར་ཚུ་ཞུན་དག་འབད།
Comment[el]=Δημιουργία εικόνων και επεξεργασία φωτογραφιών
Comment[en_CA]=Create images and edit photographs
Comment[en_GB]=Create images and edit photographs
Comment[eo]=Krei bildojn aŭ redakti fotaĵojn
Comment[es]=Cree imágenes y edite fotografías
Comment[et]=Loo pilte ja redigeeri fotosid
Comment[eu]=Sortu irudiak eta editatu argazkiak
Comment[fi]=Luo kuvia ja muokkaa valokuvia
Comment[fr]=Créer des images et modifier des photographies
Comment[gl]=Crear imaxes e editar fotografías
Comment[gu]=ચિત્રો બનાવો અને ફોટાઓમાં ફેરફાર કરો
Comment[hu]=Képek létrehozása és fotók szerkesztése
Comment[id]=Buat gambar dan sunting foto
Comment[is]=Búa til myndir og breyta ljósmyndum
Comment[it]=Crea immagini e modifica fotografie
Comment[ja]=画像の作成と写真の編集を行います
Comment[km]=បង្កើត​រូបភាព និង កែសម្រួល​រូបថត
Comment[kn]=ಚಿತ್ರಗಳನ್ನು ರಚಿಸಿ ಹಾಗು ಫೋಟೋಗ್ರಾಫ್‌ಗಳನ್ನು ಸಂಪಾದಿಸಿ
Comment[ko]=이미지를 만들고 사진을 편집합니다
Comment[lt]=Kurti paveikslėlius ir redaguoti fotografijas
Comment[lv]=Veido attēlus vai rediģē fotogrāfijas
Comment[mk]=Направи слики и уреди фотографии
Comment[my]=ရုပ်ပုံများကို ဖန်တီးပြီး ဓါတ်ပုံများကို တည်းဖြတ်ပါ
Comment[nb]=Lag bilder og rediger fotografier
Comment[ne]=छवि सिर्जना गर्नुहोस् र फोटोग्राफ सम्पादन गर्नुहोस्
Comment[nl]=Afbeeldingen of foto's aanmaken en bewerken
Comment[nn]=Lag teikningar eller rediger foto
Comment[pa]=ਚਿੱਤਰ ਬਣਾਓ ਅਤੇ ਤਸਵੀਰਾਂ ਸੋਧੋ
Comment[pl]=Tworzenie oraz obróbka obrazów i fotografii
Comment[pt]=Criar imagens e editar fotografias
Comment[pt_BR]=Crie e edite imagens ou fotografias
Comment[ro]=Creează imagini și editează fotografii
Comment[ru]=Создание изображений и редактирование фотографий
Comment[sk]=Vytvárajte a upravujte obrázky alebo fotografie
Comment[sl]=Ustvari slike in uredi fotografije
Comment[sr]=Направите слике и уредите фотографије
Comment[sr@latin]=Napravite slike i uredite fotografije
Comment[sv]=Skapa bilder och redigera fotografier
Comment[ta]=பிம்பங்களை உருவாக்கவும் மற்றும் படங்களை திருத்தவும்
Comment[te]=బొమ్మలను సృష్టించు మరియు చిత్రాలను సవరించు
Comment[tr]=Görüntü oluşturur ve fotoğraf düzenler
Comment[uk]=Створення зображень та редагування фотографій
Comment[vi]=Tạo và biên soạn ảnh hay ảnh chụp
Comment[zh_CN]=创建图像或编辑照片
Comment[zh_HK]=建立圖像與編輯照片
Comment[zh_TW]=建立圖像與編輯照片
Exec=gimp-2.8 %U
TryExec=gimp-2.8
Icon=gimp
Terminal=false
Categories=Graphics;2DGraphics;RasterGraphics;GTK;
X-GNOME-Bugzilla-Bugzilla=GNOME
X-GNOME-Bugzilla-Product=GIMP
X-GNOME-Bugzilla-Component=General
X-GNOME-Bugzilla-Version=2.8.8
X-GNOME-Bugzilla-OtherBinaries=gimp-2.8
StartupNotify=true
MimeType=image/bmp;image/g3fax;image/gif;image/x-fits;image/x-pcx;image/x-portable-anymap;image/x-portable-bitmap;image/x-portable-graymap;image/x-portable-pixmap;image/x-psd;image/x-sgi;image/x-tga;image/x-xbitmap;image/x-xwindowdump;image/x-xcf;image/x-compressed-xcf;image/x-gimp-gbr;image/x-gimp-pat;image/x-gimp-gih;image/tiff;image/jpeg;image/x-psp;application/postscript;image/png;image/x-icon;image/x-xpixmap;image/svg+xml;application/pdf;image/x-wmf;image/jp2;image/jpeg2000;image/jpx;image/x-xcursor;
0707010000002D000081A40000000000000000000000016500A7F000000057000000000000000000000000000000000000004900000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/hidden.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=hiddenApp
Exec=hiddenApp
Hidden=true
0707010000002E000081A40000000000000000000000016500A7F00000000F000000000000000000000000000000000000004200000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/history1,gimp.desktop
0707010000002F000081A40000000000000000000000016500A7F0000000B1000000000000000000000000000000000000004700000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/htop.desktop[Desktop Entry]
Version=1.0
Name=Htop
Type=Application
Comment=Show System Processes
Terminal=true
Exec=htop
Icon=htop
Categories=ConsoleOnly;System;
GenericName=Process Viewer
07070100000030000081A40000000000000000000000016500A7F0000000C2000000000000000000000000000000000000004C00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/notShowIn.desktop[Desktop Entry]
Version=1.0
Name=Htop
Type=Application
Comment=Show System Processes
Terminal=true
Exec=htop
Icon=htop
Categories=ConsoleOnly;System;
GenericName=Process Viewer
NotShowIn=i3;Kde
07070100000031000081A40000000000000000000000016500A7F0000000C0000000000000000000000000000000000000004D00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/onlyShowIn.desktop[Desktop Entry]
Version=1.0
Name=Htop
Type=Application
Comment=Show System Processes
Terminal=true
Exec=htop
Icon=htop
Categories=ConsoleOnly;System;
GenericName=Process Viewer
OnlyShowIn=i3;
07070100000032000081A40000000000000000000000016500A7F00000005A000000000000000000000000000000000000004A00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/visible.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=visibleApp
Exec=visibleApp
Hidden=false
07070100000033000081A40000000000000000000000016500A7F000000042000000000000000000000000000000000000004600000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/web.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Web
Exec=chrome
07070100000034000081A40000000000000000000000016500A7F00000004A000000000000000000000000000000000000004E00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/web_browser.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Web browser
Exec=chrome
07070100000035000081A40000000000000000000000016500A7F000000091000000000000000000000000000000000000004E00000000j4-dmenu-desktop-2.18~git20230912/test_files/applications/whitespaces.desktop[Desktop Entry]
Version=1.0
Name  =     Htop
GenericName=  Process Viewer
Type=Application
Comment=Show System Processes
Terminal=true
Exec=htop
07070100000036000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000002F00000000j4-dmenu-desktop-2.18~git20230912/test_files/b07070100000037000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000003C00000000j4-dmenu-desktop-2.18~git20230912/test_files/b/applications07070100000038000081A40000000000000000000000016500A7F000000087000000000000000000000000000000000000004B00000000j4-dmenu-desktop-2.18~git20230912/test_files/b/applications/chrome.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Chrome
GenericName=Chrome based browser
Comment=j4-dmenu-desktop test file
Exec=true
07070100000039000081A40000000000000000000000016500A7F00000007E000000000000000000000000000000000000004B00000000j4-dmenu-desktop-2.18~git20230912/test_files/b/applications/safari.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Safari
GenericName=Web browser
Comment=j4-dmenu-desktop test file
Exec=true
0707010000003A000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000002F00000000j4-dmenu-desktop-2.18~git20230912/test_files/c0707010000003B000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000003C00000000j4-dmenu-desktop-2.18~git20230912/test_files/c/applications0707010000003C000081A40000000000000000000000016500A7F00000007F000000000000000000000000000000000000004C00000000j4-dmenu-desktop-2.18~git20230912/test_files/c/applications/vivaldi.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Vivaldi
GenericName=Web browser
Comment=j4-dmenu-desktop test file
Exec=true
0707010000003D000081A40000000000000000000000016500A7F000000002000000000000000000000000000000000000003A00000000j4-dmenu-desktop-2.18~git20230912/test_files/file.desktop 
0707010000003E000081A40000000000000000000000016500A7F000000002000000000000000000000000000000000000003700000000j4-dmenu-desktop-2.18~git20230912/test_files/other.ext 
0707010000003F000041ED0000000000000000000000046500A7F000000000000000000000000000000000000000000000003100000000j4-dmenu-desktop-2.18~git20230912/test_files/usr07070100000040000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000003700000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/local07070100000041000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000003D00000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/local/share07070100000042000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000004A00000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/local/share/applications07070100000043000081A40000000000000000000000016500A7F00000005E000000000000000000000000000000000000005C00000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/local/share/applications/collision.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=Second
Exec=true
Comment=The second program
07070100000044000041ED0000000000000000000000036500A7F000000000000000000000000000000000000000000000003700000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/share07070100000045000041ED0000000000000000000000026500A7F000000000000000000000000000000000000000000000004400000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/share/applications07070100000046000081A40000000000000000000000016500A7F00000005C000000000000000000000000000000000000005600000000j4-dmenu-desktop-2.18~git20230912/test_files/usr/share/applications/collision.desktop[Desktop Entry]
Version=1.0
Type=Application
Name=First
Exec=true
Comment=The first program
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!348 blocks
openSUSE Build Service is sponsored by