./ 0000755 0000041 0000041 00000000000 12772523363 011255 5 ustar www-data www-data ./Makefile.decl 0000644 0000041 0000041 00000005407 12772523363 013631 0 ustar www-data www-data # GLIB - Library of useful C routines
#
# This file is copied almost verbatim from the GLib-2.0 distribution
#
GTESTER = gtester
GTESTER_REPORT = gtester-report
# initialize variables for unconditional += appending
EXTRA_DIST =
TEST_PROGS =
### testing rules
# test: run all tests in cwd and subdirs
test: test-nonrecursive
@ for subdir in $(SUBDIRS) . ; do \
test "$$subdir" = "." -o "$$subdir" = "po" || \
( cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $@ ) || exit $? ; \
done
# test-nonrecursive: run tests only in cwd
test-nonrecursive: ${TEST_PROGS}
@test -z "${TEST_PROGS}" || G_DEBUG=gc-friendly MALLOC_CHECK_=2 MALLOC_PERTURB_=$$(($${RANDOM:-256} % 256)) ${GTESTER} --verbose ${TEST_PROGS}
# test-report: run tests in subdirs and generate report
# perf-report: run tests in subdirs with -m perf and generate report
# full-report: like test-report: with -m perf and -m slow
test-report perf-report full-report: ${TEST_PROGS}
@test -z "${TEST_PROGS}" || { \
case $@ in \
test-report) test_options="-k";; \
perf-report) test_options="-k -m=perf";; \
full-report) test_options="-k -m=perf -m=slow";; \
esac ; \
if test -z "$$GTESTER_LOGDIR" ; then \
${GTESTER} --verbose $$test_options -o test-report.xml ${TEST_PROGS} ; \
elif test -n "${TEST_PROGS}" ; then \
${GTESTER} --verbose $$test_options -o `mktemp "$$GTESTER_LOGDIR/log-XXXXXX"` ${TEST_PROGS} ; \
fi ; \
}
@ ignore_logdir=true ; \
if test -z "$$GTESTER_LOGDIR" ; then \
GTESTER_LOGDIR=`mktemp -d "\`pwd\`/.testlogs-XXXXXX"`; export GTESTER_LOGDIR ; \
ignore_logdir=false ; \
fi ; \
REVISION=$(VERSION) ; \
for subdir in $(SUBDIRS) . ; do \
test "$$subdir" = "." -o "$$subdir" = "po" || \
( cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $@ ) || exit $? ; \
done ; \
$$ignore_logdir || { \
echo '' > $@.xml ; \
echo '' >> $@.xml ; \
echo '' >> $@.xml ; \
echo ' $(PACKAGE)' >> $@.xml ; \
echo ' $(VERSION)' >> $@.xml ; \
echo " $$REVISION" >> $@.xml ; \
echo '' >> $@.xml ; \
for lf in `ls -L "$$GTESTER_LOGDIR"/.` ; do \
sed '1,1s/^?]*?>//' <"$$GTESTER_LOGDIR"/"$$lf" >> $@.xml ; \
done ; \
echo >> $@.xml ; \
echo '' >> $@.xml ; \
rm -rf "$$GTESTER_LOGDIR"/ ; \
${GTESTER_REPORT} --version 2>/dev/null 1>&2 ; test "$$?" != 0 || ${GTESTER_REPORT} $@.xml >$@.html ; \
}
.PHONY: test test-report perf-report full-report test-nonrecursive
# run tests in cwd as part of make check
if ENABLE_HEADLESS_TESTS
check-local: test-headless
else
check-local: test-nonrecursive
endif
./NEWS 0000644 0000041 0000041 00000001716 12772523363 011761 0 ustar www-data www-data 2010-10-06: unity-place-applications 0.4.12
------------------------------------------
* Update category icons
* Make sure we don't update the model too soon, otherwise Dash flickers
* Fix duplicates in Installed and Available applications
* Unset DBUS_STARTER* environment variables which caused weird behaviour
of subprocesses
2010-06-24: unity-place-applications 0.2.1
------------------------------------------
* Prototype impl. of application sections in place.
* Pull Most Used apps from Zeitgeist
* Search still only working against Zeitgeist, no Software Center/APT
integration yet
2010-06-22: unity-place-applications 0.2.0
------------------------------------------
* Very partial implementation ofnew Unity DBus API for places.
Basically only searching works, and you'll only get results
in the "Most Used" group - pulled from Zeitgeist. Nothing
like seeing all apps - let alone restricting them by section
is ready yet.
./acinclude.m4 0000644 0000041 0000041 00000001707 12772523363 013453 0 ustar www-data www-data dnl AS_AC_EXPAND(VAR, CONFIGURE_VAR)
dnl
dnl example
dnl AS_AC_EXPAND(SYSCONFDIR, $sysconfdir)
dnl will set SYSCONFDIR to /usr/local/etc if prefix=/usr/local
AC_DEFUN([AS_AC_EXPAND],
[
EXP_VAR=[$1]
FROM_VAR=[$2]
dnl first expand prefix and exec_prefix if necessary
prefix_save=$prefix
exec_prefix_save=$exec_prefix
dnl if no prefix given, then use /usr/local, the default prefix
if test "x$prefix" = "xNONE"; then
prefix=$ac_default_prefix
fi
dnl if no exec_prefix given, then use prefix
if test "x$exec_prefix" = "xNONE"; then
exec_prefix=$prefix
fi
full_var="$FROM_VAR"
dnl loop until it doesn't change anymore
while true; do
new_full_var="`eval echo $full_var`"
if test "x$new_full_var"="x$full_var"; then break; fi
full_var=$new_full_var
done
dnl clean up
full_var=$new_full_var
AC_SUBST([$1], "$full_var")
dnl restore prefix and exec_prefix
prefix=$prefix_save
exec_prefix=$exec_prefix_save
])
./configure.ac 0000644 0000041 0000041 00000014705 12772523363 013552 0 ustar www-data www-data AC_INIT(unity-lens-applications, 7.1.0, https://launchpad.net/unity-lens-applications)
AC_COPYRIGHT([Copyright 2010-2012 Canonical])
AM_INIT_AUTOMAKE([1.11])
LT_INIT
#############################################
# Silent build rules
#############################################
m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
AC_PREREQ(2.59)
AC_CONFIG_HEADERS([config.h])
#############################################
# Init the other things we depend on
#############################################
AM_MAINTAINER_MODE([enable])
AM_PROG_VALAC([0.18.0])
AS_IF([test -z "$VALAC"], [AC_MSG_ERROR(["No valac compiler found."])])
AC_PROG_CC
AC_PROG_CXX
AM_PROG_CC_C_O
AC_HEADER_STDC
AC_LANG([C++])
LT_INIT
AC_CONFIG_MACRO_DIR([m4])
#############################################
# Gettext
#############################################
GETTEXT_PACKAGE="$PACKAGE"
AC_SUBST(GETTEXT_PACKAGE)
AC_SUBST([CONFIG_STATUS_DEPENDENCIES],['$(top_srcdir)/po/LINGUAS'])
AC_DEFINE_UNQUOTED(GETTEXT_PACKAGE, "$GETTEXT_PACKAGE", [gettext domain])
AM_GLIB_GNU_GETTEXT
# AM_GNOME_GETTEXT above substs $DATADIRNAME
# this is the directory where the *.{mo,gmo} files are installed
localedir='${prefix}/${DATADIRNAME}/locale'
AC_SUBST(localedir)
IT_PROG_INTLTOOL([0.40.0])
AC_DEFINE_UNQUOTED(LOCALE_DIR, "${PREFIX}/${DATADIRNAME}/locale",[Locale directory])
AC_DEFINE_UNQUOTED(DATADIR, "${PREFIX}/${DATADIRNAME}",[Data directory])
AC_DEFINE_UNQUOTED(PREFIXDIR, "${PREFIX}",[Prefix directory])
######################################################
# intltool rule for generating translated .scope file
######################################################
INTLTOOL_SCOPE_RULE='%.scope: %.scope.in $(INTLTOOL_MERGE) $(wildcard $(top_srcdir)/po/*.po) ; LC_ALL=C $(INTLTOOL_MERGE) -d -u -c $(top_builddir)/po/.intltool-merge-cache $(top_srcdir)/po $< [$]@'
AC_SUBST(INTLTOOL_SCOPE_RULE)
###########################
# gcov coverage reporting
###########################
m4_include([m4/gcov.m4])
AC_TDD_GCOV
AM_CONDITIONAL([HAVE_GCOV], [test "x$ac_cv_check_gcov" = xyes])
AM_CONDITIONAL([HAVE_LCOV], [test "x$ac_cv_check_lcov" = xyes])
AM_CONDITIONAL([HAVE_GCOVR], [test "x$ac_cv_check_gcovr" = xyes])
AC_SUBST(COVERAGE_CFLAGS)
AC_SUBST(COVERAGE_LDFLAGS)
#############################################
# Check for module and library dependancies
#############################################
GLIB_REQUIRED=2.27
PKG_CHECK_MODULES(LENS_DAEMON,
glib-2.0 >= $GLIB_REQUIRED
gobject-2.0 >= $GLIB_REQUIRED
gio-2.0 >= $GLIB_REQUIRED
gio-unix-2.0 >= $GLIB_REQUIRED
gee-0.8
dee-1.0 >= 0.5.16
zeitgeist-1.0 >= 0.3.8
libcolumbus >= 1.0.0
unity >= 7.1.1
unity-protocol-private
libgnome-menu-3.0 >= 3.6.0)
AC_SUBST(LENS_DAEMON_CFLAGS)
AC_SUBST(LENS_DAEMON_LIBS)
AC_CHECK_HEADER(db.h, [],
AC_MSG_FAILURE([Unable to find db.h. Please install the package libdb-dev]))
AC_CHECK_HEADER(xapian.h, [],
AC_MSG_FAILURE([Unable to find xapian.h. Please install the package libxapian-dev]))
####################################################################
# Headless tests
####################################################################
AC_ARG_ENABLE([headless-tests],
AS_HELP_STRING([--enable-headless-tests=@<:@no/yes@:>@],[enable headless test suite (requires Xvfb) @<:@default=no@:>@]),,
[enable_headless_tests=no])
AM_CONDITIONAL([ENABLE_HEADLESS_TESTS],[test "x$enable_headless_tests" != "xno"])
if test "x$enable_headless_tests" = "xyes"; then
AC_PATH_PROG([XVFB],[Xvfb])
AC_PATH_PROG([DBUS_LAUNCH],[dbus-launch])
fi
####################################################################
# C compiler warnings
####################################################################
AC_ARG_ENABLE([c-warnings],
AC_HELP_STRING([--enable-c-warnings=@<:@no/yes@:>@], [show warnings from the C compiler @<:@default=no@:>@]),,
[enable_c_warnings=no])
if test "x$enable_c_warnings" = "xyes"; then
AC_DEFINE(ENABLE_C_WARNINGS, 1, [show warnings from the C compiler])
fi
AM_CONDITIONAL(ENABLE_C_WARNINGS, test "$enable_c_warnings" = "yes")
#############################################
# local install for distcheck and stand-alone running
#############################################
with_localinstall="no"
AC_ARG_ENABLE(localinstall,
AS_HELP_STRING([--enable-localinstall],
[Install all of the files locally instead of in system directories (for distcheck)]),
with_localinstall=$enableval,
with_localinstall=no)
AM_CONDITIONAL([HAVE_LOCALINSTALL], [test "x$with_localinstall" = "xyes"])
#############################################
# Expand variables needed for config.vala
#############################################
AS_AC_EXPAND(PREFIX, $prefix)
AC_SUBST(PREFIX)
AS_AC_EXPAND(DATADIR, $datarootdir)
AC_SUBST(DATADIR)
#####################################################
# Look for protocol-private lib dir
#####################################################
PROTOCOLPRIVATELIBDIR="`$PKG_CONFIG --variable=libdir unity-protocol-private`/libunity"
AC_SUBST(PROTOCOLPRIVATELIBDIR)
#############################################
# look for dbus service dir
#############################################
if test "x$with_localinstall" = "xyes"; then
DBUSSERVICEDIR="${datadir}/dbus-1/services/"
else
DBUSSERVICEDIR=`$PKG_CONFIG --variable=session_bus_services_dir dbus-1`
fi
AC_SUBST(DBUSSERVICEDIR)
#############################################
# GSettings macros
#############################################
GLIB_GSETTINGS
#############################################
# Create the Makefiles
#############################################
AC_CONFIG_FILES([
Makefile
data/com.canonical.Unity.AppsLens.gschema.xml.in
data/Makefile
data/X-Unity-All-Applications.directory
data/unity-lens-applications.menu
src/Makefile
src/config.vala
po/Makefile.in
tests/unit/Makefile
])
AC_OUTPUT
dnl Output the results
AC_MSG_NOTICE([
Unity Applications Lens Daemon $VERSION
------------------------------------
Prefix : ${prefix}
Sysconfdir : ${sysconfdir}
Local install : ${with_localinstall}
Extra CFlags : ${CPPFLAGS} $MAINTAINER_CFLAGS
Extra ValaFlags: ${CPPFLAGS} $MAINTAINER_VALAFLAGS
Testing
Headless tests : ${enable_headless_tests}
Coverage reporting : ${use_gcov}
])
./README 0000644 0000041 0000041 00000000000 12772523363 012123 0 ustar www-data www-data ./TESTS-TODO.txt 0000644 0000041 0000041 00000001021 12772523363 013455 0 ustar www-data www-data Since testing lenses is dependant on multiple components in the system,
we use the `unity-lens-test-tool` which is able to talk to the lenses
and examine results they return.
Currently this is not hooked into the build system, but you can run the tests
by invoking `unity-lens-test-tool --test-server-mode ./tests`
Here are some of the use-cases that are missing tests currently:
1) Make sure it's possible to search for CamelCase apps by searching "case",
plus this should properly work with accented characters as well.
./COPYING 0000644 0000041 0000041 00000104374 12772523363 012321 0 ustar www-data www-data
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
./src/ 0000755 0000041 0000041 00000000000 12772523373 012045 5 ustar www-data www-data ./src/software-center-data-cache.vala 0000644 0000041 0000041 00000004632 12772523363 017776 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens {
public class SoftwareCenterDataCache: SoftwareCenterDataProviderProxy
{
public int64 category_items_lifetime { get; set; }
private HashTable category_items_last_update;
private HashTable> category_items_cached;
public SoftwareCenterDataCache (int64 category_items_lifetime)
{
category_items_last_update = new HashTable (str_hash, str_equal);
category_items_cached = new HashTable> (str_hash, str_equal);
this.category_items_lifetime = category_items_lifetime;
}
internal static bool outdated (ref int64 last_update, int64 lifetime)
{
var current_time = new GLib.DateTime.now_utc ();
int64 current_unix_time = current_time.to_unix ();
if (current_unix_time > last_update + lifetime)
{
last_update = current_unix_time;
return true;
}
return false;
}
public override async SoftwareCenterData.AppInfo?[] get_items_for_category (string category_name) throws Error
{
int64 last_update = 0;
if (category_items_last_update.contains (category_name))
{
last_update = category_items_last_update[category_name];
}
if (outdated (ref last_update, category_items_lifetime))
{
category_items_last_update[category_name] = last_update;
var data = yield base.get_items_for_category (category_name);
var results = new Gee.ArrayList ();
foreach (var item in data)
{
results.add (item);
}
category_items_cached[category_name] = results;
return data;
}
return category_items_cached[category_name].to_array ();
}
}
}
./src/app-watcher.vala 0000644 0000041 0000041 00000011221 12772523363 015121 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Michal Hruby
*
*/
using Unity;
using Gee;
namespace Unity.ApplicationsLens
{
public class AppWatcher : Object
{
private string[] prefixes;
Gee.Set running_apps;
public AppWatcher ()
{
Object ();
}
public bool has_app_id (string desktop_id)
{
return desktop_id in running_apps;
}
public signal void running_applications_changed ();
construct
{
running_apps = new HashSet ();
foreach (unowned string data_dir in Environment.get_system_data_dirs ())
{
prefixes += Path.build_path (Path.DIR_SEPARATOR_S,
data_dir,
"applications",
Path.DIR_SEPARATOR_S, null);
}
try
{
var connection = Bus.get_sync (BusType.SESSION);
connection.signal_subscribe ("org.ayatana.bamf",
"org.ayatana.bamf.matcher",
"RunningApplicationsChanged",
"/org/ayatana/bamf/matcher",
null,
DBusSignalFlags.NONE,
this.running_apps_changed);
connection.call.begin ("org.ayatana.bamf",
"/org/ayatana/bamf/matcher",
"org.ayatana.bamf.matcher",
"RunningApplicationsDesktopFiles",
null,
null,
0,
-1,
null,
this.got_running_apps);
}
catch (Error err)
{
warning ("Unable to get running applications: %s", err.message);
}
}
private void got_running_apps (Object? src_obj,
AsyncResult res)
{
var connection = src_obj as DBusConnection;
try
{
Variant reply = connection.call.end (res);
string[] paths = (string[]) reply.get_child_value (0);
foreach (var p in paths) running_apps.add (extract_desktop_id (p));
this.running_applications_changed ();
}
catch (Error e)
{
warning ("%s", e.message);
}
}
private void running_apps_changed (DBusConnection connection,
string sender_name,
string object_path,
string interface_name,
string signal_name,
Variant parameters)
{
if (!parameters.is_of_type (new VariantType ("(asas)")))
{
warning ("RunningApplicationsChanged signal has incorrect type!");
return;
}
Variant opened_apps_variant;
Variant closed_apps_variant;
parameters.get ("(@as@as)", out opened_apps_variant,
out closed_apps_variant);
string[] opened_paths = (string[]) opened_apps_variant;
string[] closed_paths = (string[]) closed_apps_variant;
foreach (unowned string closed in closed_paths)
running_apps.remove (extract_desktop_id (closed));
foreach (unowned string opened in opened_paths)
running_apps.add (extract_desktop_id (opened));
this.running_applications_changed ();
}
private string extract_desktop_id (string path)
{
if (!path.has_prefix ("/")) return path;
/* fdo menu-spec compliant desktop id extraction */
foreach (unowned string prefix in prefixes)
{
if (path.has_prefix (prefix))
{
string without_prefix = path.substring (prefix.length);
if (Path.DIR_SEPARATOR_S in without_prefix)
return without_prefix.replace (Path.DIR_SEPARATOR_S, "-");
return without_prefix;
}
}
return Path.get_basename (path);
}
}
}
./src/aptd-client.vala 0000644 0000041 0000041 00000005617 12772523363 015126 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens {
static const string APTD_DBUS_NAME = "org.debian.apt";
static const string APTD_DBUS_PATH = "/org/debian/apt";
/**
* Expose a subset of org.debian.apt interfaces -- only what's needed by applications lens.
*/
[DBus (name = "org.debian.apt")]
public interface AptdService: GLib.Object
{
public abstract async string install_packages (string[] packages) throws IOError;
public abstract async string remove_packages (string[] packages) throws IOError;
public abstract async void quit () throws IOError;
}
[DBus (name = "org.debian.apt.transaction")]
public interface AptdTransactionService: GLib.Object
{
public abstract void run () throws IOError;
public abstract void simulate () throws IOError;
public abstract void cancel () throws IOError;
public signal void finished (string exit_state);
}
public class AptdProxy: GLib.Object
{
public void connect_to_aptd () throws IOError
{
_aptd_service = Bus.get_proxy_sync (BusType.SYSTEM, APTD_DBUS_NAME, APTD_DBUS_PATH);
}
public async string install_packages (string[] packages) throws IOError
{
string res = yield _aptd_service.install_packages (packages);
return res;
}
public async string remove_packages (string[] packages) throws IOError
{
string res = yield _aptd_service.remove_packages (packages);
return res;
}
public async void quit () throws IOError
{
yield _aptd_service.quit ();
}
private AptdService _aptd_service;
}
public class AptdTransactionProxy: GLib.Object
{
public signal void finished (string transaction_id);
public void connect_to_aptd (string transaction_id) throws IOError
{
_aptd_service = Bus.get_proxy_sync (BusType.SYSTEM, APTD_DBUS_NAME, transaction_id);
_aptd_service.finished.connect ((exit_state) =>
{
debug ("aptd transaction finished: %s\n", exit_state);
finished (transaction_id);
});
}
public void simulate () throws IOError
{
_aptd_service.simulate ();
}
public void run () throws IOError
{
_aptd_service.run ();
}
private AptdTransactionService _aptd_service;
}
}
./src/software-center-utils.vala 0000644 0000041 0000041 00000004476 12772523363 017172 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
*/
namespace Unity.ApplicationsLens.SoftwareCenterUtils
{
public class MangledDesktopFileLookup
{
/* Maps demangled names to mangled names expected by S-C xapian DB (e.g. kde4-KCharSelect.desktop -> kde4__KCharSelect.desktop).
There are very few apps that need this and we only store mappings when needed, so it takes very little memory.
*/
private HashTable mangled_desktop_ids;
public MangledDesktopFileLookup ()
{
mangled_desktop_ids = new HashTable(str_hash, str_equal);
}
public bool contains (string desktop_file)
{
return mangled_desktop_ids.contains (desktop_file);
}
public string get (string desktop_file)
{
return mangled_desktop_ids[desktop_file];
}
public string extract_desktop_id (string? desktop_file,
bool unmangle = false)
{
if (desktop_file == null) return "";
string desktop_id = Path.get_basename (desktop_file);
/* S-C uses "app_name:desktop_id.desktop", get rid of the prefix */
int colon_pos = desktop_id.index_of (":");
if (unmangle && colon_pos > 0)
{
desktop_id = desktop_id[colon_pos+1:desktop_id.length];
/* well it's still not real desktop_id, S-C converts slashes to "__"
* if the desktop file is in /usr/share/applications */
string demangled_desktop_id = desktop_id.replace ("__", "-");
// store demangled name -> mangled name mapping
if (desktop_id != demangled_desktop_id)
{
mangled_desktop_ids.replace (demangled_desktop_id, desktop_id);
}
desktop_id = demangled_desktop_id;
}
return desktop_id;
}
}
} ./src/unity-package-search.h 0000644 0000041 0000041 00000007166 12772523363 016233 0 ustar www-data www-data /*
* Copyright (C) 2010 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
#include
#include
#include
typedef struct _UnityPackageSearcher UnityPackageSearcher;
typedef enum
{
UNITY_PACKAGE_SEARCHTYPE_PREFIX,
UNITY_PACKAGE_SEARCHTYPE_EXACT,
} UnityPackageSearchType;
typedef enum
{
UNITY_PACKAGE_SORT_BY_NAME,
UNITY_PACKAGE_SORT_BY_RELEVANCY,
} UnityPackageSort;
typedef struct
{
GSList *results;
gint num_hits;
gboolean fuzzy_search;
} UnityPackageSearchResult;
typedef struct
{
gchar *package_name;
gchar *application_name;
gchar *description;
gchar *desktop_file;
gchar *icon;
gchar *price;
gboolean needs_purchase;
gint relevancy;
gboolean is_master_scope;
} UnityPackageInfo;
typedef gboolean (*AppFilterCallback)(UnityPackageInfo *, void *);
#ifdef __cplusplus
extern "C" {
#endif
UnityPackageSearcher* unity_package_searcher_new ();
UnityPackageSearcher* unity_package_searcher_new_for_menu (GMenuTree *menu);
UnityPackageSearcher* unity_package_searcher_new_for_scopes (UnityProtocolScopeRegistry *scope_registry);
void unity_package_searcher_free (UnityPackageSearcher *searcher);
UnityPackageSearchResult* unity_package_searcher_search (UnityPackageSearcher *searcher,
const gchar *search_string,
guint max_hits,
UnityPackageSearchType search_type,
UnityPackageSort sort);
UnityPackageSearchResult* unity_package_searcher_get_random_apps (UnityPackageSearcher *searcher,
const gchar *filter_query,
guint n_apps);
UnityPackageSearchResult* unity_package_searcher_get_apps (UnityPackageSearcher *searcher,
const gchar *filter_query,
guint n_apps,
AppFilterCallback cb,
gpointer data);
UnityPackageSearchResult* unity_package_search_result_new ();
void unity_package_search_result_free (UnityPackageSearchResult *result);
UnityPackageInfo* unity_package_package_info_new ();
void unity_package_package_info_free (gpointer pkg);
UnityPackageSearchResult* unity_package_searcher_get_by_exact_names (UnityPackageSearcher *searcher, GSList *names);
UnityPackageInfo* unity_package_searcher_get_by_desktop_file (UnityPackageSearcher *searcher, const gchar *desktop_file);
#ifdef __cplusplus
}
#endif
./src/windows-stack.vala 0000644 0000041 0000041 00000005277 12772523363 015521 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*
*/
namespace Unity.ApplicationsLens {
public class WinStack
{
public struct Window
{
uint window_id;
string app_id;
public Window (uint window_id, string app_id)
{
this.window_id = window_id;
this.app_id = app_id;
}
}
private Gee.LinkedList winstack = new Gee.LinkedList ();
public signal void updated ();
public WinStack ()
{
}
private void add_window (uint win_id, string app_id)
{
var win = Window (win_id, app_id);
if (!winstack.contains (win))
winstack.add (win);
}
private void insert_window (uint win_id, string app_id)
{
var win = Window (win_id, app_id);
winstack.insert (0, win);
}
private void remove_window (uint win_id, string app_id)
{
var it = winstack.iterator ();
while (it.next ())
{
var win = it.get ();
if (win.app_id == app_id && win.window_id == win_id)
{
it.remove ();
return;
}
}
}
public void from_win_stack (WindowInfo[] windows)
{
debug ("Adding %u windows", windows.length);
foreach (var win in windows)
{
add_window (win.window_id, win.app_id);
}
}
public void on_window_created (uint win_id, string app_id)
{
debug ("Window created: %s", app_id);
add_window (win_id, app_id);
updated ();
}
public void on_window_destroyed (uint win_id, string app_id)
{
debug ("Window destroyed: %s", app_id);
remove_window (win_id, app_id);
updated ();
}
public void on_focused_window_changed (uint win_id, string app_id, uint stage)
{
debug ("Focused window: %s", app_id);
remove_window (win_id, app_id);
insert_window (win_id, app_id);
updated ();
}
public Gee.Iterator iterator ()
{
var it = winstack.iterator ();
return it;
}
}
} ./src/unity-ratings-db.h 0000644 0000041 0000041 00000003116 12772523363 015416 0 ustar www-data www-data /*
* Copyright (C) 2011 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
#ifndef _UNITY_RATINGS_DB_H_
#define _UNITY_RATINGS_DB_H_
#include
G_BEGIN_DECLS
/* This struct *must* start with 3 32 bit integers, to smoothly be able
* to store the results we read from the Software Center Ratings DB */
typedef struct {
gint32 average_rating;
gint32 total_rating;
gint32 dampened_rating;
} UnityRatingsResult;
typedef struct _UnityRatingsDatabase UnityRatingsDatabase;
UnityRatingsDatabase* unity_ratings_database_new (GError **error);
void unity_ratings_database_free (UnityRatingsDatabase *self);
gboolean unity_ratings_database_query (UnityRatingsDatabase *self,
const gchar *pkgname,
UnityRatingsResult *out_result);
G_END_DECLS
#endif /* _UNITY_RATINGS_DB_H_ */
./src/running-apps-search.vala 0000644 0000041 0000041 00000012705 12772523363 016602 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*
*/
namespace Unity.ApplicationsLens {
private class RunningAppsSearch : Unity.ScopeSearchBase
{
private unowned WinStack windows;
private unowned Dee.ICUTermFilter icu;
private HashTable category_map;
public RunningAppsSearch (WinStack windows, Dee.ICUTermFilter icu, HashTable category_map)
{
this.windows = windows;
this.icu = icu;
this.category_map = category_map;
}
/*
Check if categories defined in a .desktop file match any of the active filter categories.
*/
private bool category_matches (string[] desktop_file_categories, Gee.Set selected_categories)
{
bool matches = false;
foreach (var sel in selected_categories)
{
// selected categories are filter ids, remap them to real categories
unowned CategoryList? cm = category_map.lookup (sel);
if (cm == null)
return false;
foreach (var cat in cm.categories)
{
if (cat in desktop_file_categories)
{
matches = true;
break;
}
}
if (matches == false)
return false;
foreach (var cat in cm.exclude_categories)
{
if (cat in desktop_file_categories)
{
matches = false;
break;
}
}
}
return matches;
}
/*
Return ids of active filter options (categories corresponding to category_map keys)
*/
private Gee.Set get_selected_categories (Unity.OptionsFilter filter)
{
var cats = new Gee.HashSet ();
foreach (var opt in filter.options)
{
if (opt.active)
cats.add (opt.id);
}
return cats;
}
public override void run_async (ScopeSearchBaseCallback async_callback)
{
run ();
async_callback (this);
}
public override void run ()
{
// Don't add results to global searches
if (search_context.search_type == SearchType.GLOBAL)
return;
var query = icu.apply (search_context.search_query.down ());
var type_filter = search_context.filter_state.get_filter_by_id ("type") as OptionsFilter;
bool has_filter = (type_filter != null && type_filter.filtering);
var selected_categories = has_filter ? get_selected_categories (type_filter) : null;
var appmanager = AppInfoManager.get_default();
var it = windows.iterator ();
while (it.next ())
{
var win = it.get ();
debug ("Window: %s", win.app_id);
try
{
bool matches = false;
var app_id = win.app_id;
if (!app_id.has_suffix (".desktop"))
app_id += ".desktop";
var app_info = appmanager.lookup (app_id);
if (app_info == null || !(app_info is DesktopAppInfo))
{
warning ("No desktop file for %s", app_id);
continue;
}
var desktop_file = app_info as DesktopAppInfo;
if (selected_categories != null && !category_matches (desktop_file.get_categories ().split (";"), selected_categories))
continue;
if (search_context.search_query.strip () == "")
{
matches = true;
}
else
{
var display_name = icu.apply (desktop_file.get_display_name ().down ());
if (display_name.contains (query))
{
matches = true;
}
else
{
var descr = icu.apply (desktop_file.get_description ().down ());
if (descr.contains (query))
{
matches = true;
}
else
{
var exec_name = icu.apply (desktop_file.get_executable ().down ());
if (exec_name.contains (query))
matches = true;
}
}
}
if (matches)
{
var result = Unity.ScopeResult ();
result.uri = "application://" + win.app_id;
result.icon_hint = "image://screenshot/" + win.app_id;
result.category = 0;
result.result_type = Unity.ResultType.PERSONAL;
result.mimetype = "application/x-desktop";
result.title = desktop_file.get_display_name ();
result.comment = "";
result.dnd_uri = result.uri;
result.metadata = new HashTable (str_hash, str_equal);
search_context.result_set.add_result (result);
}
}
catch (Error e)
{
warning ("Error loading desktop file: %s", win.app_id);
}
}
}
}
}
./src/daemon.vala 0000644 0000041 0000041 00000163575 12772523363 014175 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2010-2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
* Neil Jagdish Patel
*
*/
using Dee;
using Zeitgeist;
using Zeitgeist.Timestamp;
using Config;
using Gee;
using GMenu;
namespace Unity.ApplicationsLens {
/* Number of 'Apps available for download' to show if no search query is provided AND a filter is active.
It shouldn't be too high as this may impact lens performance.
*/
const uint MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY = 100;
/* Number of top rated apps to show in 'Apps available for download' if no search query is provided AND NO filter is active. */
const uint MAX_TOP_RATED_APPS_FOR_EMPTY_QUERY = 12;
/* Number of "What's new" apps to show in 'Apps available for download' if no search query is provided AND NO filter is active. */
const uint MAX_WHATS_NEW_APPS_FOR_EMPTY_QUERY = 10;
/* Time between queries to SoftwareCenterDataProvider */
const int64 TOP_RATED_ITEMS_CACHE_LIFETIME = 24*3600; // 24 hours
const string ICON_PATH = Config.DATADIR + "/icons/unity-icon-theme/places/svg/";
const string GENERIC_APP_ICON = "applications-other";
const string LIBUNITY_SCHEMA = "com.canonical.Unity.Lenses";
private class ApplicationsScope : Unity.AbstractScope
{
public Zeitgeist.Log log;
public Zeitgeist.Index zg_index;
private Zeitgeist.Monitor monitor;
public Map popularity_map;
public bool popularities_dirty;
/* The searcher for online material may be null if it fails to load
* the Xapian index from the Software Center */
public Unity.Package.Searcher? pkgsearcher;
public Unity.Package.Searcher appsearcher;
/* Read the app ratings dumped by the Software Center */
private bool ratings_db_initialized = false;
public Unity.Ratings.Database? ratings = null;
/* Support aptd dbus interface; created when application install/remove was requested by preview action */
private AptdProxy aptdclient;
private AptdTransactionProxy aptd_transaction;
public SoftwareCenterUtils.MangledDesktopFileLookup sc_mangler;
/* Used for adding launcher icon on app installation from the preview */
private LauncherProxy launcherservice;
/* Desktop file & icon name for unity-install:// install candidate displayed in last preview; we store
* them here to avoid extra query for app details if app install action is activated */
public string preview_installable_desktop_file;
public string preview_installable_icon_file;
public string preview_developer_website;
/* SoftwareCenter data provider used for app preview details */
public SoftwareCenterDataProviderProxy sc_data_provider;
public Unity.ApplicationsLens.CommandsScope commands_scope;
private Gee.List image_extensions;
private HashTable file_icon_cache;
/* Monitor the favorite apps in the launcher, so we can filter them
* out of the results for Recent Apps */
public Unity.LauncherFavorites favorite_apps;
public AppWatcher app_watcher;
public PtrArray zg_templates;
/* Gnome menu structure - also used to check whether apps are installed */
private uint app_menu_changed_reindex_timeout = 0;
private GMenu.Tree app_menu = null;
private Regex? uri_regex;
private Regex mountable_regex;
private Settings gp_settings;
private const string DISPLAY_RECENT_APPS_KEY = "display-recent-apps";
private const string DISPLAY_AVAILABLE_APPS_KEY = "display-available-apps";
public bool display_recent_apps { get; set; default = true; }
public bool display_available_apps { get; set; default = true; }
public bool force_small_icons_for_suggestions { get; set; default = true; }
public PurchaseInfoHelper purchase_info = null;
construct
{
populate_zg_templates ();
log = new Zeitgeist.Log();
zg_index = new Zeitgeist.Index();
monitor = new Zeitgeist.Monitor (new Zeitgeist.TimeRange.from_now (),
zg_templates);
monitor.events_inserted.connect (mark_dirty);
monitor.events_deleted.connect (mark_dirty);
log.install_monitor (monitor);
popularity_map = new HashMap ();
popularities_dirty = true;
// refresh the popularities every now and then
Timeout.add_seconds (30 * 60, () =>
{
popularities_dirty = true;
return true;
});
this.gp_settings = new Settings ("com.canonical.Unity.ApplicationsLens");
this.gp_settings.bind(DISPLAY_RECENT_APPS_KEY, this, "display_recent_apps", SettingsBindFlags.GET);
this.gp_settings.bind(DISPLAY_AVAILABLE_APPS_KEY, this, "display_available_apps", SettingsBindFlags.GET);
pkgsearcher = new Unity.Package.Searcher ();
if (pkgsearcher == null)
{
critical ("Failed to load Software Center index. 'Apps Available for Download' will not be listed");
}
/* Image file extensions in order of popularity */
image_extensions = new Gee.ArrayList ();
image_extensions.add ("png");
image_extensions.add ("xpm");
image_extensions.add ("svg");
image_extensions.add ("tiff");
image_extensions.add ("ico");
image_extensions.add ("tif");
image_extensions.add ("jpg");
build_app_menu_index ();
file_icon_cache = new HashTable(str_hash, str_equal);
sc_mangler = new SoftwareCenterUtils.MangledDesktopFileLookup ();
/* Listen for changes in the installed applications */
AppInfoManager.get_default().changed.connect (mark_dirty);
/* Now start the RunEntry */
commands_scope = new Unity.ApplicationsLens.CommandsScope (this);
try {
uri_regex = new Regex ("^[a-z]+:.+$");
mountable_regex = new Regex ("((ftp|ssh|sftp|smb|dav)://).+");
} catch (RegexError e) {
uri_regex = null;
critical ("Failed to compile URI regex. URL launching will be disabled");
}
favorite_apps = Unity.LauncherFavorites.get_default ();
favorite_apps.changed.connect(mark_dirty);
app_watcher = new AppWatcher ();
app_watcher.running_applications_changed.connect (mark_dirty);
aptdclient = new AptdProxy ();
launcherservice = new LauncherProxy ();
}
public void init_ratings_db ()
{
if (ratings_db_initialized) return;
try
{
ratings = new Unity.Ratings.Database ();
}
catch (FileError e)
{
warning ("%s", e.message);
ratings = null;
}
ratings_db_initialized = true;
}
public override string get_group_name ()
{
return "com.canonical.Unity.Scope.Applications";
}
public override string get_unique_name ()
{
return "/com/canonical/unity/scope/applications";
}
public override Unity.CategorySet get_categories ()
{
var categories = new Unity.CategorySet ();
File icon_dir = File.new_for_path (ICON_PATH);
var cat = new Unity.Category ("apps", _("Applications"),
new FileIcon (icon_dir.get_child ("group-apps.svg")));
categories.add (cat);
cat = new Unity.Category ("recently-used", _("Recently used"),
new FileIcon (icon_dir.get_child ("group-recent.svg")));
categories.add (cat);
cat = new Unity.Category ("recent", _("Recent apps"),
new FileIcon (icon_dir.get_child ("group-apps.svg")));
categories.add (cat);
cat = new Unity.Category ("installed", _("Installed"),
new FileIcon (icon_dir.get_child ("group-installed.svg")));
categories.add (cat);
cat = new Unity.Category ("more", _("More suggestions"),
new FileIcon (icon_dir.get_child ("group-treat-yourself.svg")));
categories.add (cat);
return categories;
}
public override Unity.FilterSet get_filters()
{
var filters = new Unity.FilterSet ();
/* Type filter */
{
var filter = new CheckOptionFilter ("type", _("Type"));
filter.sort_type = Unity.OptionsFilter.SortType.DISPLAY_NAME;
filter.add_option ("accessories", _("Accessories"));
filter.add_option ("education", _("Education"));
filter.add_option ("game", _("Games"));
filter.add_option ("graphics", _("Graphics"));
filter.add_option ("internet", _("Internet"));
filter.add_option ("fonts", _("Fonts"));
filter.add_option ("office", _("Office"));
filter.add_option ("media", _("Media"));
filter.add_option ("customization", _("Customization"));
filter.add_option ("accessibility", _("Accessibility"));
filter.add_option ("developer", _("Developer"));
filter.add_option ("science-and-engineering", _("Science & engineering"));
filter.add_option ("scopes", _("Dash plugins"));
filter.add_option ("system", _("System"));
filters.add (filter);
}
/* Sources */
{
var filter = new CheckOptionFilter ("unity-sources", _("Sources"));
filter.sort_type = Unity.OptionsFilter.SortType.DISPLAY_NAME;
// TRANSLATORS: Please make sure this string is short enough to fit
// into the filter button
filter.add_option ("local", _("Local apps"));
if (display_available_apps)
{
// TRANSLATORS: Please make sure this string is short enough to fit
// into the filter button
filter.add_option ("usc", _("Software center"));
}
filters.add (filter);
}
return filters;
}
public override Unity.Schema get_schema ()
{
var schema = new Unity.Schema ();
return schema;
}
public override string get_search_hint ()
{
return _("Search applications");
}
public override string normalize_search_query (string search_query)
{
return search_query.strip ();
}
public override Unity.ScopeSearchBase create_search_for_query (Unity.SearchContext search_context)
{
return new ApplicationsSearch (this, search_context);
}
public override Unity.ResultPreviewer create_previewer (Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
return new ApplicationsResultPreviewer (this, result, metadata);
}
public override Unity.ActivationResponse? activate (Unity.ScopeResult result, Unity.SearchMetadata metadata, string? action_id)
{
if (action_id == "buy")
return start_software_center (result.uri);
else if (action_id == "install")
return app_preview_install (result.uri);
else if (action_id == "install-paid")
return start_software_center (result.uri);
else if (action_id == "uninstall")
return app_preview_uninstall (result.uri);
else if (action_id == "website")
return app_preview_website (result.uri);
else
return app_launch (result, metadata);
}
private Unity.ActivationResponse app_launch (Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
string[] args;
string exec_or_dir = null;
if (result.uri.has_prefix ("unity-install://"))
{
var prv = create_previewer (result, metadata).run ();
if (prv is Unity.Preview)
{
return new Unity.ActivationResponse.with_preview (
prv as Unity.Preview);
}
else
{
warning ("Failed to generate preview for %s", result.uri);
return new Unity.ActivationResponse (Unity.HandledType.NOT_HANDLED);
}
}
else if (result.uri.has_prefix (UNITY_RUNNER_PREFIX))
{
string orig;
orig = result.uri.offset (UNITY_RUNNER_PREFIX.length);
if (orig.has_prefix("\\\\"))
orig = orig.replace ("\\\\","smb://");
if (uri_regex != null && uri_regex.match (orig)) {
try {
/* this code ensures that a file manager will be used
* if uri it's a remote location that should be mounted */
if (mountable_regex.match (orig)) {
var muris = new GLib.List();
muris.prepend (orig);
var file_manager = AppInfo.get_default_for_type("inode/directory", true);
file_manager.launch_uris(muris,null);
} else {
AppInfo.launch_default_for_uri (orig, null);
}
} catch (GLib.Error error) {
warning ("Failed to launch URI %s", orig);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
} else {
exec_or_dir = Utils.subst_tilde (orig);
args = exec_or_dir.split (" ", 0);
for (int i = 0; i < args.length; i++)
args[i] = Utils.subst_tilde (args[i]);
}
this.commands_scope.add_history (orig);
}
else
{
/* Activation of standard application:// uris */
/* Make sure fresh install learns quickly */
if (popularity_map.size <= 5) popularities_dirty = true;
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
if ((exec_or_dir != null) && FileUtils.test (exec_or_dir, FileTest.IS_DIR))
{
try {
AppInfo.launch_default_for_uri ("file://" + exec_or_dir, null);
} catch (GLib.Error err) {
warning ("Failed to open current folder '%s' in file manager: %s",
exec_or_dir, err.message);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
}
else
{
try {
unowned string home_dir = GLib.Environment.get_home_dir ();
Process.spawn_async (home_dir, args, null, SpawnFlags.SEARCH_PATH, null, null);
} catch (SpawnError e) {
warning ("Failed to spawn software-center or direct URI activation '%s': %s",
result.uri, e.message);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
}
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
}
private async void call_install_packages (string package_name, out string tid) throws IOError
{
tid = yield aptdclient.install_packages ({package_name});
}
private async void call_remove_packages (string package_name, out string tid) throws IOError
{
tid = yield aptdclient.remove_packages ({package_name});
}
/**
* Handler for free apps installation.
* Triggers package installation via apt-daemon DBus service
*/
private Unity.ActivationResponse app_preview_install (string uri)
{
if (uri.has_prefix ("unity-install://"))
{
string app = uri.substring (16); // trim "unity-install://"
string[] parts = app.split ("/");
if (parts.length > 1)
{
string pkgname = parts[0];
string appname = parts[1];
try
{
aptdclient.connect_to_aptd ();
}
catch (IOError e)
{
warning ("Failed to connect to aptd: '%s'", e.message);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
call_install_packages.begin (pkgname, (obj, res) =>
{
try {
string tid;
call_install_packages.end (res, out tid);
debug ("transaction started: %s, pkg: %s\n", tid, pkgname);
aptd_transaction = new AptdTransactionProxy ();
aptd_transaction.connect_to_aptd (tid);
aptd_transaction.simulate ();
aptd_transaction.run ();
launcherservice.connect_to_launcher ();
string desktop_file = preview_installable_desktop_file;
Icon icon = find_pkg_icon (null, preview_installable_icon_file);
launcherservice.add_launcher_item_from_position.begin (appname, icon.to_string (), 0, 0, 32, desktop_file, tid);
}
catch (IOError e)
{
warning ("Package '%s' installation failed: %s", pkgname, e.message);
}
});
}
else
{
warning ("Bad install uri: '%s'", uri);
}
}
else
{
warning ("Can't handle '%s' in app_preview_install handler", uri);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
}
private Unity.ActivationResponse start_software_center (string uri)
{
unowned string pkg = uri.offset (16); // strip off "unity-install://" prefix
debug ("Installing: %s", pkg);
var args = new string[2];
args[0] = "software-center";
args[1] = pkg;
try
{
Process.spawn_async (GLib.Environment.get_home_dir (), args, null, SpawnFlags.SEARCH_PATH, null, null);
}
catch (SpawnError e)
{
warning ("Failed to spawn software-center for uri '%s': %s", uri, e.message);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
}
private Unity.ActivationResponse app_preview_website (string uri)
{
try
{
AppInfo.launch_default_for_uri (preview_developer_website, null);
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
}
catch (Error e)
{
warning ("Failed to launch a web browser for uri '%s': '%s'", uri, e.message);
}
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
private Unity.ActivationResponse app_preview_uninstall (string uri)
{
if (uri.has_prefix ("application://"))
{
string desktopfile = uri.substring (14); // trim "application://"
// de-mangle desktop file names back to what S-C expects
if (sc_mangler.contains (desktopfile))
{
desktopfile = sc_mangler.get (desktopfile);
}
var pkginfo = pkgsearcher.get_by_desktop_file (desktopfile);
if (pkginfo != null && pkginfo.package_name != null)
{
try
{
aptdclient.connect_to_aptd ();
}
catch (IOError e)
{
warning ("Failed to connect to aptd: '%s'", e.message);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
call_remove_packages.begin (pkginfo.package_name, (obj, res) =>
{
try {
string tid;
call_remove_packages.end (res, out tid);
debug ("transaction started: %s, pkg: %s\n", tid, pkginfo.package_name);
aptd_transaction = new AptdTransactionProxy ();
aptd_transaction.connect_to_aptd (tid);
aptd_transaction.simulate ();
aptd_transaction.run ();
}
catch (IOError e)
{
warning (@"Package '$(pkginfo.package_name)' removal failed: $(e.message)");
}
});
return new Unity.ActivationResponse(Unity.HandledType.HIDE_DASH);
}
else
{
warning (@"Cannot find package info for $uri");
}
}
warning (@"Can't handle '%s' in app_preview_uninstall handler", uri);
return new Unity.ActivationResponse(Unity.HandledType.NOT_HANDLED);
}
/* Load xdg menu info and build a Xapian index over it.
* Do throttled re-index if the menu changes */
private bool build_app_menu_index ()
{
if (app_menu == null)
{
debug ("Building initial application menu");
/* We need INCLUDE_NODISPLAY to employ proper de-duping between
* the Installed and Availabale categorys. If a NoDisplay app is installed,
* eg. Evince, it wont otherwise be in the menu index, only in the
* S-C index - thus show up in the Available category */
app_menu = new GMenu.Tree ("unity-lens-applications.menu",
GMenu.TreeFlags.INCLUDE_NODISPLAY);
app_menu.changed.connect (() => {
/* Reschedule the timeout if we already have one. The menu tree triggers
* many change events during app installation. This way we wait the full
* delay *after* the last change event has triggered */
if (app_menu_changed_reindex_timeout != 0)
{
Source.remove (app_menu_changed_reindex_timeout);
}
app_menu_changed_reindex_timeout = Timeout.add_seconds (5, build_app_menu_index_and_result_models);
});
}
// gnome menu tree needs to be loaded on startup and after receiving 'changed' signal - see gmenu-tree.c in gnome-menus-3.6.0.
try
{
app_menu.load_sync (); //FIXME: libgnome-menu doesn't provide async method (yet?)
}
catch (GLib.Error e)
{
warning ("Failed to load menu entries: %s", e.message);
}
debug ("Indexing application menu");
appsearcher = new Unity.Package.Searcher.for_menu (app_menu);
app_menu_changed_reindex_timeout = 0;
return false;
}
/* Called when our app_menu structure changes - probably because something
* has been installed or removed. We reload gnome menu tree,
* rebuild the index and update the result models for global and scope.
* We need to update both because
* we can't know exactly what Unity may be showing */
private bool build_app_menu_index_and_result_models ()
{
build_app_menu_index ();
mark_dirty ();
return false;
}
private void populate_zg_templates ()
{
/* Create a template that activation of applications */
zg_templates = new PtrArray.sized(1);
var ev = new Zeitgeist.Event.full (ZG_ACCESS_EVENT, ZG_USER_ACTIVITY, "",
new Subject.full ("application*",
"", //NFO_SOFTWARE,
"",
"", "", "", ""));
zg_templates.add ((ev as GLib.Object).ref());
}
private void mark_dirty ()
{
results_invalidated (SearchType.DEFAULT);
results_invalidated (SearchType.GLOBAL);
}
public async void update_popularities ()
{
try
{
// simulate a kind of frecency
var end_ts = Timestamp.now ();
var start_ts = end_ts - Timestamp.WEEK * 3;
var rs = yield log.find_events (new TimeRange (start_ts, end_ts),
zg_templates,
StorageState.ANY,
256,
Zeitgeist.ResultType.MOST_POPULAR_SUBJECTS,
null);
// most popular apps must have high value, so unknown apps (where
// popularity_map[app] == 0 aren't considered super popular
int relevancy = 256;
foreach (unowned Event event in rs)
{
for (int i = 0; i < event.num_subjects (); i++)
{
unowned string uri = event.get_subject (i).get_uri ();
if (uri == null) continue;
popularity_map[uri] = relevancy;
}
relevancy--;
}
}
catch (GLib.Error err)
{
warning ("%s", err.message);
}
}
public Icon find_pkg_icon (string? desktop_file, string icon_name)
{
if (desktop_file != null)
{
string desktop_id = Path.get_basename (desktop_file);
bool installed = AppInfoManager.get_default().lookup (desktop_id) != null;
/* If the app is already installed we should be able to pull the
* icon from the theme */
if (installed)
return new ThemedIcon (icon_name);
}
/* App is not installed - we need to find the right icon in the bowels
* of the software center */
if (icon_name.has_prefix ("/"))
{
return new FileIcon (File.new_for_path (icon_name));
}
else
{
Icon icon = file_icon_cache.lookup (icon_name);
if (icon != null)
return icon;
/* If the icon name contains a . it probably already have a
* type postfix - so test icon name directly */
string path;
if ("." in icon_name)
{
path = @"$(Config.DATADIR)/app-install/icons/$(icon_name)";
if (FileUtils.test (path, FileTest.EXISTS))
{
icon = new FileIcon (File.new_for_path (path));
file_icon_cache.insert (icon_name, icon);
return icon;
}
/* Try also software center cache dir */
path = Path.build_filename (Environment.get_user_cache_dir (),
"software-center",
"icons",
icon_name);
if (FileUtils.test (path, FileTest.EXISTS))
{
icon = new FileIcon (File.new_for_path (path));
file_icon_cache.insert (icon_name, icon);
return icon;
}
}
/* Now try appending all the image extensions we know */
foreach (var ext in image_extensions)
{
path = @"$(Config.DATADIR)/app-install/icons/$(icon_name).$(ext)";
if (FileUtils.test (path, FileTest.EXISTS))
{
/* Got it! Cache the icon path and return the icon */
icon = new FileIcon (File.new_for_path (path));
file_icon_cache.insert (icon_name, icon);
return icon;
}
}
}
/* Cache the fact that we couldn't find this icon */
var icon = new ThemedIcon (GENERIC_APP_ICON);
file_icon_cache.insert (icon_name, icon);
return icon;
}
public async SoftwareCenterData.AppDetailsData get_app_details (string appname, string pkgname) throws Error
{
if (sc_data_provider == null)
{
sc_data_provider = new SoftwareCenterDataCache (TOP_RATED_ITEMS_CACHE_LIFETIME);
}
debug ("Requesting pkg info: %s, %s\n", pkgname, appname);
return yield sc_data_provider.get_app_details (appname, pkgname);
}
public async bool get_version_and_screenshot (string app_id, out string version, out string screenshot)
{
version = null;
screenshot = null;
// de-mangle desktop file names back to what S-C expects
string mangled_id;
if (sc_mangler.contains (app_id))
{
mangled_id = sc_mangler.get (app_id);
}
else
{
mangled_id = app_id;
}
var pkginfo = pkgsearcher.get_by_desktop_file (mangled_id);
if (pkginfo != null)
{
SoftwareCenterData.AppDetailsData? details;
try {
details = yield get_app_details(pkginfo.application_name,
pkginfo.package_name);
} catch (Error e) {
return false;
}
if (details != null) {
version = details.version;
screenshot = details.screenshot;
return true;
}
}
return false;
}
}
private class ApplicationsSearch : Unity.ScopeSearchBase
{
private ApplicationsScope scope;
public ApplicationsSearch (ApplicationsScope scope, Unity.SearchContext search_context)
{
this.scope = scope;
set_search_context (search_context);
}
public override void run ()
{
var ml = new MainLoop ();
run_async (() => { ml.quit (); });
ml.run ();
}
public override void run_async (Unity.ScopeSearchBaseCallback async_callback)
{
dispatch_search.begin (() =>
{
async_callback (this);
});
}
private async void dispatch_search ()
{
var context = this.search_context;
if (scope.popularities_dirty)
{
scope.popularities_dirty = false;
// we're not passing the cancellable, cause cancelling this search
// shouldn't cancel getting most popular apps
yield scope.update_popularities ();
if (context.cancellable.is_cancelled ()) return;
}
if (context.search_type == SearchType.DEFAULT)
yield search_default ();
else
yield search_global ();
}
private bool local_apps_active ()
{
var filter = search_context.filter_state.get_filter_by_id ("unity-sources") as Unity.OptionsFilter;
if (filter.filtering)
{
var option = filter.get_option ("local");
return option == null || option.active;
}
return true;
}
private bool usc_apps_active ()
{
var filter = search_context.filter_state.get_filter_by_id ("unity-sources") as Unity.OptionsFilter;
if (filter.filtering)
{
var option = filter.get_option ("usc");
return option == null || option.active;
}
return true;
}
/* Returns TRUE if application is NOT installed */
public bool filter_cb (Unity.Package.PackageInfo pkginfo)
{
var appmanager = AppInfoManager.get_default();
AppInfo? app = appmanager.lookup (pkginfo.desktop_file);
return app == null;
}
private bool is_phablet_ui ()
{
var form_factor = search_context.search_metadata.form_factor;
return form_factor == "phone" || form_factor == "tablet";
}
private async void search_default ()
{
var context = this.search_context;
var result_set = context.result_set;
/* We'll clear the model once we finish waiting for the dbus-call
* to finish, to prevent flicker. */
var search_string = context.search_query;
debug ("Searching for: %s", search_string);
var type_filter = context.filter_state.get_filter_by_id ("type") as OptionsFilter;
string pkg_search_string = XapianUtils.prepare_pkg_search_string (search_string, type_filter);
bool has_filter = (type_filter != null && type_filter.filtering);
bool has_search = !Utils.is_search_empty (search_string);
bool running_on_phablet = is_phablet_ui ();
Timer timer = new Timer ();
/* Even though the Installed apps search is super fast, we wait here
* for the Most Popular search to finish, because otherwise we'll update
* the Installed category too soon and this will cause flicker
* in the Dash. (lp:868192) */
Set installed_uris = new HashSet ();
Set available_uris = new HashSet ();
var appresults = scope.appsearcher.search (
pkg_search_string, 0, Unity.Package.SearchType.PREFIX,
has_search ?
Unity.Package.Sort.BY_RELEVANCY :
Unity.Package.Sort.BY_NAME);
if (local_apps_active ())
{
if (has_search) resort_pkg_search_results (appresults);
add_pkg_search_result (appresults, installed_uris, available_uris,
result_set, Category.INSTALLED,
0, running_on_phablet);
}
timer.stop ();
debug ("Entry search listed %i Installed apps in %fms for query: %s",
appresults.num_hits, timer.elapsed ()*1000, pkg_search_string);
if (local_apps_active () && scope.display_recent_apps)
{
try
{
timer.start ();
/* Ignore the search string, we want to keep displaying the same apps
* in the recent category and just filter out those that don't match
* the search query */
var zg_search_string = XapianUtils.prepare_zg_search_string ("", type_filter);
var results = yield scope.zg_index.search (
zg_search_string,
new Zeitgeist.TimeRange.anytime (),
scope.zg_templates,
0,
20,
Zeitgeist.ResultType.MOST_RECENT_SUBJECTS,
context.cancellable.get_gcancellable ());
append_events_with_category (results, result_set, Category.RECENT,
false, 6, installed_uris);
timer.stop ();
debug ("Entry search found %u/%u Recently Used apps in %fms for query '%s'",
results.size (), results.estimated_matches (),
timer.elapsed()*1000, zg_search_string);
} catch (IOError.CANCELLED ioe) {
// no need to bother
return;
} catch (GLib.Error e) {
warning ("Error performing search '%s': %s", search_string, e.message);
}
}
result_set.flush ();
scope.purchase_info = new PurchaseInfoHelper ();
/* If we don't have a search we display 6 random apps */
if (usc_apps_active () && scope.display_available_apps && scope.pkgsearcher != null)
{
if (has_search)
{
timer.start ();
var pkgresults = scope.pkgsearcher.search (
pkg_search_string, 50, Unity.Package.SearchType.PREFIX,
Unity.Package.Sort.BY_RELEVANCY);
add_pkg_search_result (pkgresults, installed_uris, available_uris,
result_set, Category.AVAILABLE,
0, running_on_phablet);
timer.stop ();
debug ("Entry search listed %i Available apps in %fms for query: %s",
pkgresults.num_hits, timer.elapsed ()*1000, pkg_search_string);
}
else if (has_filter) /* Empty search string + active filters should get lots of results from selected categories */
{
timer.start ();
string? filter_query = XapianUtils.prepare_pkg_search_string (search_string, type_filter);
var pkgresults = scope.pkgsearcher.get_apps (filter_query, MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY, filter_cb);
scope.purchase_info.from_pkgresults (pkgresults);
add_pkg_search_result (pkgresults, installed_uris, available_uris, result_set, Category.AVAILABLE, MAX_APP_FOR_DOWNLOAD_FOR_EMPTY_QUERY, running_on_phablet);
timer.stop ();
debug ("Entry search listed %i Available apps in %fms",
pkgresults.num_hits, timer.elapsed ()*1000);
}
else
{
timer.start ();
uint hits = 0;
try
{
Set duplicates_lookup = new HashSet ();
if (scope.sc_data_provider == null)
scope.sc_data_provider = new SoftwareCenterDataCache (TOP_RATED_ITEMS_CACHE_LIFETIME);
var whats_new = yield scope.sc_data_provider.get_items_for_category ("unity-whats-new");
var query = scope.purchase_info.create_pkgsearch_query (whats_new);
var tmpresults = scope.pkgsearcher.get_by_exact_names (query);
scope.purchase_info.from_pkgresults (tmpresults);
hits = add_sc_category_results (whats_new, result_set, Category.AVAILABLE, ref duplicates_lookup, MAX_WHATS_NEW_APPS_FOR_EMPTY_QUERY);
var top_rated = yield scope.sc_data_provider.get_items_for_category ("unity-top-rated");
query = scope.purchase_info.create_pkgsearch_query (top_rated);
tmpresults = scope.pkgsearcher.get_by_exact_names (query);
scope.purchase_info.from_pkgresults (tmpresults);
hits += add_sc_category_results (top_rated, result_set, Category.AVAILABLE, ref duplicates_lookup, MAX_TOP_RATED_APPS_FOR_EMPTY_QUERY);
}
catch (GLib.Error e)
{
warning ("Failed to get top rated apps: %s", e.message);
}
timer.stop ();
debug ("Entry search listed %u top rated/new available apps in %fms",
hits, timer.elapsed ()*1000);
}
}
/* XXX:
if (model.get_n_rows () == 0)
{
search.set_reply_hint ("no-results-hint",
_("Sorry, there are no applications that match your search."));
}
*/
}
private async void search_global ()
{
var context = this.search_context;
var result_set = context.result_set;
/*
* In global search, with a non-empty search string, we collate all
* hits under one Applications category
*/
var search_string = context.search_query;
if (Utils.is_search_empty (search_string))
{
yield update_global_without_search ();
return;
}
bool running_on_phablet = is_phablet_ui ();
var pkg_search_string = XapianUtils.prepare_pkg_search_string (search_string, null);
Set installed_uris = new HashSet ();
Set available_uris = new HashSet ();
var timer = new Timer ();
var appresults = scope.appsearcher.search (
pkg_search_string, 0,
Unity.Package.SearchType.PREFIX,
Unity.Package.Sort.BY_RELEVANCY);
resort_pkg_search_results (appresults);
add_pkg_search_result (appresults, installed_uris, available_uris,
result_set, Category.APPLICATIONS, 0,
running_on_phablet);
timer.stop ();
debug ("Global search listed %i Installed apps in %fms for query: %s",
appresults.num_hits, timer.elapsed ()*1000, pkg_search_string);
}
private async void update_global_without_search ()
{
/*
* In global search, with an empty search string, we show just Recent Apps
* Excluding apps with icons in the launcher (be they running or faves)
*/
var context = this.search_context;
var result_set = context.result_set;
Timer timer = new Timer ();
if (local_apps_active () && scope.display_recent_apps)
{
try
{
var zg_search_string = XapianUtils.prepare_zg_search_string ("",
null);
var time_range = new Zeitgeist.TimeRange.anytime ();
var results = yield scope.log.find_events (
time_range,
scope.zg_templates,
Zeitgeist.StorageState.ANY,
40,
Zeitgeist.ResultType.MOST_RECENT_SUBJECTS,
context.cancellable.get_gcancellable ());
append_events_with_category (results, result_set,
Category.RECENT_APPS, false);
timer.stop ();
debug ("Entry search found %u/%u Recently Used apps in %fms for query '%s'",
results.size (), results.estimated_matches (),
timer.elapsed()*1000, zg_search_string);
} catch (IOError.CANCELLED ioe) {
// no need to bother
return;
} catch (GLib.Error e) {
warning ("Error performing search '%s': %s",
search_context.search_query, e.message);
}
}
}
/*
* Performs secondary level sorting of the results according to popularity
* of individual desktop files.
*/
private void resort_pkg_search_results (Unity.Package.SearchResult results)
{
results.results.sort_with_data ((a, b) =>
{
/* We'll cluster the relevancies into a couple of bins, because
* there can be multiple terms adding to the relevancy (especially
* when doing one/two character prefix searches - ie a "f*" search
* will have slightly higher relevancy for item with name "Search
* _f_or _f_iles" than "_F_irefox", and that's not what we want)
*/
int rel_a = a.relevancy;
int rel_b = b.relevancy;
int delta = (rel_a - rel_b).abs ();
if (delta < 10)
{
string id_a = scope.sc_mangler.extract_desktop_id (a.desktop_file);
string id_b = scope.sc_mangler.extract_desktop_id (b.desktop_file);
rel_a = scope.popularity_map["application://" + id_a];
rel_b = scope.popularity_map["application://" + id_b];
}
return rel_b - rel_a; // we want higher relevancy first
});
}
/**
* Sanitize executable name -- make it suitable for Home Lens.
*/
private static string sanitize_binary_name (string name)
{
return GLib.Path.get_basename (name);
}
private string get_annotated_icon (Icon app_icon, string price, bool paid,
bool use_small_icon = true)
{
var annotated_icon = new AnnotatedIcon (app_icon);
annotated_icon.category = CategoryType.APPLICATION;
if (price != null && price != "")
{
if (paid)
annotated_icon.ribbon = _("Paid");
else
annotated_icon.ribbon = price;
}
else
{
annotated_icon.ribbon = _("Free");
}
if (scope.force_small_icons_for_suggestions || use_small_icon
|| app_icon.to_string () == GENERIC_APP_ICON)
{
annotated_icon.size_hint = IconSizeHint.SMALL;
}
return annotated_icon.to_string ();
}
/**
* Add all results obtained from SoftwareCenterDataProvider
*/
private uint add_sc_category_results (SoftwareCenterData.AppInfo?[] results,
Unity.ResultSet result_set,
Category category,
ref Set duplicates_lookup,
uint max_results)
{
uint i = 0;
foreach (SoftwareCenterData.AppInfo app in results)
{
string uri = @"unity-install://$(app.package_name)/$(app.application_name)";
if (uri in duplicates_lookup)
continue;
string icon_obj;
Icon app_icon = scope.find_pkg_icon (app.desktop_file, app.icon);
var pinfo = scope.purchase_info.find (
app.application_name, app.package_name);
if (pinfo != null)
{
// magazines need to use large icons
bool use_small_icon = app.desktop_file.has_suffix (".desktop");
var annotated_icon = get_annotated_icon (app_icon,
pinfo.formatted_price,
pinfo.paid,
use_small_icon);
icon_obj = annotated_icon.to_string ();
}
else
{
warning ("No purchase info for: %s, %s", app.application_name, app.package_name);
icon_obj = app_icon.to_string ();
}
var result = Unity.ScopeResult ();
result.uri = uri;
result.icon_hint = icon_obj;
result.category = category;
result.result_type = pinfo != null && pinfo.paid ?
Unity.ResultType.PERSONAL : Unity.ResultType.DEFAULT;
result.mimetype = "application/x-desktop";
result.title = app.application_name;
result.comment = "";
result.dnd_uri = "file://" + app.desktop_file;
result.metadata = new HashTable (str_hash, str_equal);
result_set.add_result (result);
duplicates_lookup.add (uri);
i++;
if (i == max_results)
break;
}
return i;
}
private void add_pkg_search_result (Unity.Package.SearchResult results,
Set installed_uris,
Set available_uris,
Unity.ResultSet result_set,
Category category,
uint max_add,
bool running_on_phablet)
{
var appmanager = AppInfoManager.get_default();
uint n_added = 0;
foreach (unowned Unity.Package.PackageInfo pkginfo in results.results)
{
if (pkginfo.desktop_file == null)
continue;
string desktop_id = scope.sc_mangler.extract_desktop_id (
pkginfo.desktop_file, category == Category.AVAILABLE);
string full_path;
AppInfo? app = appmanager.lookup (desktop_id);
full_path = appmanager.get_path (desktop_id);
if (running_on_phablet)
{
// XXX: This filtering should be pushed down to the Xapian
// index and query builder logic.
bool x_ubuntu_touch = false;
bool x_is_click = false;
if (full_path != null)
{
GLib.KeyFile key_file = new GLib.KeyFile ();
try
{
key_file.load_from_file (full_path, GLib.KeyFileFlags.NONE);
x_ubuntu_touch = key_file.get_boolean ("Desktop Entry", "X-Ubuntu-Touch");
x_is_click = key_file.has_key ("Desktop Entry", "X-Ubuntu-Application-ID");
}
catch (Error e)
{
x_ubuntu_touch = false;
}
}
// click apps are handled by unity-scope-click, so don't show them here either
if (!x_ubuntu_touch || x_is_click)
{
continue;
}
}
/* De-dupe by 'application://foo.desktop' URI. Also note that we need
* to de-dupe before we chuck out NoDisplay app infos, otherwise they'd
* show up from alternate sources */
string uri = @"application://$(desktop_id)";
if (uri in installed_uris || uri in available_uris)
continue;
/* Extract basic metadata and register de-dupe keys */
var res = Unity.ScopeResult();
res.uri = uri;
res.category = category;
res.result_type = (category != Category.AVAILABLE &&
!results.fuzzy_search) ?
Unity.ResultType.PERSONAL : Unity.ResultType.DEFAULT;
res.mimetype = "application/x-desktop";
res.dnd_uri = full_path != null ? "file://" + full_path : "";
res.metadata = new HashTable (str_hash, str_equal);
switch (category)
{
case Category.INSTALLED:
case Category.APPLICATIONS:
installed_uris.add (uri);
if (app != null)
{
res.title = app.get_display_name ();
res.comment = sanitize_binary_name (app.get_executable ());
}
else
{
res.title = pkginfo.application_name;
}
break;
case Category.AVAILABLE:
available_uris.add (uri);
res.title = pkginfo.application_name;
res.comment = "";
break;
default:
warning (@"Illegal category for package search $(category)");
continue;
}
if (res.title == null) res.title = "";
if (res.comment == null) res.comment = "";
/* We can only chuck out NoDisplay and OnlyShowIn app infos after
* we have registered a de-dupe key for them - which is done in the
* switch block above) */
if (app != null && !app.should_show ())
continue;
Icon icon = scope.find_pkg_icon (pkginfo.desktop_file, pkginfo.icon);
if (category == Category.AVAILABLE)
{
/* If we have an available item, which is not a dupe, but is
* installed anyway, we weed it out here, because it's probably
* left out from the Installed section because of some rule in the
* .menu file */
if (app != null)
continue;
/* Apps that are not installed, ie. in the Available category
* use the 'unity-install://pkgname/Full App Name' URI scheme,
* but only use that after we've de-duped the results.
* But only change the URI *after* we've de-duped the results! */
res.uri = @"unity-install://$(pkginfo.package_name)/$(pkginfo.application_name)";
available_uris.add (uri);
// magazines need to use large icons
bool use_small_icon = pkginfo.desktop_file.has_suffix (".desktop");
res.icon_hint = get_annotated_icon (icon, pkginfo.price,
!pkginfo.needs_purchase,
use_small_icon);
}
else
{
res.icon_hint = icon.to_string ();
}
result_set.add_result (res);
/* Stop if we added the number of items requested */
n_added++;
if (max_add > 0 && n_added >= max_add)
return;
}
}
/* Appends the subject URIs from a set of Zeitgeist.Events to our Dee.Model
* assuming that these events are already sorted */
public void append_events_with_category (Zeitgeist.ResultSet events,
Unity.ResultSet result_set,
uint category_id,
bool include_favorites,
int max_results = int.MAX,
Set? allowed_uris = null)
{
int num_results = 0;
foreach (var ev in events)
{
string? app_uri = null;
if (ev.num_subjects () > 0)
app_uri = ev.get_subject (0).get_uri ();
if (app_uri == null)
{
warning ("Unexpected event without subject");
continue;
}
/* Assert that we indeed have a known application as actor */
string desktop_id = Utils.get_desktop_id_for_actor (app_uri);
/* Discard Recently Used apps that are in the launcher */
if ((category_id == Category.RECENT ||
category_id == Category.RECENT_APPS) &&
!include_favorites &&
(scope.favorite_apps.has_app_id (desktop_id)
|| scope.app_watcher.has_app_id (desktop_id)))
continue;
var appmanager = AppInfoManager.get_default ();
AppInfo? app = appmanager.lookup (desktop_id);
if (app == null)
continue;
if (!app.should_show ())
continue;
/* HACK! when using the max_results together with allowed_uris,
* the limit serves as a truncation point - therefore results which
* are not displayed the first time won't be displayed later
* (consider results A, B, C - all of them are allowed and we use
* limit 2 - so only A and B is displayed, later we change allowed to
* B and C, so normally we would display both B and C, but that's not
* desired because C wasn't shown in the first place, so we display
* only B) */
if (num_results++ >= max_results) break;
if (allowed_uris != null && !(app_uri in allowed_uris)) continue;
var result = Unity.ScopeResult ();
result.uri = app_uri;
result.icon_hint = app.get_icon ().to_string ();
result.category = category_id;
result.result_type = Unity.ResultType.DEFAULT;
result.mimetype = "application/x-desktop";
result.title = app.get_display_name ();
result.comment = sanitize_binary_name (app.get_executable ());
string full_path = appmanager.get_path (desktop_id);
result.dnd_uri = full_path != null ? "file://" + full_path : app_uri;
result.metadata = new HashTable (str_hash, str_equal);
result_set.add_result (result);
}
}
}
private class ApplicationsResultPreviewer : Unity.ResultPreviewer
{
private ApplicationsScope scope;
public ApplicationsResultPreviewer (ApplicationsScope scope, Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
this.scope = scope;
set_scope_result (result);
set_search_metadata (metadata);
}
public override Unity.AbstractPreview? run ()
{
var ml = new MainLoop ();
Unity.AbstractPreview? preview = null;
run_async ((obj, p) =>
{
preview = p;
ml.quit ();
});
ml.run ();
return preview;
}
public override void run_async (Unity.AbstractPreviewCallback callback)
{
make_preview.begin ((obj, res) =>
{
var preview = make_preview.end (res);
callback (this, preview);
});
}
private async Unity.AbstractPreview? make_preview ()
{
Unity.ApplicationPreview? preview = null;
string desktopfile = null;
string pkgname = "";
string appname = "";
var uri = result.uri;
bool installed = uri.has_prefix ("application://");
if (installed)
{
desktopfile = uri.substring (14); //remove "application://" prefix
// de-mangle desktop file names back to what S-C expects
if (scope.sc_mangler.contains (desktopfile))
{
desktopfile = scope.sc_mangler.get (desktopfile);
}
var pkginfo = scope.pkgsearcher.get_by_desktop_file (desktopfile);
if (pkginfo != null)
{
appname = pkginfo.application_name;
pkgname = pkginfo.package_name;
}
}
else // unity-install
{
string app = uri.substring (16); //remove "unity-install://" prefix
string[] parts = app.split ("/");
if (parts.length > 1)
{
pkgname = parts[0];
appname = parts[1];
}
}
if (pkgname != "")
{
try {
var details = yield scope.get_app_details (appname, pkgname);
Icon? icon = null;
if (installed)
icon = new GLib.ThemedIcon (details.icon);
else
{
icon = scope.find_pkg_icon (null, details.icon);
if (icon.to_string () == GENERIC_APP_ICON && details.icon_url != null && details.icon_url != "")
{
icon = new GLib.FileIcon (File.new_for_uri (details.icon_url));
}
}
Icon? screenshot = null;
if (details.screenshot != null)
{
File scr_file = File.new_for_uri (details.screenshot);
screenshot = new FileIcon (scr_file);
}
string subtitle = "";
if (details.version != "")
subtitle = _("Version %s").printf (details.version);
if (details.size > 0)
{
if (subtitle != "")
subtitle += ", ";
subtitle += (_("Size %s")).printf (GLib.format_size (details.size));
}
preview = new Unity.ApplicationPreview (details.name, subtitle, details.description, icon, screenshot);
preview.license = details.license;
scope.init_ratings_db ();
if (scope.ratings != null)
{
Unity.Ratings.Result result;
scope.ratings.query (pkgname, out result);
preview.set_rating (result.average_rating / 5.0f, result.total_rating);
}
if (details.hardware_requirements != "")
preview.add_info (new InfoHint ("hardware-requirements", _("Hardware requirements"), null, details.hardware_requirements));
if (uri.has_prefix ("unity-install://")) // application needs to be purchased/installed
{
// uninstalled and not purchased before
if (details.pkg_state == SoftwareCenterData.PackageState.NEEDS_PURCHASE)
{
var buy_action = new Unity.PreviewAction ("buy", _("Buy"), null);
if (details.price != null && details.price != "")
{
buy_action.extra_text = details.price;
}
preview.add_action (buy_action);
}
else // uninstalled, purchased before
{
Unity.PreviewAction install_action = null;
if (details.raw_price == null || details.raw_price == "")
{
install_action = new Unity.PreviewAction ("install", _("Free Download"), null);
}
else
{
install_action = new Unity.PreviewAction ("install-paid", _("Install"), null);
}
preview.add_action (install_action);
}
if (details.website != null && details.website != "")
{
scope.preview_developer_website = details.website;
var website_action = new Unity.PreviewAction ("website", _("Developer Site"), null);
preview.add_action (website_action);
}
}
else // application is already installed
{
preview.add_info (new InfoHint ("date-installed", _("Installed on"), null, details.installation_date));
var launch_action = new Unity.PreviewAction ("launch", _("Launch"), null);
preview.add_action (launch_action);
if (!details.is_desktop_dependency)
{
var uninstall_action = new Unity.PreviewAction ("uninstall", _("Uninstall"), null);
preview.add_action (uninstall_action);
}
}
scope.preview_installable_desktop_file = details.desktop_file;
scope.preview_installable_icon_file = details.icon;
}
catch (Error e)
{
warning ("Failed to get package details for '%s': %s", uri, e.message);
preview = null;
}
}
// xapian db doesn't know this .desktop file or S-C dbus data provider fails,
// fallback to DesktopAppInfo (based on installed .desktop file) if available
if (preview == null && desktopfile != null)
{
var app_info = new DesktopAppInfo (desktopfile);
if (app_info != null)
{
preview = new Unity.ApplicationPreview (app_info.get_display_name (), "", app_info.get_description () ?? "", app_info.get_icon (), null);
var launch_action = new Unity.PreviewAction ("launch", _("Launch"), null);
preview.add_action (launch_action);
}
}
if (preview == null)
{
warning ("No pksearcher nor desktop app info for '%s'", uri);
}
return preview;
}
}
} /* namespace */
./src/software-center-data-provider.vala 0000644 0000041 0000041 00000005124 12772523363 020562 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens {
static const string SCDP_DBUS_NAME = "com.ubuntu.SoftwareCenterDataProvider";
static const string SCDP_DBUS_PATH = "/com/ubuntu/SoftwareCenterDataProvider";
[DBus (name = "com.ubuntu.SoftwareCenterDataProvider")]
public interface SoftwareCenterDataProviderService: GLib.Object
{
public abstract async HashTable get_app_details (string appname, string pkgname) throws Error;
public abstract async string[] get_available_categories () throws Error;
public abstract async string[] get_available_subcategories () throws Error;
public abstract async SoftwareCenterData.AppInfo?[] get_items_for_category (string category_name) throws Error;
}
public class SoftwareCenterDataProviderProxy: GLib.Object
{
public SoftwareCenterDataProviderProxy ()
{
Bus.watch_name (BusType.SESSION, SCDP_DBUS_NAME, BusNameWatcherFlags.NONE, null, on_sc_dbus_name_vanished);
}
private async void connect_to () throws Error
{
_service = yield Bus.get_proxy (BusType.SESSION, SCDP_DBUS_NAME, SCDP_DBUS_PATH);
}
private void on_sc_dbus_name_vanished (DBusConnection conn, string name)
{
_service = null;
}
public async SoftwareCenterData.AppDetailsData get_app_details (string appname, string pkgname) throws Error
{
if (_service == null)
yield connect_to ();
HashTable data = yield _service.get_app_details (appname, pkgname);
var details = new SoftwareCenterData.AppDetailsData (data);
return details;
}
public virtual async SoftwareCenterData.AppInfo?[] get_items_for_category (string category_name) throws Error
{
if (_service == null)
yield connect_to ();
SoftwareCenterData.AppInfo?[] data = yield _service.get_items_for_category (category_name);
return data;
}
private SoftwareCenterDataProviderService _service;
}
}
./src/unity-ratings-db.c 0000644 0000041 0000041 00000013027 12772523363 015413 0 ustar www-data www-data /*
* Copyright (C) 2011 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
#include "unity-ratings-db.h"
#include
#include
/* Hacky check, but we *really* need to have the same libdb version as the
* software-center is using to avoid a cascade of fail */
#if DB_VERSION_MAJOR != 5 || DB_VERSION_MINOR != 3
#error "unity-lens-applications only compiles and works against libdb-5.3. Please install the package libdb5.3-dev"
#endif
struct _UnityRatingsDatabase {
DB_ENV *env;
DB *db;
};
/* IMPLEMENTATION NOTE: It is paramount that we create our BDB environment
* in "concurrent" mode. This makes the database
* single-writer-multiple-reader safe. Hence allowing
* us to read the DB while S-C is updating it.
*/
#define UNITY_RATINGS_DB_PATH "software-center/reviews.ubuntu.com_reviews_api_1.0_review-stats-pkgnames.p__5.3.db"
#define UNITY_RATINGS_DB_ENV_PATH UNITY_RATINGS_DB_PATH".dbenv"
UnityRatingsDatabase*
unity_ratings_database_new (GError **error)
{
UnityRatingsDatabase *self;
DB_ENV *env;
DB *db;
int error_code;
gchar *path;
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
/* Create a database environment in concurrent mode,
* enabling single-writer-multiple-reader support */
path = g_build_filename (g_get_user_cache_dir (),
UNITY_RATINGS_DB_ENV_PATH,
NULL);
db_env_create (&env, 0);
error_code = env->open (env,
path, /* db env home dir */
DB_INIT_CDB | DB_INIT_MPOOL, /* use concurrent mode */
0600 /* access mode (user-rw only) */);
if (error_code)
{
g_set_error (error, G_FILE_ERROR, error_code,
"Unable to open ratings database environment '%s': %s",
path, db_strerror (error_code)); // FIXME: Leak db_strerror() return?
env->close (env, 0);
g_free (path);
return NULL;
}
g_free (path);
/* Create a db handle in our environment */
path = g_build_filename (g_get_user_cache_dir (),
UNITY_RATINGS_DB_PATH,
NULL);
db_create (&db, env, 0);
error_code = db->open (db,
NULL, /* transaction context */
path, /* file name */
NULL, /* db name */
DB_HASH, /* db type */
DB_RDONLY, /* flags - read-only */
0600 /* access mode (user-rw only) */);
if (error_code)
{
g_set_error (error, G_FILE_ERROR, error_code,
"Unable to open ratings database '%s': %s",
path, db_strerror (error_code)); // FIXME: Leak db_strerror() return?
g_free (path);
db->close (db, 0);
env->close (env, 0);
return NULL;
}
g_free (path);
self = g_new0 (UnityRatingsDatabase, 1);
self->env = env;
self->db = db;
return self;
}
void
unity_ratings_database_free (UnityRatingsDatabase *self)
{
g_return_if_fail (self != NULL);
self->db->close (self->db, 0);
self->env->close (self->env, 0);
g_free (self);
}
gboolean
unity_ratings_database_query (UnityRatingsDatabase *self,
const gchar *pkgname,
UnityRatingsResult *out_result)
{
DBT key = { 0 }, data = { 0 };
gint error_code;
g_return_val_if_fail (self != NULL, FALSE);
g_return_val_if_fail (pkgname != NULL, FALSE);
g_return_val_if_fail (out_result != NULL, FALSE);
/* Make sure the DBTs are zeroed. Otherwise libdb throws a fit */
key.data = (gchar*)pkgname;
key.size = strlen (pkgname);
key.ulen = key.size;
key.dlen = 0;
key.doff = 0;
key.flags = DB_DBT_USERMEM;
data.data = out_result;
data.size = 0;
data.ulen = sizeof (UnityRatingsResult);
data.dlen = 0;
data.doff = 0;
data.flags= DB_DBT_USERMEM;
error_code = self->db->get (self->db,
NULL,
&key,
&data,
0);
/* error_code == 0 means success, everything else is bad */
if (error_code == DB_NOTFOUND)
{
goto not_found;
}
else if (error_code)
{
g_warning ("Error looking up ratings for '%s': %s",
pkgname, db_strerror (error_code)); // FIXME : leak strerror?
goto not_found;
}
if (data.size != 3*sizeof (gint32))
{
g_critical ("Unexpected datum size from ratings database %i bytes. "
"Expected %lu bytes", data.size, 3*sizeof (gint32));
goto not_found;
}
return TRUE;
not_found:
out_result->average_rating = 0;
out_result->total_rating = 0;
out_result->dampened_rating = 0;
return FALSE;
}
./src/xapian-utils.vala 0000644 0000041 0000041 00000011114 12772523363 015325 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
*/
namespace Unity.ApplicationsLens.XapianUtils
{
private static const string[] option_types =
{
"accessories",
"education",
"game",
"graphics",
"internet",
"fonts",
"office",
"media",
"customization",
"accessibility",
"developer",
"science-and-engineering",
"scopes",
"system"
};
/* For each section we have a set filtering query we use to restrict
* Xapian queries to that type */
internal static HashTable type_queries;
/* Pre-populates the type queries so it's easier/faster to build our search */
internal static void populate_type_queries ()
{
if (type_queries == null)
{
type_queries = new HashTable (str_hash, str_equal);
type_queries.insert ("all", "NOT category:XYZ");
type_queries.insert ("accessories", "(category:Utility AND NOT category:Accessibility)");
type_queries.insert ("education", "(category:Education AND NOT category:Science)");
type_queries.insert ("game", "category:Game");
type_queries.insert ("graphics", "category:Graphics");
type_queries.insert ("internet", "category:Network");
type_queries.insert ("fonts", "category:Fonts"); // FIXME: wtf?
type_queries.insert ("office", "category:Office");
type_queries.insert ("media", "category:AudioVideo");
type_queries.insert ("customization", "category:Settings");
type_queries.insert ("accessibility", "(category:Accessibility AND NOT category:Settings)");
type_queries.insert ("developer", "category:Development"); // FIXME emacs.desktop should be added
type_queries.insert ("science-and-engineering", "(category:Science OR category:Engineering)");
type_queries.insert ("scopes", "(pkg_wildcard:unity_scope_* OR pkg_wildcard:unity_lens_*)");
type_queries.insert ("system", "(category:System OR category:Security)");
}
}
public static string extract_type_query (OptionsFilter? options)
{
if (options == null || !options.filtering) return "NOT category:XYZ";
populate_type_queries ();
string? result = null;
foreach (unowned string type_id in option_types)
{
var option = options.get_option (type_id);
if (option == null) continue;
if (!option.active) continue;
if (result == null) result = type_queries[type_id];
else result += " OR " + type_queries[type_id];
}
return result == null ? "NOT category:XYZ" : "(%s)".printf (result);
}
public string prepare_zg_search_string (string search_string,
OptionsFilter? options)
{
string s = search_string.strip ();
if (!s.has_suffix ("*") && s != "")
s = s + "*";
if (s != "")
s = @"app:($s)";
else
return extract_type_query (options);
if (options == null || !options.filtering)
return s;
else
return s + " AND " + extract_type_query (options);
}
public static string prepare_pkg_search_string (string? search_string,
OptionsFilter? options)
{
if (Utils.is_search_empty (search_string))
{
if (options == null || !options.filtering)
return "(type:Application OR type:Scope)";
else
return "(type:Application OR type:Scope) AND " + extract_type_query (options);
}
else
{
var s = search_string;
s = s.strip ();
/* The Xapian query parser seems to handle hyphens in a special way,
* namely that it forces the joined tokens into a phrase query
* no matter if it appears as the last word in a query and we have
* the PARTIAL flag set on the query parser. This makes 'd-f' not
* match 'd-feet' etc. */
s = s.delimit ("-", ' ');
if (options == null || !options.filtering)
return "(type:Application OR type:Scope) AND " + s;
else
return "(type:Application OR type:Scope) AND %s AND %s".printf (extract_type_query (options), s);
}
}
}
./src/config.vala.in 0000644 0000041 0000041 00000000502 12772523363 014560 0 ustar www-data www-data namespace Config {
const string PREFIX = "@prefix@";
const string DATADIR = "@DATADIR@";
const string PKGDATADIR = "@DATADIR@/unity";
const string BINDIR = "@prefix@/bin";
const string LOCALEDIR = "@DATADIR@/locale";
const string PACKAGE = "@PACKAGE@";
const string VERSION = "@VERSION@";
}
./src/scopes-scope.vala 0000644 0000041 0000041 00000041700 12772523363 015316 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by James Henstridge
*
*/
namespace Unity.ApplicationsLens {
const string GENERIC_SCOPE_ICON = ICON_PATH + "service-generic.svg";
const string[] invisible_scope_ids =
{
"home.scope",
"applications-scopes.scope",
};
private class ScopesScope : Unity.AbstractScope
{
public ApplicationsScope appscope;
public Unity.Package.Searcher? searcher;
public HashTable disabled_scope_ids;
public Dee.Model remote_scopes_model;
public Dee.Index scopes_index;
public Dee.Analyzer analyzer;
public HashTable locked_scope_ids;
public ScopesScope (ApplicationsScope appscope)
{
this.appscope = appscope;
// Track the remote scopes
var shared_model = new Dee.SharedModel ("com.canonical.Unity.SmartScopes.RemoteScopesModel");
shared_model.set_schema ("s", "s", "s", "s", "s", "as");
shared_model.end_transaction.connect (this.remote_scopes_changed);
remote_scopes_model = shared_model;
scopes_index = Utils.prepare_index (remote_scopes_model,
RemoteScopesColumn.NAME,
(model, iter) =>
{
unowned string name = model.get_string (iter, RemoteScopesColumn.NAME);
return "%s\n%s".printf (_("scope"), name);
}, out analyzer);
disabled_scope_ids = new HashTable (str_hash, str_equal);
update_disabled_scopes_hash ();
var pref_man = PreferencesManager.get_default ();
pref_man.notify["disabled-scopes"].connect (update_disabled_scopes_hash);
locked_scope_ids = new HashTable (str_hash, str_equal);
var settings = new Settings (LIBUNITY_SCHEMA);
foreach (unowned string scope_id in settings.get_strv ("locked-scopes"))
{
locked_scope_ids[scope_id] = true;
}
build_scope_index.begin ();
}
private void remote_scopes_changed (uint64 begin_seqnum, uint64 end_seqnum)
{
this.results_invalidated (SearchType.DEFAULT);
}
private void update_disabled_scopes_hash ()
{
disabled_scope_ids.remove_all ();
var pref_man = PreferencesManager.get_default ();
foreach (unowned string scope_id in pref_man.disabled_scopes)
{
// using HashTable as a set (optimized in glib when done like this)
disabled_scope_ids[scope_id] = scope_id;
}
}
private void disable_scope (string scope_id)
{
if (scope_id in disabled_scope_ids) return;
var pref_man = PreferencesManager.get_default ();
var disabled_scopes = pref_man.disabled_scopes;
disabled_scopes += scope_id;
var settings = new Settings (LIBUNITY_SCHEMA);
settings.set_strv ("disabled-scopes", disabled_scopes);
}
private void enable_scope (string scope_id)
{
if (!(scope_id in disabled_scope_ids)) return;
var pref_man = PreferencesManager.get_default ();
string[] disabled_scopes = {};
foreach (unowned string disabled_scope_id in pref_man.disabled_scopes)
{
if (disabled_scope_id != scope_id)
disabled_scopes += disabled_scope_id;
}
var settings = new Settings (LIBUNITY_SCHEMA);
settings.set_strv ("disabled-scopes", disabled_scopes);
}
private async void build_scope_index ()
{
try
{
var scope_registry = yield Unity.Protocol.ScopeRegistry.find_scopes (
Config.PKGDATADIR + "/scopes");
searcher = new Unity.Package.Searcher.for_scopes (scope_registry);
}
catch (Error err)
{
warning ("Unable to find scopes: %s", err.message);
}
}
public override string get_group_name ()
{
return "com.canonical.Unity.Scope.Applications";
}
public override string get_unique_name ()
{
return "/com/canonical/unity/scope/scopes";
}
public override Unity.FilterSet get_filters ()
{
var filters = new Unity.FilterSet ();
/* Type filter */
{
var filter = new CheckOptionFilter ("type", _("Type"));
filter.sort_type = Unity.OptionsFilter.SortType.DISPLAY_NAME;
filter.add_option ("accessories", _("Accessories"));
filter.add_option ("education", _("Education"));
filter.add_option ("game", _("Games"));
filter.add_option ("graphics", _("Graphics"));
filter.add_option ("internet", _("Internet"));
filter.add_option ("fonts", _("Fonts"));
filter.add_option ("office", _("Office"));
filter.add_option ("media", _("Media"));
filter.add_option ("customization", _("Customization"));
filter.add_option ("accessibility", _("Accessibility"));
filter.add_option ("developer", _("Developer"));
filter.add_option ("science-and-engineering", _("Science & engineering"));
filter.add_option ("scopes", _("Dash plugins"));
filter.add_option ("system", _("System"));
filters.add (filter);
}
return filters;
}
public override Unity.CategorySet get_categories ()
{
Unity.CategorySet categories = new Unity.CategorySet ();
File icon_dir = File.new_for_path (ICON_PATH);
var cat = new Unity.Category ("scopes", _("Dash plugins"),
new FileIcon (icon_dir.get_child ("group-installed.svg")));
categories.add (cat);
return categories;
}
public override Unity.Schema get_schema ()
{
var schema = new Unity.Schema ();
schema.add_field ("scope_disabled", "u", Schema.FieldType.OPTIONAL);
return schema;
}
public override string normalize_search_query (string search_query)
{
return search_query.strip ();
}
public override Unity.ScopeSearchBase create_search_for_query (Unity.SearchContext search_context)
{
return new ScopesSearch (this, search_context);
}
public override Unity.ResultPreviewer create_previewer (Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
return new ScopesResultPreviewer (this, result, metadata);
}
public override Unity.ActivationResponse? activate (Unity.ScopeResult result, Unity.SearchMetadata metadata, string? action_id)
{
// uris are "scope://scope_id.scope"
var scope_id = result.uri.substring (8);
if (action_id == "enable-scope")
{
enable_scope (scope_id);
}
else if (action_id == "disable-scope")
{
disable_scope (scope_id);
}
/* Make a preview */
var preview = create_previewer (result, metadata).run ();
if (preview is Unity.Preview)
{
return new Unity.ActivationResponse.with_preview (preview as Unity.Preview);
}
else
{
warning ("Failed to generate preview for %s", result.uri);
return new Unity.ActivationResponse (Unity.HandledType.NOT_HANDLED);
}
}
public static Icon? get_default_icon ()
{
try
{
return Icon.new_for_string (GENERIC_SCOPE_ICON);
}
catch (Error err)
{
warning ("%s", err.message);
}
return null;
}
}
private class ScopesSearch : Unity.ScopeSearchBase
{
private ScopesScope scope;
public ScopesSearch (ScopesScope scope, Unity.SearchContext search_context)
{
this.scope = scope;
this.search_context = search_context;
}
public override void run ()
{
if (this.scope.searcher == null)
return;
var context = this.search_context;
// Don't add results to global searches
if (context.search_type == SearchType.GLOBAL)
return;
var filter = context.filter_state.get_filter_by_id ("type") as OptionsFilter;
if (filter != null && filter.filtering &&
!filter.get_option ("scopes").active)
return;
add_local_results (context.search_query, context.result_set);
add_remote_results (context.search_query, context.result_set);
}
public override void run_async (ScopeSearchBaseCallback callback)
{
// just run the matching in the origin thread, it's cheap
run ();
callback (this);
}
private string get_scope_icon (string icon_hint, bool is_disabled)
{
try
{
Icon base_icon = icon_hint == null || icon_hint == "" ?
ScopesScope.get_default_icon () : Icon.new_for_string (icon_hint);
var anno_icon = new AnnotatedIcon (base_icon);
anno_icon.size_hint = IconSizeHint.SMALL;
// dim disabled icons by decreasing their alpha
if (is_disabled)
anno_icon.set_colorize_rgba (1.0, 1.0, 1.0, 0.5);
return anno_icon.to_string ();
}
catch (Error err)
{
return "";
}
}
private void add_local_results (string search_query, Unity.ResultSet result_set)
{
bool has_search = !Utils.is_search_empty (search_query);
var pkg_search_string = XapianUtils.prepare_pkg_search_string (
search_query, null);
var search_result = this.scope.searcher.search (
pkg_search_string, 0, Unity.Package.SearchType.PREFIX,
has_search ?
Unity.Package.Sort.BY_RELEVANCY : Unity.Package.Sort.BY_NAME);
foreach (unowned Unity.Package.PackageInfo info in search_result.results)
{
/* Don't include master scopes in the search results. This is
* performed after deduping so the master scopes don't just
* move to the "available" category. */
if (info.is_master_scope)
continue;
if (info.desktop_file in invisible_scope_ids)
continue;
bool is_disabled = info.desktop_file in scope.disabled_scope_ids;
var result = Unity.ScopeResult ();
result.uri = @"scope://$(info.desktop_file)";
result.category = 0;
result.icon_hint = get_scope_icon (info.icon, is_disabled);
result.result_type = Unity.ResultType.DEFAULT;
result.mimetype = "application/x-unity-scope";
result.title = info.application_name;
if (result.title == null)
result.title = "";
result.comment = "";
result.dnd_uri = "";
result.metadata = new HashTable (str_hash, str_equal);
result.metadata["scope_disabled"] = new Variant.uint32 (is_disabled ? 1 : 0);
result_set.add_result (result);
}
}
private void add_remote_results (string search_query, Unity.ResultSet result_set)
{
var results = Utils.search_index (
scope.scopes_index, scope.analyzer, search_query);
foreach (var iter in results)
{
unowned string scope_id =
scope.remote_scopes_model.get_string (iter, RemoteScopesColumn.SCOPE_ID);
unowned string icon_hint =
scope.remote_scopes_model.get_string (iter, RemoteScopesColumn.ICON_HINT);
bool is_disabled = scope_id in scope.disabled_scope_ids;
var result = Unity.ScopeResult ();
result.uri = @"scope://$(scope_id)";
result.category = 0;
result.icon_hint = get_scope_icon (icon_hint, is_disabled);
result.result_type = Unity.ResultType.DEFAULT;
result.mimetype = "application/x-unity-scope";
result.title =
scope.remote_scopes_model.get_string (iter, RemoteScopesColumn.NAME);
result.comment = "";
result.dnd_uri = "";
result.metadata = new HashTable (str_hash, str_equal);
result.metadata["scope_disabled"] = new Variant.uint32 (is_disabled ? 1 : 0);
result_set.add_result (result);
}
}
}
private class ScopesResultPreviewer : Unity.ResultPreviewer
{
private ScopesScope scope;
public ScopesResultPreviewer (ScopesScope scope, Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
this.scope = scope;
set_scope_result (result);
set_search_metadata (metadata);
}
public override Unity.AbstractPreview? run ()
{
var ml = new MainLoop ();
Unity.AbstractPreview? preview = null;
run_async ((obj, p) =>
{
preview = p;
ml.quit ();
});
ml.run ();
return preview;
}
public override void run_async (Unity.AbstractPreviewCallback callback)
{
make_preview.begin ((obj, res) =>
{
var preview = make_preview.end (res);
callback (this, preview);
});
}
private async Unity.AbstractPreview? make_preview ()
{
Unity.ApplicationPreview? preview = null;
// uris are "scope://scope_id.scope"
var scope_id = result.uri.substring (8);
bool scope_disabled = scope_id in scope.disabled_scope_ids;
// figure out if the scope is remote
bool is_remote_scope = false;
var info = scope.searcher.get_by_desktop_file (scope_id);
Dee.ModelIter found_iter = null;
if (info == null)
{
var iter = scope.remote_scopes_model.get_first_iter ();
var end_iter = scope.remote_scopes_model.get_last_iter ();
while (iter != end_iter)
{
if (scope.remote_scopes_model.get_string (iter, 0) == scope_id)
{
is_remote_scope = true;
found_iter = iter;
break;
}
iter = scope.remote_scopes_model.next (iter);
}
}
if (is_remote_scope)
{
var name = scope.remote_scopes_model.get_string (found_iter, 1);
if (name == null || name == "")
name = scope.remote_scopes_model.get_string (found_iter, 0);
var description = scope.remote_scopes_model.get_string (found_iter, 2);
if (description != null)
description = Markup.escape_text(description);
Icon? icon = null;
Icon? screenshot = null;
var icon_hint = scope.remote_scopes_model.get_string (found_iter, 3);
var screenshot_url = scope.remote_scopes_model.get_string (found_iter, 4);
try
{
if (icon_hint != "") icon = Icon.new_for_string (icon_hint);
if (screenshot_url != "") screenshot = Icon.new_for_string (screenshot_url);
}
catch (Error err)
{
warning ("%s", err.message);
}
if (icon == null) icon = ScopesScope.get_default_icon ();
preview = new Unity.ApplicationPreview (name,
"",
description,
icon,
screenshot);
}
else if (info != null)
{
var name = info.application_name;
if (name == null || name == "")
name = info.desktop_file;
var subtitle = "";
var description = info.description;
if (description != null)
description = Markup.escape_text(description);
Icon? icon = null;
Icon? screenshot = null;
try
{
if (info.icon != null && info.icon != "")
icon = Icon.new_for_string (info.icon);
}
catch (Error err)
{
warning ("%s", err.message);
}
if (icon == null)
icon = ScopesScope.get_default_icon ();
string version, screenshot_uri;
if (yield scope.appscope.get_version_and_screenshot (
scope_id, out version, out screenshot_uri))
{
if (version != "")
subtitle = _("Version %s").printf (version);
if (screenshot_uri != null)
{
File scr_file = File.new_for_uri (screenshot_uri);
screenshot = new FileIcon (scr_file);
}
}
preview = new Unity.ApplicationPreview (name,
subtitle,
description,
icon,
screenshot);
}
if (preview != null && !(scope_id in invisible_scope_ids)
&& !(scope_id in scope.locked_scope_ids))
{
PreviewAction action;
preview.set_rating(-1.0f, 0);
if (scope_disabled)
{
action = new Unity.PreviewAction ("enable-scope", _("Enable"), null);
}
else
{
action = new Unity.PreviewAction ("disable-scope", _("Disable"), null);
}
preview.add_action (action);
}
return preview;
}
}
}
./src/commands-scope.vala 0000644 0000041 0000041 00000037351 12772523363 015632 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2011-2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Didier Roche
*
*/
using Dee;
using Gee;
namespace Unity.ApplicationsLens {
public static const string UNITY_RUNNER_PREFIX = "x-unity-no-preview:";
private class AboutEntry {
public string name;
public string exec;
public Icon icon;
public AboutEntry (string name, string exec, Icon icon)
{
this.name = name;
this.exec = exec;
this.icon = icon;
}
}
private class CommandsScope : Unity.AbstractScope
{
// The ApplicationsScope holds a reference to us, so avoid a
// reference cycle.
public unowned ApplicationsScope appscope;
/* for now, load the same keys as gnome-panel */
private const string HISTORY_KEY = "history";
private const int MAX_HISTORY = 10;
public Gee.HashMap about_entries;
public Gee.List history;
public ExecSearcher exec_searcher = new ExecSearcher ();
private Settings gp_settings;
public CommandsScope (ApplicationsScope appscope)
{
this.appscope = appscope;
/* create the private about entries */
about_entries = new Gee.HashMap ();
load_about_entries ();
this.gp_settings = new Settings ("com.canonical.Unity.Runner");
history = new Gee.ArrayList ();
load_history ();
}
public void add_history (string last_command)
{
// new history list: better, greatest, latest!
var new_history = new Gee.ArrayList ();
var history_store = new string [this.history.size + 1];
int i = 1;
new_history.add (last_command);
history_store[0] = last_command;
for (var j = 0; (j < this.history.size) && (i < MAX_HISTORY); j++)
{
if (this.history[j] == last_command)
continue;
new_history.add(history[j]);
history_store[i] = history[j];
i++;
}
this.history = new_history;
// store in gsettings
this.gp_settings.set_strv (HISTORY_KEY, history_store);
// force a search to refresh history order (TODO: be more clever in the future)
results_invalidated (SearchType.DEFAULT);
}
private void load_history ()
{
int i = 0;
string[] history_store = this.gp_settings.get_strv (HISTORY_KEY);
foreach (var command in history_store)
{
if (i >= MAX_HISTORY)
break;
this.history.add((string) command.data);
i++;
}
}
private void load_about_entries ()
{
AboutEntry entry;
string name;
string exec;
Icon icon;
// first about:config
name = "about:config";
exec = "ccsm -p unityshell";
try {
icon = Icon.new_for_string (@"$(Config.PREFIX)/share/ccsm/icons/hicolor/64x64/apps/plugin-unityshell.png");
}
catch (Error err) {
warning ("Can't find unityshell icon: %s", err.message);
icon = new ThemedIcon ("gtk-execute");
}
entry = new AboutEntry (name, exec, icon);
about_entries[name] = entry;
about_entries[exec] = entry;
// second about:robots
name = "Robots have a plan.";
exec = "firefox about:robots";
entry = new AboutEntry (name, exec, icon = new ThemedIcon ("battery"));
about_entries["about:robots"] = entry;
about_entries[exec] = entry;
}
public override string get_group_name ()
{
return "com.canonical.Unity.Scope.Applications";
}
public override string get_unique_name ()
{
return "/com/canonical/unity/scope/commands";
}
public override Unity.CategorySet get_categories ()
{
var categories = new Unity.CategorySet ();
var icon_dir = File.new_for_path (ICON_PATH);
var cat = new Unity.Category ("results", _("Results"),
new FileIcon (icon_dir.get_child ("group-installed.svg")));
categories.add (cat);
cat = new Unity.Category ("history", _("History"),
new FileIcon (icon_dir.get_child ("group-available.svg")));
categories.add (cat);
return categories;
}
public override Unity.FilterSet get_filters ()
{
var filters = new Unity.FilterSet ();
return filters;
}
public override Unity.Schema get_schema ()
{
var schema = new Unity.Schema ();
return schema;
}
public override string get_search_hint ()
{
return _("Run a command");
}
public override string normalize_search_query (string search_query)
{
return search_query.strip();
}
public override Unity.ScopeSearchBase create_search_for_query (Unity.SearchContext search_context)
{
return new CommandsSearch (this, search_context);
}
public override Unity.ResultPreviewer create_previewer (Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
return null;
}
public override Unity.ActivationResponse? activate (Unity.ScopeResult result, Unity.SearchMetadata metadata, string? action_id)
{
return appscope.activate (result, metadata, action_id);
}
}
private class CommandsSearch : Unity.ScopeSearchBase
{
private CommandsScope scope;
public CommandsSearch (CommandsScope scope, Unity.SearchContext search_context)
{
this.scope = scope;
set_search_context (search_context);
}
public override void run ()
{
var ml = new MainLoop ();
run_async (() => { ml.quit (); });
ml.run ();
}
public override void run_async (Unity.ScopeSearchBaseCallback async_callback)
{
update_search.begin (() =>
{
async_callback (this);
});
}
private void add_result (Unity.ResultSet result_set, string uri,
string icon_hint, uint category_id,
string mimetype, string title)
{
var result = Unity.ScopeResult ();
result.uri = uri;
result.icon_hint = icon_hint;
result.category = category_id;
result.result_type = ResultType.DEFAULT;
result.mimetype = mimetype;
result.title = title;
result.comment = "";
result.dnd_uri = uri;
result.metadata = new HashTable (str_hash, str_equal);
result_set.add_result (result);
}
private async void update_search ()
{
var context = this.search_context;
var result_set = context.result_set;
var executables_match = new Gee.ArrayList ();
var dirs_match = new Gee.ArrayList ();
var search_string = context.search_query;
bool has_search = !Utils.is_search_empty (search_string);
string uri;
Icon icon;
string mimetype;
string display_name;
var category_id = RunnerCategory.HISTORY;
foreach (var command in scope.history)
{
display_name = get_icon_uri_and_mimetype (command, out icon, out uri, out mimetype);
add_result (result_set, uri, icon.to_string (), category_id, mimetype,
display_name);
}
if (!has_search)
{
return;
}
Timer timer = new Timer ();
/* no easter egg in unity */
if (search_string == "free the fish")
{
uri = "about:blank";
string commenteaster = _("There is no easter egg in Unity");
icon = new ThemedIcon ("gnome-panel-fish");
add_result (result_set, uri, icon.to_string (), 0, "text/plain",
commenteaster);
return;
}
else if (search_string == "gegls from outer space")
{
uri = "about:blank";
string commentnoeaster = _("Still no easter egg in Unity");
icon = new ThemedIcon ("gnome-panel-fish");
add_result (result_set, uri, icon.to_string (), 0, "text/plain",
commentnoeaster);
return;
}
/* manual seek with directory and executables result */
if (search_string.has_prefix ("/") || search_string.has_prefix ("~"))
{
search_string = Utils.subst_tilde (search_string);
var search_dirname = Path.get_dirname (search_string);
var directory = File.new_for_path (search_dirname);
var search_dirname_in_path = false;
/* strip path_directory if in executable in path */
foreach (var path_directory in Environment.get_variable ("PATH").split(":"))
{
if (search_dirname == path_directory || search_dirname == path_directory + "/")
{
search_dirname_in_path = true;
break;
}
}
try {
var iterator = directory.enumerate_children (FileAttribute.STANDARD_NAME + "," + FileAttribute.STANDARD_TYPE + "," + FileAttribute.ACCESS_CAN_EXECUTE,
0, null);
while (true)
{
var subelem_info = iterator.next_file ();
if (subelem_info == null)
break;
var complete_path = Path.build_filename (search_dirname, subelem_info.get_name ());
if (complete_path.has_prefix (search_string))
{
if (subelem_info.get_file_type () == FileType.DIRECTORY)
{
dirs_match.add (complete_path);
}
else if (subelem_info.get_attribute_boolean (FileAttribute.ACCESS_CAN_EXECUTE))
{
// only include exec name if we are in the PATH
if (search_dirname_in_path)
executables_match.add (subelem_info.get_name ());
else
executables_match.add (complete_path);
}
}
}
}
catch (Error err) {
warning("Error listing directory executables: %s\n", err.message);
}
}
/* complete again system executables */
else
{
var matching_executables = yield scope.exec_searcher.find_prefixed (search_string);
foreach (var matching_exec in matching_executables)
{
executables_match.add (matching_exec);
}
}
executables_match.sort ();
dirs_match.sort ();
category_id = RunnerCategory.RESULTS;
// populate results
// 1. enable launching the exact search string if no other result
if ((executables_match.size == 0) && (dirs_match.size == 0))
{
display_name = get_icon_uri_and_mimetype (search_string, out icon, out uri, out mimetype);
add_result (result_set, uri.strip (), icon.to_string (),
category_id, mimetype, display_name);
}
// 2. add possible directories (we don't store them)
mimetype = "inode/directory";
icon = ContentType.get_icon (mimetype);
foreach (var dir in dirs_match)
{
uri = UNITY_RUNNER_PREFIX + dir;
add_result (result_set, uri, icon.to_string (),
category_id, mimetype, dir);
}
// 3. add available exec
foreach (var final_exec in executables_match)
{
// TODO: try to match to a desktop file for the icon
uri = UNITY_RUNNER_PREFIX + final_exec;
display_name = get_icon_uri_and_mimetype (final_exec, out icon, out uri, out mimetype);
add_result (result_set, uri, icon.to_string (),
category_id, mimetype, display_name);
}
timer.stop ();
debug ("Entry search listed %i dir matches and %i exec matches in %fms for search: %s",
dirs_match.size, executables_match.size, timer.elapsed ()*1000, search_string);
}
private string get_icon_uri_and_mimetype (string exec_string, out Icon? icon, out string? uri, out string? mimetype)
{
AboutEntry? entry = null;
mimetype = "application/x-unity-run";
entry = scope.about_entries[exec_string];
if (entry != null)
{
uri = UNITY_RUNNER_PREFIX + entry.exec;
icon = entry.icon;
return entry.name;
}
uri = UNITY_RUNNER_PREFIX + exec_string;
// if it's a folder, show… a folder icone! + right exec
if (FileUtils.test (exec_string, FileTest.IS_DIR))
{
mimetype = "inode/directory";
icon = ContentType.get_icon (mimetype);
return exec_string;
}
var s = exec_string.delimit ("-", '_').split (" ", 0)[0];
var appresults = scope.appscope.appsearcher.search (
@"type:Application AND exec:$s", 0,
Unity.Package.SearchType.EXACT,
Unity.Package.Sort.BY_NAME);
foreach (unowned Unity.Package.PackageInfo pkginfo in appresults.results)
{
if (pkginfo.desktop_file == null)
continue;
// pick the first one
icon = scope.appscope.find_pkg_icon (pkginfo.desktop_file, pkginfo.icon);
return exec_string;
}
// if no result, default icon
icon = new ThemedIcon ("gtk-execute");
return exec_string;
}
}
private class ExecSearcher: Object
{
public ExecSearcher ()
{
Object ();
}
private Gee.List executables;
construct
{
executables = new Gee.ArrayList ();
listing_status = ListingStatus.NOT_STARTED;
}
// TODO: add reload
private async void find_system_executables ()
{
if (this.executables.size > 0)
return;
foreach (var path_directory in Environment.get_variable ("PATH").split(":"))
{
var dir = File.new_for_path (path_directory);
try {
var e = yield dir.enumerate_children_async (FileAttribute.STANDARD_NAME + "," + FileAttribute.ACCESS_CAN_EXECUTE,
0, Priority.DEFAULT, null);
while (true) {
var files = yield e.next_files_async (64, Priority.DEFAULT, null);
if (files == null)
break;
foreach (var info in files) {
if (info.get_attribute_boolean (FileAttribute.ACCESS_CAN_EXECUTE))
{
this.executables.add (info.get_name ());
}
}
}
}
catch (Error err) {
warning("Error listing directory executables: %s\n", err.message);
}
}
}
private enum ListingStatus
{
NOT_STARTED,
STARTED,
FINISHED
}
public int listing_status { get; private set; }
public async Gee.Collection find_prefixed (string search_string)
{
// initialize the available binaries lazily
if (listing_status == ListingStatus.NOT_STARTED)
{
listing_status = ListingStatus.STARTED;
yield find_system_executables ();
listing_status = ListingStatus.FINISHED;
}
else if (listing_status == ListingStatus.STARTED)
{
var sig_id = this.notify["listing-status"].connect (() =>
{
if (listing_status == ListingStatus.FINISHED)
find_prefixed.callback ();
});
yield;
SignalHandler.disconnect (this, sig_id);
}
var matching = new Gee.ArrayList ();
foreach (var exec_candidate in executables)
{
if (exec_candidate.has_prefix (search_string))
{
matching.add (exec_candidate);
}
}
return matching;
}
}
}
./src/schemas.vala 0000644 0000041 0000041 00000002221 12772523363 014331 0 ustar www-data www-data /*
* Copyright (C) 2010 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
namespace Unity.ApplicationsLens {
public enum ResultsColumn
{
URI = 0,
ICON_HINT,
GROUP_ID,
MIMETYPE,
DISPLAY_NAME,
COMMENT
}
public enum Category
{
APPLICATIONS,
RECENT,
RECENT_APPS,
INSTALLED,
AVAILABLE,
}
public enum RemoteScopesColumn
{
SCOPE_ID,
NAME,
DESCRIPTION,
ICON_HINT,
SCREENSHOT_URL,
KEYWORDS
}
public enum RunnerCategory
{
RESULTS,
HISTORY
}
}
./src/software-center-app-details.vala 0000644 0000041 0000041 00000006750 12772523363 020232 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens.SoftwareCenterData
{
public enum PackageState
{
UNINSTALLED,
INSTALLED,
NEEDS_PURCHASE,
UNKNOWN
}
public struct AppInfo
{
string application_name;
string package_name;
string icon;
string desktop_file;
}
public class AppDetailsData
{
public string name { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string version { get; set; }
public string screenshot { get; set; }
public string desktop_file { get; set; }
public string license { get; set; }
public string icon { get; set; }
public string icon_url { get; set; }
public string price { get; set; }
public string raw_price { get; set; }
public PackageState pkg_state { get; set; }
public string installation_date { get; set; }
public string website { get; set; }
public int64 size { get; set; }
public string hardware_requirements { get; set; }
public bool is_desktop_dependency { get; set; }
public AppDetailsData (HashTable data)
{
from_ht (data);
}
public void from_ht (HashTable data)
{
name = data["name"].get_string ();
summary = data["summary"].get_string ();
description = data["description"].get_string ();
version = data["version"].get_string ();
desktop_file = data["desktop_file"].get_string ();
license = data["license"].get_string ();
icon = data["icon_file_name"].get_string ();
icon_url = data["icon_url"].get_string ();
price = data["price"].get_string ();
raw_price = data["raw_price"].get_string ();
installation_date = data["installation_date"].get_string ();
website = data["website"].get_string ();
hardware_requirements = data["hardware_requirements"].get_string ();
size = int64.parse (data["size"].get_string ());
is_desktop_dependency = data["is_desktop_dependency"].get_boolean ();
var state = data["pkg_state"].get_string ();
switch (state)
{
case "installed":
pkg_state = PackageState.INSTALLED;
break;
case "uninstalled":
pkg_state = PackageState.UNINSTALLED;
break;
case "needs_purchase":
pkg_state = PackageState.NEEDS_PURCHASE;
break;
default:
pkg_state = PackageState.UNKNOWN;
break;
}
screenshot = null;
if (data.contains ("screenshots"))
{
var screenshot_var = data["screenshots"].get_child_value (0).lookup_value ("large_image_url", VariantType.STRING);
if (screenshot_var != null)
{
screenshot = screenshot_var.get_string ();
}
}
if (screenshot == null)
{
screenshot = "";
}
}
}
} ./src/launcher-client.vala 0000644 0000041 0000041 00000003337 12772523363 015774 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens {
static const string LAUNCHER_DBUS_NAME = "com.canonical.Unity.Launcher";
static const string LAUNCHER_DBUS_PATH = "/com/canonical/Unity/Launcher";
[DBus (name = "com.canonical.Unity.Launcher")]
public interface LauncherService: GLib.Object
{
public abstract async void add_launcher_item_from_position (string title, string icon, int icon_x, int icon_y, int icon_size, string desktop_file, string aptdaemon_task) throws IOError;
}
public class LauncherProxy: GLib.Object
{
public void connect_to_launcher () throws IOError
{
_launcher_service = Bus.get_proxy_sync (BusType.SESSION, LAUNCHER_DBUS_NAME, LAUNCHER_DBUS_PATH);
}
public async void add_launcher_item_from_position (string title, string icon, int icon_x, int icon_y, int icon_size, string desktop_file, string aptdaemon_task) throws IOError
{
yield _launcher_service.add_launcher_item_from_position (title, icon, icon_x, icon_y, icon_size, desktop_file, aptdaemon_task);
}
private LauncherService _launcher_service;
}
} ./src/utils.vala 0000644 0000041 0000041 00000016400 12772523363 014052 0 ustar www-data www-data /*
* Copyright (C) 2010 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
using Posix;
using Unity;
using Gee;
namespace Unity.ApplicationsLens.Utils
{
public AppInfo? get_app_info_for_actor (string actor)
{
string desktop_id = get_desktop_id_for_actor (actor);
return AppInfoManager.get_default ().lookup (desktop_id);
}
public bool check_actor_has_category (string actor, Set? categories)
{
if (categories == null)
return false;
AppInfoManager appman = AppInfoManager.get_default ();
string desktop_id = get_desktop_id_for_actor (actor);
AppInfo? appinfo = appman.lookup (desktop_id);
if (appinfo == null)
return false;
unowned string[]? actor_cats = appman.get_categories (desktop_id);
if (actor_cats == null)
return false;
foreach (var cat in actor_cats)
{
if (cat in categories)
return true;
}
return false;
}
public string get_desktop_id_for_actor (string actor)
{
if (actor.has_prefix("application://"))
return actor.substring(14);
else if (actor.has_prefix("app://"))
return actor.substring(6);
else if (actor.has_prefix("/"))
{
return Path.get_basename (actor);
}
/* At this point we assume that @actor is already the basename of the
* .desktop file */
return actor;
}
public bool is_search_empty (string? search_string)
{
if (search_string == null) return true;
return search_string == "";
}
private static Dee.ICUTermFilter icu_filter;
public string preprocess_string (string text)
{
if (icu_filter == null)
{
icu_filter = new Dee.ICUTermFilter.ascii_folder ();
}
var uncamelcased = uncamelcase (text);
if (text != uncamelcased)
{
// make sure we don't discard the original completely
uncamelcased = "%s\n%s".printf (text, uncamelcased);
}
var folded = icu_filter.apply (uncamelcased);
if (uncamelcased == folded) return uncamelcased;
return "%s\n%s".printf (uncamelcased, folded);
}
private static Regex camelcase_matcher;
public string uncamelcase (string text)
{
if (camelcase_matcher == null)
{
try
{
// 1+ upper characters followed by 1+ non-upper
// (but preceded by non-upper or start of the string)
camelcase_matcher = new Regex ("(?<=^|[^[:upper:]\\s])[[:upper:]]+[^[:upper:]]+",
RegexCompileFlags.OPTIMIZE);
}
catch (Error e) { warning ("%s", e.message); }
}
/* we want to do "pyKaraoke" -> "py Karaoke",
"CompizConfig" -> "Compiz Config", but leave "System Monitor" alone
*/
try
{
string result;
result = camelcase_matcher.replace_eval (text, -1, 0, 0,(mi, builder) =>
{
int start_pos;
mi.fetch_pos (0, out start_pos, null);
if (start_pos != 0) builder.append_c (' ');
builder.append (mi.fetch (0));
return false;
});
return result;
}
catch (Error e)
{
warning ("%s", e.message);
return text;
}
}
public Dee.Index prepare_index (Dee.Model model,
uint sort_column,
owned Dee.ModelReaderFunc reader_func,
out Dee.Analyzer out_analyzer)
{
// reuse the icu_filter
if (icu_filter == null)
{
icu_filter = new Dee.ICUTermFilter.ascii_folder ();
}
var sort_filter = Dee.Filter.new_collator (sort_column);
var filter_model = new Dee.FilterModel (model, sort_filter);
var analyzer = new Dee.TextAnalyzer ();
analyzer.add_term_filter ((terms_in, terms_out) =>
{
for (uint i = 0; i < terms_in.num_terms (); i++)
{
unowned string term = terms_in.get_term (i);
var folded = icu_filter.apply (term);
terms_out.add_term (term);
if (folded != term) terms_out.add_term (folded);
}
});
out_analyzer = analyzer;
var reader = Dee.ModelReader.new ((owned) reader_func);
return new Dee.TreeIndex (filter_model, analyzer, reader);
}
public SList search_index (Dee.Index index,
Dee.Analyzer analyzer,
string query)
{
if (is_search_empty (query))
{
var model = index.get_model ();
var iter = model.get_first_iter ();
var end_iter = model.get_last_iter ();
var result = new SList ();
while (iter != end_iter)
{
result.prepend (iter);
iter = model.next (iter);
}
result.reverse ();
return result;
}
var term_list = Object.new (typeof (Dee.TermList)) as Dee.TermList;
analyzer.tokenize (query, term_list);
var matches = new Sequence ();
uint num_terms = term_list.num_terms ();
for (uint i = 0; i < num_terms; i++)
{
var rs = index.lookup (term_list.get_term (i),
i < num_terms - 1 ? Dee.TermMatchFlag.EXACT : Dee.TermMatchFlag.PREFIX);
bool first_pass = i == 0;
CompareDataFunc cmp_func = (a, b) =>
{
return a == b ? 0 : ((void*) a > (void*) b ? 1 : -1);
};
// intersect the results (cause we want to AND the terms)
var remaining = new Sequence ();
foreach (var item in rs)
{
if (first_pass)
matches.insert_sorted (item, cmp_func);
else if (matches.lookup (item, cmp_func) != null)
remaining.insert_sorted (item, cmp_func);
}
if (!first_pass) matches = (owned) remaining;
// final result set empty already?
if (matches.get_begin_iter () == matches.get_end_iter ()) break;
}
var result = new SList ();
var iter = matches.get_begin_iter ();
var end_iter = matches.get_end_iter ();
while (iter != end_iter)
{
result.prepend (iter.get ());
iter = iter.next ();
}
result.reverse ();
return result;
}
/* Substitute tilde character in @s by the home directory.
* Expansion of ~username also works if 'username' is found. */
public string subst_tilde (string s)
{
int k;
string name;
unowned Passwd? pw;
if (s[0] != '~')
return s;
if (s.length == 1 || s[1] == '/')
return Environment.get_home_dir () + s.substring (1, -1);
k = s.index_of ("/");
if (k == -1)
name = s.substring (1, -1);
else
name = s.substring (1, k-1);
pw = Posix.getpwnam (name);
if (pw == null)
return s;
if (k == -1)
return pw.pw_dir;
else
return pw.pw_dir + s.substring (k, -1);
}
}
./src/Makefile.am 0000644 0000041 0000041 00000006456 12772523363 014113 0 ustar www-data www-data NULL =
BUILT_SOURCES =
CLEANFILES =
EXTRA_DIST =
DATADIR = $(datadir)
unitylibdir = $(libdir)/unity
unitylib_LTLIBRARIES = unity-scope-applications.la unity-scope-runningapps.la
AM_CPPFLAGS = \
-DDATADIR=\"$(DATADIR)\" \
-DPKGDATADIR=\"$(PKGDATADIR)\" \
-DGETTEXT_PACKAGE=\"$(GETTEXT_PACKAGE)\" \
-DG_LOG_DOMAIN=\"unity-applications-daemon\" \
-DGMENU_I_KNOW_THIS_IS_UNSTABLE \
$(LENS_DAEMON_CFLAGS) \
$(MAINTAINER_CFLAGS) \
-I$(srcdir) \
$(COVERAGE_CFLAGS) \
-g
if !ENABLE_C_WARNINGS
AM_CPPFLAGS += -w
endif
AM_CXXFLAGS = --std=c++11
# Note that we require glib 2.26 because libzeitgeist
# expects us to use g_ptr_array_unref instead of g_ptr_array_free.
AM_VALAFLAGS = \
-C \
--vapidir=$(top_srcdir)/vapi \
--pkg posix \
--pkg gio-2.0 \
--pkg gio-unix-2.0 \
--pkg dee-1.0 \
--pkg zeitgeist-1.0 \
--pkg unity \
--pkg unity-protocol \
--pkg gee-0.8 \
--pkg libgnome-menu-3.0 \
--pkg unity-package-search \
--pkg unity-ratings-db \
--target-glib=2.26 \
$(MAINTAINER_VALAFLAGS)
unity_package_search_libs = -lxapian -lstdc++
unity_ratings_db_libs = -ldb
unity_scope_applications_la_LIBADD = \
$(LENS_DAEMON_LIBS) \
$(unity_package_search_libs) \
$(unity_ratings_db_libs) \
$(NULL)
unity_scope_runningapps_la_LIBADD = \
$(LENS_DAEMON_LIBS) \
$(NULL)
unity_scope_applications_la_LDFLAGS = \
-module -shared -avoid-version \
-R $(PROTOCOLPRIVATELIBDIR) $(COVERAGE_LDFLAGS)
unity_scope_runningapps_la_LDFLAGS = \
-module -shared -avoid-version \
-R $(PROTOCOLPRIVATELIBDIR) $(COVERAGE_LDFLAGS)
unity_scope_applications_la_VALASOURCES = \
app-watcher.vala \
config.vala \
daemon.vala \
launcher-client.vala \
main.vala \
commands-scope.vala \
scopes-scope.vala \
schemas.vala \
utils.vala \
aptd-client.vala \
purchase-info-helper.vala \
software-center-data-provider.vala \
software-center-data-cache.vala \
software-center-app-details.vala \
software-center-utils.vala \
xapian-utils.vala \
$(NULL)
unity_scope_runningapps_la_VALASOURCES = \
running-apps-scope.vala \
running-apps-search.vala \
winstack-client.vala \
windows-stack.vala \
schemas.vala \
config.vala \
$(NULL)
unity_scope_applications_la_SOURCES = \
$(unity_scope_applications_la_VALASOURCES:.vala=.c) \
unity-package-search.cc \
unity-package-search.h \
unity-ratings-db.c \
unity-ratings-db.h \
$(NULL)
unity_scope_runningapps_la_SOURCES = \
$(unity_scope_runningapps_la_VALASOURCES:.vala=.c) \
$(NULL)
BUILT_SOURCES += \
unity-scope-applications.vala.stamp \
unity-scope-runningapps.vala.stamp \
$(NULL)
EXTRA_DIST += \
unity-scope-applications.vala.stamp \
unity-scope-runningapps.vala.stamp \
$(unity_scope_applications_la_VALASOURCES) \
$(unity_scope_runningapps_la_VALASOURCES) \
unity-package-search.cc \
unity-package-search.h \
unity-ratings-db.c \
unity-ratings-db.h \
$(NULL)
unity-scope-applications.vala.stamp: $(unity_scope_applications_la_VALASOURCES)
$(AM_V_GEN) $(VALAC) $(AM_VALAFLAGS) $^
@touch $@
unity-scope-runningapps.vala.stamp: $(unity_scope_runningapps_la_VALASOURCES)
$(AM_V_GEN) $(VALAC) $(AM_VALAFLAGS) $^
@touch $@
CLEANFILES += \
*.stamp \
*.vapi \
$(unity_scope_applications_la_VALASOURCES:.vala=.c) \
$(unity_scope_runningapps_la_VALASOURCES:.vala=.c) \
unity-package-search.h.gch \
$(NULL)
./src/unity-package-search.cc 0000644 0000041 0000041 00000100716 12772523363 016364 0 ustar www-data www-data /*
* Copyright (C) 2010 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
/*
* This file contains C bindings written in C++ to hook up with the
* Xapian indexes generated by Ubuntu Software Center.
*
* It also hooks up with libgnome-menu and creates an attached in-memory
* Xapian index of the menu contents.
*/
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define SOFTWARE_CENTER_INDEX "/var/cache/software-center/xapian"
#define QUERY_PARSER_EXACTSEARCH_FLAGS Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_LOVEHATE
#define QUERY_PARSER_PREFIXSEARCH_FLAGS QUERY_PARSER_EXACTSEARCH_FLAGS|Xapian::QueryParser::FLAG_WILDCARD|Xapian::QueryParser::FLAG_PARTIAL
#define QUERY_PARSER_FILTER_FLAGS Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE
// values used in the database
#define XAPIAN_VALUE_APPNAME 170
#define XAPIAN_VALUE_PKGNAME 171
#define XAPIAN_VALUE_ICON 172
#define XAPIAN_VALUE_GETTEXT_DOMAIN 173
#define XAPIAN_VALUE_ARCHIVE_SECTION 174
#define XAPIAN_VALUE_ARCHIVE_ARCH 175
#define XAPIAN_VALUE_POPCON 176
#define XAPIAN_VALUE_SUMMARY 177
#define XAPIAN_VALUE_ARCHIVE_CHANNEL 178
#define XAPIAN_VALUE_DESKTOP_FILE 179
#define XAPIAN_VALUE_PRICE 180
#define XAPIAN_VALUE_PURCHASED_DATE 184
#define XAPIAN_VALUE_SCREENSHOT_URLS 185
#define XAPIAN_VALUE_DESCRIPTION 188
#define XAPIAN_VALUE_VERSION_INFO 198
#define XAPIAN_VALUE_EXENAME 294
#define XAPIAN_VALUE_CURRENCY 201
/* this isn't a Software Center slot, but we use it to mark master
* scopes in the scope index. */
#define XAPIAN_VALUE_MASTERSCOPE 1000
#include "unity-package-search.h"
#include "columbus.hh"
struct _UnityPackageSearcher
{
Xapian::Database *db;
Xapian::KeyMaker *sorter;
Xapian::Enquire *enquire;
Xapian::QueryParser *query_parser;
GRand *random;
Columbus::Matcher *matcher;
vector col_mapping;
bool db_merged;
};
static void buildMatcher(UnityPackageSearcher *searcher) {
Columbus::Matcher *m = searcher->matcher;
Xapian::Database *db = searcher->db;
Columbus::Corpus c;
Columbus::Word appnameField("appname");
Columbus::Word summaryField("summary");
Columbus::Word pkgnameField("pkgname");
Columbus::Word exenameField("exename");
for(Xapian::PostingIterator post = db->postlist_begin(""); post != db->postlist_end(""); post++) {
Xapian::Document xdoc = db->get_document(*post);
DocumentID id;
if(searcher->db_merged) {
searcher->col_mapping.push_back(xdoc.get_value(XAPIAN_VALUE_APPNAME));
id = searcher->col_mapping.size()-1;
} else {
id = xdoc.get_docid();
}
Columbus::Document cdoc(id);
std::string val;
val = xdoc.get_value(XAPIAN_VALUE_APPNAME);
if(!val.empty()) {
cdoc.addText(appnameField, val.c_str());
}
/* It turned out that fuzzy matching non-visible content
* is confusing to users, so let's not index these at all.
* In the future we might want to explore better ways
* of exposing this info.
val = xdoc.get_value(XAPIAN_VALUE_SUMMARY);
if(!val.empty()) {
cdoc.addText(summaryField, val.c_str());
}
val = xdoc.get_value(XAPIAN_VALUE_PKGNAME);
if(!val.empty()) {
cdoc.addText(pkgnameField, val.c_str());
}
*/
val = xdoc.get_value(XAPIAN_VALUE_EXENAME);
if(!val.empty()) {
cdoc.addText(exenameField, val.c_str());
}
c.addDocument(cdoc);
}
m->index(c);
m->getErrorValues().addStandardErrors();
// Substring mode resulted in too many false positives,
// so disable it for the time being.
//m->getErrorValues().setSubstringMode();
m->getIndexWeights().setWeight(summaryField, 0.5);
}
extern "C"
{
extern gchar* unity_applications_lens_utils_preprocess_string (const gchar* input);
}
/* A Xapian::Sorter that respects the collation rules for the current locale */
class LocaleKeyMaker : public Xapian::KeyMaker
{
private:
Xapian::valueno value;
public:
LocaleKeyMaker (Xapian::valueno value)
{
this->value = value;
}
virtual ~LocaleKeyMaker() { }
virtual std::string operator() (const Xapian::Document &doc) const
{
string val = doc.get_value (value);
gchar* col_key_c = g_utf8_collate_key (val.c_str (), -1);
string col_key_mm = col_key_c;
g_free (col_key_c);
return col_key_mm;
}
};
/* Do generic searcher setup */
static void
init_searcher (UnityPackageSearcher *searcher)
{
// Activate Xapian CJK support
setenv("XAPIAN_CJK_NGRAM", "1", 1);
Xapian::Database db = *searcher->db;
// Start an enquire session
Xapian::Enquire *enquire = new Xapian::Enquire (db);
enquire->set_sort_by_value (XAPIAN_VALUE_APPNAME, FALSE);
searcher->enquire = enquire;
// Make sure we respect sorting rules for the current locale
searcher->sorter = new LocaleKeyMaker (XAPIAN_VALUE_APPNAME);
enquire->set_sort_by_key (searcher->sorter, FALSE);
// Create query parser
Xapian::QueryParser *query_parser = new Xapian::QueryParser ();
query_parser->add_prefix ("section", "AE");
query_parser->add_prefix ("type", "AT");
query_parser->add_prefix ("category", "AC");
query_parser->add_prefix ("name", "AA");
query_parser->add_prefix ("pkgname", "AP");
query_parser->add_prefix ("exec", "XX");
query_parser->add_prefix ("keyword", "KW");
query_parser->add_prefix ("pkg_wildcard", "XP");
query_parser->add_prefix ("pkg_wildcard", "XPM");
query_parser->add_prefix ("pkg_wildcard", "AP");
query_parser->add_prefix ("pkg_wildcard", "APM");
query_parser->set_default_op (Xapian::Query::OP_AND);
query_parser->set_database (db);
searcher->query_parser = query_parser;
// Init random number generator from 32 lowest bits of system time
searcher->random = g_rand_new_with_seed (g_get_monotonic_time ());
}
/* Recursively traverse a menu tree and add it to the index */
static void
index_menu_item (Xapian::WritableDatabase *db,
Xapian::TermGenerator *indexer,
GMenuTreeDirectory *item)
{
GMenuTreeEntry *entry;
GMenuTreeDirectory *dir;
GMenuTreeIter *iter;
GDesktopAppInfo *info;
GAppInfo *app_info;
GMenuTreeItemType item_type;
UnityAppInfoManager *appman;
gchar **cats, **keywords;
gchar *dum1, *dum2, *dum3;
gint i, len;
g_return_if_fail (db != NULL);
g_return_if_fail (indexer != NULL);
g_return_if_fail (item != NULL);
iter = gmenu_tree_directory_iter (item);
while ((item_type = gmenu_tree_iter_next (iter)) != GMENU_TREE_ITEM_INVALID)
{
Xapian::Document doc;
switch (item_type)
{
case GMENU_TREE_ITEM_DIRECTORY:
/* Recurse into directory */
dir = gmenu_tree_iter_get_directory (iter);
index_menu_item (db, indexer, dir);
break;
case GMENU_TREE_ITEM_ENTRY:
/* Add this entry to the index */
entry = gmenu_tree_iter_get_entry (iter);
info = gmenu_tree_entry_get_app_info (entry);
app_info = G_APP_INFO (info);
/* Store relevant values */
if (g_app_info_get_display_name (app_info))
doc.add_value (XAPIAN_VALUE_APPNAME, g_app_info_get_display_name (app_info));
if (g_app_info_get_description (app_info))
doc.add_value (XAPIAN_VALUE_DESCRIPTION, g_app_info_get_description (app_info));
if (g_app_info_get_icon (app_info))
{
gchar *icon_str = g_icon_to_string (g_app_info_get_icon (app_info));
if (icon_str != NULL)
{
doc.add_value (XAPIAN_VALUE_ICON, icon_str);
g_free (icon_str);
}
}
if (gmenu_tree_entry_get_desktop_file_id (entry))
{
doc.add_value (XAPIAN_VALUE_DESKTOP_FILE, gmenu_tree_entry_get_desktop_file_id (entry));
}
/* Index full text data */
indexer->set_document(doc);
if (g_app_info_get_display_name (app_info))
{
dum1 = unity_applications_lens_utils_preprocess_string (g_app_info_get_display_name (app_info));
indexer->index_text(dum1, 5);
g_free (dum1);
}
if (g_app_info_get_name (app_info))
{
dum1 = unity_applications_lens_utils_preprocess_string (g_app_info_get_name (app_info));
indexer->index_text(dum1, 5);
g_free (dum1);
}
if (g_app_info_get_description (app_info))
{
dum1 = unity_applications_lens_utils_preprocess_string (g_app_info_get_description (app_info));
indexer->index_text (dum1, 0);
g_free (dum1);
}
/* Index the XDG categories */
appman = unity_app_info_manager_get_default ();
cats = unity_app_info_manager_get_categories (appman, // const return
gmenu_tree_entry_get_desktop_file_id (entry),
&len);
/* Note: Wine apps and app launchers created with Alacarte commonly
* don't have any category metadata, so they'll only show up under
* All Applications */
for (i = 0; i < len; i++)
{
dum1 = g_ascii_strdown (cats[i], -1);
dum2 = g_strconcat ("AC", dum1, NULL);
doc.add_term (dum2);
g_free (dum1);
g_free (dum2);
}
/* Index Keywords*/
keywords = unity_app_info_manager_get_keywords (appman, // const return
gmenu_tree_entry_get_desktop_file_id (entry),
&len);
for (i = 0; i < len; i++)
{
dum1 = unity_applications_lens_utils_preprocess_string (keywords[i]);
indexer->index_text (dum1, 0);
indexer->index_text (dum1, 0, "KW");
g_free (dum1);
}
g_object_unref (appman);
/* Always assume Type=Application for items in a menu... */
doc.add_term ("ATapplication");
/* Index application names */
dum1 = (gchar *) g_app_info_get_display_name (app_info);
dum2 = g_strconcat ("AA", dum1, NULL);
doc.add_term (dum2);
g_free (dum2);
dum1 = (gchar *) g_app_info_get_name (app_info);
dum2 = g_strconcat ("AA", dum1, NULL);
doc.add_term (dum2);
g_free (dum2);
/* Index executable name, change - in _ for exec */
dum1 = g_strdup (g_app_info_get_commandline (app_info)); // alloc
if (dum1)
{
dum2 = strstr (dum1, " "); // const
dum2 == NULL ? : *dum2 = '\0'; // const
dum2 = g_path_get_basename (dum1); // alloc
doc.add_value(XAPIAN_VALUE_EXENAME, dum2);
indexer->index_text (dum2, 2);
g_free (dum1);
dum1 = g_strdelimit (dum2, "-", '_'); // in place switch, dum1 own mem
dum2 = g_strconcat ("AA", dum1, NULL); // alloc
doc.add_term (dum2);
g_free (dum2);
dum2 = g_strconcat ("XX", dum1, NULL); // alloc
doc.add_term (dum2);
g_free (dum2);
g_free (dum1);
}
db->add_document(doc);
break;
case GMENU_TREE_ITEM_SEPARATOR:
case GMENU_TREE_ITEM_HEADER:
case GMENU_TREE_ITEM_ALIAS:
break;
default:
g_warning ("Unexpected GMenuTreeItemType %u", item_type);
break;
}
}
// Add the document to the database.
}
/* Create a searcher that searches in a menu tree. The menu tree
* will be indexed into an in-memory Xapian index */
UnityPackageSearcher*
unity_package_searcher_new_for_menu (GMenuTree *menu)
{
UnityPackageSearcher *searcher;
Xapian::WritableDatabase *db;
searcher = new UnityPackageSearcher;
db = new Xapian::WritableDatabase ();
searcher->db = db;
searcher->db->add_database (Xapian::InMemory::open ());
init_searcher (searcher);
/* Index the menu recursively */
searcher->db_merged = false;
Xapian::TermGenerator *indexer = new Xapian::TermGenerator ();
index_menu_item (db, indexer, gmenu_tree_get_root_directory (menu));
delete indexer;
db->flush ();
searcher->matcher = new Columbus::Matcher();
buildMatcher(searcher);
return searcher;
}
/* Recursively traverse the set of scopes */
static void
index_scope (Xapian::WritableDatabase *db,
Xapian::TermGenerator *indexer,
UnityProtocolScopeRegistryScopeMetadata *info)
{
Xapian::Document doc;
char *dum1;
if (info->name != NULL)
doc.add_value (XAPIAN_VALUE_APPNAME, info->name);
if (info->description != NULL)
doc.add_value (XAPIAN_VALUE_DESCRIPTION, info->description);
if (info->icon != NULL)
doc.add_value (XAPIAN_VALUE_ICON, info->icon);
if (info->id != NULL)
doc.add_value (XAPIAN_VALUE_DESKTOP_FILE, info->id);
if (info->is_master)
doc.add_value (XAPIAN_VALUE_MASTERSCOPE, "true");
indexer->set_document (doc);
if (info->name != NULL)
{
dum1 = unity_applications_lens_utils_preprocess_string (info->name);
indexer->index_text (dum1, 5);
g_free (dum1);
}
if (info->description != NULL)
{
dum1 = unity_applications_lens_utils_preprocess_string (info->description);
indexer->index_text (dum1, 5);
g_free (dum1);
}
for (GSList *l = info->keywords; l != NULL; l = l->next)
{
dum1 = unity_applications_lens_utils_preprocess_string ((char *)l->data);
indexer->index_text (dum1, 0);
indexer->index_text (dum1, 0, "KW");
g_free (dum1);
}
/* Always assume Type=Scope for scopes... */
doc.add_term ("ATscope");
/* Index application name */
dum1 = g_strconcat ("AA", info->name, NULL);
doc.add_term (dum1);
g_free (dum1);
db->add_document (doc);
}
UnityPackageSearcher*
unity_package_searcher_new_for_scopes (UnityProtocolScopeRegistry *scope_registry)
{
UnityPackageSearcher *searcher;
Xapian::WritableDatabase *db;
searcher = new UnityPackageSearcher;
db = new Xapian::WritableDatabase ();
searcher->db = db;
searcher->db->add_database (Xapian::InMemory::open ());
init_searcher (searcher);
/* Index the menu recursively */
searcher->db_merged = false;
Xapian::TermGenerator *indexer = new Xapian::TermGenerator ();
GSList *scopes = unity_protocol_scope_registry_get_scopes (scope_registry);
for (GSList *l = scopes; l != NULL; l = l->next)
{
UnityProtocolScopeRegistryScopeRegistryNode *node = (UnityProtocolScopeRegistryScopeRegistryNode *)l->data;
index_scope (db, indexer, node->scope_info);
// Also index any sub-scopes
for (GSList *sl = node->sub_scopes; sl != NULL; sl = sl->next)
{
UnityProtocolScopeRegistryScopeMetadata *info = (UnityProtocolScopeRegistryScopeMetadata *)sl->data;
index_scope (db, indexer, info);
}
}
delete indexer;
db->flush ();
searcher->matcher = new Columbus::Matcher();
buildMatcher(searcher);
return searcher;
}
/* Create a new searcher that searches into the Xapian index
* provided by the Software Center */
UnityPackageSearcher*
unity_package_searcher_new ()
{
UnityPackageSearcher *searcher;
gchar *agent = NULL;
searcher = new UnityPackageSearcher;
// Xapian initialization
try
{
searcher->db = new Xapian::Database (SOFTWARE_CENTER_INDEX);
}
catch(const Xapian::Error &error)
{
cerr << "Error loading package indexes: " << error.get_msg() << endl;
return NULL;
}
// add software-center-agent.db
try
{
agent = g_strdup_printf("%s/software-center/software-center-agent.db",
g_get_user_cache_dir());
if (g_file_test(agent, G_FILE_TEST_IS_DIR))
searcher->db->add_database (Xapian::Database (agent));
g_free(agent);
}
catch(const Xapian::Error &error)
{
cerr << "Error loading agent indexes: " << error.get_msg() << endl;
}
init_searcher (searcher);
searcher->db_merged = true;
searcher->matcher = new Columbus::Matcher();
buildMatcher(searcher);
return searcher;
}
void
unity_package_searcher_free (UnityPackageSearcher *searcher)
{
g_return_if_fail (searcher != NULL);
delete searcher->db;
delete searcher->sorter;
delete searcher->enquire;
delete searcher->query_parser;
delete searcher->matcher;
g_rand_free (searcher->random);
delete searcher;
}
static UnityPackageInfo*
_pkginfo_from_document (Xapian::Document doc) throw (Xapian::Error)
{
UnityPackageInfo *pkginfo = g_slice_new0 (UnityPackageInfo);
string pkgname = doc.get_value (XAPIAN_VALUE_PKGNAME);
pkginfo->package_name = g_strdup (pkgname.c_str ());
string appname = doc.get_value (XAPIAN_VALUE_APPNAME);
pkginfo->application_name = g_strdup (appname.c_str ());
string description = doc.get_value (XAPIAN_VALUE_DESCRIPTION);
pkginfo->description = g_strdup (description.c_str ());
string desktop_file = doc.get_value (XAPIAN_VALUE_DESKTOP_FILE);
pkginfo->desktop_file = g_strdup (desktop_file.c_str ());
string icon = doc.get_value (XAPIAN_VALUE_ICON);
pkginfo->icon = g_strdup (icon.c_str ());
// FIXME: we may want to format it according to locales at some point
string price = doc.get_value (XAPIAN_VALUE_CURRENCY);
if (!price.empty ())
{
price += " " + doc.get_value (XAPIAN_VALUE_PRICE);
}
pkginfo->price = g_strdup (price.c_str ());
const string purchase_date = doc.get_value (XAPIAN_VALUE_PURCHASED_DATE);
pkginfo->needs_purchase = purchase_date.empty ();
string is_master = doc.get_value (XAPIAN_VALUE_MASTERSCOPE);
pkginfo->is_master_scope = (is_master == "true");
return pkginfo;
}
UnityPackageInfo* unity_package_package_info_new ()
{
UnityPackageInfo *pkginfo = g_slice_new0 (UnityPackageInfo);
pkginfo->package_name = g_strdup ("");
pkginfo->application_name = g_strdup ("");
pkginfo->desktop_file = g_strdup ("");
pkginfo->price = g_strdup ("");
pkginfo->icon = g_strdup ("");
return pkginfo;
}
void unity_package_package_info_free (gpointer pkg)
{
g_return_if_fail (pkg != NULL);
UnityPackageInfo *pkginfo = (UnityPackageInfo*) pkg;
g_free (pkginfo->package_name);
g_free (pkginfo->application_name);
g_free (pkginfo->desktop_file);
g_free (pkginfo->price);
g_free (pkginfo->icon);
g_slice_free (UnityPackageInfo, pkginfo);
}
Xapian::Document get_doc_from_col_match(UnityPackageSearcher *searcher, DocumentID id) {
if(searcher->db_merged) {
string name = searcher->col_mapping[id];
string query = "AA\"";
query += name;
query += "\"";
Xapian::QueryParser p;
Xapian::Query q;
Xapian::Enquire e(*searcher->db);
Xapian::MSet matches;
p.set_database(*searcher->db);
q = p.parse_query(query);
e.set_query(q);
matches = e.get_mset(0, 1);
return matches.begin().get_document();
} else {
return searcher->db->get_document(id);
}
}
static UnityPackageSearchResult*
xapian_search (UnityPackageSearcher *searcher,
const gchar *search_string,
guint max_hits,
UnityPackageSearchType search_type,
UnityPackageSort sort)
{
UnityPackageSearchResult* result;
string _search_string (search_string);
Xapian::Query query;
try
{
switch (search_type)
{
case UNITY_PACKAGE_SEARCHTYPE_PREFIX:
query = searcher->query_parser->parse_query (_search_string, QUERY_PARSER_PREFIXSEARCH_FLAGS);
break;
case UNITY_PACKAGE_SEARCHTYPE_EXACT:
query = searcher->query_parser->parse_query (_search_string, QUERY_PARSER_EXACTSEARCH_FLAGS);
break;
default:
g_critical ("Unknown search type '%i'. Fallback to a prefix search", search_type);
query = searcher->query_parser->parse_query (_search_string, QUERY_PARSER_PREFIXSEARCH_FLAGS);
break;
}
}
catch (Xapian::Error &e)
{
g_warning ("Error parsing query '%s': %s", search_string, e.get_msg().c_str());
return g_slice_new0 (UnityPackageSearchResult);
}
switch (sort)
{
case UNITY_PACKAGE_SORT_BY_NAME:
searcher->enquire->set_sort_by_key (searcher->sorter, FALSE);
break;
case UNITY_PACKAGE_SORT_BY_RELEVANCY:
searcher->enquire->set_sort_by_relevance ();
break;
default:
g_critical ("Unknown sort type '%i'", sort);
searcher->enquire->set_sort_by_relevance ();
break;
}
result = g_slice_new0 (UnityPackageSearchResult);
try
{
// Perform search
searcher->enquire->set_collapse_key(XAPIAN_VALUE_DESKTOP_FILE);
max_hits = (max_hits != 0 ? max_hits : searcher->db->get_doccount ());
searcher->enquire->set_query(query);
Xapian::MSet matches = searcher->enquire->get_mset(0, max_hits);
// Retrieve the results, note that we build the result->results
// list in reverse order and then reverse it before we return it
result->num_hits = matches.get_matches_estimated ();
result->fuzzy_search = false;
for (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i)
{
try
{
Xapian::Document doc = i.get_document();
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
pkginfo->relevancy = i.get_percent();
result->results = g_slist_prepend (result->results, pkginfo);
}
catch (Xapian::Error &e)
{
g_warning ("Unable to read document from result set: %s",
e.get_msg().c_str());
}
}
result->results = g_slist_reverse (result->results);
}
catch(const Xapian::Error &e)
{
g_warning ("Error running query '%s': %s", search_string, e.get_msg().c_str());
}
return result;
}
static UnityPackageSearchResult*
libcolumbus_search(UnityPackageSearcher *searcher, const char *str) {
Columbus::MatchResults results;
UnityPackageSearchResult* result;
result = g_slice_new0 (UnityPackageSearchResult);
results = searcher->matcher->match(str);
for (size_t i = 0; i < results.size(); ++i)
{
try
{
Xapian::Document doc = get_doc_from_col_match(searcher, results.getDocumentID(i));
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
pkginfo->relevancy = results.getRelevancy(i);
result->results = g_slist_prepend (result->results, pkginfo);
}
catch (Xapian::Error &e)
{
g_warning ("Unable to read document from result set: %s",
e.get_msg().c_str());
}
}
result->results = g_slist_reverse (result->results);
result->fuzzy_search = true;
return result;
}
UnityPackageSearchResult*
unity_package_searcher_search (UnityPackageSearcher *searcher,
const gchar *search_string,
guint max_hits,
UnityPackageSearchType search_type,
UnityPackageSort sort)
{
UnityPackageSearchResult *xap_result;
g_return_val_if_fail (searcher != NULL, NULL);
g_return_val_if_fail (search_string != NULL, NULL);
bool is_filtered = strstr(search_string, "category:") != NULL
|| strstr(search_string, "pkg_wildcard:") != NULL;
const char *col_query_str = strstr(search_string, "AND");
xap_result = xapian_search(searcher, search_string, max_hits, search_type, sort);
// If Xapian does not find anything, try fuzzy matching.
if (g_slist_length(xap_result->results) == 0 && (!is_filtered && col_query_str)) {
g_slice_free(UnityPackageSearchResult, xap_result);
col_query_str += 3;
UnityPackageSearchResult *res = libcolumbus_search(searcher, col_query_str);
return res;
}
return xap_result;
}
/**
* Get applications matching given xapian filter query and additionally filter results out
* using AppFilterCallback, until n_apps matching apps are found.
* Results are filtered out if AppFilterCallback returns FALSE.
*/
UnityPackageSearchResult* unity_package_searcher_get_apps (UnityPackageSearcher *searcher,
const gchar *filter_query,
guint n_apps,
AppFilterCallback cb,
gpointer data)
{
UnityPackageSearchResult *result;
GHashTable *unique;
guint num_matches = 0;
g_return_val_if_fail (searcher != NULL, NULL);
unique = g_hash_table_new (g_str_hash, g_str_equal);
result = g_slice_new0 (UnityPackageSearchResult);
g_debug ("FILTER %s", filter_query);
Xapian::Query query;
try
{
query = searcher->query_parser->parse_query (filter_query, QUERY_PARSER_FILTER_FLAGS);
searcher->enquire->set_sort_by_relevance ();
searcher->enquire->set_query(query);
Xapian::MSet matches = searcher->enquire->get_mset(0, searcher->db->get_doccount ());
Xapian::MSetIterator iter = matches.begin();
while (num_matches < n_apps && iter != matches.end())
{
Xapian::Document doc = iter.get_document ();
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
if (g_hash_table_lookup_extended (unique, pkginfo->package_name, NULL, NULL) || cb(pkginfo, data) == FALSE)
{
unity_package_package_info_free (pkginfo);
}
else
{
g_hash_table_insert (unique, pkginfo->package_name, NULL);
result->results = g_slist_prepend (result->results, pkginfo);
num_matches++;
}
++iter;
}
}
catch (Xapian::Error e)
{
g_debug ("Error getting apps for query '%s': %s", filter_query, e.get_msg().c_str());
return g_slice_new0 (UnityPackageSearchResult);
}
g_hash_table_unref (unique);
result->num_hits = num_matches;
result->fuzzy_search = false;
return result;
}
UnityPackageSearchResult*
unity_package_searcher_get_random_apps (UnityPackageSearcher *searcher,
const gchar *filter_query,
guint n_apps)
{
UnityPackageSearchResult *result;
GHashTable *unique;
guint i, n_unique, lastdocid, docid;
g_return_val_if_fail (searcher != NULL, NULL);
result = g_slice_new0 (UnityPackageSearchResult);
result->num_hits = n_apps;
result->fuzzy_search = false;
lastdocid = searcher->db->get_lastdocid ();
/* Since we really just pick random apps we may end up with dupes */
unique = g_hash_table_new (g_str_hash, g_str_equal);
/* When looking for random apps we check up to twice the number of
* requested apps in order to try and avoid dupes. This is a sloppy
* check, but works well enough in practice */
if (filter_query == NULL)
{
g_debug ("RANDOM");
for (i = 0, n_unique = 0; i < n_apps*2, n_unique < n_apps; i++)
{
Xapian::Document doc;
try
{
doc = searcher->db->get_document (
g_rand_int_range (searcher->random, 1, lastdocid));
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
if (g_hash_table_lookup_extended (unique, pkginfo->package_name, NULL, NULL))
{
unity_package_package_info_free (pkginfo);
}
else
{
g_hash_table_insert (unique, pkginfo->package_name, NULL);
result->results = g_slist_prepend (result->results, pkginfo);
n_unique++;
}
}
catch (Xapian::Error &e)
{
g_warning ("Error getting random apps: %s", e.get_msg().c_str());
continue;
}
}
}
else
{
g_debug ("FILTER %s", filter_query);
Xapian::Query query;
try
{
query = searcher->query_parser->parse_query (filter_query, QUERY_PARSER_FILTER_FLAGS);
searcher->enquire->set_sort_by_relevance ();
searcher->enquire->set_query(query);
Xapian::MSet matches = searcher->enquire->get_mset(0, searcher->db->get_doccount ());
for (i = 0, n_unique = 0; i < n_apps*4, n_unique < n_apps; i++)
{
docid = g_rand_int_range (searcher->random, 0, matches.size ());
Xapian::MSetIterator iter = matches[docid];
Xapian::Document doc = iter.get_document ();
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
if (g_hash_table_lookup_extended (unique, pkginfo->package_name, NULL, NULL))
{
unity_package_package_info_free (pkginfo);
}
else
{
g_hash_table_insert (unique, pkginfo->package_name, NULL);
result->results = g_slist_prepend (result->results, pkginfo);
n_unique++;
}
}
}
catch (Xapian::Error &e)
{
g_debug ("Error getting random apps for query '%s': %s", filter_query, e.get_msg().c_str());
return g_slice_new0 (UnityPackageSearchResult);
}
}
g_hash_table_unref (unique);
result->results = g_slist_reverse (result->results);
return result;
}
/**
* Returns all apps that match exactly app+pkg names.
* names must be a flat list of appname1, pkgname1, appname2, pkgname2... strings (must have even number of elements).
*/
UnityPackageSearchResult*
unity_package_searcher_get_by_exact_names (UnityPackageSearcher *searcher, GSList *names)
{
g_return_val_if_fail (searcher != NULL, NULL);
vector query_list;
GSList *iter = names;
while (iter)
{
const string appname ((char *)iter->data);
iter = g_slist_next (iter);
if (iter == NULL)
{
g_warning ("List should have even list of arguments");
return NULL;
}
const string pkgname = ((char *)iter->data);
Xapian::Query query1 ("AA" + appname);
Xapian::Query query2 ("AP" + pkgname);
Xapian::Query query (Xapian::Query::OP_AND, query1, query2);
query_list.push_back (query);
iter = g_slist_next (iter);
}
guint num_matches = 0;
UnityPackageSearchResult *result;
result = g_slice_new0 (UnityPackageSearchResult);
try
{
Xapian::Query top_query = Xapian::Query (Xapian::Query::OP_OR, query_list.begin (), query_list.end ());
searcher->enquire->set_sort_by_relevance ();
//this is crucial; we want all the requested packages, some commercial stuff don't have desktop files, we don't want to collapse them
searcher->enquire->set_collapse_key(Xapian::BAD_VALUENO);
searcher->enquire->set_query (top_query);
Xapian::MSet matches = searcher->enquire->get_mset(0, searcher->db->get_doccount ());
Xapian::MSetIterator iter = matches.begin();
while (iter != matches.end ())
{
Xapian::Document doc = iter.get_document ();
UnityPackageInfo *pkginfo = _pkginfo_from_document (doc);
result->results = g_slist_prepend (result->results, pkginfo);
num_matches++;
++iter;
}
}
catch (Xapian::Error e)
{
g_debug ("Error getting apps: %s", e.get_msg().c_str());
return g_slice_new0 (UnityPackageSearchResult);
}
result->num_hits = num_matches;
result->fuzzy_search = false;
return result;
}
UnityPackageInfo *
unity_package_searcher_get_by_desktop_file (UnityPackageSearcher *searcher, const gchar *desktop_file)
{
g_return_val_if_fail (searcher != NULL, NULL);
UnityPackageInfo *pkginfo = NULL;
Xapian::PostingIterator it = searcher->db->postlist_begin ("");
Xapian::PostingIterator end_it = searcher->db->postlist_end ("");
const string query = desktop_file;
while (it != end_it)
{
Xapian::Document doc = searcher->db->get_document (*it);
string value = doc.get_value (XAPIAN_VALUE_DESKTOP_FILE);
bool matches = false;
size_t sep = value.find (':');
if (sep != string::npos)
{
matches = value.compare (sep+1, value.size() - sep, query) == 0;
}
else
{
matches = value == query;
}
if (matches)
{
pkginfo = _pkginfo_from_document (doc);
return pkginfo;
}
++it;
}
return pkginfo;
}
UnityPackageSearchResult* unity_package_search_result_new ()
{
UnityPackageSearchResult* result = g_slice_new0 (UnityPackageSearchResult);
return result;
}
void
unity_package_search_result_free (UnityPackageSearchResult *result)
{
g_return_if_fail (result != NULL);
g_slist_free_full (result->results, unity_package_package_info_free);
g_slice_free (UnityPackageSearchResult, result);
}
./src/main.vala 0000644 0000041 0000041 00000003022 12772523373 013633 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2011-2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Mikkel Kamstrup Erlandsen
*
*/
using GLib;
using Config;
public int unity_scope_module_get_version ()
{
return Unity.SCOPE_API_VERSION;
}
public List unity_scope_module_load_scopes () throws Error
{
/* Sort up locale to get translations but also sorting and
* punctuation right */
GLib.Intl.bindtextdomain (Config.PACKAGE, Config.LOCALEDIR);
GLib.Intl.bind_textdomain_codeset (Config.PACKAGE, "UTF-8");
GLib.Intl.setlocale(GLib.LocaleCategory.ALL, "");
var scopes = new List ();
var apps_scope = new Unity.ApplicationsLens.ApplicationsScope ();
var scopes_scope = new Unity.ApplicationsLens.ScopesScope (apps_scope);
scopes.append(apps_scope);
scopes.append(apps_scope.commands_scope);
scopes.append(scopes_scope);
return scopes;
}
./src/running-apps-scope.vala 0000644 0000041 0000041 00000015212 12772523363 016442 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*
*/
public int unity_scope_module_get_version ()
{
return Unity.SCOPE_API_VERSION;
}
public List unity_scope_module_load_scopes () throws Error
{
/* Sort up locale to get translations but also sorting and
* punctuation right */
GLib.Intl.bindtextdomain (Config.PACKAGE, Config.LOCALEDIR);
GLib.Intl.bind_textdomain_codeset (Config.PACKAGE, "UTF-8");
GLib.Intl.setlocale(GLib.LocaleCategory.ALL, "");
var scopes = new List ();
scopes.append(new Unity.ApplicationsLens.RunningAppsScope ());
return scopes;
}
namespace Unity.ApplicationsLens {
const string ICON_PATH = Config.DATADIR + "/icons/unity-icon-theme/places/svg/";
internal struct CategoryList
{
Gee.Set categories;
Gee.Set exclude_categories;
public CategoryList (string[] cats, string[] exclude)
{
categories = new Gee.HashSet ();
exclude_categories = new Gee.HashSet ();
foreach (var cat in cats)
{
categories.add (cat);
}
foreach (var cat in exclude)
{
exclude_categories.add (cat);
}
}
}
public class RunningAppsScope : Unity.AbstractScope
{
internal HashTable category_map = new HashTable (str_hash, str_equal);
private WindowStackProxy? winproxy = null;
internal WinStack windows = new WinStack ();
internal Dee.ICUTermFilter icu = new Dee.ICUTermFilter.ascii_folder ();
public RunningAppsScope ()
{
init_proxy ();
windows.updated.connect (on_winstack_changed);
populate_category_map ();
}
public override string get_group_name ()
{
return "com.canonical.Unity.Scope.RunningApps";
}
public override string get_unique_name ()
{
return "/com/canonical/unity/scope/runningapps";
}
public override Unity.FilterSet get_filters ()
{
var filters = new Unity.FilterSet ();
/* Type filter */
{
var filter = new CheckOptionFilter ("type", _("Type"));
filter.sort_type = Unity.OptionsFilter.SortType.DISPLAY_NAME;
filter.add_option ("accessories", _("Accessories"));
filter.add_option ("education", _("Education"));
filter.add_option ("game", _("Games"));
filter.add_option ("graphics", _("Graphics"));
filter.add_option ("internet", _("Internet"));
filter.add_option ("fonts", _("Fonts"));
filter.add_option ("office", _("Office"));
filter.add_option ("media", _("Media"));
filter.add_option ("customization", _("Customization"));
filter.add_option ("accessibility", _("Accessibility"));
filter.add_option ("developer", _("Developer"));
filter.add_option ("science-and-engineering", _("Science & engineering"));
filter.add_option ("scopes", _("Search plugins"));
filter.add_option ("system", _("System"));
filters.add (filter);
}
return filters;
}
public override Unity.CategorySet get_categories ()
{
File icon_dir = File.new_for_path (ICON_PATH);
Unity.CategorySet categories = new Unity.CategorySet ();
var cat = new Unity.Category ("recent", _("Recent apps"),
new FileIcon (icon_dir.get_child ("group-apps.svg")));
categories.add (cat);
return categories;
}
public override Unity.Schema get_schema ()
{
var schema = new Unity.Schema ();
return schema;
}
public override string normalize_search_query (string search_query)
{
return search_query.strip ();
}
public override Unity.ScopeSearchBase create_search_for_query (Unity.SearchContext search_context)
{
var search = new RunningAppsSearch (windows, icu, category_map);
search.set_search_context (search_context);
return search;
}
public override Unity.ResultPreviewer create_previewer (Unity.ScopeResult result, Unity.SearchMetadata metadata)
{
return null;
}
public override Unity.ActivationResponse? activate (Unity.ScopeResult result, Unity.SearchMetadata metadata, string? action_id)
{
return new Unity.ActivationResponse (Unity.HandledType.NOT_HANDLED);
}
internal void init_proxy ()
{
debug ("Initializing winstack proxy");
try
{
winproxy = WindowStackProxy.get_proxy ();
// request current windows stack
var winstack = winproxy.get_window_stack_sync ();
winproxy.window_created.connect (windows.on_window_created);
winproxy.window_destroyed.connect (windows.on_window_destroyed);
winproxy.focused_window_changed.connect (windows.on_focused_window_changed);
windows.from_win_stack (winstack);
}
catch (Error e)
{
warning ("Failed to create WindowStackProxy: %s", e.message);
}
}
private void populate_category_map ()
{
category_map["accessories"] = CategoryList ({"Utility"}, {"Accessibility"});
category_map["education"] = CategoryList ({"Education"}, {"Science"});
category_map["game"] = CategoryList ({"Game"}, {});
category_map["graphics"] = CategoryList ({"Graphics"}, {});
category_map["internet"] = CategoryList ({"Network"}, {});
category_map["fonts"] = CategoryList ({"Fonts"}, {});
category_map["office"] = CategoryList ({"Office"}, {});
category_map["media"] = CategoryList ({"AudioVideo"}, {});
category_map["customization"] = CategoryList ({"Settings"}, {});
category_map["accessibility"] = CategoryList ({"Accessibility"}, {"Settings"});
category_map["developer"] = CategoryList ({"Development"}, {});
category_map["science-and-engineering"] = CategoryList ({"Science", "Engineering"}, {});
category_map["system"] = CategoryList ({"System", "Security"}, {});
}
private void on_winstack_changed ()
{
results_invalidated (Unity.SearchType.DEFAULT);
}
}
} ./src/winstack-client.vala 0000644 0000041 0000041 00000006344 12772523363 016017 0 ustar www-data www-data /* -*- mode: vala; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Copyright (C) 2013 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*
*/
namespace Unity.ApplicationsLens {
static const string WINSTACK_DBUS_NAME = "com.canonical.Unity.WindowStack";
static const string WINSTACK_DBUS_PATH = "/com/canonical/Unity/WindowStack";
public struct WindowInfo
{
uint window_id;
string app_id;
bool has_focus;
uint stage;
}
/* Only expose what's required by the scope, e.g. GetAppIdFromPid is not implemented */
[DBus (name = "com.canonical.Unity.WindowStack")]
public interface WindowStackService: GLib.Object
{
public signal void window_created (uint window_id, string app_id);
public signal void window_destroyed (uint window_id, string app_id);
public signal void focused_window_changed (uint window_id, string app_id, uint stage);
public abstract async WindowInfo[] get_window_stack () throws Error;
}
public class WindowStackProxy: GLib.Object
{
public signal void window_created (uint window_id, string app_id);
public signal void window_destroyed (uint window_id, string app_id);
public signal void focused_window_changed (uint window_id, string app_id, uint stage);
private WindowStackProxy ()
{
}
public static WindowStackProxy get_proxy () throws Error
{
var proxy = new WindowStackProxy ();
proxy.service = Bus.get_proxy_sync (BusType.SESSION, WINSTACK_DBUS_NAME, WINSTACK_DBUS_PATH);
proxy.service.window_created.connect ((win_id, app_id) =>
{
proxy.window_created (win_id, app_id);
});
proxy.service.window_destroyed.connect ((win_id, app_id) =>
{
proxy.window_destroyed (win_id, app_id);
});
proxy.service.focused_window_changed.connect ((win_id, app_id, stage) =>
{
proxy.focused_window_changed (win_id, app_id, stage);
});
return proxy;
}
public async WindowInfo[] get_window_stack () throws Error
{
var res = yield service.get_window_stack();
return res;
}
public WindowInfo[] get_window_stack_sync () throws Error
{
WindowInfo[] win = {};
MainLoop ml = new MainLoop ();
Error? error = null;
service.get_window_stack.begin ((obj, res) =>
{
try
{
win = service.get_window_stack.end (res);
}
catch (Error e)
{
error = e;
}
finally
{
ml.quit ();
}
});
ml.run ();
if (error != null)
throw error;
return win;
}
private WindowStackService service;
}
}
./src/purchase-info-helper.vala 0000644 0000041 0000041 00000004152 12772523363 016733 0 ustar www-data www-data /*
* Copyright (C) 2012 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 .
*
* Authored by Pawel Stolowski
*/
namespace Unity.ApplicationsLens {
class PurchaseInfoHelper
{
public struct AppInfo
{
string formatted_price;
bool paid;
}
private HashTable data;
public PurchaseInfoHelper ()
{
data = new HashTable (str_hash, str_equal);
}
public void from_pkgresults (Unity.Package.SearchResult results)
{
foreach (unowned Unity.Package.PackageInfo pkg in results.results)
{
var app_info = from_pkgresult (pkg);
data.insert (pkg.application_name + "/" + pkg.package_name, app_info);
}
}
private AppInfo from_pkgresult (Unity.Package.PackageInfo pkg)
{
bool purchased = (pkg.price != null && pkg.price != "" && !pkg.needs_purchase);
var app_info = AppInfo ()
{
formatted_price = pkg.price,
paid = purchased
};
return app_info;
}
public GLib.SList create_pkgsearch_query (SoftwareCenterData.AppInfo?[] results)
{
var params = new GLib.SList ();
foreach (var res in results)
{
params.append (res.application_name);
params.append (res.package_name);
}
return params;
}
public AppInfo? find (string application_name, string package_name)
{
string key = application_name + "/" + package_name;
if (data.contains (key))
{
return data[key];
}
return null;
}
}
} ./autogen.sh 0000755 0000041 0000041 00000000307 12772523363 013256 0 ustar www-data www-data #!/bin/sh
srcdir=`dirname $0`
PKG_NAME="unity-place-applications"
which gnome-autogen.sh || {
echo "You need gnome-common from GNOME SVN"
exit 1
}
USE_GNOME2_MACROS=1 \
. gnome-autogen.sh "$@"
./vapi/ 0000755 0000041 0000041 00000000000 12772523363 012214 5 ustar www-data www-data ./vapi/unity-package-search.deps 0000644 0000041 0000041 00000000052 12772523363 017072 0 ustar www-data www-data glib-2.0
libgnome-menu-3.0
unity-protocol
./vapi/unity-ratings-db.deps 0000644 0000041 0000041 00000000022 12772523363 016263 0 ustar www-data www-data glib-2.0
gio-2.0
./vapi/unity-package-search.vapi 0000644 0000041 0000041 00000004763 12772523363 017113 0 ustar www-data www-data /* unity-package-search.vapi hand crafted by Mikkel Kamstrup Erlandsen */
[CCode (cprefix = "Unity", lower_case_cprefix = "unity_", cheader_filename = "unity-package-search.h")]
namespace Unity {
[CCode (cprefix = "UnityPackage", lower_case_cprefix = "unity_package_")]
namespace Package {
[CCode (cprefix = "UNITY_PACKAGE_SEARCHTYPE_", has_type_id = false, cheader_filename = "unity-package-search.h")]
public enum SearchType {
PREFIX,
EXACT
}
[CCode (cprefix = "UNITY_PACKAGE_SORT_", has_type_id = false, cheader_filename = "unity-package-search.h")]
public enum Sort {
BY_NAME,
BY_RELEVANCY
}
public delegate bool AppFilterCallback (PackageInfo pkginfo);
[Compact]
[CCode (free_function = "unity_package_searcher_free", cheader_filename = "unity-package-search.h")]
public class Searcher {
[CCode (cname = "unity_package_searcher_new")]
public Searcher ();
[CCode (cname = "unity_package_searcher_new_for_menu")]
public Searcher.for_menu(GMenu.Tree menu);
[CCode (cname = "unity_package_searcher_new_for_scopes")]
public Searcher.for_scopes(Unity.Protocol.ScopeRegistry scope_registry);
public SearchResult search (string search_string, uint max_hits, Unity.Package.SearchType search_type, Unity.Package.Sort sort);
public SearchResult get_random_apps (string? filter_query, uint n_apps);
public SearchResult get_apps (string? filter_query, uint n_apps, AppFilterCallback cb);
public SearchResult get_by_exact_names (GLib.SList names);
public PackageInfo? get_by_desktop_file (string desktop_file);
}
[Compact]
[CCode (free_function = "unity_package_search_result_free", cheader_filename = "unity-package-search.h")]
public class SearchResult {
[CCode (cname="unity_package_search_result_new")]
public SearchResult ();
public GLib.SList results;
public int num_hits;
public bool fuzzy_search;
}
[Compact]
[CCode (cname = "UnityPackageInfo", free_function = "unity_package_package_info_free", cheader_filename = "unity-package-search.h")]
public class PackageInfo {
public PackageInfo ();
public string package_name;
public string application_name;
public string description;
public string desktop_file;
public string icon;
public string price;
public bool needs_purchase;
public int relevancy;
public bool is_master_scope;
}
}
}
./vapi/unity-ratings-db.vapi 0000644 0000041 0000041 00000001437 12772523363 016302 0 ustar www-data www-data /* unity-ratings-db.vapi hand crafted by Mikkel Kamstrup Erlandsen */
[CCode (cprefix = "Unity", lower_case_cprefix = "unity_", cheader_filename = "unity-ratings-db.h")]
namespace Unity {
[CCode (cprefix = "UnityRatings", lower_case_cprefix = "unity_ratings_")]
namespace Ratings {
[CCode (cheader_filename = "unity-ratings-db.h")]
public struct Result {
public int32 average_rating;
public int32 total_rating;
public int32 dampened_rating;
}
[Compact]
[CCode (free_function = "unity_ratings_database_free", cheader_filename = "unity-ratings-db.h")]
public class Database {
[CCode (cname = "unity_ratings_database_new")]
public Database () throws GLib.FileError;
public bool query (string pkgname, out Result result);
}
}
}
./ChangeLog 0000644 0000041 0000041 00000000000 12772523363 013015 0 ustar www-data www-data ./HACKING 0000644 0000041 0000041 00000000001 12772523363 012233 0 ustar www-data www-data
./Makefile.am.coverage 0000644 0000041 0000041 00000002505 12772523363 015105 0 ustar www-data www-data
# Coverage targets
.PHONY: clean-gcno clean-gcda \
coverage-html generate-coverage-html clean-coverage-html \
coverage-gcovr generate-coverage-gcovr clean-coverage-gcovr
clean-local: clean-gcno clean-coverage-html clean-coverage-gcovr
if HAVE_GCOV
clean-gcno:
@echo Removing old coverage instrumentation
-find -name '*.gcno' -print | xargs -r rm
clean-gcda:
@echo Removing old coverage results
-find -name '*.gcda' -print | xargs -r rm
coverage-html: clean-gcda
-$(MAKE) $(AM_MAKEFLAGS) -k check
$(MAKE) $(AM_MAKEFLAGS) generate-coverage-html
generate-coverage-html:
@echo Collecting coverage data
$(LCOV) --directory $(top_builddir) --capture --output-file coverage.info --no-checksum --compat-libtool
LANG=C $(GENHTML) --prefix $(top_builddir) --output-directory coveragereport --title "Code Coverage" --legend --show-details coverage.info
clean-coverage-html: clean-gcda
-$(LCOV) --directory $(top_builddir) -z
-rm -rf coverage.info coveragereport
if HAVE_GCOVR
coverage-gcovr: clean-gcda
-$(MAKE) $(AM_MAKEFLAGS) -k check
$(MAKE) $(AM_MAKEFLAGS) generate-coverage-gcovr
generate-coverage-gcovr:
@echo Generating coverage GCOVR report
$(GCOVR) -x -r $(top_builddir) -o $(top_builddir)/coverage.xml
clean-coverage-gcovr: clean-gcda
-rm -rf $(top_builddir)/coverage.xml
endif # HAVE_GCOVR
endif # HAVE_GCOV
./tests/ 0000755 0000041 0000041 00000000000 12772523363 012417 5 ustar www-data www-data ./tests/test-no-partial-commands.sh 0000755 0000041 0000041 00000000667 12772523363 017611 0 ustar www-data www-data #!/bin/sh
# Search for "modpro", print the results, this search should only include
# "modprobe", not "modpro" itself
test `unity-tool -n com.canonical.Unity.Lens.Applications -p /com/canonical/unity/lens/commands -s "modpro" --no-search-reply -r | grep "modpro" | wc -l` -eq `unity-tool -n com.canonical.Unity.Lens.Applications -p /com/canonical/unity/lens/commands -s "modpro" --no-search-reply -r | grep "modprobe" | wc -l` || exit 1
./tests/test-full-and-partial.sh 0000755 0000041 0000041 00000000667 12772523363 017100 0 ustar www-data www-data #!/bin/sh
# Search for "ls", print the results, this search should only include both
# "ls", not "ls.+"
test `unity-tool -n com.canonical.Unity.Lens.Applications -p /com/canonical/unity/lens/commands -s "ls" --no-search-reply -r | grep "\\" | wc -l` -eq 1 || exit 1
test `unity-tool -n com.canonical.Unity.Lens.Applications -p /com/canonical/unity/lens/commands -s "ls" --no-search-reply -r | grep "\\