./0000755000004100000410000000000012772523363011255 5ustar www-datawww-data./Makefile.decl0000644000004100000410000000540712772523363013631 0ustar www-datawww-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 ./NEWS0000644000004100000410000000171612772523363011761 0ustar www-datawww-data2010-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.m40000644000004100000410000000170712772523363013453 0ustar www-datawww-datadnl 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.ac0000644000004100000410000001470512772523363013552 0ustar www-datawww-dataAC_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} ]) ./README0000644000004100000410000000000012772523363012123 0ustar www-datawww-data./TESTS-TODO.txt0000644000004100000410000000102112772523363013455 0ustar www-datawww-dataSince 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. ./COPYING0000644000004100000410000010437412772523363012321 0ustar www-datawww-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/0000755000004100000410000000000012772523373012045 5ustar www-datawww-data./src/software-center-data-cache.vala0000644000004100000410000000463212772523363017776 0ustar www-datawww-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.vala0000644000004100000410000001122112772523363015121 0ustar www-datawww-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.vala0000644000004100000410000000561712772523363015126 0ustar www-datawww-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.vala0000644000004100000410000000447612772523363017172 0ustar www-datawww-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.h0000644000004100000410000000716612772523363016233 0ustar www-datawww-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.vala0000644000004100000410000000527712772523363015521 0ustar www-datawww-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.h0000644000004100000410000000311612772523363015416 0ustar www-datawww-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.vala0000644000004100000410000001270512772523363016602 0ustar www-datawww-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.vala0000644000004100000410000016357512772523363014175 0ustar www-datawww-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.vala0000644000004100000410000000512412772523363020562 0ustar www-datawww-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.c0000644000004100000410000001302712772523363015413 0ustar www-datawww-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.vala0000644000004100000410000001111412772523363015325 0ustar www-datawww-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.in0000644000004100000410000000050212772523363014560 0ustar www-datawww-datanamespace 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.vala0000644000004100000410000004170012772523363015316 0ustar www-datawww-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.vala0000644000004100000410000003735112772523363015632 0ustar www-datawww-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.vala0000644000004100000410000000222112772523363014331 0ustar www-datawww-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.vala0000644000004100000410000000675012772523363020232 0ustar www-datawww-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.vala0000644000004100000410000000333712772523363015774 0ustar www-datawww-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.vala0000644000004100000410000001640012772523363014052 0ustar www-datawww-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.am0000644000004100000410000000645612772523363014113 0ustar www-datawww-dataNULL = 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.cc0000644000004100000410000010071612772523363016364 0ustar www-datawww-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.vala0000644000004100000410000000302212772523373013633 0ustar www-datawww-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.vala0000644000004100000410000001521212772523363016442 0ustar www-datawww-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.vala0000644000004100000410000000634412772523363016017 0ustar www-datawww-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.vala0000644000004100000410000000415212772523363016733 0ustar www-datawww-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.sh0000755000004100000410000000030712772523363013256 0ustar www-datawww-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/0000755000004100000410000000000012772523363012214 5ustar www-datawww-data./vapi/unity-package-search.deps0000644000004100000410000000005212772523363017072 0ustar www-datawww-dataglib-2.0 libgnome-menu-3.0 unity-protocol ./vapi/unity-ratings-db.deps0000644000004100000410000000002212772523363016263 0ustar www-datawww-dataglib-2.0 gio-2.0 ./vapi/unity-package-search.vapi0000644000004100000410000000476312772523363017113 0ustar www-datawww-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.vapi0000644000004100000410000000143712772523363016302 0ustar www-datawww-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); } } } ./ChangeLog0000644000004100000410000000000012772523363013015 0ustar www-datawww-data./HACKING0000644000004100000410000000000112772523363012233 0ustar www-datawww-data ./Makefile.am.coverage0000644000004100000410000000250512772523363015105 0ustar www-datawww-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/0000755000004100000410000000000012772523363012417 5ustar www-datawww-data./tests/test-no-partial-commands.sh0000755000004100000410000000066712772523363017611 0ustar www-datawww-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.sh0000755000004100000410000000066712772523363017100 0ustar www-datawww-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 "\\. # # Authored by Pawel Stolowski # # # This is a simple simulator/mock of com.canonical.Unity.WindowStack DBus service, # meant for testing of unity-scope-runningapps. It doesn't implement all the API calls - # only what's needed by the scope. # # Usage: # - to run indefinitely, with window events every 2 secs. # ./mock-winstack.py # # - to run with specific number of simulation steps and given interval: # ./mock-winstack.py # (where interval is in seconds; use steps = 0 for infinity). # import dbus import dbus.service import sys from dbus.mainloop.glib import DBusGMainLoop from gi.repository import GLib, GObject WINSTACK_DBUS_IFACE = "com.canonical.Unity.WindowStack" WINSTACK_DBUS_NAME = "com.canonical.Unity.WindowStack" WINSTACK_DBUS_PATH = "/com/canonical/Unity/WindowStack" START = 0 FOCUS = 1 CLOSE = 2 APP_WEB = 'org.mozilla.firefox' APP_EDITOR = 'org.gnome.gedit' APP_NOTES = 'com.canonical.notes' APP_GALLERY = 'com.canonical.gallery' main_loop = GLib.MainLoop() class WinStackSim (GObject.GObject): __gsignals__ = { 'window_created': (GObject.SIGNAL_RUN_FIRST, None, (int, str,)), 'window_destroyed': (GObject.SIGNAL_RUN_FIRST, None, (int, str,)), 'focused_window_changed': (GObject.SIGNAL_RUN_FIRST, None, (int, str, int)) } # # window events to be generated in every simulation step; # every step contains at least one event. _SIM_STEPS = ( ( (START, APP_WEB), (START, APP_NOTES), (FOCUS, APP_WEB) ), ( (START, APP_EDITOR), ), ( (FOCUS, APP_NOTES), ), ( (FOCUS, APP_WEB), ), ( (CLOSE, APP_WEB), (FOCUS, APP_NOTES) ), ( (CLOSE, APP_NOTES), ), ( (START, APP_GALLERY), (FOCUS, APP_GALLERY) ), ( (FOCUS, APP_EDITOR), ), ( (CLOSE, APP_EDITOR), (FOCUS, APP_GALLERY), (CLOSE, APP_GALLERY) ) # make sure that the last step leaves window stack in a state # that makes sense when all the steps are repeated # in infinite loop. ) def __init__(self): GObject.GObject.__init__(self) self._windows = [] self._total_step = 0 self._sim_step = 0 self._steps = 0 self._focused = None def start_sim(self, interval_secs, steps = 0): self._sim_step = 0 self._steps = steps GLib.timeout_add_seconds(interval_secs, self.do_sim_step) def do_sim_step(self): sim_data = self._SIM_STEPS[self._sim_step] for s in sim_data: if s[0] == START: self.emit('window_created', 0, s[1]) self._windows.append(s[1]) elif s[0] == CLOSE: self.emit('window_destroyed', 0, s[1]) self._windows.remove(s[1]) elif s[0] == FOCUS: self._focused = s[1] self.emit('focused_window_changed', 0, s[1], 0) self._total_step += 1 self._sim_step = (self._sim_step + 1) % len(self._SIM_STEPS) if self._steps > 0 and self._total_step >= self._steps: main_loop.quit() return True def get_window_stack(self): return [(0, win, self._focused == win, 0) for win in self._windows] class WinStackServiceMock (dbus.service.Object): def __init__(self, sim): dbus.service.Object.__init__(self) self._sim = sim self._sim.connect('window_created', self.on_window_created) self._sim.connect('window_destroyed', self.on_window_destroyed) self._sim.connect('focused_window_changed', self.on_focused_window_changed) bus_name = dbus.service.BusName(WINSTACK_DBUS_NAME, bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, WINSTACK_DBUS_PATH) def on_window_created(self, sim, window_id, app_id): self.WindowCreated(window_id, app_id) def on_window_destroyed(self, sim, window_id, app_id): self.WindowDestroyed(window_id, app_id) def on_focused_window_changed(self, sim, window_id, app_id, stage): self.FocusedWindowChanged(window_id, app_id, stage) @dbus.service.signal(dbus_interface=WINSTACK_DBUS_IFACE, signature='us') def WindowCreated(self, window_id, app_id): pass @dbus.service.signal(dbus_interface=WINSTACK_DBUS_IFACE, signature='us') def WindowDestroyed(self, window_id, app_id): pass @dbus.service.signal(dbus_interface=WINSTACK_DBUS_IFACE, signature='usu') def FocusedWindowChanged(self, window_id, app_id, stage): pass @dbus.service.method(WINSTACK_DBUS_NAME, out_signature='a(usbu)') def GetWindowStack(self): return self._sim.get_window_stack() ##################################################### main ####################################################### interval = 2 steps = 0 if len(sys.argv) > 2: (interval, steps) = int(sys.argv[1]), int(sys.argv[2]) print("Starting WinStack mock service with interval = %d and %s simulation steps" % (interval, steps if steps > 0 else 'unlimited')) sim = WinStackSim() DBusGMainLoop(set_as_default=True) myservice = WinStackServiceMock(sim) sim.start_sim(interval, steps) main_loop.run() ./tests/manual/0000755000004100000410000000000012772523363013674 5ustar www-datawww-data./tests/manual/apps-lens-tests.txt0000644000004100000410000000737412772523363017512 0ustar www-datawww-dataApplication lens sort order --------------------------- Tests that the sort order of the "Installed" category is alphabetical. Setup: At least default ubuntu applications installed. Actions: Open the Dash and switch to the application lens. Make sure that the search string is empty. Expected Result: The "Installed" category should be shown and the items within should be sorted alphabetically (respecting sorting of your locale). Search for applications with CamelCase names -------------------------------------------- Searching for applications should work by searching for the whole name of a CamelCase application as well as with any part of the Camel name. Setup: At least default ubuntu applications installed. Actions: Open the Dash and switch to the application lens. Search for an application with CamelCase name (for example "AisleRiot"). Expected Result: The search has to find the application when searching both "aisleriot" as well as "aisle" or "riot". Prices for search results ------------------------ Price ribbon in search results and Buy/Free Download button correctly reflects application price. Setup: Software-Center cache is updated (launch Software-Center at least once). Actions: 1. Spot some commercial non-free apps as some free open-source apps in the app lens earch results. 2. Right-click an app to activate its preview (repeat for commercial and free apps). Expected Result: Open-source free applications display 'Free' string in ribbons in the search results. Their previews should have 'Developer site' and 'Free Download' buttons. Commercial apps should have the price displayed in ribbons (e.g. 'US$ 8.40'). Their previews should have 'Developer site' and 'Buy US$ ...' buttons. Test updates to gnome menu structure ------------------------------------ Check that adding/removing applications updates applications lens contents. Setup: At least default ubuntu applications installed. Actions: Open the Dash and switch to the application lens. Right-click one of free apps listed in 'More suggestions' category and install it via its preview. Open the Dash and switch to the application lens again. Expected Result: 'Recently used', 'Installed', 'More suggestions' categories are displayed. The new application is listed in the 'Installed' category (note: this may take a few seconds after installation finished). Preview activation ------------------ LMB activates an application preview for installable/purchasable applications. Setup: Software-Center cache is updated (launch Software-Center at least once). Actions: 1. Left-click an application from 'More suggestions' category of Applications Lens. Expected Result: Application preview is displayed in the Dash, with buttons to download/buy the application and visit developer's site (may not always be present if not available). Preview activation (RMB) ------------------------ RMB activates an application preview for all categories of applications (Installed/Recently used/More suggestions). Setup: Software-Center cache is updated (launch Software-Center at least once). Actions: 1. Right-click an application in any of the Applications Lens categories. Expected Result: Application preview is displayed in the Dash, with buttons to download/buy the application and visit developer's site (may not always be present if not available) for installable apps or Uninstall/Launch for installed apps (Uninstall may not be available for some important base packages). Starting applications --------------------- LMB starts an application from Recently used/Installed category. Setup: Software-Center cache is updated (launch Software-Center at least once). Actions: 1. Left-click an application from 'Installed' or 'Recently used' category of Applications Lens. Expected Result: Application gets started and Dash hides. ./tests/manual/fuzzy-search-test.txt0000644000004100000410000000153512772523363020050 0ustar www-datawww-dataFuzzy searching in the Dash --------------------------- Tests that fuzzy matching works in the Dash. Actions: Tap super. Enter an application name that is slightly misspelled. Check that the Dash. returns valid replies. Examples: fimp -> Gimp fierfox -> Firefox sttings -> settings Fuzzy searching in the app lens ------------------------------- Tests that fuzzy matching works in the app lens. Actions: Tap super. Select app lens. Do the same searches as in the previous test. Check that they return the same results. Searching with filters ---------------------- When filters are enabled, the search falls back to non-fuzzy mode. Actions: Tap super. Select app lens. Enable filters, activate "graphics". Type "fimp" in search field, Gimp should not be show in the results. Type "gimp" in search field, Gimp should be shown in the results. ./tests/test-keyword-relevancy.sh0000755000004100000410000000055712772523363017414 0ustar www-datawww-data#!/bin/sh # This test is pretty flaky, feel free to remove if it starts failing... :( # Search for display, print the results, make sure first is: # gnome-display-panel.desktop unity-tool -n com.canonical.Unity.Lens.Applications -p /com/canonical/unity/lens/applications -s "display" --no-search-reply -r | head -n1 | grep -q gnome-display-panel.desktop || exit 1 ./tests/unit/0000755000004100000410000000000012772523363013376 5ustar www-datawww-data./tests/unit/test-software-center-app-details.vala0000644000004100000410000001032412772523363022531 0ustar www-datawww-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 static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/AppDetailsCtor", test_app_details_ctor); Test.add_data_func ("/Unit/AppDetailsPkgStates", test_app_details_pkg_states); Test.run (); return 0; } internal HashTable create_sc_app_details_data () { var data = new HashTable (str_hash, str_equal); data.insert ("name", "Foo"); data.insert ("summary", "Foobar application"); data.insert ("description", "Completly useless application"); data.insert ("version", "1.0"); var bld = new GLib.VariantBuilder (new VariantType ("aa{sv}")); bld.open (new VariantType ("a{sv}")); bld.add ("{sv}", "large_image_url", new Variant.string ("http://foo-bar.org/screenshot.png")); bld.add ("{sv}", "small_image_url", new Variant.string ("http://foo-bar.org/screenshot_small.png")); bld.close (); data.insert ("screenshots", bld.end ()); data.insert ("signing_key_id", ""); data.insert ("region_requirements_satisfied", true); data.insert ("desktop_file", "foo.desktop"); data.insert ("license", "GPL"); data.insert ("icon_file_name", "foo.png"); data.insert ("icon_url", "http://foo-bar.org/icon.png"); data.insert ("price", "1 EUR"); data.insert ("raw_price", "1"); data.insert ("installation_date", "01-01-2012"); data.insert ("website", "http://foo-bar.org"); data.insert ("hardware_requirements", "PC"); data.insert ("size", "10000"); data.insert ("is_desktop_dependency", true); data.insert ("pkg_state", "installed"); return data; } internal static void test_app_details_ctor () { var data = create_sc_app_details_data (); var app_details = new SoftwareCenterData.AppDetailsData (data); assert (app_details.name == "Foo"); assert (app_details.summary == "Foobar application"); assert (app_details.description == "Completly useless application"); assert (app_details.version == "1.0"); assert (app_details.screenshot == "http://foo-bar.org/screenshot.png"); assert (app_details.desktop_file == "foo.desktop"); assert (app_details.license == "GPL"); assert (app_details.icon == "foo.png"); assert (app_details.icon_url == "http://foo-bar.org/icon.png"); assert (app_details.price == "1 EUR"); assert (app_details.raw_price == "1"); assert (app_details.installation_date == "01-01-2012"); assert (app_details.website == "http://foo-bar.org"); assert (app_details.size == 10000); assert (app_details.hardware_requirements == "PC"); assert (app_details.is_desktop_dependency == true); assert (app_details.pkg_state == SoftwareCenterData.PackageState.INSTALLED); } internal static void test_app_details_pkg_states () { var data = create_sc_app_details_data (); var app_details = new SoftwareCenterData.AppDetailsData (data); assert (app_details.pkg_state == SoftwareCenterData.PackageState.INSTALLED); data.replace ("pkg_state", "uninstalled"); app_details = new SoftwareCenterData.AppDetailsData (data); assert (app_details.pkg_state == SoftwareCenterData.PackageState.UNINSTALLED); data.replace ("pkg_state", "needs_purchase"); app_details = new SoftwareCenterData.AppDetailsData (data); assert (app_details.pkg_state == SoftwareCenterData.PackageState.NEEDS_PURCHASE); data.replace ("pkg_state", ""); app_details = new SoftwareCenterData.AppDetailsData (data); assert (app_details.pkg_state == SoftwareCenterData.PackageState.UNKNOWN); } }./tests/unit/software-center-data-provider-mock.vala0000644000004100000410000000334212772523363023043 0ustar www-datawww-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 SoftwareCenterDataProviderProxy: GLib.Object { private HashTable> data; public SoftwareCenterDataProviderProxy () { data = new HashTable> (str_hash, str_equal); data["unity-top-rated"] = new Gee.ArrayList (); data["unity-whats-new"] = new Gee.ArrayList (); } public void mock_add (string category, string appname, string pkgname) { var app = SoftwareCenterData.AppInfo () { application_name = appname, package_name = pkgname, icon = null, desktop_file = null }; data[category].add (app); } public void mock_clear (string category) { data[category].clear (); } public virtual async SoftwareCenterData.AppInfo?[] get_items_for_category (string category_name) throws Error { return data[category_name].to_array (); } } } ./tests/unit/test-software-center-utils.vala0000644000004100000410000000352112772523363021467 0ustar www-datawww-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 static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/DesktopIdLookupWithMangling", test_desktop_file_lookup_with_unmangling); Test.add_data_func ("/Unit/DesktopIdLookupWithoutMangling", test_desktop_file_lookup_without_unmangling); Test.run (); return 0; } internal static void test_desktop_file_lookup_with_unmangling () { var lookup = new SoftwareCenterUtils.MangledDesktopFileLookup (); string desktop_file = "/foo/bar/kde4:kde4__KCharSelect.desktop"; var result = lookup.extract_desktop_id (desktop_file, true /* unmangle */); assert (result == "kde4-KCharSelect.desktop"); assert (lookup.contains (result) == true); assert (lookup.get (result) == "kde4__KCharSelect.desktop"); } internal static void test_desktop_file_lookup_without_unmangling () { var lookup = new SoftwareCenterUtils.MangledDesktopFileLookup (); string desktop_file = "/foo/bar/evince.desktop"; var result = lookup.extract_desktop_id (desktop_file, false); assert (result == "evince.desktop"); assert (lookup.contains (result) == false); } }./tests/unit/test-xapian-utils.vala0000644000004100000410000001520612772523363017642 0ustar www-datawww-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 static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/EmptySearchQuery", test_empty_search_query); Test.add_data_func ("/Unit/EmptySearchWithSingleCategoryFilter", test_empty_search_with_single_cat_filter); Test.add_data_func ("/Unit/EmptySearchWithMultipleCategoryFilter", test_empty_search_with_multi_cat_filter); Test.add_data_func ("/Unit/SearchQueryWithNoFilters", test_search_query_no_filters); Test.add_data_func ("/Unit/SearchQueryWithSingleCategoryFilter", test_search_query_with_single_cat_filter); Test.add_data_func ("/Unit/SearchQueryWithMultipleCategoryFilter", test_search_query_with_multi_cat_filter); Test.add_data_func ("/Unit/ZgEmptySearchQuery", test_zg_empty_search_query); Test.add_data_func ("/Unit/ZgEmptySearchWithSingleCategoryFilter", test_zg_empty_search_with_single_cat_filter); Test.add_data_func ("/Unit/ZgEmptySearchWithMultipleCategoryFilter", test_zg_empty_search_with_multi_cat_filter); Test.add_data_func ("/Unit/ZgSearchQuery", test_zg_search_query_no_filters); Test.add_data_func ("/Unit/ZgSearchQueryWithSingleCategoryFilter", test_zg_search_query_with_single_cat_filter); Test.add_data_func ("/Unit/ZgSearchQueryWithMultipleCategoryFilter", test_zg_search_query_with_multi_cat_filter); Test.run (); return 0; } internal static void test_empty_search_query () { var query = XapianUtils.prepare_pkg_search_string ("", null); assert (query == "(type:Application OR type:Scope)"); } internal static void test_empty_search_with_single_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null).active = true; filter.add_option ("internet", "Internet", null); var query = XapianUtils.prepare_pkg_search_string ("", filter); assert (query == "(type:Application OR type:Scope) AND (category:AudioVideo)"); } internal static void test_empty_search_with_multi_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null).active = true; filter.add_option ("internet", "Internet", null); filter.add_option ("game", "Game", null).active = true; var query = XapianUtils.prepare_pkg_search_string ("", filter); assert (query == "(type:Application OR type:Scope) AND (category:Game OR category:AudioVideo)"); } internal static void test_search_query_no_filters () { var query = XapianUtils.prepare_pkg_search_string (" foo ", null); assert (query == "(type:Application OR type:Scope) AND foo"); query = XapianUtils.prepare_pkg_search_string ("foo", null); assert (query == "(type:Application OR type:Scope) AND foo"); } internal static void test_search_query_with_single_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("internet", "Internet", null).active = true; var query = XapianUtils.prepare_pkg_search_string ("foo", filter); assert (query == "(type:Application OR type:Scope) AND (category:Network) AND foo"); } internal static void test_search_query_with_multi_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("internet", "Internet", null).active = true; filter.add_option ("game", "Game", null).active = true; var query = XapianUtils.prepare_pkg_search_string ("foo", filter); assert (query == "(type:Application OR type:Scope) AND (category:Game OR category:Network) AND foo"); } internal static void test_zg_empty_search_query () { var query = XapianUtils.prepare_zg_search_string ("", null); assert (query == "NOT category:XYZ"); } internal static void test_zg_empty_search_with_single_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("office", "Office", null).active = true; var query = XapianUtils.prepare_zg_search_string ("", filter); assert (query == "(category:Office)"); } internal static void test_zg_empty_search_with_multi_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("office", "Office", null).active = true; filter.add_option ("customization", "Customization", null).active = true; var query = XapianUtils.prepare_zg_search_string ("", filter); assert (query == "(category:Office OR category:Settings)"); } internal static void test_zg_search_query_no_filters () { var query = XapianUtils.prepare_zg_search_string (" foo ", null); assert (query == "app:(foo*)"); query = XapianUtils.prepare_zg_search_string (" foo*", null); assert (query == "app:(foo*)"); } internal static void test_zg_search_query_with_single_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("internet", "Internet", null).active = true; var query = XapianUtils.prepare_zg_search_string (" foo* ", filter); assert (query == "app:(foo*) AND (category:Network)"); } internal static void test_zg_search_query_with_multi_cat_filter () { var filter = new Unity.CheckOptionFilter ("filter", "Filter"); filter.filtering = true; filter.add_option ("media", "Media", null); filter.add_option ("internet", "Internet", null).active = true; filter.add_option ("game", "Game", null).active = true; var query = XapianUtils.prepare_zg_search_string (" foo* ", filter); assert (query == "app:(foo*) AND (category:Game OR category:Network)"); } } ./tests/unit/test-software-center-data-cache.vala0000644000004100000410000000626612772523363022312 0ustar www-datawww-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 static const string TOP_RATED = "unity-top-rated"; public static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/ItemsForCategoryCache", test_category_cache); Test.run (); return 0; } public bool has_app (SoftwareCenterData.AppInfo?[] items, string appname, string pkgname) { foreach (var item in items) { if (item.application_name == appname && item.package_name == pkgname) return true; } return false; } internal static bool run_with_timeout (MainLoop ml, uint timeout_ms = 5000) { bool timeout_reached = false; var t_id = Timeout.add (timeout_ms, () => { timeout_reached = true; debug ("Timeout reached"); ml.quit (); return false; }); ml.run (); if (!timeout_reached) Source.remove (t_id); return !timeout_reached; } internal static SoftwareCenterData.AppInfo?[] get_items (SoftwareCenterDataCache cache, string category) { var ml = new MainLoop (); SoftwareCenterData.AppInfo?[] items = null; cache.get_items_for_category.begin (category, (obj, result) => { items = cache.get_items_for_category.end (result); ml.quit (); }); assert (run_with_timeout (ml)); return items; } internal static void test_category_cache () { var cache = new SoftwareCenterDataCache (1); // lifetime of cache items = 1s // add items to mock base class cache.mock_add (TOP_RATED, "Evince", "evince"); // at this point items are fetched by cache and kept for 1s var items = get_items (cache, TOP_RATED); assert (items.length == 1); // remove & add new items to the mock, but get_items_for_category should still // return old cached values. cache.mock_clear (TOP_RATED); cache.mock_add (TOP_RATED, "Blender", "blender"); cache.mock_add (TOP_RATED, "Firefox", "firefox"); cache.mock_add (TOP_RATED, "Thunderbird", "thunderbird"); var items_2 = get_items (cache, TOP_RATED); assert (items_2.length == 1); assert (has_app (items_2, "Evince", "evince") == true); // wait 3s for cache items to expire GLib.Thread.usleep (2 * 1000000); // cache will fetch new items now. var items_3 = get_items (cache, TOP_RATED); assert (items_3.length == 3); assert (has_app (items_3, "Blender", "blender") == true); assert (has_app (items_3, "Firefox", "firefox") == true); assert (has_app (items_3, "Thunderbird", "thunderbird") == true); } } ./tests/unit/test-purchase-info-helper.vala0000644000004100000410000000633512772523363021247 0ustar www-datawww-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 static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/Find", test_find); Test.add_data_func ("/Unit/CreatePkgSearchQuery", test_pkgsearch_query); Test.run (); return 0; } public Unity.Package.SearchResult create_search_result () { Unity.Package.SearchResult search_results = new Unity.Package.SearchResult (); var pi = new Unity.Package.PackageInfo (); pi.application_name = "Evince"; pi.package_name = "evince"; pi.needs_purchase = false; search_results.results.append ((owned) pi); pi = new Unity.Package.PackageInfo (); pi.application_name = "Commercial App1"; pi.package_name = "commercial_app1"; pi.price = "10 EUR"; pi.needs_purchase = true; search_results.results.append ((owned) pi); pi = new Unity.Package.PackageInfo (); pi.application_name = "Commercial App2"; pi.package_name = "commercial_app2"; pi.price = "20 EUR"; pi.needs_purchase = false; search_results.results.append ((owned) pi); search_results.num_hits = 3; return search_results; } internal static void test_find () { // populate search results var search_results = create_search_result (); var phelper = new PurchaseInfoHelper (); phelper.from_pkgresults (search_results); assert (phelper.find ("FooApp", "foopkg") == null); var appinfo = phelper.find ("Evince", "evince"); assert (appinfo != null); assert (appinfo.formatted_price == ""); assert (appinfo.paid == false); appinfo = phelper.find ("Commercial App1", "commercial_app1"); assert (appinfo != null); assert (appinfo.formatted_price == "10 EUR"); assert (appinfo.paid == false); appinfo = phelper.find ("Commercial App2", "commercial_app2"); assert (appinfo != null); assert (appinfo.formatted_price == "20 EUR"); assert (appinfo.paid == true); } internal static void test_pkgsearch_query () { SoftwareCenterData.AppInfo?[] data = new SoftwareCenterData.AppInfo?[2] { SoftwareCenterData.AppInfo () { package_name = "evince", application_name = "Evince" }, SoftwareCenterData.AppInfo () { package_name = "skype", application_name = "Skype" } }; var phelper = new PurchaseInfoHelper (); var query = phelper.create_pkgsearch_query (data); assert (query.length () == 4); assert (query.nth_data (0) == "Evince"); assert (query.nth_data (1) == "evince"); assert (query.nth_data (2) == "Skype"); assert (query.nth_data (3) == "skype"); } }./tests/unit/Makefile.am0000644000004100000410000001245112772523363015435 0ustar www-datawww-datainclude $(top_srcdir)/Makefile.decl check_PROGRAMS = \ test-software-center-data-cache \ test-purchase-info-helper \ test-software-center-utils \ test-software-center-details \ test-xapian-utils \ test-utils TEST_PROGS += $(check_PROGRAMS) AM_VALAFLAGS = \ --vapidir $(top_srcdir)/vapi \ --pkg glib-2.0 \ --pkg posix \ --pkg dee-1.0 \ --pkg gio-2.0 \ --pkg gee-0.8 \ --pkg gio-unix-2.0 \ --pkg unity-package-search \ --pkg unity \ --target-glib=2.26 \ $(MAINTAINER_VALAFLAGS) \ $(NULL) UNITY_PACKAGE_SEARCH_LIBS = -lxapian -lstdc++ LDADD = $(LENS_DAEMON_LIBS) \ $(test_libs) \ $(UNITY_PACKAGE_SEARCH_LIBS) LDFLAGS += -rpath $(PROTOCOLPRIVATELIBDIR) AM_CPPFLAGS = \ $(LENS_DAEMON_CFLAGS) \ -I$(srcdir) \ -I$(top_srcdir)/src \ -DGETTEXT_PACKAGE=\"$(GETTEXT_PACKAGE)\" \ -DGMENU_I_KNOW_THIS_IS_UNSTABLE \ $(COVERAGE_CFLAGS) \ $(NULL) if !ENABLE_C_WARNINGS AM_CPPFLAGS += -w endif AM_LDFLAGS = $(COVERAGE_LDFLAGS) test_software_center_data_cache_VALASOURCES = \ test-software-center-data-cache.vala \ $(top_srcdir)/src/software-center-data-cache.vala \ $(top_srcdir)/src/software-center-app-details.vala \ software-center-data-provider-mock.vala \ $(NULL) nodist_test_software_center_data_cache_SOURCES = $(test_software_center_data_cache_VALASOURCES:.vala=.c) test_purchase_info_helper_VALASOURCES = \ test-purchase-info-helper.vala \ $(top_srcdir)/src/purchase-info-helper.vala \ $(top_srcdir)/src/software-center-app-details.vala \ $(top_srcdir)/src/utils.vala \ $(NULL) nodist_test_purchase_info_helper_SOURCES = $(test_purchase_info_helper_VALASOURCES:.vala=.c) test_purchase_info_helper_LDADD = \ $(LDADD) \ unity-package-search.o \ unity-ratings-db.o \ -ldb test_software_center_utils_VALASOURCES = \ test-software-center-utils.vala \ $(top_srcdir)/src/software-center-utils.vala \ $(NULL) nodist_test_software_center_utils_SOURCES = $(test_software_center_utils_VALASOURCES:.vala=.c) test_xapian_utils_VALASOURCES = \ test-xapian-utils.vala \ $(top_srcdir)/src/xapian-utils.vala \ $(top_srcdir)/src/utils.vala \ $(NULL) nodist_test_xapian_utils_SOURCES = $(test_xapian_utils_VALASOURCES:.vala=.c) # Also includes source files that don't have proper tests # so they show up in coverage reports. test_utils_VALASOURCES = \ test-utils.vala \ $(top_srcdir)/src/utils.vala \ $(top_srcdir)/src/app-watcher.vala \ $(top_srcdir)/src/aptd-client.vala \ $(top_srcdir)/src/schemas.vala \ $(top_srcdir)/src/xapian-utils.vala \ $(NULL) nodist_test_utils_SOURCES = $(test_utils_VALASOURCES:.vala=.c) test_software_center_details_VALASOURCES = \ test-software-center-app-details.vala \ $(top_srcdir)/src/software-center-app-details.vala \ $(NULL) nodist_test_software_center_details_SOURCES = $(test_software_center_details_VALASOURCES:.vala=.c) unity-package-search.o : $(top_srcdir)/src/unity-package-search.cc $(top_srcdir)/src/unity-package-search.h $(AM_V_GEN)$(CXX) --std=c++11 -g $(COVERAGE_CFLAGS) $(UNITY_PACKAGE_SEARCH_LIBS) -DGMENU_I_KNOW_THIS_IS_UNSTABLE `pkg-config --cflags --libs glib-2.0 libgnome-menu-3.0 unity gee-0.8 libcolumbus` -c $(top_srcdir)/src/unity-package-search.cc unity-ratings-db.o : $(top_srcdir)/src/unity-ratings-db.c $(top_srcdir)/src/unity-ratings-db.h $(AM_V_CC)$(CC) -g $(COVERAGE_CFLAGS) $(unity_ratings_db_libs) `pkg-config --cflags --libs glib-2.0` -c $(top_srcdir)/src/unity-ratings-db.c CLEANFILES = *.stamp \ $(test_software_center_data_cache_VALASOURCES:.vala=.c) \ $(test_purchase_info_helper_VALASOURCES:.vala=.c) \ $(test_software_center_utils_VALASOURCES:.vala=.c) \ $(test_xapian_utils_VALASOURCES:.vala=.c) \ $(test_utils_VALASOURCES:.vala=.c) \ $(test_software_center_details_VALASOURCES:.vala=.c) \ $(NULL) BUILT_SOURCES = \ test-software-center-data-cache.vala.stamp \ test-purchase-info-helper.vala.stamp \ test-software-center-utils.vala.stamp \ test-software-center-details.vala.stamp \ test-xapian-utils.vala.stamp \ test-utils.vala.stamp \ $(NULL) test-software-center-data-cache.vala.stamp: $(test_software_center_data_cache_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ test-purchase-info-helper.vala.stamp: $(test_purchase_info_helper_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ test-software-center-utils.vala.stamp: $(test_software_center_utils_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ test-software-center-details.vala.stamp: $(test_software_center_details_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ test-xapian-utils.vala.stamp: $(test_xapian_utils_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ test-utils.vala.stamp: $(test_utils_VALASOURCES) $(AM_V_GEN)$(VALAC) -C $(AM_VALAFLAGS) $(VALAFLAGS) $^ @touch $@ # START HEADLESS TESTS if ENABLE_HEADLESS_TESTS DISPLAY = :27 LOG_PATH = headless-logs test-headless: set -e; \ export DISPLAY=$(DISPLAY); \ rm -rf $(LOG_PATH); \ mkdir $(LOG_PATH); \ $(XVFB) $(DISPLAY) -screen 0 1024x768x8 > $(LOG_PATH)/Xvfb.out 2>&1 & \ sleep 1; \ \ $(DBUS_LAUNCH) > $(LOG_PATH)/sessionbus.sh; \ source $(LOG_PATH)/sessionbus.sh; \ sleep 1; \ \ make test; \ sleep 1; \ \ kill `grep DBUS_SESSION_BUS_PID $(LOG_PATH)/sessionbus.sh | grep -oE '[0-9]+'`; \ pkill Xvfb; endif # END HEADLESS TESTS ./tests/unit/test-utils.vala0000644000004100000410000000576612772523363016376 0ustar www-datawww-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 static int main (string[] args) { Test.init (ref args); Test.add_data_func ("/Unit/GetDesktopIdForActor", test_get_desktop_id_for_actor); Test.add_data_func ("/Unit/IsSearchEmpty", test_is_search_empty); Test.add_data_func ("/Unit/PreprocessString", test_preprocess_string); Test.add_data_func ("/Unit/Uncamelcase", test_uncamelcase); Test.add_data_func ("/Unit/SubstTilde", test_subst_tilde); Test.run (); return 0; } internal static void test_get_desktop_id_for_actor () { assert (Utils.get_desktop_id_for_actor ("application://foobar") == "foobar"); assert (Utils.get_desktop_id_for_actor ("app://foobar") == "foobar"); assert (Utils.get_desktop_id_for_actor ("/etc/passwd") == "passwd"); assert (Utils.get_desktop_id_for_actor ("foo.desktop") == "foo.desktop"); assert (Utils.get_desktop_id_for_actor ("foo") == "foo"); } internal static void test_is_search_empty () { assert (Utils.is_search_empty (null) == true); assert (Utils.is_search_empty ("") == true); assert (Utils.is_search_empty (" ") == false); } internal static void test_preprocess_string () { assert (Utils.preprocess_string ("AisleRiot Solitaire") == "AisleRiot Solitaire\nAisle Riot Solitaire"); assert (Utils.preprocess_string ("FooBar") == "FooBar\nFoo Bar"); assert (Utils.preprocess_string ("Foo Bar") == "Foo Bar"); } internal static void test_uncamelcase () { assert (Utils.uncamelcase ("FooBar") == "Foo Bar"); assert (Utils.uncamelcase ("fooBar") == "foo Bar"); assert (Utils.uncamelcase ("Foo Bar") == "Foo Bar"); assert (Utils.uncamelcase ("foobar") == "foobar"); assert (Utils.uncamelcase ("FOoBar") == "FOo Bar"); } internal static void test_subst_tilde () { assert (Utils.subst_tilde ("foo") == "foo"); var home = Environment.get_home_dir (); var path = Utils.subst_tilde ("~"); assert (path == home); path = Utils.subst_tilde ("~/foo/bar.txt"); assert (path == home + "/foo/bar.txt"); // test ~username expansion var username = GLib.Environment.get_user_name (); assert (username.length > 0); // sanity check to ensure we're really testing ~username expansion path = Utils.subst_tilde ("~" + GLib.Environment.get_user_name ()); assert (path == home); } }./po/0000755000004100000410000000000012772523363011673 5ustar www-datawww-data./po/POTFILES.skip0000644000004100000410000000025112772523363014006 0ustar www-datawww-datasrc/main.c src/daemon.c src/utils.c src/commands-scope.c src/scopes-scope.c src/running-apps-search.c src/winstack-client.c src/windows-stack.c src/running-apps-scope.c ./po/POTFILES.in0000644000004100000410000000055512772523363013455 0ustar www-datawww-data[encoding: UTF-8] src/daemon.vala src/commands-scope.vala src/scopes-scope.vala src/utils.vala src/main.vala src/running-apps-scope.vala data/X-Unity-All-Applications.directory.in [type: gettext/ini]data/applications.scope.in.in [type: gettext/ini]data/commands.scope.in.in [type: gettext/ini]data/scopes.scope.in.in [type: gettext/ini]data/runningapps.scope.in.in ./po/LINGUAS0000644000004100000410000000000412772523363012712 0ustar www-datawww-datada ./po/da.po0000644000004100000410000000511512772523363012621 0ustar www-datawww-data# Danish translation for unity-place-applications # Copyright (c) 2010 Rosetta Contributors and Canonical Ltd 2010 # This file is distributed under the same license as the unity-place-applications package. # FIRST AUTHOR , 2010. # msgid "" msgstr "" "Project-Id-Version: unity-place-applications\n" "Report-Msgid-Bugs-To: FULL NAME \n" "POT-Creation-Date: 2010-08-23 21:02+0200\n" "PO-Revision-Date: 2010-08-23 19:45+0000\n" "Last-Translator: Mikkel Kamstrup Erlandsen \n" "Language-Team: Danish \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Launchpad-Export-Date: 2010-08-25 06:44+0000\n" "X-Generator: Launchpad (build Unknown)\n" #: ../src/daemon.vala:223 msgid "All Applications" msgstr "Alle programmer" #: ../src/daemon.vala:225 msgid "Accessories" msgstr "Tilbehør" #: ../src/daemon.vala:227 msgid "Games" msgstr "Spil" #: ../src/daemon.vala:229 msgid "Internet" msgstr "Internet" #: ../src/daemon.vala:231 msgid "Media" msgstr "Medie" #: ../src/daemon.vala:233 msgid "Office" msgstr "Kontor" #: ../src/daemon.vala:235 msgid "System" msgstr "System" #: ../src/daemon.vala:251 msgid "Most Used" msgstr "Mest brugte" #: ../src/daemon.vala:254 msgid "Installed" msgstr "Installeret" #: ../src/daemon.vala:257 msgid "Available" msgstr "Tilgængelig" #: ../src/daemon.vala:774 msgid "You search did not match any applications" msgstr "Ingen programmer matchede din søgning" #: ../src/daemon.vala:784 msgid "Search the web" msgstr "Søg på nettet" #: ../src/daemon.vala:800 ../src/daemon.vala:821 msgid "applications" msgstr "programmer" #: ../src/daemon.vala:803 msgid "accessories" msgstr "tilbehør" #: ../src/daemon.vala:806 msgid "games" msgstr "spil" #: ../src/daemon.vala:809 msgid "internet applications" msgstr "internetprogrammer" #: ../src/daemon.vala:812 msgid "media applications" msgstr "mediaprogrammer" #: ../src/daemon.vala:815 msgid "office applications" msgstr "kontorprogrammer" #: ../src/daemon.vala:818 msgid "system applications" msgstr "systemprogrammer" #: ../src/daemon.vala:830 msgid "There are no $section_name installed on this computer" msgstr "Der er ingen $section_name installeret på denne computer" #: ../src/main.vala:50 msgid "" "Another Applications Place daemon appears to be running.\n" "Bailing out." msgstr "" "Der kører allerede en anden programdæmon.\n" "Afslutter." #: ../src/main.vala:54 #, c-format msgid "" "Error connecting to session bus: %s.\n" "Bailing out." msgstr "" "Fejl ved opkobling til sessionsbus: %s.\n" "Afslutter." ./MAINTAINERS0000644000004100000410000000014412772523363012751 0ustar www-datawww-dataMikkel Kamstrup Erlandsen Michal Hruby ./Makefile.am0000644000004100000410000000162712772523363013317 0ustar www-datawww-dataNULL = SUBDIRS = src data po tests/unit DISTCHECK_CONFIGURE_FLAGS = --enable-localinstall # ChangeLog file created at distcheck time dist-hook: @if test -d "$(srcdir)/.bzr"; \ then \ echo Creating ChangeLog && \ ( cd "$(top_srcdir)" && \ echo '# Generated by Makefile. Do not edit.'; echo; \ $(top_srcdir)/missing --run bzr log --gnu-changelog ) > ChangeLog.tmp \ && mv -f ChangeLog.tmp $(top_distdir)/ChangeLog \ || (rm -f ChangeLog.tmp; \ echo Failed to generate ChangeLog >&2 ); \ else \ echo Failed to generate ChangeLog: not a branch >&2; \ fi EXTRA_DIST = \ autogen.sh \ AUTHORS \ COPYING \ HACKING \ MAINTAINERS \ README \ vapi/unity-package-search.vapi \ vapi/unity-package-search.deps \ vapi/unity-ratings-db.vapi \ vapi/unity-ratings-db.deps \ $(NULL) CLEANFILES = \ $(scope_DATA) \ $(NULL) include $(top_srcdir)/Makefile.am.coverage ./m4/0000755000004100000410000000000012772523363011575 5ustar www-datawww-data./m4/gcov.m40000644000004100000410000000470512772523363013003 0ustar www-datawww-data# Checks for existence of coverage tools: # * gcov # * lcov # * genhtml # * gcovr # # Sets ac_cv_check_gcov to yes if tooling is present # and reports the executables to the variables LCOV, GCOVR and GENHTML. AC_DEFUN([AC_TDD_GCOV], [ AC_ARG_ENABLE(gcov, AS_HELP_STRING([--enable-gcov], [enable coverage testing with gcov]), [use_gcov=$enableval], [use_gcov=no]) if test "x$use_gcov" = "xyes"; then # we need gcc: if test "$GCC" != "yes"; then AC_MSG_ERROR([GCC is required for --enable-gcov]) fi # Check if ccache is being used AC_CHECK_PROG(SHTOOL, shtool, shtool) case `$SHTOOL path $CC` in *ccache*[)] gcc_ccache=yes;; *[)] gcc_ccache=no;; esac if test "$gcc_ccache" = "yes" && (test -z "$CCACHE_DISABLE" || test "$CCACHE_DISABLE" != "1"); then AC_MSG_ERROR([ccache must be disabled when --enable-gcov option is used. You can disable ccache by setting environment variable CCACHE_DISABLE=1.]) fi lcov_version_list="1.6 1.7 1.8 1.9" AC_CHECK_PROG(LCOV, lcov, lcov) AC_CHECK_PROG(GENHTML, genhtml, genhtml) if test "$LCOV"; then AC_CACHE_CHECK([for lcov version], glib_cv_lcov_version, [ glib_cv_lcov_version=invalid lcov_version=`$LCOV -v 2>/dev/null | $SED -e 's/^.* //'` for lcov_check_version in $lcov_version_list; do if test "$lcov_version" = "$lcov_check_version"; then glib_cv_lcov_version="$lcov_check_version (ok)" fi done ]) else lcov_msg="To enable code coverage reporting you must have one of the following lcov versions installed: $lcov_version_list" AC_MSG_ERROR([$lcov_msg]) fi case $glib_cv_lcov_version in ""|invalid[)] lcov_msg="You must have one of the following versions of lcov: $lcov_version_list (found: $lcov_version)." AC_MSG_ERROR([$lcov_msg]) LCOV="exit 0;" ;; esac if test -z "$GENHTML"; then AC_MSG_ERROR([Could not find genhtml from the lcov package]) fi ac_cv_check_gcov=yes ac_cv_check_lcov=yes # Remove all optimization flags from CFLAGS changequote({,}) CFLAGS=`echo "$CFLAGS" | $SED -e 's/-O[0-9]*//g'` changequote([,]) # Add the special gcc flags COVERAGE_CFLAGS="-O0 -fprofile-arcs -ftest-coverage" COVERAGE_CXXFLAGS="-O0 -fprofile-arcs -ftest-coverage" COVERAGE_LDFLAGS="-lgcov" # Check availability of gcovr AC_CHECK_PROG(GCOVR, gcovr, gcovr) if test -z "$GCOVR"; then ac_cv_check_gcovr=no else ac_cv_check_gcovr=yes fi fi ]) # AC_TDD_GCOV ./AUTHORS0000644000004100000410000000022212772523363012321 0ustar www-datawww-dataMikkel Kamstrup Erlandsen Neil Jagdish Patel Michal Hruby ./data/0000755000004100000410000000000012772523363012166 5ustar www-datawww-data./data/com.canonical.Unity.AppsLens.gschema.xml.in.in0000644000004100000410000000202612772523363022667 0ustar www-datawww-data true Display Apps Available for Download in the Applications lens. Display Apps Available for Download in the Applications lens. true Display Recently Used apps in the Applications lens. Display Recently Used Apps in the Applications lens. [] History of Alt + F2 command Key for storing the history of the Alt + F2 command. ./data/applications.png0000644000004100000410000000333312772523363015364 0ustar www-datawww-dataPNG  IHDR00 1 bKGD) oFFsn pHYsHHFk> vpAg54OIDATXõ]W>BEBQ`!q>2,Ł38sP:Й;s`gi HThKTR)Lݳ`<๏=[kՃ91t`} h@gF .@{F++HtJOJlk Ft"J$.0&ϡȇ:i¶L`Ig$HJFP߷&C&A){T)/ beIRNXI"o5D\ PP,kx͇<گ4X?)PW '-,\H2bØER4inynrNJJ5+3k&k",dO%Exղ{iJ4kHff2YbjE k$ChXD!o"59ҬG.s?xRBFFQBPhHd%2fXigӏt|Y#}'ѫ!HOѢ@Itu1q[|H᛼ndBkw%DJH+V Kϸxxк_r?=>g~^{!b!^A*Y-jC.6 V-0Fnh?l (Mw.j~^8 ^n;8 KG7E5IMBi~9,WZy4Sĩ?Jߺ:<_/馮m5 ^TYYGʬtUK] ߋ7x~gz|iz KPm_Pp"pw׸u]ϥm/^.;q`5$¢h1a Kyګ f!X_?Hhemfx睹"PX{k)^(,uJvHcoj({ĦS.^|P0"K l/J]/E:/|F;H* g <*]рK&Mnr-8-LZJH^6h*`.-ycSp7Cz0IkZה,u~%g6 "9&1፸T_A)+@CBw"X͢-Qx]N޶{`ؒ\{c~Q6#W{73vP{v.I_;pCgMoRyndf6%tEXtdate:create2011-03-30T13:14:10+01:00+s%tEXtdate:modify2011-03-24T14:39:49+00:00TXtEXtSoftwareAdobe ImageReadyqe<IENDB`./data/unity-lens-applications.menu.in0000644000004100000410000000746312772523363020266 0ustar www-datawww-data Applications X-GNOME-Menu-Applications.directory /etc/X11/applnk /usr/share/gnome/apps gnomecc.desktop All Applications X-Unity-All-Applications.directory Settings System Screensaver Accessories Utility.directory Utility Accessibility Universal Access Utility-Accessibility.directory Accessibility Settings Developer Tools Development emacs.desktop Education Education.directory Education Science Science & Engineering Science Engineering Games Game.directory Game Graphics Graphics.directory Graphics Internet Network.directory Network Multimedia AudioVideo.directory AudioVideo Office Office.directory Office Themes & Tweaks Settings System System.directory Settings.directory Settings-System.directory System Security gnomecc.desktop ./data/scopes.scope.in.in0000644000004100000410000000120612772523363015526 0ustar www-datawww-data[Scope] DBusName=com.canonical.Unity.Scope.Applications DBusPath=/com/canonical/unity/scope/scopes Module=@libdir@/unity/unity-scope-applications.so ModuleType=C Icon=@prefix@/share/unity/icons/lens-nav-app.svg _Name=Dash plugins _Description=This is an Ubuntu search plugin that enables information from available search plugins to be searched and displayed in the Dash underneath the Dash plugins header. If you do not wish to search this content source, you can disable this search plugin. Type=applications _SearchHint=Search search plugins OptionalMetadata=scope_disabled[u] [Desktop Entry] X-Ubuntu-Gettext-Domain=unity-lens-applications ./data/unity-scope-applications.service.in0000644000004100000410000000024612772523363021122 0ustar www-datawww-data[D-BUS Service] Name=com.canonical.Unity.Scope.Applications Exec=@bindir@/unity-scope-loader applications/applications.scope applications/scopes.scope commands.scope ./data/X-Unity-All-Applications.directory.in0000644000004100000410000000024212772523363021166 0ustar www-datawww-data[Desktop Entry] _Name=All Applications _Comment=All Available Applications Icon=applications-other Type=Directory X-Ubuntu-Gettext-Domain=unity-lens-applications ./data/runningapps.scope.in.in0000644000004100000410000000112012772523363016571 0ustar www-datawww-data[Scope] DBusName=com.canonical.Unity.Scope.Applications DBusPath=/com/canonical/unity/scope/runningapps Module=@libdir@/unity/unity-scope-runningapps.so ModuleType=C Icon= _Name=Running Applications _Description=This is an Ubuntu search plugin that enables information from running applications to be searched and displayed in the Dash underneath the Applications header. If you do not wish to search this content source, you can disable this search plugin. Type=applications _SearchHint=Search running applications Timeout=-1 [Desktop Entry] X-Ubuntu-Gettext-Domain=unity-lens-applications ./data/applications.scope.in.in0000644000004100000410000000116712772523363016726 0ustar www-datawww-data[Scope] DBusName=com.canonical.Unity.Scope.Applications DBusPath=/com/canonical/unity/scope/applications Module=@libdir@/unity/unity-scope-applications.so ModuleType=C Timeout=-1 Icon=@prefix@/share/unity/icons/lens-nav-app.svg _Name=Applications _Description=This is an Ubuntu search plugin that enables information from local applications to be searched and displayed in the Dash underneath the Applications header. If you do not wish to search this content source, you can disable this search plugin. Type=applications _SearchHint=Search applications Shortcut=a [Desktop Entry] X-Ubuntu-Gettext-Domain=unity-lens-applications ./data/commands.scope.in.in0000644000004100000410000000101212772523363016026 0ustar www-datawww-data[Scope] DBusName=com.canonical.Unity.Scope.Applications DBusPath=/com/canonical/unity/scope/commands Module=@libdir@/unity/unity-scope-applications.so ModuleType=C _Name=Commands _Description=This is an Ubuntu search plugin that enables information from local binaries to be searched and displayed in the Dash. If you do not wish to search this content source, you can disable this search plugin. Icon= Type=commands _SearchHint=Run a command Visible=false [Desktop Entry] X-Ubuntu-Gettext-Domain=unity-lens-applications ./data/Makefile.am0000644000004100000410000000371612772523363014231 0ustar www-datawww-data############################################################# # Unity scope files ############################################################# @INTLTOOL_SCOPE_RULE@ %.scope.in: %.scope.in.in sed -e "s|\@prefix\@|$(prefix)|" -e "s|\@libdir\@|$(libdir)|" $< > $@ scope_in_in_files = applications.scope.in.in scopes.scope.in.in commands.scope.in.in scopedir = $(datadir)/unity/scopes scope_DATA = commands.scope appscopedir = $(scopedir)/applications appscope_DATA = applications.scope scopes.scope icondir = $(datadir)/unity/themes icon_DATA = applications.png ############################################################# # DBus service files ############################################################# dbus_servicesdir = $(DBUSSERVICEDIR) service_in_files = unity-scope-applications.service.in dbus_services_DATA = $(service_in_files:.service.in=.service) %.service: %.service.in sed -e "s|\@bindir\@|$(bindir)|" $< > $@ ############################################################# # XDG Menu files ############################################################# @INTLTOOL_DIRECTORY_RULE@ directorydir = $(datadir)/desktop-directories directory_in_files = \ X-Unity-All-Applications.directory directory_DATA = $(directory_in_files:.directory.in=.directory) menudir = $(sysconfdir)/xdg/menus menu_in_files = \ unity-lens-applications.menu.in menu_DATA = $(menu_in_files:.menu.in=.menu) ############################################################# # GSettings schemas ############################################################# gsettings_SCHEMAS = com.canonical.Unity.AppsLens.gschema.xml @INTLTOOL_XML_NOMERGE_RULE@ @GSETTINGS_RULES@ EXTRA_DIST = \ applications.png \ $(scope_in_in_files) \ com.canonical.Unity.AppsLens.gschema.xml.in.in \ $(service_in_files) \ $(directory_in_files) \ $(menu_in_files) CLEANFILES = \ $(scope_DATA) \ $(scope_in_in_files:.scope.in.in=.scope.in) \ unity-scope-applications.service \ $(gsettings_SCHEMAS)