Initial import from the monolithic kde-workspace.

This is the beginning of revision history for this module. If you
want to look at revision history older than this, please refer to the
techbase wiki for how to use Git history grafting. At the time of
writing, this wiki is located here:

http://community.kde.org/Frameworks/GitOldHistory

If you have already performed the grafting and you don't see any
history beyond this commit, try running "git log" with the "--follow"
argument.

Branched from the monolithic repo kde-workspace, frameworks  branch, at commit
049113e719dd2fc4446d054fa1a3aada330094f0
This commit is contained in:
Aleix Pol 2014-03-31 03:48:38 +02:00
commit 88ae0b60b8
845 changed files with 117937 additions and 0 deletions

109
CMakeLists.txt Normal file
View file

@ -0,0 +1,109 @@
project(plasma-desktop)
cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR)
set(QT_MIN_VERSION "5.2.0")
find_package(ECM 0.0.11 REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR})
include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings)
include(ECMInstallIcons)
include(FeatureSummary)
include(CheckIncludeFiles)
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
Quick
DBus
Widgets
X11Extras
Concurrent
)
find_package(KF5 CONFIG REQUIRED COMPONENTS
Plasma
DocTools
I18n
KCMUtils
NewStuff
KDE4Support
NotifyConfig
Su
Runner
)
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
find_package(KDecorations REQUIRED CONFIG)
find_package(LibKWorkspace CONFIG REQUIRED)
find_package(LibTaskManager CONFIG REQUIRED)
find_package(KWinDBusInterface CONFIG REQUIRED)
find_package(ScreenSaverDBusInterface CONFIG REQUIRED)
find_package(KRunnerAppDBusInterface CONFIG REQUIRED)
find_package(KSMServerDBusInterface CONFIG REQUIRED)
endif()
find_package(KF5Activities ${KF5_VERSION})
set_package_properties(KF5Activities PROPERTIES DESCRIPTION "management of Plasma activities"
TYPE OPTIONAL
PURPOSE "Needed by activity related plasmoids and the pager."
)
find_package(USB)
set(HAVE_LIBUSB ${LIBUSB_FOUND})
set_package_properties(USB PROPERTIES DESCRIPTION "User level access to USB devices"
URL "http://libusb.sourceforge.net"
TYPE OPTIONAL
PURPOSE "Provides Logitech mouse support in KControl."
)
find_package(Fontconfig)
set_package_properties(Fontconfig PROPERTIES DESCRIPTION "Font access configuration library"
URL "http://www.freedesktop.org/wiki/Software/fontconfig"
TYPE OPTIONAL
PURPOSE "Needed to build font configuration and installation tools"
)
find_package(X11)
set_package_properties(X11 PROPERTIES DESCRIPTION "X11 libraries"
URL "http://www.x.org"
TYPE OPTIONAL
PURPOSE "Required for building the X11 based workspace"
)
if(X11_FOUND)
find_package(XCB REQUIRED COMPONENTS XCB XFIXES DAMAGE COMPOSITE SHAPE SYNC RENDER RANDR KEYSYMS IMAGE SHM XTEST)
set_package_properties(XCB PROPERTIES TYPE REQUIRED)
find_package(XCB COMPONENTS ICCCM)
add_feature_info("XCB-ICCCM" XCB_ICCCM_FOUND "Required for building test applications for KWin")
endif()
include_directories("${CMAKE_CURRENT_BINARY_DIR}")
include(ConfigureChecks.cmake)
configure_file(config-workspace.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-workspace.h)
configure_file(config-unix.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-unix.h )
configure_file(config-X11.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-X11.h)
set(PLASMADESKTOP_VERSION_MAJOR 4)
set(PLASMADESKTOP_VERSION_MINOR 95)
set(PLASMADESKTOP_VERSION_PATCH 0)
set(PLASMADESKTOP_VERSION ${PLASMADESKTOP_VERSION_MAJOR}.${PLASMADESKTOP_VERSION_MINOR}.${PLASMADESKTOP_VERSION_PATCH} )
set(GENERIC_LIB_SOVERSION ${PLASMADESKTOP_VERSION_MAJOR})
set(GENERIC_LIB_VERSION "${PLASMADESKTOP_VERSION_MAJOR}.${PLASMADESKTOP_VERSION_MINOR}.${PLASMADESKTOP_VERSION_PATCH}")
plasma_install_package(desktoppackage org.kde.desktop plasma/shells shell)
add_subdirectory(doc)
# add_subdirectory(ktouchpadenabler)
# add_subdirectory(solid-actions-kcm)
# add_subdirectory(runners)
add_subdirectory(containments)
add_subdirectory(toolboxes)
add_subdirectory(applets)
add_subdirectory(kcms)
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
endif()

346
COPYING Normal file
View file

@ -0,0 +1,346 @@
NOTE! The GPL below is copyrighted by the Free Software Foundation, but
the instance of code that it refers to (the kde programs) are copyrighted
by the authors who actually wrote it.
---------------------------------------------------------------------------
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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 Library General
Public License instead of this License.

397
COPYING.DOC Normal file
View file

@ -0,0 +1,397 @@
GNU Free Documentation License
Version 1.2, November 2002
Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other
functional and useful document "free" in the sense of freedom: to
assure everyone the effective freedom to copy and redistribute it,
with or without modifying it, either commercially or noncommercially.
Secondarily, this License preserves for the author and publisher a way
to get credit for their work, while not being considered responsible
for modifications made by others.
This License is a kind of "copyleft", which means that derivative
works of the document must themselves be free in the same sense. It
complements the GNU General Public License, which is a copyleft
license designed for free software.
We have designed this License in order to use it for manuals for free
software, because free software needs free documentation: a free
program should come with manuals providing the same freedoms that the
software does. But this License is not limited to software manuals;
it can be used for any textual work, regardless of subject matter or
whether it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that
contains a notice placed by the copyright holder saying it can be
distributed under the terms of this License. Such a notice grants a
world-wide, royalty-free license, unlimited in duration, to use that
work under the conditions stated herein. The "Document", below,
refers to any such manual or work. Any member of the public is a
licensee, and is addressed as "you". You accept the license if you
copy, modify or distribute the work in a way requiring permission
under copyright law.
A "Modified Version" of the Document means any work containing the
Document or a portion of it, either copied verbatim, or with
modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a front-matter section of
the Document that deals exclusively with the relationship of the
publishers or authors of the Document to the Document's overall subject
(or to related matters) and contains nothing that could fall directly
within that overall subject. (Thus, if the Document is in part a
textbook of mathematics, a Secondary Section may not explain any
mathematics.) The relationship could be a matter of historical
connection with the subject or with related matters, or of legal,
commercial, philosophical, ethical or political position regarding
them.
The "Invariant Sections" are certain Secondary Sections whose titles
are designated, as being those of Invariant Sections, in the notice
that says that the Document is released under this License. If a
section does not fit the above definition of Secondary then it is not
allowed to be designated as Invariant. The Document may contain zero
Invariant Sections. If the Document does not identify any Invariant
Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed,
as Front-Cover Texts or Back-Cover Texts, in the notice that says that
the Document is released under this License. A Front-Cover Text may
be at most 5 words, and a Back-Cover Text may be at most 25 words.
A "Transparent" copy of the Document means a machine-readable copy,
represented in a format whose specification is available to the
general public, that is suitable for revising the document
straightforwardly with generic text editors or (for images composed of
pixels) generic paint programs or (for drawings) some widely available
drawing editor, and that is suitable for input to text formatters or
for automatic translation to a variety of formats suitable for input
to text formatters. A copy made in an otherwise Transparent file
format whose markup, or absence of markup, has been arranged to thwart
or discourage subsequent modification by readers is not Transparent.
An image format is not Transparent if used for any substantial amount
of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain
ASCII without markup, Texinfo input format, LaTeX input format, SGML
or XML using a publicly available DTD, and standard-conforming simple
HTML, PostScript or PDF designed for human modification. Examples of
transparent image formats include PNG, XCF and JPG. Opaque formats
include proprietary formats that can be read and edited only by
proprietary word processors, SGML or XML for which the DTD and/or
processing tools are not generally available, and the
machine-generated HTML, PostScript or PDF produced by some word
processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself,
plus such following pages as are needed to hold, legibly, the material
this License requires to appear in the title page. For works in
formats which do not have any title page as such, "Title Page" means
the text near the most prominent appearance of the work's title,
preceding the beginning of the body of the text.
A section "Entitled XYZ" means a named subunit of the Document whose
title either is precisely XYZ or contains XYZ in parentheses following
text that translates XYZ in another language. (Here XYZ stands for a
specific section name mentioned below, such as "Acknowledgements",
"Dedications", "Endorsements", or "History".) To "Preserve the Title"
of such a section when you modify the Document means that it remains a
section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which
states that this License applies to the Document. These Warranty
Disclaimers are considered to be included by reference in this
License, but only as regards disclaiming warranties: any other
implication that these Warranty Disclaimers may have is void and has
no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either
commercially or noncommercially, provided that this License, the
copyright notices, and the license notice saying this License applies
to the Document are reproduced in all copies, and that you add no other
conditions whatsoever to those of this License. You may not use
technical measures to obstruct or control the reading or further
copying of the copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a large enough
number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and
you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have
printed covers) of the Document, numbering more than 100, and the
Document's license notice requires Cover Texts, you must enclose the
copies in covers that carry, clearly and legibly, all these Cover
Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly identify
you as the publisher of these copies. The front cover must present
the full title with all words of the title equally prominent and
visible. You may add other material on the covers in addition.
Copying with changes limited to the covers, as long as they preserve
the title of the Document and satisfy these conditions, can be treated
as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit
legibly, you should put the first ones listed (as many as fit
reasonably) on the actual cover, and continue the rest onto adjacent
pages.
If you publish or distribute Opaque copies of the Document numbering
more than 100, you must either include a machine-readable Transparent
copy along with each Opaque copy, or state in or with each Opaque copy
a computer-network location from which the general network-using
public has access to download using public-standard network protocols
a complete Transparent copy of the Document, free of added material.
If you use the latter option, you must take reasonably prudent steps,
when you begin distribution of Opaque copies in quantity, to ensure
that this Transparent copy will remain thus accessible at the stated
location until at least one year after the last time you distribute an
Opaque copy (directly or through your agents or retailers) of that
edition to the public.
It is requested, but not required, that you contact the authors of the
Document well before redistributing any large number of copies, to give
them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under
the conditions of sections 2 and 3 above, provided that you release
the Modified Version under precisely this License, with the Modified
Version filling the role of the Document, thus licensing distribution
and modification of the Modified Version to whoever possesses a copy
of it. In addition, you must do these things in the Modified Version:
A. Use in the Title Page (and on the covers, if any) a title distinct
from that of the Document, and from those of previous versions
(which should, if there were any, be listed in the History section
of the Document). You may use the same title as a previous version
if the original publisher of that version gives permission.
B. List on the Title Page, as authors, one or more persons or entities
responsible for authorship of the modifications in the Modified
Version, together with at least five of the principal authors of the
Document (all of its principal authors, if it has fewer than five),
unless they release you from this requirement.
C. State on the Title page the name of the publisher of the
Modified Version, as the publisher.
D. Preserve all the copyright notices of the Document.
E. Add an appropriate copyright notice for your modifications
adjacent to the other copyright notices.
F. Include, immediately after the copyright notices, a license notice
giving the public permission to use the Modified Version under the
terms of this License, in the form shown in the Addendum below.
G. Preserve in that license notice the full lists of Invariant Sections
and required Cover Texts given in the Document's license notice.
H. Include an unaltered copy of this License.
I. Preserve the section Entitled "History", Preserve its Title, and add
to it an item stating at least the title, year, new authors, and
publisher of the Modified Version as given on the Title Page. If
there is no section Entitled "History" in the Document, create one
stating the title, year, authors, and publisher of the Document as
given on its Title Page, then add an item describing the Modified
Version as stated in the previous sentence.
J. Preserve the network location, if any, given in the Document for
public access to a Transparent copy of the Document, and likewise
the network locations given in the Document for previous versions
it was based on. These may be placed in the "History" section.
You may omit a network location for a work that was published at
least four years before the Document itself, or if the original
publisher of the version it refers to gives permission.
K. For any section Entitled "Acknowledgements" or "Dedications",
Preserve the Title of the section, and preserve in the section all
the substance and tone of each of the contributor acknowledgements
and/or dedications given therein.
L. Preserve all the Invariant Sections of the Document,
unaltered in their text and in their titles. Section numbers
or the equivalent are not considered part of the section titles.
M. Delete any section Entitled "Endorsements". Such a section
may not be included in the Modified Version.
N. Do not retitle any existing section to be Entitled "Endorsements"
or to conflict in title with any Invariant Section.
O. Preserve any Warranty Disclaimers.
If the Modified Version includes new front-matter sections or
appendices that qualify as Secondary Sections and contain no material
copied from the Document, you may at your option designate some or all
of these sections as invariant. To do this, add their titles to the
list of Invariant Sections in the Modified Version's license notice.
These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains
nothing but endorsements of your Modified Version by various
parties--for example, statements of peer review or that the text has
been approved by an organization as the authoritative definition of a
standard.
You may add a passage of up to five words as a Front-Cover Text, and a
passage of up to 25 words as a Back-Cover Text, to the end of the list
of Cover Texts in the Modified Version. Only one passage of
Front-Cover Text and one of Back-Cover Text may be added by (or
through arrangements made by) any one entity. If the Document already
includes a cover text for the same cover, previously added by you or
by arrangement made by the same entity you are acting on behalf of,
you may not add another; but you may replace the old one, on explicit
permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License
give permission to use their names for publicity for or to assert or
imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this
License, under the terms defined in section 4 above for modified
versions, provided that you include in the combination all of the
Invariant Sections of all of the original documents, unmodified, and
list them all as Invariant Sections of your combined work in its
license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and
multiple identical Invariant Sections may be replaced with a single
copy. If there are multiple Invariant Sections with the same name but
different contents, make the title of each such section unique by
adding at the end of it, in parentheses, the name of the original
author or publisher of that section if known, or else a unique number.
Make the same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History"
in the various original documents, forming one section Entitled
"History"; likewise combine any sections Entitled "Acknowledgements",
and any sections Entitled "Dedications". You must delete all sections
Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents
released under this License, and replace the individual copies of this
License in the various documents with a single copy that is included in
the collection, provided that you follow the rules of this License for
verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute
it individually under this License, provided you insert a copy of this
License into the extracted document, and follow this License in all
other respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate
and independent documents or works, in or on a volume of a storage or
distribution medium, is called an "aggregate" if the copyright
resulting from the compilation is not used to limit the legal rights
of the compilation's users beyond what the individual works permit.
When the Document is included in an aggregate, this License does not
apply to the other works in the aggregate which are not themselves
derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these
copies of the Document, then if the Document is less than one half of
the entire aggregate, the Document's Cover Texts may be placed on
covers that bracket the Document within the aggregate, or the
electronic equivalent of covers if the Document is in electronic form.
Otherwise they must appear on printed covers that bracket the whole
aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may
distribute translations of the Document under the terms of section 4.
Replacing Invariant Sections with translations requires special
permission from their copyright holders, but you may include
translations of some or all Invariant Sections in addition to the
original versions of these Invariant Sections. You may include a
translation of this License, and all the license notices in the
Document, and any Warranty Disclaimers, provided that you also include
the original English version of this License and the original versions
of those notices and disclaimers. In case of a disagreement between
the translation and the original version of this License or a notice
or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements",
"Dedications", or "History", the requirement (section 4) to Preserve
its Title (section 1) will typically require changing the actual
title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except
as expressly provided for under this License. Any other attempt to
copy, modify, sublicense or distribute the Document is void, and will
automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions
of the GNU Free Documentation 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. See
http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number.
If the Document specifies that a particular numbered version of this
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that specified version or
of any later version that has been published (not as a draft) by the
Free Software Foundation. If the Document does not specify a version
number of this License, you may choose any version ever published (not
as a draft) by the Free Software Foundation.
ADDENDUM: How to use this License for your documents
To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and
license notices just after the title page:
Copyright (c) YEAR YOUR NAME.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
replace the "with...Texts." line with this:
with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.
If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License,
to permit their use in free software.

54
ConfigureChecks.cmake Normal file
View file

@ -0,0 +1,54 @@
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH} )
find_program(some_x_program NAMES iceauth xrdb xterm)
if (NOT some_x_program)
set(some_x_program /usr/bin/xrdb)
message(WARNING "Warning: Could not determine X binary directory. Assuming /usr/bin.")
endif (NOT some_x_program)
get_filename_component(proto_xbindir "${some_x_program}" PATH)
get_filename_component(XBINDIR "${proto_xbindir}" ABSOLUTE)
get_filename_component(xrootdir "${XBINDIR}" PATH)
set(XLIBDIR "${xrootdir}/lib/X11")
check_function_exists(getpassphrase HAVE_GETPASSPHRASE)
check_function_exists(vsyslog HAVE_VSYSLOG)
check_function_exists(statvfs HAVE_STATVFS)
check_include_files(limits.h HAVE_LIMITS_H)
check_include_files(sys/time.h HAVE_SYS_TIME_H) # ksmserver, ksplashml, sftp
check_include_files(stdint.h HAVE_STDINT_H) # kcontrol/kfontinst
check_include_files("sys/stat.h;sys/vfs.h" HAVE_SYS_VFS_H) # statvfs for plasma/solid
check_include_files("sys/stat.h;sys/statvfs.h" HAVE_SYS_STATVFS_H) # statvfs for plasma/solid
check_include_files(sys/param.h HAVE_SYS_PARAM_H)
check_include_files("sys/param.h;sys/mount.h" HAVE_SYS_MOUNT_H)
check_include_files("sys/types.h;sys/statfs.h" HAVE_SYS_STATFS_H)
check_include_files(unistd.h HAVE_UNISTD_H)
check_include_files(malloc.h HAVE_MALLOC_H)
check_function_exists(statfs HAVE_STATFS)
macro_bool_to_01(FONTCONFIG_FOUND HAVE_FONTCONFIG) # kcontrol/{fonts,kfontinst}
macro_bool_to_01(FREETYPE_FOUND HAVE_FREETYPE) # kcontrol/fonts
macro_bool_to_01(OPENGL_FOUND HAVE_OPENGL) # kwin
macro_bool_to_01(X11_XShm_FOUND HAVE_XSHM) # kwin, ksplash
macro_bool_to_01(X11_XTest_FOUND HAVE_XTEST) # khotkeys, kxkb, kdm
macro_bool_to_01(X11_Xcomposite_FOUND HAVE_XCOMPOSITE) # kicker, kwin
macro_bool_to_01(X11_Xcursor_FOUND HAVE_XCURSOR) # many uses
macro_bool_to_01(X11_Xdamage_FOUND HAVE_XDAMAGE) # kwin
macro_bool_to_01(X11_Xfixes_FOUND HAVE_XFIXES) # klipper, kicker, kwin
macro_bool_to_01(X11_Xinerama_FOUND HAVE_XINERAMA)
macro_bool_to_01(X11_Xrandr_FOUND HAVE_XRANDR) # kwin
macro_bool_to_01(X11_Xrender_FOUND HAVE_XRENDER) # kcontrol/style, kicker
macro_bool_to_01(X11_xf86misc_FOUND HAVE_XF86MISC) # kdesktop and kcontrol/lock
macro_bool_to_01(X11_dpms_FOUND HAVE_DPMS) # kdesktop
macro_bool_to_01(X11_XSync_FOUND HAVE_XSYNC) # kwin
set(CMAKE_EXTRA_INCLUDE_FILES sys/socket.h)
check_function_exists(getpeereid HAVE_GETPEEREID) # kdesu
check_function_exists(setpriority HAVE_SETPRIORITY) # kscreenlocker
set(CMAKE_REQUIRED_INCLUDES ${X11_Xrandr_INCLUDE_PATH}/Xrandr.h)
set(CMAKE_REQUIRED_LIBRARIES ${X11_Xrandr_LIB})
check_function_exists(XRRGetScreenSizeRange XRANDR_1_2_FOUND)
macro_bool_to_01(XRANDR_1_2_FOUND HAS_RANDR_1_2)
check_function_exists(XRRGetScreenResourcesCurrent XRANDR_1_3_FOUND)
macro_bool_to_01(XRANDR_1_3_FOUND HAS_RANDR_1_3)

21
HACKING Normal file
View file

@ -0,0 +1,21 @@
Understanding the Code
======================
Various design documents can be found in the design/ directory and API documentation
generated from the headers is hosted at http://api.kde.org.
Finding the Team
================
You can find the Plasma team on:
* our development mailing list at plasma-devel@kde.org
* our irc channel in #plasma on irc.freenode.net
Coding Style
============
New code should follow the kdelibs hacking style, as found here:
http://techbase.kde.org/Policies/Kdelibs_Coding_Style
Existing code that does not follow this style should be migrated over during
editting.

21
Mainpage.dox Normal file
View file

@ -0,0 +1,21 @@
/** @mainpage Plasma
Documentation for the Plasma libraries and utilities.
<p>
- <a href="../engines/html/index.html"><b>engines</b></a>
(<a href="../engines/html/classes.html">classes</a>)\n
<i>Engines for Plasma</i>
- <a href="../applets/html/index.html"><b>applets</b></a>
(<a href="../applets/html/classes.html">classes</a>)\n
<i>Plasma Applets</i>
- <a href="../animators/html/index.html"><b>animators</b></a>
(<a href="../animators/html/classes.html">classes</a>)\n
<i>Plasma Animators</i>
*/
// DOXYGEN_SET_PROJECT_NAME = Plasma
// DOXYGEN_SET_RECURSIVE = YES
// DOXYGEN_EXCLUDE = engines applets animators
// vim:ts=4:sw=4:expandtab:filetype=doxygen

13
applets/CMakeLists.txt Normal file
View file

@ -0,0 +1,13 @@
add_subdirectory(kickoff)
plasma_install_package(trash org.kde.plasma.trash)
if(NOT WIN32)
# tasks and windowlist depend on libs/taskmanager
add_subdirectory(taskmanager)
plasma_install_package(window-list org.kde.plasma.windowlist)
if(KF5Activities_FOUND)
add_subdirectory(pager)
add_subdirectory(showActivityManager)
endif()
endif()

View file

@ -0,0 +1,62 @@
#######################################################################################
# Package
plasma_install_package(package org.kde.plasma.kickoff)
#######################################################################################
# Kickoff Library
set(libkickoff_SRCS
core/applicationmodel.cpp
core/favoritesmodel.cpp
core/itemhandlers.cpp
core/kickoffabstractmodel.cpp
core/kickoffmodel.cpp
core/kickoffproxymodel.cpp
core/kickoffplugin.cpp
core/krunnermodel.cpp
core/leavemodel.cpp
core/models.cpp
core/recentapplications.cpp
core/recentlyusedmodel.cpp
core/systemmodel.cpp
core/kuserproxy.cpp
core/urlitemlauncher.cpp
)
qt5_add_dbus_adaptor(libkickoff_SRCS core/org.kde.kickoff.xml core/applicationmodel.h Kickoff::ApplicationModel)
qt5_add_dbus_adaptor(libkickoff_SRCS core/org.kde.kickoff.recent.xml core/recentlyusedmodel.h Kickoff::RecentlyUsedModel)
if(${CMAKE_SOURCE_DIR} STREQUAL ${plasma-desktop_SOURCE_DIR})
set(screensaver_xml ${SCREENSAVER_DBUS_INTERFACE})
set(krunner_xml ${KRUNNERAPP_INTERFACE})
set(ksmserver_xml ${KSMSERVER_DBUS_INTERFACE})
else()
set(screensaver_xml ${CMAKE_SOURCE_DIR}/plasma-workspace/ksmserver/screenlocker/dbus/org.freedesktop.ScreenSaver.xml)
set(krunner_xml ${CMAKE_SOURCE_DIR}/plasma-workspace/krunner/dbus/org.kde.krunner.App.xml)
set(ksmserver_xml ${CMAKE_SOURCE_DIR}/plasma-workspace/ksmserver/org.kde.KSMServerInterface.xml)
endif()
qt5_add_dbus_interface(libkickoff_SRCS ${screensaver_xml} screensaver_interface)
qt5_add_dbus_interface(libkickoff_SRCS ${krunner_xml} krunner_interface)
qt5_add_dbus_interface(libkickoff_SRCS ${ksmserver_xml} ksmserver_interface)
install(FILES core/qmldir DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/kickoff)
add_library(kickoffplugin SHARED ${libkickoff_SRCS})
target_link_libraries(kickoffplugin
Qt5::Core
Qt5::Qml
Qt5::DBus
KF5::CoreAddons
KF5::I18n
KF5::KIOCore
KF5::KIOWidgets
KF5::KIOFileWidgets
KF5::Runner
KF5::Solid
KF5::Service
KF5::KDE4Support
PW::KWorkspace)
install(TARGETS kickoffplugin DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/kickoff)

View file

@ -0,0 +1,71 @@
Project Proposal: Kickoff KDE 4 Rewrite
This is a re-implementation of the Kickoff menu for KDE 3 originally created
by the OpenSuSE team.
Overall goals:
1. Implement the Kickoff user interface using Qt/KDE 4 technology
2. Make it easy for distributions to modify the menu contents
3. Make it easy for distributions to add their own branding
Detailed goals:
1. Implement the Kickoff user interface using Qt/KDE 4 technology
-> Clean separation of core and user interface
-> eg. Make good use of Qt 4's model/view classes
-> Use Strigi for search and analysis (or possibly just Xesam interface?)
-> Use Solid for getting data for removable device list
-> Attractive, original, but not overbearing graphical effects
using Qt 4's new painting and animation features.
To decide on:
-> Consult the Kickoff/KDE 3 developers and OpenSuSE users about
any desired changes to the user interface.
-> Whether to use Plasma applets and widgets or Qt's widgets and
QAbstractItemView as the base for the view classes.
-> Provision of Plasma data engines for applets to use to query
applications, recent documents, favorites etc.
-> Should facilities be provided for distributions to replace
Strigi with their choice of search engine?
Ideas to explore in future:
-> Use Sonnet for spell-checking the user's search query
-> Use Phonon for previews of audio and video content
in the favorites and recently used sections
-> Light KWin integration for interesting effects for revealing,
hiding or rendering the Kickoff launcher on composited '3D'
desktops.
Goals 2 and 3 are derived from looking at the KDE 3 implementation
of Kickoff and also the way in which distributions customise KDE.
Consulting distribution representatives is important to clarify
these particular goals.
2. Make it easy for distributions to modify the menu contents
-> Different distributions may have different tools for system
configuration ( eg. System Settings , YaST , Mandriva's tools )
-> The available options on the leave page and the way in which
those tools work varies depending on the distribution
3. Make it easy for distributions to add their own branding
-> The launcher menu is a highly visible part of the desktop,
distributions are therefore likely to want to brand it with
their own logos, colors, icons etc.
This does not mean infinite theme-ability, but rather a good
out-of-the-box look which distros can easily tweak so that
it is obvious which distribution is being used from looking
at a screenshot, and also to allow distros to make some
obvious cosmetic changes between versions.
(See the Ubuntu art specs for example which state that each
new version is supposed to have a visual look which is
distinct from the previous version)

View file

@ -0,0 +1,4 @@
#! /usr/bin/env bash
$EXTRACTRC `find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` >> rc.cpp
$XGETTEXT `find . -name \*.qml -o -name \*.cpp` -o $podir/plasma_applet_kickoff.pot
rm -f rc.cpp

View file

@ -0,0 +1,66 @@
Current status of Kickoff/KDE 4:
Bugs and missing features (indicated with a '-')
are listed in priority order for each category.
================================================
Favorites View
+ Works
- Favorites are not remembered correctly between sessions
when Kickoff is run from a Plasma applet
- Missing drag and drop of items from other views into favorites
- Missing drag and drop re-arranging of items
Applications View
+ Works.
+ When KDE 3 and KDE 4 versions of an application are available only
the KDE 4 one is shown.
- Oxygen application category icons are not shown next to categories
My Computer View
+ Works.
+ Uses Solid to query devices and respond to addition or removal of
devices
- Folders are currently opened in Konqueror. They should open in
Dolphin
Recently Used (History?) View
+ Works
- Missing a suitable icon for the tab
Leave View
+ Log-off, Shutdown and Restart work
- Sleep, Hibernate do not work
- Log-off, Shutdown and Restart show an unnecessary confirmation
dialog which gives users the Log-off/Shutdown/Restart choice again
- Missing icons for the Sleep, Shutdown, Restart actions
Search View
+ Application search by name, generic name or keywords works
- Strigi search doesn't work due to a Strigi problem which Jos' is
presently fixing
* The other search handlers that query Bookmarks,
Contacts etc. should probably be shared with KRunner. This needs
mailing list discussion.
Presentation
+ When used as a Plasma applet the Kickoff window does not
appear and disappear smoothly. (Works okay when standalone
Kickoff application is run) [Also Performance?]
- Missing the custom QTabBar styling to draw the view names
under their icons and draw a pretty gradient
- Missing the "username on computer" text
- Missing the branding logo
+ Experimented with multiple columns in the Favorites/My Computer/Recently Used/Leave
views.
Performance:
- Scrolling up and down in the application view is not as smooth
as it should be in some categories. Perhaps an issue with icons
from certain sources?
- When opening a previously unopened application category there
may be a slight delay and HDD activity causing the scrolling animation
to have few frames (the animation duration is not affected)
- Currently no delayed initialization is performed. The data required
for all tabs is loaded on startup, except the application view where
only the root branch is loaded initially.

View file

@ -0,0 +1,696 @@
/*
Copyright 2007 Pino Toscano <pino@kde.org>
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "applicationmodel.h"
// Qt
#include <QtCore/QtAlgorithms>
#include <QDebug>
// KDE
#include <kauthorized.h>
#include <khistorycombobox.h>
#include <kdesktopfile.h>
#include <klineedit.h>
#include <klocale.h>
#include <kiconloader.h>
#include <krun.h>
#include <kstandarddirs.h>
#include <kstringhandler.h>
#include <kmimetypetrader.h>
#include <kurlcompletion.h>
#include <kmimetype.h>
#include <kservicegroup.h>
#include <ksycoca.h>
#include <kglobalsettings.h>
#include <KLocalizedString>
#include <KIcon>
#include <assert.h>
#include <stdlib.h>
#include <kconfiggroup.h>
#include "kickoffadaptor.h"
// Local
#include "models.h"
#include <Plasma/Applet>
template <> inline
void KConfigGroup::writeEntry(const char *pKey,
const KGlobalSettings::Completion& aValue,
KConfigBase::WriteConfigFlags flags)
{
writeEntry(pKey, int(aValue), flags);
}
namespace Kickoff
{
class AppNode
{
public:
AppNode()
: parent(0),
fetched(false),
isDir(false),
isSeparator(false),
subTitleMandatory(false)
{
}
~AppNode()
{
qDeleteAll(children);
}
QList<AppNode*> children;
QIcon icon;
QString iconName;
QString genericName;
QString appName;
QString relPath;
QString desktopEntry;
AppNode *parent;
DisplayOrder displayOrder;
bool fetched : 1;
bool isDir : 1;
bool isSeparator : 1;
bool subTitleMandatory : 1;
};
class ApplicationModelPrivate
{
public:
ApplicationModelPrivate(ApplicationModel *qq, bool _allowSeparators)
: q(qq),
root(new AppNode()),
duplicatePolicy(ApplicationModel::ShowDuplicatesPolicy),
systemApplicationPolicy(ApplicationModel::ShowApplicationAndSystemPolicy),
// primaryNamePolicy(ApplicationModel::GenericNamePrimary),
displayOrder(NameAfterDescription),
allowSeparators(_allowSeparators),
showRecentlyInstalled(true)
{
systemApplications = Kickoff::systemApplicationList();
reloadTimer = new QTimer(qq);
reloadTimer->setSingleShot(true);
QObject::connect(reloadTimer, SIGNAL(timeout()), qq, SLOT(delayedReloadMenu()));
}
~ApplicationModelPrivate()
{
delete root;
}
void fillNode(const QString &relPath, AppNode *node);
static QHash<QString, QString> iconNameMap();
ApplicationModel *q;
QWeakPointer<Plasma::Applet> applet;
AppNode *root;
ApplicationModel::DuplicatePolicy duplicatePolicy;
ApplicationModel::SystemApplicationPolicy systemApplicationPolicy;
QStringList systemApplications;
DisplayOrder displayOrder;
bool allowSeparators;
bool showRecentlyInstalled;
QTimer *reloadTimer;
QStringList newInstalledPrograms;
QHash<QString, QDate> seenPrograms;
};
void ApplicationModelPrivate::fillNode(const QString &_relPath, AppNode *node)
{
if (_relPath=="new/") {
Q_FOREACH (const QString &it, newInstalledPrograms) {
KService::Ptr p = KService::serviceByStorageId(it);
if (p->noDisplay()) {
continue;
}
AppNode *newnode = new AppNode();
newnode->icon = KIcon(p->icon());
newnode->appName = p->name();
newnode->genericName = p->genericName();
newnode->desktopEntry = p->entryPath();
newnode->parent = node;
node->children.append(newnode);
}
return;
}
KServiceGroup::Ptr root = KServiceGroup::group(_relPath);
if (!root || !root->isValid()) {
return;
}
const KServiceGroup::List list = root->entries(true /* sorted */,
true /* exclude no display entries */,
allowSeparators /* allow separators */,
true /* sort by generic name */);
// application name <-> service map for detecting duplicate entries
QHash<QString, KService::Ptr> existingServices;
// generic name <-> node mapping to determinate duplicate generic names
QHash<QString,QList<AppNode*> > genericNames;
for (KServiceGroup::List::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it) {
QString icon;
QString appName;
QString genericName;
QString relPath = _relPath;
QString desktopEntry;
bool isDir = false;
bool isSeparator = false;
const KSycocaEntry::Ptr p = (*it);
if (p->isType(KST_KService)) {
const KService::Ptr service = p;
if (service->noDisplay()) {
continue;
}
icon = service->icon();
appName = service->name();
genericName = service->genericName();
desktopEntry = service->entryPath();
// check for duplicates (eg. KDE 3 and KDE 4 versions of application
// both present)
if (duplicatePolicy == ApplicationModel::ShowLatestOnlyPolicy &&
existingServices.contains(appName)) {
if (Kickoff::isLaterVersion(existingServices[appName], service)) {
continue;
} else {
// find and remove the existing entry with the same name
for (int i = node->children.count() - 1; i >= 0; --i) {
AppNode *app = node->children.at(i);
if (app->appName == appName &&
app->genericName == genericName &&
app->iconName == icon) {
app = node->children.takeAt(i);
const QString s = app->genericName.toLower();
if (genericNames.contains(s)) {
QList<AppNode*> list = genericNames[s];
for (int j = list.count() - 1; j >= 0; --j) {
if(list.at(j) == app) {
list.takeAt(j);
}
}
genericNames[s] = list;
}
delete app;
}
}
}
}
if (systemApplicationPolicy == ApplicationModel::ShowSystemOnlyPolicy &&
systemApplications.contains(service->desktopEntryName())) {
// don't duplicate applications that are configured to appear in the System tab
// in the Applications tab
continue;
}
existingServices[appName] = service;
} else if (p->isType(KST_KServiceGroup)) {
const KServiceGroup::Ptr serviceGroup = p;
if (serviceGroup->noDisplay() || serviceGroup->childCount() == 0) {
continue;
}
qDebug() << "Service group" << serviceGroup->entryPath() << serviceGroup->icon() << serviceGroup->relPath() << serviceGroup->directoryEntryPath();
icon = serviceGroup->icon();
if (iconNameMap().contains(icon)) {
icon = iconNameMap().value(icon);
}
desktopEntry = serviceGroup->entryPath();
genericName = serviceGroup->caption();
relPath = serviceGroup->relPath();
appName = serviceGroup->comment();
isDir = true;
} else if (p->isType(KST_KServiceSeparator)) {
isSeparator = true;
} else {
qWarning() << "KServiceGroup: Unexpected object in list!";
continue;
}
AppNode *newnode = new AppNode();
newnode->iconName = icon;
newnode->icon = KIcon(icon);
newnode->appName = appName;
newnode->genericName = genericName;
newnode->relPath = relPath;
newnode->desktopEntry = desktopEntry;
newnode->isDir = isDir;
newnode->isSeparator = isSeparator;
newnode->parent = node;
node->children.append(newnode);
if (p->isType(KST_KService)) {
const QString s = genericName.toLower();
QList<AppNode*> list = genericNames.value(s);
list.append(newnode);
genericNames[s] = list;
}
}
if (showRecentlyInstalled && _relPath.isEmpty() && !newInstalledPrograms.isEmpty()) {
AppNode *newnode = new AppNode();
newnode->icon = KIcon("chronometer");
newnode->appName = i18n("Recently Installed");
newnode->relPath = "new/";
newnode->isDir = true;
newnode->parent = node;
node->children.prepend(newnode);
}
// set the subTitleMandatory field for nodes that do not provide a unique generic
// name what may help us on display to show in such cases also the subtitle to
// provide a hint to the user what the duplicate entries are about.
foreach (const QList<AppNode*> &list, genericNames) {
if (list.count() > 1) {
foreach (AppNode* n, list) {
n->subTitleMandatory = true;
}
}
}
}
ApplicationModel::ApplicationModel(QObject *parent, bool allowSeparators)
: KickoffAbstractModel(parent),
d(new ApplicationModelPrivate(this, allowSeparators))
{
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "display";
roles[Qt::DecorationRole] = "decoration";
roles[Kickoff::SubTitleRole] = "subtitle";
roles[Kickoff::UrlRole] = "url";
roles[Kickoff::GroupNameRole] = "group";
setRoleNames(roles);
QDBusConnection dbus = QDBusConnection::sessionBus();
(void)new KickoffAdaptor(this);
QDBusConnection::sessionBus().registerObject("/kickoff", this);
dbus.connect(QString(), "/kickoff", "org.kde.plasma", "reloadMenu", this, SLOT(reloadMenu()));
connect(KSycoca::self(), SIGNAL(databaseChanged(QStringList)), this, SLOT(checkSycocaChange(QStringList)));
// TODO: remove me again
reloadMenu();
}
ApplicationModel::~ApplicationModel()
{
delete d;
}
bool ApplicationModel::canFetchMore(const QModelIndex &parent) const
{
if (!parent.isValid())
return false;
AppNode *node = static_cast<AppNode*>(parent.internalPointer());
return node->isDir && !node->fetched;
}
// void ApplicationModel::setNameDisplayOrder(DisplayOrder displayOrder)
// {
// d->displayOrder = displayOrder;
// }
//
// DisplayOrder ApplicationModel::nameDisplayOrder() const
// {
// return d->displayOrder;
// }
void ApplicationModel::setShowRecentlyInstalled(bool showRecentlyInstalled)
{
if (d->showRecentlyInstalled != showRecentlyInstalled) {
d->showRecentlyInstalled = showRecentlyInstalled;
reloadMenu();
}
}
bool ApplicationModel::showRecentlyInstalled() const
{
return d->showRecentlyInstalled;
}
int ApplicationModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 1;
}
QVariant ApplicationModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
AppNode *node = static_cast<AppNode*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
if (node->genericName.isEmpty()) {
return node->appName;
} else {
return node->genericName;
}
case Kickoff::SubTitleRole:
if (node->appName.isEmpty() || node->appName == node->genericName) {
return QString(); //return empty string to avoid errors in QML assigning null to Text
} else {
return node->appName;
}
case Kickoff::UrlRole:
if (node->isDir) {
return QString::fromLatin1("applications://%1").arg(node->desktopEntry);
} else {
return node->desktopEntry;
}
break;
case Kickoff::SubTitleMandatoryRole:
return node->subTitleMandatory;
break;
case Kickoff::SeparatorRole:
return node->isSeparator;
break;
case Qt::DecorationRole:
return node->icon;
break;
case Kickoff::RelPathRole:
return node->relPath;
break;
case Kickoff::IconNameRole:
return node->iconName;
break;
default:
;
}
return QVariant();
}
void ApplicationModel::fetchMore(const QModelIndex &parent)
{
if (!parent.isValid()) {
return;
}
AppNode *node = static_cast<AppNode*>(parent.internalPointer());
if (!node->isDir) {
return;
}
// FIXME? QML's QQmlAdaptorModel (the "backend" used for VisualDataModel) always hard-resets
// the model when the source model (this one) changes layout, which breaks kickoff's
// navigation as opening a category for the first time calls this and then calls
// layoutChanged() --> QML's VisualDataModel is reset, that in turn invalidates
// VDM's rootIndex and when that happens, Kickoff is switched to the root level.
// Disabling the layout signals makes Kickoff's navigation work properly.
// emit layoutAboutToBeChanged(QList<QPersistentModelIndex>() << parent);
d->fillNode(node->relPath, node);
node->fetched = true;
// changePersistentIndex(parent, parent);
// emit layoutChanged(QList<QPersistentModelIndex>() << parent);
}
bool ApplicationModel::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return true;
}
AppNode *node = static_cast<AppNode*>(parent.internalPointer());
return node->isDir;
}
QVariant ApplicationModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || section != 0) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
return i18n("All Applications");
break;
default:
return QVariant();
}
}
QModelIndex ApplicationModel::index(int row, int column, const QModelIndex &parent) const
{
if (row < 0 || column != 0)
return QModelIndex();
AppNode *node = d->root;
if (parent.isValid())
node = static_cast<AppNode*>(parent.internalPointer());
if (row >= node->children.count())
return QModelIndex();
else
return createIndex(row, 0, node->children.at(row));
}
QModelIndex ApplicationModel::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
AppNode *node = static_cast<AppNode*>(index.internalPointer());
if (node->parent->parent) {
int id = node->parent->parent->children.indexOf(node->parent);
if (id >= 0 && id < node->parent->parent->children.count()) {
return createIndex(id, 0, node->parent);
}
}
return QModelIndex();
}
int ApplicationModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return d->root->children.count();
}
AppNode *node = static_cast<AppNode*>(parent.internalPointer());
return node->children.count();
}
void ApplicationModel::setDuplicatePolicy(DuplicatePolicy policy)
{
if (d->duplicatePolicy != policy) {
d->duplicatePolicy = policy;
reloadMenu();
}
}
void ApplicationModel::setSystemApplicationPolicy(SystemApplicationPolicy policy)
{
if (d->systemApplicationPolicy != policy) {
d->systemApplicationPolicy = policy;
reloadMenu();
}
}
void ApplicationModel::delayedReloadMenu()
{
if (!d->reloadTimer->isActive()) {
d->reloadTimer->start(200);
}
}
void ApplicationModel::reloadMenu()
{
beginResetModel();
delete d->root;
d->root = new AppNode();
createNewProgramList();
d->fillNode(QString(), d->root);
endResetModel();
}
void ApplicationModel::checkSycocaChange(const QStringList &changes)
{
if (changes.contains("services") || changes.contains("apps")) {
reloadMenu();
}
}
ApplicationModel::DuplicatePolicy ApplicationModel::duplicatePolicy() const
{
return d->duplicatePolicy;
}
ApplicationModel::SystemApplicationPolicy ApplicationModel::systemApplicationPolicy() const
{
return d->systemApplicationPolicy;
}
void ApplicationModel::setApplet(Plasma::Applet *applet)
{
if (d->applet.data() != applet) {
d->applet = applet;
createNewProgramList();
}
}
void ApplicationModel::createNewProgramList()
{
if (!d->applet) {
return;
}
d->newInstalledPrograms.clear();
if (!d->showRecentlyInstalled) {
return;
}
//FIXME
KConfigGroup kickoffrc = d->applet.data()->config();
foreach (const QString &it, kickoffrc.keyList()) {
d->seenPrograms.insert(it, QDate::fromString(kickoffrc.readEntry(it), Qt::ISODate));
}
bool initialize = (d->seenPrograms.isEmpty());
bool seenProgramsChanged = createNewProgramListForPath(QString());
if (initialize) {
// on first start, set all entries' dates to empty (means: they are not new)
for (QHash<QString, QDate>::Iterator it = d->seenPrograms.begin(); it != d->seenPrograms.end(); ++it)
*it = QDate();
d->newInstalledPrograms.clear();
}
if (seenProgramsChanged) {
for (QHash<QString, QDate>::Iterator it = d->seenPrograms.begin(); it != d->seenPrograms.end(); ++it) {
kickoffrc.writeEntry(it.key(), it.value().toString(Qt::ISODate));
}
kickoffrc.sync();
}
}
bool ApplicationModel::createNewProgramListForPath(const QString &relPath)
{
bool seenProgramsChanged = false;
KServiceGroup::Ptr group = KServiceGroup::group(relPath);
if (!group || !group->isValid()) {
return false;
}
const KServiceGroup::List list = group->entries();
KServiceGroup::List::ConstIterator it = list.begin();
for (; it != list.end(); ++it) {
KSycocaEntry::Ptr e = (*it);
if (e->isType(KST_KServiceGroup)) {
KServiceGroup::Ptr g(e);
if (!g->noDisplay()) {
if (createNewProgramListForPath(g->relPath()))
seenProgramsChanged = true;
}
} else if (e->isType(KST_KService)) {
KService::Ptr s(e);
if (s->isApplication() && !s->noDisplay()) {
QString shortStorageId = s->storageId().remove(".desktop");
QHash<QString, QDate>::Iterator it_find = d->seenPrograms.find(shortStorageId);
if (it_find == d->seenPrograms.end()) {
seenProgramsChanged = true;
d->seenPrograms.insert(shortStorageId, QDate::currentDate());
if (!d->newInstalledPrograms.contains(s->storageId())) {
d->newInstalledPrograms += s->storageId();
}
}
else {
QDate date = it_find.value();
if (date.isValid()) {
if (date.daysTo(QDate::currentDate()) < 3) {
if (!d->newInstalledPrograms.contains(s->storageId())) {
d->newInstalledPrograms += s->storageId();
}
}
else {
seenProgramsChanged = true;
(*it_find) = QDate(); // this entry is not new anymore
}
}
}
}
}
}
return seenProgramsChanged;
}
/**
* FIXME This is a temporary workaround to map the icon names found
* in the desktop directory files (from /usr/share/desktop-directories)
* into the Oxygen icon names. (Only applies if the Gnome menu files
* are also installed)
*
* This list was compiled from Kubuntu 7.04 with the gnome-menus
* package present.
*
* This needs to be discussed on kde-core-devel and fixed
*/
QHash<QString, QString> ApplicationModelPrivate::iconNameMap()
{
static QHash<QString, QString> map;
if (map.isEmpty()) {
map.insert("gnome-util", "applications-accessories");
// accessibility Oxygen icon was missing when this list was compiled
map.insert("accessibility-directory", "applications-other");
map.insert("gnome-devel", "applications-development");
map.insert("package_edutainment", "applications-education");
map.insert("gnome-joystick", "applications-games");
map.insert("gnome-graphics", "applications-graphics");
map.insert("gnome-globe", "applications-internet");
map.insert("gnome-multimedia", "applications-multimedia");
map.insert("gnome-applications", "applications-office");
map.insert("gnome-system", "applications-system");
}
return map;
}
} // namespace Kickoff
#include "applicationmodel.moc"

View file

@ -0,0 +1,131 @@
/*
Copyright 2007 Pino Toscano <pino@kde.org>
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef APPLICATIONMODEL_H
#define APPLICATIONMODEL_H
#include "kickoffabstractmodel.h"
#include "models.h"
namespace Plasma
{
class Applet;
} // namespace Plasma
namespace Kickoff
{
class ApplicationModelPrivate;
/**
* ApplicationModel provides a tree model containing all of the user's installed graphical programs.
* The applications are arranged into categories, based on the information in their .desktop files.
*/
class ApplicationModel : public KickoffAbstractModel
{
Q_OBJECT
public:
ApplicationModel(QObject *parent = 0, bool allowSeparators = false);
virtual ~ApplicationModel();
/**
* This enum describes the policy for
* handling duplicate applications (that is,
* two applications with the same name in the same group)
*/
enum DuplicatePolicy {
/** Display duplicate entries. */
ShowDuplicatesPolicy,
/**
* Show only the entry for the most recent
* version of the application.
*
* Currently only a crude heuristic to determine whether the
* application is from KDE 3 or KDE 4 is used to determine
* recent-ness.
*
* eg. If MyGame/KDE 3 and MyGame/KDE 4 are found
* show only MyGame/KDE 4
*/
ShowLatestOnlyPolicy
};
/**
* This enum describes the policy for
* handling applications that are configured to appear
* in the System tab.
*/
enum SystemApplicationPolicy {
/** Display entries in Applications tab and System tab. */
ShowApplicationAndSystemPolicy,
/** Display entry only in System tab. */
ShowSystemOnlyPolicy
};
/**
* Sets the policy for handling duplicate applications.
* See DuplicatePolicy
*/
void setDuplicatePolicy(DuplicatePolicy policy);
/** See setDuplicatePolicy() */
DuplicatePolicy duplicatePolicy() const;
/**
* Sets the policy for handling System applications.
* See SystemApplicationPolicy
*/
void setSystemApplicationPolicy(SystemApplicationPolicy policy);
/** See setSystemApplicationPolicy() */
SystemApplicationPolicy systemApplicationPolicy() const;
// reimplemented from QAbstractItemModel
virtual bool canFetchMore(const QModelIndex &parent) const;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual void fetchMore(const QModelIndex &parent);
virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex parent(const QModelIndex &index) const;
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
void setApplet(Plasma::Applet *applet);
void setShowRecentlyInstalled(bool showRecentlyInstalled);
bool showRecentlyInstalled() const;
public Q_SLOTS:
void reloadMenu();
void delayedReloadMenu();
void checkSycocaChange(const QStringList &changes);
private:
friend class ApplicationModelPrivate;
ApplicationModelPrivate *const d;
void createNewProgramList();
bool createNewProgramListForPath(const QString &relPath);
Q_DISABLE_COPY(ApplicationModel)
};
}
#endif

View file

@ -0,0 +1,376 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
//Own
#include "favoritesmodel.h"
#include "krunnermodel.h"
// Qt
#include <QHash>
#include <QList>
#include <QMimeData>
#include <QFileInfo>
#include <QDebug>
// KDE
#include <KConfigGroup>
#include <KService>
#include <KDesktopFile>
#include <KLocalizedString>
#include <KUrl>
using namespace Kickoff;
class FavoritesModel::Private
{
public:
Private(FavoritesModel *parent)
: q(parent),
displayOrder(NameAfterDescription)
{
init();
}
void init()
{
}
void addFavoriteItem(const QString& url)
{
QStandardItem *item = StandardItemFactory::createItemForUrl(url, displayOrder);
item->setData(i18n("Favorites"), Kickoff::GroupNameRole);
q->appendRow(item);
}
void moveFavoriteItem(int startRow, int destRow)
{
if (destRow == startRow) {
return;
}
QStandardItem *item = q->takeItem(startRow);
q->removeRow(startRow);
q->insertRow(destRow, item);
}
void removeFavoriteItem(const QString& url)
{
Q_UNUSED(url)
QModelIndexList matches = q->match(q->index(0, 0), UrlRole,
url, -1,
Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap | Qt::MatchRecursive));
qDebug() << "Removing item matches" << matches;
foreach (const QModelIndex& index, matches) {
QStandardItem *item = q->itemFromIndex(index);
if (item->parent()) {
item->parent()->removeRow(item->row());
} else {
qDeleteAll(q->takeRow(item->row()));
}
}
}
static void loadFavorites()
{
globalFavoriteList.clear();
globalFavoriteSet.clear();
KConfigGroup favoritesGroup = componentData().config()->group("Favorites");
QList<QString> favoriteList = favoritesGroup.readEntry("FavoriteURLs", QList<QString>());
if (favoriteList.isEmpty()) {
favoriteList = defaultFavorites();
}
foreach (const QString &favorite, favoriteList) {
FavoritesModel::add(favorite);
}
}
static QList<QString> defaultFavorites()
{
QList<QString> applications;
applications << "konqbrowser" << "KMail2" << "kdesystemsettings" << "dolphin" << "konsole" << "kate" << "kwrite" << "kinfocenter";
QList<QString> desktopFiles;
foreach (const QString& application, applications) {
KService::Ptr service = KService::serviceByStorageId(application + ".desktop");
if (service) {
desktopFiles << service->entryPath();
}
}
return desktopFiles;
}
static void saveFavorites()
{
KConfigGroup favoritesGroup = componentData().config()->group("Favorites");
favoritesGroup.writeEntry("FavoriteURLs", globalFavoriteList);
favoritesGroup.config()->sync();
}
static QList<QString> globalFavoriteList;
static QSet<QString> globalFavoriteSet;
static QSet<FavoritesModel*> models;
FavoritesModel * const q;
DisplayOrder displayOrder;
};
QList<QString> FavoritesModel::Private::globalFavoriteList;
QSet<QString> FavoritesModel::Private::globalFavoriteSet;
QSet<FavoritesModel*> FavoritesModel::Private::models;
FavoritesModel::FavoritesModel(QObject *parent)
: KickoffModel(parent)
, d(new Private(this))
{
Private::models << this;
if (Private::models.count() == 1 && Private::globalFavoriteList.isEmpty()) {
Private::loadFavorites();
} else {
foreach (const QString &url, Private::globalFavoriteList) {
d->addFavoriteItem(url);
}
}
}
FavoritesModel::~FavoritesModel()
{
Private::models.remove(this);
if (Private::models.isEmpty()) {
Private::saveFavorites();
}
delete d;
}
void FavoritesModel::add(const QString& url)
{
QString handledUrl;
KService::Ptr service = Kickoff::serviceForUrl(url);
if (service) {
handledUrl = service->entryPath();
} else {
handledUrl = url;
}
Private::globalFavoriteList << handledUrl;
Private::globalFavoriteSet << handledUrl;
foreach (FavoritesModel* model, Private::models) {
model->d->addFavoriteItem(handledUrl);
}
// save after each add in case we crash
Private::saveFavorites();
}
void FavoritesModel::move(int startRow, int destRow)
{
// just move the item
// Private::globalFavoriteList.move(startRow, destRow);
foreach (FavoritesModel* model, Private::models) {
qDebug() << "Move : " << startRow << destRow << model->rowCount();
if (destRow >= model->rowCount()) {
destRow = model->rowCount() - 1;
}
if (startRow >= model->rowCount()) {
startRow = model->rowCount() - 1;
}
qDebug() << "Move : " << startRow << destRow << model->rowCount();
Private::globalFavoriteList.move(startRow, destRow);
model->d->moveFavoriteItem(startRow, destRow);
}
// save after each add in case we crash
Private::saveFavorites();
}
void FavoritesModel::remove(const QString& url)
{
Private::globalFavoriteList.removeAll(url);
Private::globalFavoriteSet.remove(url);
foreach (FavoritesModel* model, Private::models) {
model->d->removeFavoriteItem(url);
}
// save after each remove in case of crash or other mishaps
Private::saveFavorites();
}
bool FavoritesModel::isFavorite(const QString& url)
{
QString handledUrl;
KService::Ptr service = Kickoff::serviceForUrl(url);
if (service) {
handledUrl = service->entryPath();
} else {
handledUrl = url;
}
return Private::globalFavoriteSet.contains(handledUrl);
}
int FavoritesModel::numberOfFavorites()
{
foreach (FavoritesModel* model, Private::models) {
return model->d->q->rowCount() - 1;
}
return 0;
}
void FavoritesModel::sortFavorites(Qt::SortOrder order)
{
if(Private::models.isEmpty()) {
return;
}
foreach (FavoritesModel *model, Private::models) {
model->d->q->sort(0, order);
}
Private::globalFavoriteList.clear();
FavoritesModel *model = *Private::models.begin();
QStandardItem *childData;
for (int i = 0; i <= numberOfFavorites(); i++) {
childData = model->d->q->item(i, 0);
Private::globalFavoriteList.append(childData->data(Kickoff::UrlRole).toString());
}
Private::saveFavorites();
}
void FavoritesModel::sortFavoritesAscending()
{
sortFavorites(Qt::AscendingOrder);
}
void FavoritesModel::sortFavoritesDescending()
{
sortFavorites(Qt::DescendingOrder);
}
bool FavoritesModel::dropMimeData(const QString& text, const QVariantList& urls,
int row, int column)
{
qDebug() << "Dropping into row: " << row << urls;
// FIXME: pass DropAction by qml
Qt::DropAction action = Qt::MoveAction;
if (action == Qt::IgnoreAction) {
return true;
}
if (column > 0 || row > numberOfFavorites()) {
qDebug() << "Exit " << numberOfFavorites();
return false;
}
if (action == Qt::MoveAction) {
QModelIndex modelIndex;
QStandardItem *startItem;
int startRow = -1;
int destRow = row;
qDebug() << "Moving ..." << startRow << destRow;
// look for the favorite that was dragged
bool conv = false;
startRow = text.toInt(&conv, 10);
if (!conv) {
bool dropped = false;
foreach (const QVariant &varUrl, urls) {
if (!varUrl.value<QUrl>().isValid()) {
continue;
}
const QString path = varUrl.value<QUrl>().toLocalFile();
if (!KDesktopFile::isDesktopFile(path)) {
continue;
}
KDesktopFile dFile(path);
if (dFile.hasApplicationType() && !dFile.noDisplay()) {
FavoritesModel::add(path);
dropped = true;
}
}
qDebug() << " now move the item to it's new location " << startRow << destRow;
return dropped;
}
if (destRow < 0) {
qDebug() << "Returning here" << startRow << destRow;
return false;
}
// now move the item to it's new location
FavoritesModel::move(startRow, destRow);
return true;
}
return true;
}
QVariant FavoritesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || section != 0) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
return i18nc("@title:column", "Favorites");
break;
default:
return QVariant();
}
}
void FavoritesModel::setNameDisplayOrder(DisplayOrder displayOrder)
{
if (d->displayOrder == displayOrder) {
return;
}
d->displayOrder = displayOrder;
foreach (FavoritesModel* model, Private::models) {
model->clear();
model->d->init();
}
Private::loadFavorites();
}
DisplayOrder FavoritesModel::nameDisplayOrder() const
{
return d->displayOrder;
}
#include "favoritesmodel.moc"

View file

@ -0,0 +1,72 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef FAVORITESMODEL_H
#define FAVORITESMODEL_H
#include "kickoffmodel.h"
#include "models.h"
namespace Kickoff
{
/**
* A model which provides an ordered list of 'favorite' items chosen by the user.
* The items may represent documents, folders, applications, devices or anything else
* identified by a URL.
*
* The information persists between sessions.
*/
class FavoritesModel : public KickoffModel
{
Q_OBJECT
public:
FavoritesModel(QObject *parent = NULL);
virtual ~FavoritesModel();
/** Add a new item for @p url to the user's favorites list. */
Q_INVOKABLE static void add(const QString& url);
/** Remove the item associated with @p url from the user's favorites list. */
Q_INVOKABLE static void remove(const QString& url);
/** Returns true if @p url is in the list of the user's favorite URLs. */
Q_INVOKABLE static void move(int startRow, int destRow);
static int numberOfFavorites();
static void sortFavorites(Qt::SortOrder order);
Q_INVOKABLE static bool isFavorite(const QString& url);
using QAbstractItemModel::dropMimeData;
Q_INVOKABLE virtual bool dropMimeData(const QString& text, const QVariantList& urls,
int row, int column);
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
void setNameDisplayOrder(DisplayOrder displayOrder);
DisplayOrder nameDisplayOrder() const;
public Q_SLOTS:
void sortFavoritesAscending();
void sortFavoritesDescending();
private:
class Private;
Private * const d;
};
}
#endif // FAVORITESMODEL_H

View file

@ -0,0 +1,191 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "itemhandlers.h"
// Qt
#include <QTimer>
// KDE
#include <KAuthorized>
#include <QDebug>
#include <KJob>
#include <KService>
#include <KToolInvocation>
#include <KUrl>
#include <Solid/PowerManagement>
// KDE Base
#include <kworkspace.h>
// Local
#include "recentapplications.h"
// DBus
#include "krunner_interface.h"
#include "screensaver_interface.h"
#include "ksmserver_interface.h"
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
using namespace Kickoff;
bool ServiceItemHandler::openUrl(const KUrl& url)
{
int result = KToolInvocation::startServiceByDesktopPath(url.pathOrUrl(), QStringList(), 0, 0, 0, "", true);
if (result == 0) {
KService::Ptr service = KService::serviceByDesktopPath(url.pathOrUrl());
if (service) {
RecentApplications::self()->add(service);
} else {
qWarning() << "Failed to find service for" << url;
return false;
}
}
return result == 0;
}
LeaveItemHandler::LeaveItemHandler(QObject *parent)
: QObject (parent)
{
}
bool LeaveItemHandler::openUrl(const KUrl& url)
{
m_logoutAction = url.path().remove('/');
if (m_logoutAction == "sleep") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(suspendRAM()));
return true;
} else if (m_logoutAction == "hibernate") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(suspendDisk()));
return true;
} else if (m_logoutAction == "lock") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(lock()));
return true;
} else if (m_logoutAction == "switch") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(switchUser()));
return true;
} else if (m_logoutAction == "logout" || m_logoutAction == "logoutonly" ||
m_logoutAction == "restart" || m_logoutAction == "shutdown") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(logout()));
return true;
} else if (m_logoutAction == "savesession") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(saveSession()));
return true;
} else if (m_logoutAction == "standby") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(standby()));
return true;
} else if (m_logoutAction == "suspendram") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(suspendRAM()));
return true;
} else if (m_logoutAction == "suspenddisk") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(suspendDisk()));
return true;
} else if (m_logoutAction == "run") {
// decouple dbus call, otherwise we'll run into a dead-lock
QTimer::singleShot(0, this, SLOT(runCommand()));
return true;
}
return false;
}
void LeaveItemHandler::runCommand()
{
if (KAuthorized::authorize("run_command")) {
QString interface("org.kde.krunner");
org::kde::krunner::App krunner(interface, "/App", QDBusConnection::sessionBus());
krunner.display();
}
}
void LeaveItemHandler::logout()
{
KWorkSpace::ShutdownConfirm confirm = KWorkSpace::ShutdownConfirmDefault;
KWorkSpace::ShutdownType type = KWorkSpace::ShutdownTypeNone;
if (m_logoutAction == "logout" || m_logoutAction == "logoutonly") {
type = KWorkSpace::ShutdownTypeNone;
} else if (m_logoutAction == "lock") {
qDebug() << "Locking screen";
} else if (m_logoutAction == "switch") {
qDebug() << "Switching user";
} else if (m_logoutAction == "restart") {
type = KWorkSpace::ShutdownTypeReboot;
} else if (m_logoutAction == "shutdown") {
type = KWorkSpace::ShutdownTypeHalt;
}
KWorkSpace::requestShutDown(confirm, type);
}
void LeaveItemHandler::lock()
{
QString interface("org.freedesktop.ScreenSaver");
org::freedesktop::ScreenSaver screensaver(interface, "/ScreenSaver", QDBusConnection::sessionBus());
screensaver.Lock();
}
void LeaveItemHandler::switchUser()
{
QString interface("org.kde.krunner");
org::kde::krunner::App krunner(interface, "/App", QDBusConnection::sessionBus());
krunner.switchUser();
}
void LeaveItemHandler::saveSession()
{
QString interface("org.kde.ksmserver");
org::kde::KSMServerInterface ksmserver(interface, "/KSMServer", QDBusConnection::sessionBus());
if (ksmserver.isValid()) {
ksmserver.saveCurrentSession();
}
}
void LeaveItemHandler::standby()
{
// FIXME: Use standby from KDE Power Management System's interface
suspendRAM();
}
void LeaveItemHandler::suspendRAM()
{
Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState, 0, 0);
}
void LeaveItemHandler::suspendDisk()
{
Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState, 0, 0);
}
#include "itemhandlers.moc"

View file

@ -0,0 +1,59 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef ITEMHANDLERS_H
#define ITEMHANDLERS_H
#include <QtCore/QObject>
#include "urlitemlauncher.h"
namespace Kickoff
{
class ServiceItemHandler : public UrlItemHandler
{
public:
virtual bool openUrl(const KUrl& url);
};
class LeaveItemHandler : public QObject, public UrlItemHandler
{
Q_OBJECT
public:
explicit LeaveItemHandler(QObject *parent = 0);
virtual bool openUrl(const KUrl& url);
private Q_SLOTS:
void runCommand();
void logout();
void lock();
void switchUser();
void saveSession();
void standby();
void suspendRAM();
void suspendDisk();
private:
QString m_logoutAction;
};
}
#endif // ITEMHANDLERS_H

View file

@ -0,0 +1,92 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "kickoffabstractmodel.h"
// Qt
#include <QMimeData>
// KDE
#include <KUrl>
#include <QDebug>
// Local
#include "models.h"
using namespace Kickoff;
KickoffAbstractModel::KickoffAbstractModel(QObject *parent)
: QAbstractItemModel(parent)
{}
KickoffAbstractModel::~KickoffAbstractModel()
{}
Qt::ItemFlags KickoffAbstractModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QAbstractItemModel::flags(index);
if (index.isValid()) {
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
} else {
return 0;
}
}
QMimeData *KickoffAbstractModel::mimeData(const QModelIndexList &indexes) const
{
KUrl::List urls;
QByteArray itemData;
foreach(const QModelIndex &index, indexes) {
KUrl itemUrl = KUrl(data(index, UrlRole).toString());
if (itemUrl.isValid()) {
urls << itemUrl;
}
}
QMimeData *mimeData = new QMimeData();
if (!urls.isEmpty()) {
urls.populateMimeData(mimeData);
}
return mimeData;
}
QStringList KickoffAbstractModel::mimeTypes() const
{
QStringList types;
types << QLatin1String("text/uri-list");
return types;
}
Qt::DropActions KickoffAbstractModel::supportedDropActions() const
{
return 0;
}
Qt::DropActions KickoffAbstractModel::supportedDragActions() const
{
return Qt::CopyAction;
}
#include "kickoffabstractmodel.moc"

View file

@ -0,0 +1,53 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KICKOFFABSTRACTMODEL_H
#define KICKOFFABSTRACTMODEL_H
// Qt
#include <QAbstractItemModel>
// KDE
namespace Kickoff
{
/**
* Base model for Kickoff models based on QAbstractItemModel, enables drag and drop support
*/
class KickoffAbstractModel : public QAbstractItemModel
{
Q_OBJECT
public:
/** Construct a new KickoffModel with the specified parent. */
KickoffAbstractModel(QObject *parent = 0);
virtual ~KickoffAbstractModel();
//Reimplementations
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const;
virtual QStringList mimeTypes() const;
virtual Qt::DropActions supportedDropActions() const;
virtual Qt::DropActions supportedDragActions() const;
};
}
#endif // KICKOFFABSTRACTMODEL_H

View file

@ -0,0 +1,99 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "kickoffmodel.h"
// Qt
#include <QMimeData>
// KDE
#include <KUrl>
#include <QDebug>
// Local
#include "models.h"
using namespace Kickoff;
KickoffModel::KickoffModel(QObject *parent)
: QStandardItemModel(parent)
{
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "display";
roles[Qt::DecorationRole] = "decoration";
roles[Kickoff::SubTitleRole] = "subtitle";
roles[Kickoff::UrlRole] = "url";
roles[GroupNameRole] = "group";
setRoleNames(roles);
}
KickoffModel::~KickoffModel()
{}
Qt::ItemFlags KickoffModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QStandardItemModel::flags(index);
if (index.isValid()) {
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
} else {
return 0;
}
}
QMimeData *KickoffModel::mimeData(const QModelIndexList &indexes) const
{
KUrl::List urls;
foreach (const QModelIndex &index, indexes) {
KUrl itemUrl = KUrl(data(index, UrlRole).toString());
if (itemUrl.isValid()) {
urls << itemUrl;
}
}
QMimeData *mimeData = new QMimeData();
if (!urls.isEmpty()) {
urls.populateMimeData(mimeData);
}
return mimeData;
}
QStringList KickoffModel::mimeTypes() const
{
QStringList types;
types << QLatin1String("text/uri-list");
return types;
}
Qt::DropActions KickoffModel::supportedDropActions() const
{
return Qt::MoveAction;
}
Qt::DropActions KickoffModel::supportedDragActions() const
{
return Qt::CopyAction;
}
#include "kickoffmodel.moc"

View file

@ -0,0 +1,55 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KICKOFFMODEL_H
#define KICKOFFMODEL_H
// Qt
#include <QStandardItemModel>
// KDE
namespace Kickoff
{
/**
* Base model for Kickoff models based on QStandardItemModel, enables drag and drop support
*/
class KickoffModel : public QStandardItemModel
{
Q_OBJECT
public:
/** Construct a new KickoffModel with the specified parent. */
KickoffModel(QObject *parent = 0);
virtual ~KickoffModel();
//Reimplementations
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const;
virtual QStringList mimeTypes() const;
virtual Qt::DropActions supportedDropActions() const;
virtual Qt::DropActions supportedDragActions() const;
private:
};
}
#endif // KICKOFFMODEL_H

View file

@ -0,0 +1,45 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "kickoffplugin.h"
#include "applicationmodel.h"
#include "favoritesmodel.h"
#include "krunnermodel.h"
#include "leavemodel.h"
#include "recentlyusedmodel.h"
#include "systemmodel.h"
#include "kuserproxy.h"
#include "urlitemlauncher.h"
#include <QtQml>
void KickoffPlugin::registerTypes (const char *uri)
{
Q_ASSERT(uri == QLatin1String("org.kde.plasma.private.kickoff"));
qmlRegisterType<Kickoff::ApplicationModel>(uri, 0, 1, "ApplicationModel");
qmlRegisterType<Kickoff::FavoritesModel>(uri, 0, 1, "FavoritesModel");
qmlRegisterType<Kickoff::KRunnerModel>(uri, 0, 1, "KRunnerModel");
qmlRegisterType<Kickoff::LeaveModel>(uri, 0, 1, "LeaveModel");
qmlRegisterType<Kickoff::RecentlyUsedModel>(uri, 0, 1, "RecentlyUsedModel");
qmlRegisterType<Kickoff::SystemModel>(uri, 0, 1, "SystemModel");
qmlRegisterType<Kickoff::UrlItemLauncher>(uri, 0, 1, "Launcher");
qmlRegisterType<KUserProxy>(uri, 0, 1, "KUser");
}
#include "kickoffplugin.moc"

View file

@ -0,0 +1,35 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef KICKOFFPLUGIN_H
#define KICKOFFPLUGIN_H
#include <QQmlEngine>
#include <QQmlExtensionPlugin>
class KickoffPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
public:
virtual void registerTypes(const char *uri);
};
#endif // KICKOFFPLUGIN_H

View file

@ -0,0 +1,92 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "kickoffproxymodel.h"
// Qt
#include <QMimeData>
// KDE
#include <KUrl>
#include <QDebug>
// Local
#include "models.h"
using namespace Kickoff;
KickoffProxyModel::KickoffProxyModel(QObject *parent)
: QAbstractProxyModel(parent)
{}
KickoffProxyModel::~KickoffProxyModel()
{}
Qt::ItemFlags KickoffProxyModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QAbstractProxyModel::flags(index);
if (index.isValid()) {
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
} else {
return 0;
}
}
QMimeData *KickoffProxyModel::mimeData(const QModelIndexList &indexes) const
{
KUrl::List urls;
QByteArray itemData;
foreach(const QModelIndex &index, indexes) {
KUrl itemUrl = KUrl(data(index, UrlRole).toString());
if (itemUrl.isValid()) {
urls << itemUrl;
}
}
QMimeData *mimeData = new QMimeData();
if (!urls.isEmpty()) {
urls.populateMimeData(mimeData);
}
return mimeData;
}
QStringList KickoffProxyModel::mimeTypes() const
{
QStringList types;
types << QLatin1String("text/uri-list");
return types;
}
Qt::DropActions KickoffProxyModel::supportedDropActions() const
{
return 0;
}
Qt::DropActions KickoffProxyModel::supportedDragActions() const
{
return Qt::CopyAction;
}
#include "kickoffproxymodel.moc"

View file

@ -0,0 +1,53 @@
/*
Copyright 2008 Marco Martin <notmart@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KICKOFFPROXYMODEL_H
#define KICKOFFPROXYMODEL_H
// Qt
#include <QAbstractProxyModel>
// KDE
namespace Kickoff
{
/**
* Base model for Kickoff models based on QAbstractProxyModel, enables drag and drop support
*/
class KickoffProxyModel : public QAbstractProxyModel
{
Q_OBJECT
public:
/** Construct a new KickoffModel with the specified parent. */
KickoffProxyModel(QObject *parent = 0);
virtual ~KickoffProxyModel();
//Reimplementations
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const;
virtual QStringList mimeTypes() const;
virtual Qt::DropActions supportedDropActions() const;
virtual Qt::DropActions supportedDragActions() const;
};
}
#endif // KICKOFFPROXYMODEL_H

View file

@ -0,0 +1,289 @@
/*
Copyright 2009 Ivan Cukic <ivan.cukic+kde@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "krunnermodel.h"
// Qt
#include <QBasicTimer>
#include <QDebug>
#include <QList>
#include <QMimeData>
#include <QString>
#include <QTimerEvent>
// KDE
#include <KService>
#include <KStandardDirs>
#include <KLocalizedString>
#include <KUrl>
//#include <KRunner/AbstractRunner>
//#include <KRunner/RunnerManager>
#include <krunner/abstractrunner.h>
#include <krunner/runnermanager.h>
// Local
#include "recentapplications.h"
#define DELAY_TIME 50
using namespace Kickoff;
Plasma::RunnerManager * _runnerManager = NULL;
Plasma::RunnerManager * runnerManager() {
if (_runnerManager == NULL) {
KConfigGroup conf =
componentData().config()->group("KRunner");
conf.writeEntry("loadAll", false);
_runnerManager = new Plasma::RunnerManager(conf);
// initializing allowed runners
QStringList allowed;
allowed
<< "places"
<< "shell"
<< "services"
<< "bookmarks"
<< "recentdocuments"
<< "locations"
<< "baloosearch";
_runnerManager->setAllowedRunners(allowed);
conf.sync();
// runner: "konquerorsessions" "Konqueror Sessions"
// runner: "desktopsessions" "Desktop Sessions"
// runner: "places" "Places"
// runner: "windows" "Windows"
// runner: "plasma-desktop" "Plasma Desktop Shell"
// runner: "services" "Applications"
// runner: "PowerDevil" "PowerDevil"
// runner: "browserhistory" "Web Browser History"
// runner: "shell" "Command Line"
// runner: "katesessions" "Kate Sessions"
// runner: "locations" "Locations"
// runner: "webshortcuts" "Web Shortcuts"
// runner: "kabccontacts" "Contacts"
// runner: "konsolesessions" "Konsole Sessions"
// runner: "recentdocuments" "Recent Documents"
// runner: "calculator" "Calculator"
// runner: "amarok" "Amarok"
// runner: "wikipedia" "Wikipedia"
// runner: "kopete" "Kopete Contact Runner"
// runner: "bookmarks" "Bookmarks"
// runner: "unitconverter" "Unit Converter"
}
return _runnerManager;
}
KService::Ptr Kickoff::serviceForUrl(const KUrl & url)
{
QString runner = url.host();
QString id = url.path();
if (id.startsWith(QLatin1Char('/'))) {
id = id.remove(0, 1);
}
if (runner != QLatin1String("services")) {
return KService::Ptr(NULL);
}
// URL path example: services_kde4-kate.desktop
// or: services_firefox.desktop
id.remove("services_");
return KService::serviceByStorageId(id);
}
class ResultItem {
public:
ResultItem()
{
}
ResultItem(QIcon _icon, QString _name, QString _description, QVariant _data)
: icon(_icon),
name(_name),
description(_description),
data(_data)
{
}
QIcon icon;
QString name, description;
QVariant data;
};
bool KRunnerItemHandler::openUrl(const KUrl& url)
{
QString runner = url.host();
QString id = url.path();
if (id.startsWith(QLatin1Char('/'))) {
id = id.remove(0, 1);
}
// Since krunner:// urls can't be added to recent applications,
// we find the local .desktop entry.
KService::Ptr service = serviceForUrl(url);
if (service) {
RecentApplications::self()->add(service);
} else {
qWarning() << "Failed to find service for" << url;
}
runnerManager()->run(id);
return true;
}
class KRunnerModel::Private {
public:
Private()
{
}
~Private()
{
}
QBasicTimer searchDelay;
QString searchQuery;
DisplayOrder displayOrder;
};
KRunnerModel::KRunnerModel(QObject *parent)
: KickoffModel(parent)
, d(new Private())
{
connect(runnerManager(),
SIGNAL(matchesChanged(QList<Plasma::QueryMatch>)),
this,
SLOT(matchesChanged(QList<Plasma::QueryMatch>)));
UrlItemLauncher::addGlobalHandler(UrlItemLauncher::ProtocolHandler, "krunner", new KRunnerItemHandler);
}
KRunnerModel::~KRunnerModel()
{
delete d;
}
void KRunnerModel::setQuery(const QString& query)
{
runnerManager()->reset();
clear();
d->searchQuery = query.trimmed();
if (d->searchQuery.isEmpty()) {
return;
}
d->searchDelay.start(DELAY_TIME, this);
}
void KRunnerModel::timerEvent(QTimerEvent * event)
{
KickoffModel::timerEvent(event);
if (event->timerId() == d->searchDelay.timerId()) {
d->searchDelay.stop();
runnerManager()->launchQuery(d->searchQuery);
};
}
void KRunnerModel::setNameDisplayOrder(DisplayOrder displayOrder)
{
d->displayOrder = displayOrder;
}
DisplayOrder KRunnerModel::nameDisplayOrder() const
{
return d->displayOrder;
}
void KRunnerModel::matchesChanged(const QList< Plasma::QueryMatch > & m)
{
QList< Plasma::QueryMatch > matches = m;
qSort(matches.begin(), matches.end());
clear();
while (matches.size()) {
Plasma::QueryMatch match = matches.takeLast();
qDebug() << "matches " << QString("krunner://") + match.runner()->id() + "/" + match.id();
appendRow(
StandardItemFactory::createItem(
match.icon(),
match.text(),
match.subtext(),
QString("krunner://") + match.runner()->id() + "/" + match.id()
)
);
}
}
Qt::ItemFlags KRunnerModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = KickoffModel::flags(index);
if (index.isValid()) {
KUrl url = data(index, UrlRole).toString();
QString host = url.host();
if (host != "services") {
flags &= ~ ( Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled );
}
} else {
flags = 0;
}
return flags;
}
QMimeData * KRunnerModel::mimeData(const QModelIndexList &indexes) const
{
KUrl::List urls;
foreach (const QModelIndex & index, indexes) {
KUrl url = data(index, UrlRole).toString();
KService::Ptr service = serviceForUrl(url);
if (service) {
urls << KUrl(service->entryPath());
}
}
QMimeData *mimeData = new QMimeData();
if (!urls.isEmpty()) {
urls.populateMimeData(mimeData);
}
return mimeData;
}
#include "krunnermodel.moc"

View file

@ -0,0 +1,76 @@
/*
Copyright 2009 Ivan Cukic <ivan.cukic+kde@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KRUNNERMODEL_H
#define KRUNNERMODEL_H
#include "models.h"
#include "kickoffmodel.h"
#include "urlitemlauncher.h"
namespace Plasma {
class QueryMatch;
}
namespace Kickoff {
KService::Ptr serviceForUrl(const KUrl & url);
class KRunnerItemHandler : public UrlItemHandler {
public:
virtual bool openUrl(const KUrl& url);
};
class KRunnerModel : public KickoffModel
{
Q_OBJECT
public:
KRunnerModel(QObject *parent = NULL);
virtual ~KRunnerModel();
void setNameDisplayOrder(DisplayOrder displayOrder);
DisplayOrder nameDisplayOrder() const;
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
virtual QMimeData *mimeData(const QModelIndexList &indexes) const;
// virtual QStringList mimeTypes() const;
// virtual Qt::DropActions supportedDropActions() const;
// virtual Qt::DropActions supportedDragActions() const;
private:
void timerEvent(QTimerEvent * event);
public Q_SLOTS:
void setQuery(const QString& query);
private Q_SLOTS:
void matchesChanged(const QList< Plasma::QueryMatch > & matches);
Q_SIGNALS:
void resultsAvailable();
private:
class Private;
Private * const d;
};
}
#endif // KRUNNERMODEL_H

View file

@ -0,0 +1,101 @@
/***************************************************************************
* Copyright 2013 Marco Martin <mart@kde.org> *
* Copyright 2014 Sebastian Kugler <sebas@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include <unistd.h>
#include "kuserproxy.h"
#include <QFile>
#include <QTextStream>
#include <QUrl>
#include <KLocalizedString>
#include <QDebug>
KUserProxy::KUserProxy (QObject *parent)
: QObject(parent)
{
}
KUserProxy::~KUserProxy()
{
}
QString KUserProxy::fullName() const
{
return m_user.property(KUser::FullName).toString();
}
QString KUserProxy::loginName() const
{
return m_user.loginName();
}
QString KUserProxy::faceIconPath() const
{
const QString u = m_user.faceIconPath();
const QFile f(u);
if (f.exists(u)) {
// We need to return a file URL, not a simple path
return QUrl::fromLocalFile(u).toString();
}
return QString();
}
QString KUserProxy::os()
{
if (m_os.isEmpty()) {
m_os = i18n("Plasma by KDE");
QFile osfile("/etc/os-release");
if (osfile.exists()) {
if (!osfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
return QString();
}
QTextStream in(&osfile);
while(!in.atEnd()) {
QString line = in.readLine();
if (line.startsWith("PRETTY_NAME")) {
QStringList fields = line.split("PRETTY_NAME=\"");
if (fields.count() == 2) {
osfile.close();
QString pretty = fields.at(1);
pretty.chop(1);
m_os = pretty;
return pretty;
}
}
}
osfile.close();
}
}
return m_os;
}
QString KUserProxy::host() const
{
char hostname[256];
hostname[0] = '\0';
if (!gethostname(hostname, sizeof(hostname))) {
hostname[sizeof(hostname)-1] = '\0';
}
return QString(hostname);
}

View file

@ -0,0 +1,53 @@
/***************************************************************************
* Copyright 2014 Sebastian Kügler <sebas@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#ifndef KUSERPROXY_H
#define KUSERPROXY_H
#include <QObject>
#include <KUser>
class KUserProxy : public QObject
{
Q_OBJECT
Q_PROPERTY(QString fullName READ fullName CONSTANT)
Q_PROPERTY(QString loginName READ loginName CONSTANT)
Q_PROPERTY(QString faceIconPath READ faceIconPath CONSTANT)
Q_PROPERTY(QString os READ os CONSTANT)
Q_PROPERTY(QString host READ host CONSTANT)
public:
KUserProxy(QObject *parent = 0);
~KUserProxy();
QString fullName() const;
QString loginName() const;
QString faceIconPath() const;
QString os();
QString host() const;
private:
KUser m_user;
QString m_os;
};
#endif //KUSERPROXY_H

View file

@ -0,0 +1,212 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "leavemodel.h"
// Qt
#include <QFileInfo>
// KDE
#include <KAuthorized>
#include <KConfigGroup>
#include <KLocalizedString>
#include <QDebug>
#include <KIcon>
#include <Solid/PowerManagement>
#include <kworkspace.h>
#include <kdisplaymanager.h>
// Local
#include "models.h"
#include "itemhandlers.h"
using namespace Kickoff;
class LeaveModel::Private
{
};
QStandardItem* LeaveModel::createStandardItem(const QString& url)
{
//Q_ASSERT(KUrl(url).scheme() == "leave");
QStandardItem *item = new QStandardItem();
const QString basename = QFileInfo(url).baseName();
if (basename == "logoutonly") {
item->setText(i18n("Log out"));
item->setIcon(KIcon("system-log-out"));
item->setData(i18n("End session"), Kickoff::SubTitleRole);
} else if (basename == "lock") {
item->setText(i18n("Lock"));
item->setIcon(KIcon("system-lock-screen"));
item->setData(i18n("Lock screen"), Kickoff::SubTitleRole);
} else if (basename == "switch") {
item->setText(i18n("Switch user"));
item->setIcon(KIcon("system-switch-user"));
item->setData(i18n("Start a parallel session as a different user"), Kickoff::SubTitleRole);
} else if (basename == "shutdown") {
item->setText(i18n("Shut down"));
item->setIcon(KIcon("system-shutdown"));
item->setData(i18n("Turn off computer"), Kickoff::SubTitleRole);
} else if (basename == "restart") {
item->setText(i18nc("Restart computer", "Restart"));
item->setIcon(KIcon("system-reboot"));
item->setData(i18n("Restart computer"), Kickoff::SubTitleRole);
} else if (basename == "savesession") {
item->setText(i18n("Save Session"));
item->setIcon(KIcon("document-save"));
item->setData(i18n("Save current session for next login"), Kickoff::SubTitleRole);
} else if (basename == "standby") {
item->setText(i18nc("Puts the system on standby", "Standby"));
item->setIcon(KIcon("system-suspend"));
item->setData(i18n("Pause without logging out"), Kickoff::SubTitleRole);
} else if (basename == "suspenddisk") {
item->setText(i18n("Hibernate"));
item->setIcon(KIcon("system-suspend-hibernate"));
item->setData(i18n("Suspend to disk"), Kickoff::SubTitleRole);
} else if (basename == "suspendram") {
item->setText(i18n("Sleep"));
item->setIcon(KIcon("system-suspend"));
item->setData(i18n("Suspend to RAM"), Kickoff::SubTitleRole);
} else {
item->setText(basename);
item->setData(url, Kickoff::SubTitleRole);
}
item->setData(url, Kickoff::UrlRole);
return item;
}
LeaveModel::LeaveModel(QObject *parent)
: QStandardItemModel(parent)
, d(0)
{
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "display";
roles[Qt::DecorationRole] = "decoration";
roles[Kickoff::SubTitleRole] = "subtitle";
roles[Kickoff::UrlRole] = "url";
roles[GroupNameRole] = "group";
setRoleNames(roles);
updateModel();
Kickoff::UrlItemLauncher::addGlobalHandler(Kickoff::UrlItemLauncher::ProtocolHandler, "leave", new Kickoff::LeaveItemHandler);
}
QVariant LeaveModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || section != 0) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
return i18n("Leave");
break;
default:
return QVariant();
}
}
void LeaveModel::updateModel()
{
clear();
// Session Options
const QString session = i18n("Session");
// Logout
const bool canLogout = KAuthorized::authorizeKAction("logout") && KAuthorized::authorize("logout");
if (canLogout) {
QStandardItem *logoutOption = createStandardItem("leave:/logoutonly");
logoutOption->setData(session, Kickoff::GroupNameRole);
appendRow(logoutOption);
}
// Lock
if (KAuthorized::authorizeKAction("lock_screen")) {
QStandardItem *lockOption = createStandardItem("leave:/lock");
lockOption->setData(session, Kickoff::GroupNameRole);
appendRow(lockOption);
}
// Save Session
if (canLogout) {
KConfigGroup c(KSharedConfig::openConfig("ksmserverrc", KConfig::NoGlobals), "General");
if (c.readEntry("loginMode") == "restoreSavedSession") {
QStandardItem *saveSessionOption = createStandardItem("leave:/savesession");
saveSessionOption->setData(session, Kickoff::GroupNameRole);
appendRow(saveSessionOption);
}
}
// Switch User
if (KDisplayManager().isSwitchable() && KAuthorized::authorize(QLatin1String("switch_user"))) {
QStandardItem *switchUserOption = createStandardItem("leave:/switch");
switchUserOption->setData(session, Kickoff::GroupNameRole);
appendRow(switchUserOption);
}
// System Options
//FIXME: the proper fix is to implement the KWorkSpace methods for Windows
#ifndef Q_WS_WIN
const QString system = i18n("System");
QSet< Solid::PowerManagement::SleepState > spdMethods = Solid::PowerManagement::supportedSleepStates();
if (spdMethods.contains(Solid::PowerManagement::StandbyState)) {
QStandardItem *standbyOption = createStandardItem("leave:/standby");
standbyOption->setData(system, Kickoff::GroupNameRole);
appendRow(standbyOption);
}
if (spdMethods.contains(Solid::PowerManagement::SuspendState)) {
QStandardItem *suspendramOption = createStandardItem("leave:/suspendram");
suspendramOption->setData(system, Kickoff::GroupNameRole);
appendRow(suspendramOption);
}
if (spdMethods.contains(Solid::PowerManagement::HibernateState)) {
QStandardItem *suspenddiskOption = createStandardItem("leave:/suspenddisk");
suspenddiskOption->setData(system, Kickoff::GroupNameRole);
appendRow(suspenddiskOption);
}
if (canLogout) {
if (KWorkSpace::canShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeReboot)) {
// Restart
QStandardItem *restartOption = createStandardItem("leave:/restart");
restartOption->setData(system, Kickoff::GroupNameRole);
appendRow(restartOption);
}
if (KWorkSpace::canShutDown(KWorkSpace::ShutdownConfirmDefault, KWorkSpace::ShutdownTypeHalt)) {
// Shutdown
QStandardItem *shutDownOption = createStandardItem("leave:/shutdown");
shutDownOption->setData(system, Kickoff::GroupNameRole);
appendRow(shutDownOption);
}
}
#endif
}
LeaveModel::~LeaveModel()
{
delete d;
}
#include "leavemodel.moc"

View file

@ -0,0 +1,48 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef LEAVEMODEL_H
#define LEAVEMODEL_H
#include <QStandardItemModel>
namespace Kickoff
{
class LeaveModel : public QStandardItemModel
{
Q_OBJECT
public:
LeaveModel(QObject *parent = NULL);
~LeaveModel();
static QStandardItem* createStandardItem(const QString& url);
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
void updateModel();
private:
class Private;
Private * const d;
};
}
#endif // LEAVEMODEL_H

View file

@ -0,0 +1,214 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "models.h"
#include "leavemodel.h"
// Qt
#include <QFileInfo>
#include <QStandardItem>
#include <QDir>
// KDE
#include <QDebug>
#include <KConfigGroup>
#include <KDesktopFile>
#include <KIcon>
#include <KMimeType>
#include <KLocalizedString>
#include <KGlobal>
#include <KUrl>
#include <Solid/Device>
#include <Solid/StorageAccess>
#include <Solid/StorageDrive>
using namespace Kickoff;
namespace Kickoff
{
Q_GLOBAL_STATIC_WITH_ARGS(KUrl, homeUrl, (QDir::homePath()))
Q_GLOBAL_STATIC_WITH_ARGS(KUrl, remoteUrl, ("remote:/"))
K_GLOBAL_STATIC(StandardItemFactoryData, factoryData)
StandardItemFactoryData* deviceFactoryData()
{
return factoryData;
}
} // namespace Kickoff
QStandardItem *StandardItemFactory::createItemForUrl(const QString& urlString, DisplayOrder displayOrder)
{
KUrl url(urlString);
QStandardItem *item = 0;
// Match files ending with ".desktop" and being local or having a relative
// path. For instance applications that still installs .desktop files at
// /usr/share/applnk, like KVirc 3
if (urlString.endsWith(QLatin1String(".desktop")) && (url.isLocalFile() || url.isRelative())) {
// .desktop files may be services (type field == 'Application' or 'Service')
// or they may be other types such as links.
//
// first look in the KDE service database to see if this file is a service,
// otherwise represent it as a generic .desktop file
KService::Ptr service = KService::serviceByDesktopPath(url.toLocalFile());
if (service) {
return createItemForService(service, displayOrder);
}
item = new QStandardItem;
KDesktopFile desktopFile(url.toLocalFile());
item->setText(QFileInfo(urlString.mid(0, urlString.lastIndexOf('.'))).completeBaseName());
item->setIcon(KIcon(desktopFile.readIcon()));
//FIXME: desktopUrl is a hack around borkage in KRecentDocuments which
// stores a path in the URL field!
KUrl desktopUrl(desktopFile.desktopGroup().readPathEntry("URL", QString()));
if (!desktopUrl.url().isEmpty()) {
item->setData(desktopUrl.url(), Kickoff::UrlRole);
} else {
// desktopUrl.url() is empty if the file doesn't exist so set the
// url role to that which was passed so that the item can still be
// manually removed
item->setData(urlString, Kickoff::UrlRole);
}
QString subTitle = desktopUrl.isLocalFile() ? desktopUrl.toLocalFile() : desktopUrl.prettyUrl();
item->setData(subTitle, Kickoff::SubTitleRole);
setSpecialUrlProperties(desktopUrl, item);
} else if (url.scheme() == "leave") {
item = LeaveModel::createStandardItem(urlString);
} else {
item = new QStandardItem;
const QString subTitle = url.isLocalFile() ? url.toLocalFile() : url.prettyUrl();
QString basename = QFileInfo(url.prettyUrl()).completeBaseName();
if (basename.isNull()) {
basename = subTitle;
}
item->setText(basename);
//FIXME
// item->setIcon(KIcon(KMimeType::iconNameForUrl(url)));
item->setData(url.url(), Kickoff::UrlRole);
item->setData(subTitle, Kickoff::SubTitleRole);
setSpecialUrlProperties(url, item);
}
return item;
}
void StandardItemFactory::setSpecialUrlProperties(const KUrl& url, QStandardItem *item)
{
// specially handled URLs
if (homeUrl() && url == *homeUrl()) {
item->setText(i18n("Home Folder"));
item->setIcon(KIcon("user-home"));
} else if (remoteUrl() && url == *remoteUrl()) {
item->setText(i18n("Network Folders"));
}
}
QStandardItem *StandardItemFactory::createItem(const QIcon & icon, const QString & title,
const QString & description, const QString & url)
{
QStandardItem *appItem = new QStandardItem;
appItem->setText(title);
appItem->setIcon(icon);
appItem->setData(description, Kickoff::SubTitleRole);
appItem->setData(url, Kickoff::UrlRole);
return appItem;
}
QStandardItem *StandardItemFactory::createItemForService(KService::Ptr service, DisplayOrder displayOrder)
{
QStandardItem *appItem = new QStandardItem;
QString genericName = service->genericName();
QString appName = service->name();
bool nameFirst = displayOrder == NameBeforeDescription;
appItem->setText(nameFirst || genericName.isEmpty() ? appName : genericName);
appItem->setIcon(KIcon(service->icon()));
appItem->setData(service->entryPath(), Kickoff::UrlRole);
if (nameFirst) {
if (!genericName.isEmpty()) {
appItem->setData(genericName, Kickoff::SubTitleRole);
}
} else if (!genericName.isEmpty()) {
// we only set the subtitle to appname if the generic name is empty because if
// the generic name IS empty, then the app name is used as the title role
// and we don't want it repeated twice.
appItem->setData(appName, Kickoff::SubTitleRole);
}
return appItem;
}
bool Kickoff::isLaterVersion(KService::Ptr first , KService::Ptr second)
{
// a very crude heuristic using the .desktop path names
// which only understands kde3 vs kde4
bool firstIsKde4 = first->entryPath().contains("kde4");
bool secondIsKde4 = second->entryPath().contains("kde4");
return firstIsKde4 && !secondIsKde4;
}
QStringList Kickoff::systemApplicationList()
{
KConfigGroup appsGroup = componentData().config()->group("SystemApplications");
QStringList apps;
apps << "systemsettings";
apps = appsGroup.readEntry("DesktopFiles", apps);
return apps;
}
#if 0
void Kickoff::swapModelIndexes(QModelIndex& first, QModelIndex& second)
{
Q_ASSERT(first.isValid());
Q_ASSERT(second.isValid());
QAbstractItemModel *firstModel = const_cast<QAbstractItemModel*>(first.model());
QAbstractItemModel *secondModel = const_cast<QAbstractItemModel*>(second.model());
Q_ASSERT(firstModel && secondModel);
QMap<int, QVariant> firstIndexData = firstModel->itemData(first);
QMap<int, QVariant> secondIndexData = secondModel->itemData(second);
firstModel->setItemData(first, secondIndexData);
secondModel->setItemData(second, firstIndexData);
}
#endif
K_GLOBAL_STATIC_WITH_ARGS(KComponentData, kickoffComponent, ("kickoff", QByteArray(), KComponentData::SkipMainComponentRegistration))
KComponentData Kickoff::componentData()
{
return *kickoffComponent;
}

View file

@ -0,0 +1,140 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef MODELS_H
#define MODELS_H
// Qt
// KDE
#include <KService>
#include <KComponentData>
class QStandardItem;
class KUrl;
class QModelIndex;
namespace Solid
{
class Device;
}
namespace Kickoff
{
class StandardItemFactoryData
{
public:
QHash<QString, Solid::Device> deviceByUrl;
};
StandardItemFactoryData* deviceFactoryData();
/**
* List of applications contained in the DesktopFiles key in the
* SystemApplications group, used to populate the System model
* @return list of desktop entry names
*/
QStringList systemApplicationList();
/**
* Additional data roles for data which the Kickoff models supply with their items
* for use when rendering the items and launching them.
*/
enum DataRole {
/** A sub title to be displayed below the text from the item's Qt::DisplayRole data */
SubTitleRole = Qt::UserRole + 1,
FirstDataRole = SubTitleRole,
/** The URL to be opened when executing the item. */
UrlRole = Qt::UserRole + 2,
/** The Solid device identifier for items which represent devices. */
DeviceUdiRole = Qt::UserRole + 3,
/** The amount of space (in Kilobytes) used for items which represent storage. */
DiskUsedSpaceRole = Qt::UserRole + 4,
/** The amount of free space (in Kilobytes) for items which represent storage. */
DiskFreeSpaceRole = Qt::UserRole + 5,
SubTitleMandatoryRole = Qt::UserRole + 6,
/** Is item a separator. **/
SeparatorRole = Qt::UserRole + 7,
/** relative path of the item */
RelPathRole = Qt::UserRole + 8,
IconNameRole = Qt::UserRole + 9,
GroupNameRole = IconNameRole,
LastDataRole = Qt::UserRole + 10
};
/**
* This enum describes the policy for displaying
* Name of Application - Description
* Description - Name of Application
*/
enum DisplayOrder {
NameAfterDescription,
NameBeforeDescription
};
/**
* Factory for creating QStandardItems with appropriate text, icons, URL
* and other Kickoff-specific information for a given URL or Service.
*/
class StandardItemFactory
{
public:
static QStandardItem *createItemForUrl(const QString& url, DisplayOrder displayOrder);
static QStandardItem *createItemForService(KService::Ptr service,
DisplayOrder displayOrder);
static QStandardItem *createItem(const QIcon & icon, const QString & title,
const QString & description, const QString & url);
private:
static void setSpecialUrlProperties(const KUrl& url, QStandardItem *item);
};
/**
* Abstract base class for delegates which provide information about a model
* item's state in a particular view.
*/
class ItemStateProvider
{
public:
virtual ~ItemStateProvider() {}
/**
* Returns true if a @p index should be drawn in the view or
* false if it should be hidden.
*/
virtual bool isVisible(const QModelIndex& index) const = 0;
};
// returns true if 'first' represents a more recent version of
// an application than 'second'
//
// eg. isLaterVersion(myapp_kde4,myapp_kde3) returns true
bool isLaterVersion(KService::Ptr first , KService::Ptr second);
#if 0
/** Swaps the data for two indexes in a QAbstractItemModel */
void swapModelIndexes(QModelIndex& first, QModelIndex& second);
#endif
// returns the Kickoff component data, this is mainly used
// to access the Kickoff shared config data
KComponentData componentData();
}
#endif //MODELS_H

View file

@ -0,0 +1,7 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.kde.kickoff.recent">
<signal name="clearRecentDocumentsAndApplications"/>
</interface>
</node>

View file

@ -0,0 +1,7 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.kde.kickoff">
<signal name="reloadMenu"/>
</interface>
</node>

View file

@ -0,0 +1 @@
plugin kickoffplugin

View file

@ -0,0 +1,195 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "recentapplications.h"
// Qt
#include <QtCore/QHash>
#include <QtCore/QLinkedList>
// KDE
#include <KConfigGroup>
#include <KGlobal>
#include <QDebug>
// Local
#include "models.h"
using namespace Kickoff;
class RecentApplications::Private
{
public:
class ServiceInfo;
Private() : defaultMaxServices(DEFAULT_MAX_SERVICES) {
KConfigGroup recentGroup = componentData().config()->group("RecentlyUsed");
QList<QString> recentApplications = recentGroup.readEntry("Applications", QList<QString>());
defaultMaxServices = maxServices = qMax(0, recentGroup.readEntry("MaxApplications", defaultMaxServices));
// TESTING
// the actual last date/time is not currently recorded, instead we just use
// the current date/time and adjust it by one second after each item is added
// to preserve the order of the applications in the list loaded from the KConfig
// source
QDateTime dateTime = QDateTime::currentDateTime();
foreach(const QString& application, recentApplications) {
ServiceInfo info;
info.storageId = application;
info.startCount = 1;
info.lastStartedTime = dateTime;
addEntry(info.storageId, info);
dateTime = dateTime.addSecs(1);
}
};
~Private() {
KConfigGroup recentGroup = componentData().config()->group("RecentlyUsed");
QList<ServiceInfo> services = serviceInfo.values();
qSort(services.begin(), services.end());
// TESTING
// only the desktop file used is currently recorded, information such
// as start count and date/time of last used is lost
QList<QString> recentApplications;
foreach(const ServiceInfo& info, services) {
recentApplications << info.storageId;
}
recentGroup.writeEntry("Applications", recentApplications);
recentGroup.config()->sync();
}
void addEntry(const QString& id, ServiceInfo& info) {
// if this service is already in the list then remove the existing
// queue entry (so that there are no duplicates in the queue)
if (serviceInfo.contains(id)) {
qDebug() << "Duplicate entry added. Removing existing entry from queue.";
serviceQueue.erase(serviceInfo[id].queueIter);
}
serviceQueue.append(id);
info.queueIter = --serviceQueue.end();
serviceInfo.insert(id, info);
}
void removeExpiredEntries() {
// if more than the maximum number of services have been added
// remove the least recently used service
while (serviceQueue.count() > maxServices) {
QString removeId = serviceQueue.takeFirst();
qDebug() << "More than the maximal " << maxServices << " services added. Removing" << removeId << "from queue.";
serviceInfo.remove(removeId);
emit instance.applicationRemoved(KService::serviceByStorageId(removeId));
}
}
class ServiceInfo
{
public:
ServiceInfo() : startCount(0) {}
QString storageId;
int startCount;
QDateTime lastStartedTime;
QLinkedList<QString>::iterator queueIter;
bool operator<(const ServiceInfo& rhs) const {
return this->lastStartedTime < rhs.lastStartedTime;
}
};
static const int DEFAULT_MAX_SERVICES = 5;
int defaultMaxServices, maxServices;
// queue to keep track of the order in which services have been used
// (most recently used at the back)
QLinkedList<QString> serviceQueue;
QHash<QString, ServiceInfo> serviceInfo;
RecentApplications instance;
};
K_GLOBAL_STATIC(RecentApplications::Private, privateSelf)
RecentApplications *RecentApplications::self()
{
return &privateSelf->instance;
}
RecentApplications::RecentApplications()
{
}
QList<KService::Ptr> RecentApplications::recentApplications() const
{
QList<Private::ServiceInfo> services = privateSelf->serviceInfo.values();
qSort(services.begin(), services.end(), qGreater<Private::ServiceInfo>());
QList<KService::Ptr> servicePtrs;
foreach(const Private::ServiceInfo& info, services) {
KService::Ptr s = KService::serviceByStorageId(info.storageId);
if (s) {
servicePtrs << s;
}
}
return servicePtrs;
}
int RecentApplications::startCount(KService::Ptr service) const
{
return privateSelf->serviceInfo[service->storageId()].startCount;
}
QDateTime RecentApplications::lastStartedTime(KService::Ptr service) const
{
return privateSelf->serviceInfo[service->storageId()].lastStartedTime;
}
void RecentApplications::setMaximum(int maximum)
{
Q_ASSERT(maximum >= 0);
privateSelf->maxServices = maximum;
privateSelf->removeExpiredEntries();
}
int RecentApplications::maximum() const
{
return privateSelf->maxServices;
}
int RecentApplications::defaultMaximum() const
{
return privateSelf->defaultMaxServices;
}
void RecentApplications::add(KService::Ptr service)
{
Private::ServiceInfo info = privateSelf->serviceInfo.value(service->storageId());
info.storageId = service->storageId();
info.startCount++;
info.lastStartedTime = QDateTime::currentDateTime();
privateSelf->addEntry(info.storageId, info);
qDebug() << "Recent app added" << info.storageId << info.startCount;
emit applicationAdded(service, info.startCount);
privateSelf->removeExpiredEntries();
}
void RecentApplications::clear()
{
privateSelf->serviceInfo.clear();
emit cleared();
}
#include "recentapplications.moc"

View file

@ -0,0 +1,91 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef RECENTAPPLICATIONS_H
#define RECENTAPPLICATIONS_H
// Qt
#include <QtCore/QObject>
#include <QDateTime>
// KDE
#include <KService>
namespace Kickoff
{
/**
* Singleton class which can be used to keep track of recently started applications
* in the Kickoff launcher.
*
* RecentApplications information persists between sessions.
*/
class RecentApplications : public QObject
{
Q_OBJECT
public:
class Private;
friend class Private;
static RecentApplications *self();
/**
* List of service pointers for recently started applications in the order in which
* they were started, with the most recently used application first.
*/
QList<KService::Ptr> recentApplications() const;
/** Returns the number of times an application represented by @p service has been started. */
int startCount(KService::Ptr service) const;
/** Returns the last time and date with the application represented by @p service was started. */
QDateTime lastStartedTime(KService::Ptr service) const;
/** Sets the maximum number of recently used applications to remember. */
void setMaximum(int max);
/** Returns the maximum number of recently used applications that are remembered. */
int maximum() const;
/** Returns the default maximum number of recently used applications that are remembered as defined
either in the configfile as "MaxApplications" or via the DEFAULT_MAX_SERVICES macro. */
int defaultMaximum() const;
public Q_SLOTS:
/**
* Registers the startup of an application. This should be called whenever a new application
* or service is started.
*/
void add(KService::Ptr service);
/** Clear the list of recent applications. */
void clear();
Q_SIGNALS:
/** Emitted after add() has been called. */
void applicationAdded(KService::Ptr service, int startCount);
/** Emitted after remove() has been called. */
void applicationRemoved(KService::Ptr service);
/** Emitted after clear() has been called. */
void cleared();
private:
RecentApplications();
};
}
#endif // RECENTAPPLICATIONS_H

View file

@ -0,0 +1,282 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
Copyright 2011 Martin Gräßlin <mgraesslin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "recentlyusedmodel.h"
// Qt
// KDE
#include <KDesktopFile>
#include <KDirWatch>
#include <KRecentDocument>
#include <KLocalizedString>
#include <KUrl>
#include <QDebug>
// Local
#include "recentapplications.h"
#include "recentadaptor.h"
using namespace Kickoff;
class RecentlyUsedModel::Private
{
public:
Private(RecentlyUsedModel *parent, RecentType recenttype, int maxRecentApps)
: q(parent),
recenttype(recenttype),
maxRecentApps(maxRecentApps >= 0 ? maxRecentApps : Kickoff::RecentApplications::self()->defaultMaximum()),
displayOrder(NameAfterDescription),
applicationTitle(i18n("Applications")),
documentTitle(i18n("Documents")),
recentApplicationCount(0)
{
}
bool removeExistingItem(const QString& path) {
if (!itemsByPath.contains(path)) {
return false;
}
QStandardItem *existingItem = itemsByPath[path];
qDebug() << "Removing existing item" << existingItem;
QModelIndex index = q->indexFromItem(existingItem);
if (!index.isValid()) {
qDebug() << "Now Index for our existing item";
return false;
}
q->takeRow(index.row());
itemsByPath.remove(path);
delete existingItem;
return true;
}
void addRecentApplication(KService::Ptr service, bool append) {
// remove existing item if any
if (removeExistingItem(service->entryPath())) {
--recentApplicationCount;
}
QStandardItem *appItem = StandardItemFactory::createItemForService(service, displayOrder);
appItem->setData(applicationTitle, Kickoff::GroupNameRole);
itemsByPath.insert(service->entryPath(), appItem);
if (append) {
q->insertRow(recentApplicationCount, appItem);
} else {
q->insertRow(0, appItem);
}
++recentApplicationCount;
while (recentApplicationCount > maxRecentApps) {
--recentApplicationCount;
QList<QStandardItem*> row = q->takeRow(recentApplicationCount);
//don't leave pending stuff in itemsByPath
if (!row.isEmpty()) {
itemsByPath.remove(row.first()->data(UrlRole).toString());
qDeleteAll(row.begin(), row.end());
}
}
}
void addRecentDocument(const QString& desktopPath, bool append) {
// remove existing item if any
KDesktopFile desktopFile(desktopPath);
KUrl documentUrl = desktopFile.readUrl();
removeExistingItem(documentUrl.url());
QStandardItem *documentItem = StandardItemFactory::createItemForUrl(desktopPath, displayOrder);
documentItem->setData(true, Kickoff::SubTitleMandatoryRole);
documentItem->setData(documentTitle, Kickoff::GroupNameRole);
itemsByPath.insert(desktopPath, documentItem);
//qDebug() << "Document item" << documentItem << "text" << documentItem->text() << "url" << documentUrl.url();
if (append) {
q->appendRow(documentItem);
} else {
q->insertRow(0, documentItem);
}
}
void loadRecentDocuments()
{
// create branch for documents and add existing items
const QStringList documents = KRecentDocument::recentDocuments();
foreach(const QString& document, documents) {
addRecentDocument(document, true);
}
}
void loadRecentApplications()
{
const QList<KService::Ptr> services = RecentApplications::self()->recentApplications();
for(int i = 0; i < maxRecentApps && i < services.count(); ++i) {
addRecentApplication(services[i], true);
}
}
RecentlyUsedModel * const q;
RecentType recenttype;
int maxRecentApps;
QHash<QString, QStandardItem*> itemsByPath;
DisplayOrder displayOrder;
QString applicationTitle;
QString documentTitle;
int recentApplicationCount;
};
RecentlyUsedModel::RecentlyUsedModel(QObject *parent, RecentType recenttype, int maxRecentApps)
: KickoffModel(parent),
d(new Private(this, recenttype, maxRecentApps))
{
QDBusConnection dbus = QDBusConnection::sessionBus();
(void)new RecentAdaptor(this);
QDBusConnection::sessionBus().registerObject("/kickoff/RecentAppDoc", this);
dbus.connect(QString(), "/kickoff/RecentAppDoc", "org.kde.plasma", "clearRecentDocumentsAndApplications", this, SLOT(clearRecentDocumentsAndApplications()));
if (recenttype != DocumentsOnly) {
d->loadRecentApplications();
// listen for changes to the list of recent applications
connect(RecentApplications::self(), SIGNAL(applicationAdded(KService::Ptr,int)),
this, SLOT(recentApplicationAdded(KService::Ptr,int)));
connect(RecentApplications::self(), SIGNAL(applicationRemoved(KService::Ptr)),
this, SLOT(recentApplicationRemoved(KService::Ptr)));
connect(RecentApplications::self(), SIGNAL(cleared()),
this, SLOT(recentApplicationsCleared()));
}
if (recenttype != ApplicationsOnly) {
d->loadRecentDocuments();
// listen for changes to the list of recent documents
KDirWatch *recentDocWatch = new KDirWatch(this);
recentDocWatch->addDir(KRecentDocument::recentDocumentDirectory(), KDirWatch::WatchFiles);
connect(recentDocWatch, SIGNAL(created(QString)), this, SLOT(recentDocumentAdded(QString)));
connect(recentDocWatch, SIGNAL(deleted(QString)), this, SLOT(recentDocumentRemoved(QString)));
}
}
RecentlyUsedModel::~RecentlyUsedModel()
{
delete d;
}
QVariant RecentlyUsedModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || section != 0) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
if (d->recenttype == DocumentsAndApplications) {
return i18n("Recently Used");
} else if (d->recenttype == DocumentsOnly) {
return i18n("Recently Used Documents");
} else if (d->recenttype == ApplicationsOnly) {
return i18n("Recently Used Applications");
}
default:
return QVariant();
}
}
void RecentlyUsedModel::setNameDisplayOrder(DisplayOrder displayOrder)
{
if (d->displayOrder == displayOrder) {
return;
}
d->displayOrder = displayOrder;
d->itemsByPath.clear();
clear();
if (d->recenttype != DocumentsOnly) {
d->loadRecentApplications();
}
if (d->recenttype != ApplicationsOnly) {
d->loadRecentDocuments();
}
}
DisplayOrder RecentlyUsedModel::nameDisplayOrder() const
{
return d->displayOrder;
}
void RecentlyUsedModel::recentDocumentAdded(const QString& path)
{
qDebug() << "Recent document added" << path;
d->addRecentDocument(path, false);
}
void RecentlyUsedModel::recentDocumentRemoved(const QString& path)
{
qDebug() << "Recent document removed" << path;
d->removeExistingItem(path);
}
void RecentlyUsedModel::recentApplicationAdded(KService::Ptr service, int)
{
if (service) {
d->addRecentApplication(service, false);
}
}
void RecentlyUsedModel::recentApplicationRemoved(KService::Ptr service)
{
if (service) {
d->removeExistingItem(service->entryPath());
}
}
void RecentlyUsedModel::recentApplicationsCleared()
{
while (d->recentApplicationCount != 0) {
delete takeItem(0);
takeRow(0);
--d->recentApplicationCount;
}
}
void RecentlyUsedModel::clearRecentApplications()
{
RecentApplications::self()->clear();
}
void RecentlyUsedModel::clearRecentDocuments()
{
KRecentDocument::clear();
}
void RecentlyUsedModel::clearRecentDocumentsAndApplications()
{
clearRecentDocuments();
clearRecentApplications();
}
#include "recentlyusedmodel.moc"

View file

@ -0,0 +1,78 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef RECENTLYUSEDMODEL_H
#define RECENTLYUSEDMODEL_H
#include "kickoffmodel.h"
#include "models.h"
// Qt
// KDE
#include <KService>
namespace Kickoff
{
/**
* Model for the Recently Used view which provides a tree of recently used
* applications and documents.
*/
class RecentlyUsedModel : public KickoffModel
{
Q_OBJECT
public:
/** Defines what the model should display. */
enum RecentType {
DocumentsAndApplications, ///< display recently used documents and applications.
DocumentsOnly, ///< documents only. recently used applications will not be displayed.
ApplicationsOnly ///< applications only, recently used documents will not be displayed.
};
/** Construct a new RecentlyUsedModel with the specified parent. */
explicit RecentlyUsedModel(QObject *parent = 0, RecentType recenttype = DocumentsAndApplications, int maxRecentApps = -1);
virtual ~RecentlyUsedModel();
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
void setNameDisplayOrder(DisplayOrder displayOrder);
DisplayOrder nameDisplayOrder() const;
public Q_SLOTS:
void clearRecentApplications();
void clearRecentDocuments();
void clearRecentDocumentsAndApplications();
private Q_SLOTS:
void recentDocumentAdded(const QString& path);
void recentDocumentRemoved(const QString& path);
void recentApplicationAdded(KService::Ptr, int startCount);
void recentApplicationRemoved(KService::Ptr);
void recentApplicationsCleared();
private:
class Private;
Private * const d;
};
}
#endif // RECENTLYUSEDMODEL_H

View file

@ -0,0 +1,489 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
Copyright 2007 Kevin Ottens <ervin@kde.org>
Copyright 2011 Martin Gräßlin <mgraesslin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "systemmodel.h"
// Qt
#include <QHash>
#include <QTimer>
// KDE
#include <KAuthorized>
#include <QDebug>
#include <KDiskFreeSpaceInfo>
#include <KIcon>
#include <KUrl>
#include <KSycoca>
#include <KFilePlacesModel>
#include <KLocalizedString>
#include <Solid/Device>
#include <Solid/DeviceInterface>
#include <Solid/DeviceNotifier>
#include <Solid/StorageAccess>
#include <Solid/StorageDrive>
// Local
#include "models.h"
#include "systemmodel.h"
using namespace Kickoff;
static const int OFFSET = 100;
class SystemModel::Private
{
public:
Private(SystemModel *parent)
: q(parent),
placesModel(new KFilePlacesModel(parent)),
refreshRequested(false)
{
q->setSourceModel(placesModel);
connect(placesModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
q, SLOT(sourceDataChanged(QModelIndex,QModelIndex)));
connect(placesModel, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
q, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int)));
connect(placesModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
q, SLOT(sourceRowsInserted(QModelIndex,int,int)));
connect(placesModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
q, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
connect(placesModel, SIGNAL(rowsRemoved(QModelIndex,int,int)),
q, SLOT(sourceRowsRemoved(QModelIndex,int,int)));
connect(KSycoca::self(), SIGNAL(databaseChanged(QStringList)), q, SLOT(reloadApplications()));
}
SystemModel * const q;
KFilePlacesModel *placesModel;
KService::List appsList;
QMap<QString, UsageInfo> usageByMountpoint;
QWeakPointer<UsageFinder> usageFinder;
bool refreshRequested;
};
SystemModel::SystemModel(QObject *parent)
: KickoffProxyModel(parent)
, d(new Private(this))
{
qRegisterMetaType<UsageInfo>("UsageInfo");
QHash<int, QByteArray> roles;
roles[Qt::DisplayRole] = "display";
roles[Qt::DecorationRole] = "decoration";
roles[Kickoff::SubTitleRole] = "subtitle";
roles[Kickoff::UrlRole] = "url";
roles[Kickoff::GroupNameRole] = "group";
setRoleNames(roles);
}
SystemModel::~SystemModel()
{
delete d;
}
QModelIndex SystemModel::mapFromSource(const QModelIndex &sourceIndex) const
{
if (!sourceIndex.isValid()) {
return QModelIndex();
}
if (d->placesModel->isHidden(sourceIndex)) {
// hidden items not in our model
return QModelIndex();
}
if (d->placesModel->isDevice(sourceIndex)) {
if (d->placesModel->data(sourceIndex, KFilePlacesModel::FixedDeviceRole).toBool()) {
// fixed devices not in our list
return QModelIndex();
}
}
int count = d->appsList.size() -1;
if (KAuthorized::authorize("run_command")) {
++count;
}
for (int i=0; i<d->placesModel->rowCount(); ++i) {
if (i == sourceIndex.row()) {
break;
}
const QModelIndex index = d->placesModel->index(i, 0);
if (d->placesModel->isHidden(index)) {
continue;
}
if (d->placesModel->isDevice(index)) {
if (!d->placesModel->data(index, KFilePlacesModel::FixedDeviceRole).toBool()) {
++count;
}
} else {
// visible place
++count;
}
}
return index(count, 0);
}
QModelIndex SystemModel::mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid()) {
return QModelIndex();
}
if (proxyIndex.internalId() == 0) {
// application index
return QModelIndex();
}
return d->placesModel->index(proxyIndex.internalId() - OFFSET, 0);
}
QModelIndex SystemModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
int count = d->appsList.size()-1;
if (KAuthorized::authorize("run_command")) {
++count;
}
if (row <= count) {
return createIndex(row, column);
}
// find the source
for (int i=0; i<d->placesModel->rowCount(); ++i) {
const QModelIndex index = d->placesModel->index(i, 0);
if (d->placesModel->isHidden(index)) {
continue;
}
if (d->placesModel->isDevice(index)) {
if (!d->placesModel->data(index, KFilePlacesModel::FixedDeviceRole).toBool()) {
++count;
}
} else {
// visible place
++count;
}
if (row == count) {
return createIndex(row, column, i + OFFSET);
}
}
return QModelIndex();
}
QModelIndex SystemModel::parent(const QModelIndex &item) const
{
Q_UNUSED(item)
return QModelIndex();
}
int SystemModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
int count = d->appsList.size();
if (KAuthorized::authorize("run_command")) {
++count;
}
for (int i=0; i<d->placesModel->rowCount(); ++i) {
const QModelIndex index = d->placesModel->index(i, 0);
if (d->placesModel->isHidden(index)) {
continue;
}
if (d->placesModel->isDevice(index)) {
if (!d->placesModel->data(index, KFilePlacesModel::FixedDeviceRole).toBool()) {
++count;
}
} else {
// visible place
++count;
}
}
return count;
}
int SystemModel::columnCount(const QModelIndex &/*parent*/) const
{
return 1;
}
QVariant SystemModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (index.internalId() == 0) {
if (role == GroupNameRole) {
return i18n("Applications");
}
if (d->appsList.count() < index.row()) {
return QVariant();
} else if (d->appsList.count() == index.row()) {
// "Run Command"
switch (role) {
case Qt::DisplayRole:
return i18n("Run Command...");
case Qt::DecorationRole:
return KIcon("system-run");
case SubTitleRole:
return i18n("Run a command or a search query");
case UrlRole:
return "run:/";
default:
return QVariant();
}
}
KService::Ptr service = d->appsList[index.row()];
switch (role) {
case Qt::DisplayRole:
return service->name();
case Qt::DecorationRole:
return KIcon(service->icon());
case SubTitleRole:
return service->genericName();
case UrlRole:
return service->entryPath();
default:
return QVariant();
}
}
if (role == UrlRole) {
return d->placesModel->url(mapToSource(index)).url();
}
if (role == SubTitleRole) {
QModelIndex sourceIndex = mapToSource(index);
if (d->placesModel->isDevice(sourceIndex)) {
Solid::Device dev = d->placesModel->deviceForIndex(sourceIndex);
Solid::StorageAccess *access = dev.as<Solid::StorageAccess>();
if (access) {
return access->filePath();
}
} else {
KUrl url = d->placesModel->url(sourceIndex);
return url.isLocalFile() ? url.toLocalFile() : url.prettyUrl();
}
return QVariant();
}
if (role == GroupNameRole) {
if (d->placesModel->isDevice(mapToSource(index))) {
return i18n("Removable Storage");
} else {
return i18n("Places");
}
}
return d->placesModel->data(mapToSource(index), role);
}
QVariant SystemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || section != 0) {
return QVariant();
}
switch (role) {
case Qt::DisplayRole:
return i18n("Computer");
break;
default:
return QVariant();
}
}
UsageFinder::UsageFinder(QObject *parent)
: QThread(parent)
{
}
void UsageFinder::add(int index, const QString &mountPoint)
{
//NOTE: this is not particularly perfect for a threaded object ;)
// but the assumption here is that add is called before run()
m_toCheck.append(qMakePair(index, mountPoint));
}
void UsageFinder::run()
{
typedef QPair<int, QString> CheckPair;
foreach (CheckPair check, m_toCheck) {
KDiskFreeSpaceInfo freeSpace = KDiskFreeSpaceInfo::freeSpaceInfo(check.second);
if (freeSpace.isValid()) {
UsageInfo info;
info.used = freeSpace.used() / 1024;
info.available = freeSpace.available() / 1024;
emit usageInfo(check.first, check.second, info);
}
}
}
bool SystemModel::hasChildren(const QModelIndex& parent) const
{
Q_UNUSED(parent);
// return always false, else the model states that items in appsList are having children
return false;
}
void SystemModel::refreshUsageInfo()
{
if (d->usageFinder) {
d->refreshRequested = true;
} else {
QTimer::singleShot(100, this, SLOT(startUsageInfoFetch()));
}
}
void SystemModel::setUsageInfo(int index, const QString &mountPoint, const UsageInfo &usageInfo)
{
QModelIndex sourceIndex = d->placesModel->index(index, 0);
if (sourceIndex.isValid()) {
d->usageByMountpoint[mountPoint] = usageInfo;
QModelIndex index = mapFromSource(sourceIndex);
emit dataChanged(index, index);
}
}
void SystemModel::stopRefreshingUsageInfo()
{
d->refreshRequested = false;
}
void SystemModel::usageFinderFinished()
{
if (d->refreshRequested) {
d->refreshRequested = false;
QTimer::singleShot(100, this, SLOT(startUsageInfoFetch()));
}
}
void SystemModel::startUsageInfoFetch()
{
if (d->usageFinder) {
return;
}
UsageFinder *usageFinder = new UsageFinder(this);
d->usageFinder = usageFinder;
connect(usageFinder, SIGNAL(finished()),
this, SLOT(usageFinderFinished()));
connect(usageFinder, SIGNAL(finished()),
usageFinder, SLOT(deleteLater()));
connect(usageFinder, SIGNAL(usageInfo(int,QString,UsageInfo)),
this, SLOT(setUsageInfo(int,QString,UsageInfo)));
bool hasDevices = false;
for (int i = 0; i < d->placesModel->rowCount(); ++i) {
QModelIndex sourceIndex = d->placesModel->index(i, 0);
if (d->placesModel->isDevice(sourceIndex)) {
Solid::Device dev = d->placesModel->deviceForIndex(sourceIndex);
Solid::StorageAccess *access = dev.as<Solid::StorageAccess>();
if (access && !access->filePath().isEmpty()) {
usageFinder->add(i, access->filePath());
hasDevices = true;
}
}
}
if (hasDevices) {
usageFinder->start();
} else {
delete usageFinder;
}
}
void SystemModel::reloadApplications()
{
const QStringList apps = Kickoff::systemApplicationList();
d->appsList.clear();
foreach (const QString &app, apps) {
KService::Ptr service = KService::serviceByStorageId(app);
if (service) {
d->appsList << service;
}
}
}
void Kickoff::SystemModel::sourceDataChanged(const QModelIndex &start, const QModelIndex &end)
{
if (start.parent().isValid()) return;
QModelIndex ourStart = QModelIndex();
QModelIndex ourEnd = QModelIndex();
// find our start
for (int i=start.row(); i<=end.row(); ++i) {
const QModelIndex ourIndex = mapFromSource(d->placesModel->index(i, 0));
if (ourIndex.isValid()) {
ourStart = ourIndex;
break;
}
}
if (!ourStart.isValid()) {
return;
}
// find our end
for (int i=end.row(); i>=start.row(); --i) {
const QModelIndex ourIndex = mapFromSource(d->placesModel->index(i, 0));
if (ourIndex.isValid()) {
ourEnd = ourIndex;
break;
}
}
if (ourEnd.isValid()) {
emit dataChanged(ourStart, ourEnd);
}
}
void Kickoff::SystemModel::sourceRowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent)
Q_UNUSED(start)
Q_UNUSED(end)
// TODO: can we update without resetting the model?
beginResetModel();
}
void Kickoff::SystemModel::sourceRowsInserted(const QModelIndex &parent, int /*start*/, int /*end*/)
{
Q_UNUSED(parent)
// TODO: can we update without resetting the model?
endResetModel();
}
void Kickoff::SystemModel::sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
Q_UNUSED(parent)
Q_UNUSED(start)
Q_UNUSED(end)
// TODO: can we update without resetting the model?
beginResetModel();
}
void Kickoff::SystemModel::sourceRowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
{
Q_UNUSED(parent)
// TODO: can we update without resetting the model?
endResetModel();
}
#include "systemmodel.moc"

View file

@ -0,0 +1,103 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
Copyright 2007 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef SYSTEMMODEL_H
#define SYSTEMMODEL_H
#include "kickoffproxymodel.h"
#include <QThread>
namespace Kickoff
{
struct UsageInfo {
UsageInfo()
: used(0),
available(0)
{}
quint64 used;
quint64 available;
};
class UsageFinder : public QThread
{
Q_OBJECT
public:
UsageFinder(QObject *parent);
void add(int index, const QString &mountPoint);
Q_SIGNALS:
void usageInfo(int index, const QString &mountPoint, const UsageInfo &usageInfo);
protected:
void run();
private:
QList<QPair<int, QString> > m_toCheck;
};
/**
* Model which provides a tree of items for important system setup tools (eg. System Settings) ,
* folders (eg. the user's home folder and the local network) and fixed and removable storage.
*/
class SystemModel : public KickoffProxyModel
{
Q_OBJECT
public:
/** Constructs a new SystemModel with the specified parent. */
SystemModel(QObject *parent = 0);
virtual ~SystemModel();
virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const;
virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
virtual QModelIndex parent(const QModelIndex &item) const;
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
virtual bool hasChildren(const QModelIndex& parent = QModelIndex()) const;
void refreshUsageInfo();
void stopRefreshingUsageInfo();
private Q_SLOTS:
void startUsageInfoFetch();
void reloadApplications();
void sourceDataChanged(const QModelIndex &start, const QModelIndex &end);
void sourceRowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
void sourceRowsInserted(const QModelIndex &parent, int start, int end);
void sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
void sourceRowsRemoved(const QModelIndex &parent, int start, int end);
void setUsageInfo(int index, const QString &mountPoint, const UsageInfo &usageInfo);
void usageFinderFinished();
private:
class Private;
Private * const d;
};
}
#endif // SYSTEMMODEL_H

View file

@ -0,0 +1,164 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
Copyright 2007 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "urlitemlauncher.h"
// Qt
#include <QFileInfo>
#include <QHash>
#include <QModelIndex>
// KDE
#include <KAuthorized>
#include <QDebug>
#include <KRun>
#include <KUrl>
#include <Solid/Device>
#include <Solid/StorageAccess>
// Local
#include "models.h"
// DBus
#include "krunner_interface.h"
using namespace Kickoff;
class HandlerInfo
{
public:
HandlerInfo() : type(UrlItemLauncher::ProtocolHandler) , handler(0) {}
UrlItemLauncher::HandlerType type;
UrlItemHandler *handler;
};
class GenericItemHandler : public UrlItemHandler
{
public:
virtual bool openUrl(const KUrl& url) {
if (url.protocol() == "run" && KAuthorized::authorize("run_command")) {
QString interface("org.kde.krunner");
org::kde::krunner::App krunner(interface, "/App", QDBusConnection::sessionBus());
krunner.display();
return true;
}
new KRun(url, 0);
return true;
}
};
class UrlItemLauncher::Private
{
public:
static QHash<QString, HandlerInfo> globalHandlers;
static GenericItemHandler genericHandler;
static bool openUrl(const QString &urlString) {
qDebug() << "Opening item with URL" << urlString;
KUrl url(urlString);
HandlerInfo protocolHandler = globalHandlers[url.scheme()];
if (protocolHandler.type == ProtocolHandler && protocolHandler.handler != 0) {
return protocolHandler.handler->openUrl(url);
}
QString extension = QFileInfo(url.path()).suffix();
HandlerInfo extensionHandler = globalHandlers[extension];
if (extensionHandler.type == ExtensionHandler && extensionHandler.handler != 0) {
return extensionHandler.handler->openUrl(url);
}
return genericHandler.openUrl(url);
}
};
QHash<QString, HandlerInfo> UrlItemLauncher::Private::globalHandlers;
GenericItemHandler UrlItemLauncher::Private::genericHandler;
UrlItemLauncher::UrlItemLauncher(QObject *parent)
: QObject(parent)
, d(new Private)
{
}
UrlItemLauncher::~UrlItemLauncher()
{
delete d;
}
bool UrlItemLauncher::openItem(const QModelIndex& index)
{
QString urlString = index.data(UrlRole).value<QString>();
if (urlString.isEmpty()) {
QString udi = index.data(DeviceUdiRole).toString();
if (!udi.isEmpty()) {
Solid::Device device(udi);
Solid::StorageAccess *access = device.as<Solid::StorageAccess>();
if (access && !access->isAccessible()) {
connect(access, SIGNAL(setupDone(Solid::ErrorType,QVariant,QString)),
this, SLOT(onSetupDone(Solid::ErrorType,QVariant,QString)));
access->setup();
return true;
}
}
qDebug() << "Item" << index.data(Qt::DisplayRole) << "has no URL to open.";
return false;
}
return Private::openUrl(urlString);
}
bool UrlItemLauncher::openUrl(const QString& url)
{
return Private::openUrl(url);
}
void UrlItemLauncher::onSetupDone(Solid::ErrorType error, QVariant errorData, const QString &udi)
{
Q_UNUSED(errorData);
if (error != Solid::NoError) {
return;
}
Solid::Device device(udi);
Solid::StorageAccess *access = device.as<Solid::StorageAccess>();
Q_ASSERT(access);
QString urlString = "file://" + access->filePath();
Private::openUrl(urlString);
}
// FIXME: the handlers are leaked, as they are added with each new Kickoff instance,
// but never deleted.
void UrlItemLauncher::addGlobalHandler(HandlerType type, const QString& name, UrlItemHandler *handler)
{
HandlerInfo info;
info.type = type;
info.handler = handler;
Private::globalHandlers.insert(name, info);
}
#include "urlitemlauncher.moc"

View file

@ -0,0 +1,87 @@
/*
Copyright 2007 Robert Knight <robertknight@gmail.com>
Copyright 2007 Kevin Ottens <ervin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef URLITEMLAUNCHER_H
#define URLITEMLAUNCHER_H
#include <QObject>
#include <solid/storageaccess.h>
class QModelIndex;
class KUrl;
namespace Kickoff
{
/**
* UrlItemHandler is an abstract base class for handlers which can open particular
* types of URL.
*
* @see UrlItemLauncher
*/
class UrlItemHandler
{
public:
virtual ~UrlItemHandler() {}
virtual bool openUrl(const KUrl& url) = 0;
};
/**
* UrlItemLauncher provides facilities to open a item from a Kickoff model based on its UrlRole
* data.
*
* By default, a UrlItemLauncher opens all URLs using the KRun class. Additional handlers can be created
* to handle URLs with particular protocols or extensions differently. Handlers can be
* registered using the static addGlobalHandler() method.
*/
class UrlItemLauncher : public QObject
{
Q_OBJECT
public:
UrlItemLauncher(QObject *parent = 0);
virtual ~UrlItemLauncher();
enum HandlerType {
ProtocolHandler,
ExtensionHandler
};
static void addGlobalHandler(HandlerType type,
const QString& name,
UrlItemHandler *handler);
public Q_SLOTS:
/** Open the specified @p index from a Kickoff model. */
bool openItem(const QModelIndex& index);
/** Open the specified @p url */
bool openUrl(const QString& url);
private Q_SLOTS:
void onSetupDone(Solid::ErrorType error, QVariant errorData, const QString &udi);
private:
class Private;
Private * const d;
};
}
#endif // URLITEMLAUNCHER_H

View file

@ -0,0 +1,29 @@
/*
* Copyright 2013 Marco Martin <mart@kde.org>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 2.010-1301, USA.
*/
import QtQuick 2.0
import org.kde.plasma.configuration 2.0
ConfigModel {
ConfigCategory {
name: "Appearance"
icon: "preferences-desktop-color"
source: "configGeneral.qml"
}
}

View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="switchTabsOnHover" type="Bool">
<default>true</default>
</entry>
<entry name="showAppsByName" type="Bool">
<default>false</default>
</entry>
<entry name="showRecentlyInstalled" type="Bool">
<default>false</default>
</entry>
</group>
</kcfg>

View file

@ -0,0 +1,217 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Gregor Taetzner <gregor@freenet.de>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.private.kickoff 0.1 as Kickoff
Item {
id: appViewContainer
anchors.fill: parent
objectName: "ApplicationsView"
function decrementCurrentIndex() {
applicationsView.decrementCurrentIndex();
}
function incrementCurrentIndex() {
applicationsView.incrementCurrentIndex();
}
function activateCurrentIndex(start) {
if (!applicationsView.currentItem.modelChildren)
if (!start)
return;
appViewScrollArea.state = "OutgoingLeft";
}
function deactivateCurrentIndex() {
if (crumbModel.count > 0) { // this is not the case when switching from the "Applications" to the "Favorites" tab using the "Left" key
breadcrumbsElement.children[crumbModel.count-1].clickCrumb();
appViewScrollArea.state = "OutgoingRight";
return true;
}
return false;
}
ContextMenu {
id: contextMenu
}
Item {
id: crumbContainer
anchors {
top: parent.top
left: parent.left
right: parent.right
}
height: childrenRect.height
Flickable {
anchors {
top: parent.top
left: parent.left
right: parent.right
}
height: breadcrumbsElement.height
contentWidth: breadcrumbsElement.width
contentX: contentWidth - width
PlasmaComponents.ButtonRow {
id: breadcrumbsElement
exclusive: false
Breadcrumb {
id: rootBreadcrumb
root: true
text: i18n("All Applications")
depth: 0
}
Repeater {
model: ListModel {
id: crumbModel
// Array of the category indexes
property var indexes: []
}
Breadcrumb {
root: false
text: model.text
}
}
}
} // Flickable
} // crumbContainer
PlasmaExtras.ScrollArea {
id: appViewScrollArea
anchors {
top: crumbContainer.bottom
bottom: parent.bottom
rightMargin: -units.largeSpacing
leftMargin: -units.largeSpacing
}
width: parent.width
function moveRight() {
state = "";
applicationsView.currentItem.activate();
}
function moveLeft() {
state = "";
// newModelIndex set by clicked breadcrumb
applicationsView.model.rootIndex = applicationsView.newModelIndex;
}
ListView {
id: applicationsView
property variant newModelIndex
focus: true
keyNavigationWraps: true
boundsBehavior: Flickable.StopAtBounds
highlight: PlasmaComponents.Highlight {}
model: VisualDataModel {
id: vmodel
delegate: KickoffItem {
id: kickoffItem
appView: true
PlasmaCore.SvgItem {
anchors {
right: parent.right
verticalCenter: parent.verticalCenter
rightMargin: y
}
height: units.iconSizes.small
width: height
svg: arrowSvg
elementId: "go-next"
visible: hasModelChildren
}
}
model: Kickoff.ApplicationModel {}
} // VisualDataModel
function addBreadcrumb(categoryIndex, title) {
crumbModel.append({"text": title, "depth": crumbModel.count+1})
crumbModel.indexes.push(categoryIndex);
}
PlasmaCore.Svg {
id: arrowSvg
imagePath: "toolbar-icons/go"
}
} // applicationsView
states: [
State {
name: "OutgoingLeft"
PropertyChanges {
target: appViewScrollArea
x: -parent.width
opacity: 0.0
}
},
State {
name: "OutgoingRight"
PropertyChanges {
target: appViewScrollArea
x: parent.width
opacity: 0.0
}
}
]
transitions: [
Transition {
to: "OutgoingLeft"
SequentialAnimation {
NumberAnimation { properties: "x,opacity"; easing.type: Easing.InQuad; duration: units.longDuration }
ScriptAction { script: appViewScrollArea.moveRight() }
}
},
Transition {
to: "OutgoingRight"
SequentialAnimation {
NumberAnimation { properties: "x,opacity"; easing.type: Easing.InQuad; duration: units.longDuration }
ScriptAction { script: appViewScrollArea.moveLeft() }
}
}
]
} // appViewScrollArea
} // appViewContainer

View file

@ -0,0 +1,65 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.draganddrop 2.0
Item {
property alias model: kickoffListView.model
function decrementCurrentIndex() {
kickoffListView.decrementCurrentIndex();
}
function incrementCurrentIndex() {
kickoffListView.incrementCurrentIndex();
}
function activateCurrentIndex() {
kickoffListView.currentItem.activate();
}
PlasmaExtras.ScrollArea {
anchors.fill: parent
ListView {
id: kickoffListView
anchors.fill: parent
interactive: contentHeight > height
boundsBehavior: Flickable.StopAtBounds
currentIndex: -1
keyNavigationWraps: true
highlight: PlasmaComponents.Highlight {}
delegate: KickoffItem {}
section {
property: "group"
criteria: ViewSection.FullString
delegate: SectionDelegate {}
}
}
}
}

View file

@ -0,0 +1,74 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
Item {
id: crumbRoot
height: crumb.implicitHeight
width: crumb.implicitWidth + arrowSvg.width
property string text
property bool root: false
property int depth: model.depth
function clickCrumb() {
crumb.clicked();
}
PlasmaComponents.ToolButton {
id: crumb
anchors.left: arrowSvg.right
text: crumbRoot.text
enabled: crumbRoot.depth < crumbModel.count
onClicked: {
// Remove all the breadcrumbs in front of the clicked one
while (crumbModel.count > 0 && crumbRoot.depth < crumbModel.get(crumbModel.count-1).depth) {
crumbModel.remove(crumbModel.count-1)
crumbModel.indexes.pop()
}
if (crumbRoot.root) {
applicationsView.newModelIndex = 0;
} else {
applicationsView.newModelIndex = crumbModel.indexes[index];
}
appViewScrollArea.state = "OutgoingRight";
}
}
PlasmaCore.SvgItem {
id: arrowSvg
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
height: crumbRoot.height / 2
width: visible ? height : 0
svg: PlasmaCore.Svg {
imagePath: "toolbar-icons/go"
}
elementId: "go-next"
visible: !crumbRoot.root
}
} // crumbRoot

View file

@ -0,0 +1,85 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.kquickcontrolsaddons 2.0
PlasmaComponents.ContextMenu {
id: contextMenu
property string title
property variant model
property bool isFavorite: favoritesModel.isFavorite(contextMenu.model.url)
property bool isApp: contextMenu.model.url.indexOf(".desktop") !== -1
function openAt(title, model, x, y) {
contextMenu.title = title
contextMenu.model = model
open(x, y)
}
/*
* context menu items
*/
PlasmaComponents.MenuItem {
id: titleMenuItem
text: contextMenu.title
icon: contextMenu.model.decoration
checkable: false
enabled: false
}
PlasmaComponents.MenuItem {
id: titleSeparator
separator: true
}
PlasmaComponents.MenuItem {
id: addToFavorites
text: contextMenu.isFavorite ? i18n("Remove From Favorites") : i18n("Add To Favorites")
icon: contextMenu.isFavorite ? "list-remove" : "bookmark-new"
visible: contextMenu.isApp
onClicked: {
// FIXME: apparently contextMenu.model is empty
if (contextMenu.isFavorite) {
favoritesModel.remove(contextMenu.model.url);
} else {
favoritesModel.add(contextMenu.model.url);
}
}
}
PlasmaComponents.MenuItem {
id: uninstallApp
text: i18n("Uninstall")
visible: packagekitSource.data["Status"] !== undefined && contextMenu.isApp
onClicked: {
var service = packagekitSource.serviceForSource("Status")
var operation = service.operationDescription("uninstallApplication")
operation.Url = contextMenu.model.url;
var job = service.startOperationCall(operation)
}
}
} // contextMenu

View file

@ -0,0 +1,169 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.draganddrop 2.0
import org.kde.plasma.private.kickoff 0.1 as Kickoff
Item {
anchors.fill: parent
objectName: "FavoritesView"
function decrementCurrentIndex() {
kickoffListView.decrementCurrentIndex();
}
function incrementCurrentIndex() {
kickoffListView.incrementCurrentIndex();
}
function activateCurrentIndex() {
kickoffListView.currentItem.activate();
}
ContextMenu {
id: contextMenu
PlasmaComponents.MenuItem {
id: actionsSeparator
separator: true
}
PlasmaComponents.MenuItem {
id: sortFavoritesAscending
text: i18n("Sort Alphabetically (A to Z)")
icon: "view-sort-ascending"
onClicked: {
favoritesModel.sortFavoritesAscending();
}
}
PlasmaComponents.MenuItem {
id: sortFavoritesDescending
text: i18n("Sort Alphabetically (Z to A)")
icon: "view-sort-descending"
onClicked: {
favoritesModel.sortFavoritesDescending();
}
}
}
DropArea {
property string dragUrl: ""
property Item dragItem: null
property int startRow: -1
property int itemHeight: units.gridUnit * 3
anchors.fill: scrollArea
function syncTarget(event) {
kickoffListView.currentIndex = kickoffListView.indexAt(event.x, event.y + kickoffListView.contentY + itemHeight) + 1
if (kickoffListView.currentIndex === -1) {
if (event.y < itemHeight/2) {
kickoffListView.currentIndex = 0
}
}
if (kickoffListView.currentItem != null && event.y + itemHeight < kickoffListView.currentItem.y) {
dropTarget.y = (kickoffListView.currentIndex) * itemHeight - kickoffListView.contentY
} else {
dropTarget.y = (kickoffListView.count ) * itemHeight
}
}
onDrop: {
var row = dropTarget.y / itemHeight;
print("Dropping into row : " + startRow + " " + row + " " + (event.y + kickoffListView.contentY) + " " + dragUrl);
row = Math.max(0, row)
row = Math.round(row)
//kickoffListView.model.dropMimeData(event.mimeData.text, [dragUrl], row, 0);
kickoffListView.model.move(startRow, row);
dropTarget.visible = false;
}
onDragEnter: {
// print("Drag enter");
dragUrl = kickoffListView.currentItem.url;
startRow = kickoffListView.currentIndex;
syncTarget(event);
// print("Dragging " + dragUrl + " from row " + startRow);
dropTarget.visible = true;
}
onDragMove: syncTarget(event);
onDragLeave: {
dropTarget.visible = false;
}
Rectangle {
id: dropTarget
width: parent.width
height: Math.max(2, units.smallSpacing)
visible: false
color: theme.highlightColor
}
}
PlasmaExtras.ScrollArea {
id: scrollArea
anchors.fill: parent
ListView {
id: kickoffListView
anchors.fill: parent
currentIndex: -1
keyNavigationWraps: true
interactive: contentHeight > height
/*
delegate: KQuickControlsAddons.MouseEventListener {
hoverEnabled: true
onContainsMouseChanged: {
if (containsMouse) {
kickoffListView.currentIndex = index;
}
}
KickoffItem { id: koitem; anchors.fill: parent; }
}
*/
delegate: KickoffItem {}
highlight: PlasmaComponents.Highlight {}
model: favoritesModel
section {
property: "group"
criteria: ViewSection.FullString
//delegate: SectionDelegate {}
}
}
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (C) 2012 Gregor Taetzner <gregor@freenet.de>
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.kquickcontrolsaddons 2.0
Item {
id: footer
height: statusLabel.height
PlasmaComponents.Label {
id: statusLabel
//text: kickoff.footerText // FIXME: where does this come from? Is it still needed?
anchors {
verticalCenter: parent.verticalCenter
left: parent.left
}
}
PlasmaCore.SvgItem {
id: brandingButton
svg {
PlasmaCore.Svg {
imagePath: "widgets/branding"
}
}
elementId: "brilliant"
height: Math.min(implicitHeight, parent.height) //don't be bigger than the text or the logo size
width: implicitWidth * (height / implicitHeight)
anchors {
verticalCenter: parent.verticalCenter
left: statusLabel.right
leftMargin: 4
}
}
}

View file

@ -0,0 +1,225 @@
/*
* Copyright 2014 Sebastian Kügler <sebas@kde.org>
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.private.kickoff 0.1 as Kickoff
Item {
id: header
height: units.gridUnit * 5
property alias query: queryField.text
property Item input: queryField
Kickoff.KUser {
id: kuser
}
state: (header.query != "") ? "query" : "hint"
Timer {
id: labelTimer
interval: 5000
running: header.state === "hint" && plasmoid.expanded && (header.query === "")
onTriggered: {
if (header.state == "info") {
header.state = "hint";
} else if (header.state == "hint") {
header.state = "info";
}
}
}
Rectangle { color: "orange"; visible: root.debug; anchors.fill: parent; opacity: 0.3 }
Image {
id: faceIcon
source: kuser.faceIconPath
visible: source != ""
width: units.gridUnit * 3
height: width
anchors {
top: parent.top
left: parent.left
topMargin: units.gridUnit
leftMargin: units.gridUnit
}
Rectangle { color: "green"; opacity: 0.3; anchors.fill: parent; visible: root.debug; }
}
PlasmaCore.IconItem {
source: "user-identity"
visible: faceIcon.source == ""
width: units.gridUnit * 3
height: width
anchors {
top: faceIcon.top
right: faceIcon.right
rightMargin: -units.gridUnit/2
}
}
PlasmaExtras.Heading {
id: nameLabel
level: 2
text: kuser.fullName
elide: Text.ElideRight
verticalAlignment: Text.AlignTop
height: paintedHeight
anchors {
left: faceIcon.right
top: faceIcon.top
right: parent.right
leftMargin: units.gridUnit
rightMargin: units.gridUnit
}
}
Item {
id: searchWidget
property int animationDuration: units.longDuration
property real normalOpacity: .6
property int yOffset: height / 2
height: infoLabel.height
anchors {
left: nameLabel.left
top: nameLabel.bottom
right: nameLabel.right
}
PlasmaComponents.Label {
id: infoLabel
anchors {
left: parent.left
right: parent.right
}
verticalAlignment: Text.AlignBottom
text: kuser.os != "" ? i18n("%2@%3 (%1)", kuser.os, kuser.loginName, kuser.host) : i18n("%1@%2", kuser.loginName, kuser.host)
elide: Text.ElideRight
Behavior on opacity { NumberAnimation { duration: searchWidget.animationDuration; easing.type: Easing.InOutQuad; } }
Behavior on y { NumberAnimation { duration: searchWidget.animationDuration; easing.type: Easing.InOutQuad; } }
}
PlasmaComponents.Label {
id: hintLabel
anchors {
left: parent.left
right: parent.right
}
verticalAlignment: Text.AlignBottom
text: i18n("Type to search...")
Behavior on opacity { NumberAnimation { duration: searchWidget.animationDuration; easing.type: Easing.InOutQuad; } }
Behavior on y { NumberAnimation { duration: searchWidget.animationDuration; easing.type: Easing.InOutQuad; } }
}
PlasmaComponents.TextField {
id: queryField
anchors.fill: parent
clearButtonShown: true
Behavior on opacity { NumberAnimation { duration: searchWidget.animationDuration / 4 } }
onTextChanged: {
if (root.state != "Search") {
root.previousState = root.state;
root.state = "Search";
}
if (text == "") {
root.state = root.previousState;
root.forceActiveFocus();
header.state = "info";
} else {
header.state = "query";
}
}
}
Connections {
target: plasmoid
onExpandedChanged: {
if (!expanded) {
header.query = "";
}
}
}
}
states: [
State {
name: "info"
PropertyChanges {
target: infoLabel
opacity: searchWidget.normalOpacity
y: 0
}
PropertyChanges {
target: hintLabel
opacity: 0
y: searchWidget.yOffset
}
PropertyChanges {
target: queryField
opacity: 0
}
},
State {
name: "hint"
PropertyChanges {
target: infoLabel
y: -searchWidget.yOffset
opacity: 0
}
PropertyChanges {
target: hintLabel
y: 0
opacity: searchWidget.normalOpacity
}
PropertyChanges {
target: queryField
opacity: 0
}
},
State {
name: "query"
PropertyChanges {
target: infoLabel
opacity: 0
}
PropertyChanges {
target: hintLabel
opacity: 0
}
PropertyChanges {
target: queryField
opacity: 1
}
}
] // states
}

View file

@ -0,0 +1,404 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Gregor Taetzner <gregor@freenet.de>
Copyright (C) 2012 Marco Martin <mart@kde.org>
Copyright (C) 2013 David Edmundson <davidedmundson@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.plasmoid 2.0
import QtQuick.Layouts 1.1
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.kquickcontrolsaddons 2.0
Item {
Plasmoid.switchWidth: units.gridUnit * 200
Plasmoid.switchHeight: units.gridUnit * 300
Plasmoid.fullRepresentation: Item {
id: root
Layout.minimumWidth: units.gridUnit * 26
Layout.minimumHeight: units.gridUnit * 33
property string previousState
property bool switchTabsOnHover: plasmoid.configuration.switchTabsOnHover
property bool showAppsByName: plasmoid.configuration.showAppsByName
property Item currentView: mainStack.currentTab.decrementCurrentIndex ? mainStack.currentTab : mainStack.currentTab.item
property int pad: units.gridUnit
property bool debug: false
// implicitWidth: root.minimumWidth
// implicitHeight: root.minimumHeight
state: "Normal"
focus: true
PlasmaCore.DataSource {
id: packagekitSource
engine: "packagekit"
connectedSources: ["Status"]
}
Kickoff.Launcher {
id: launcher
}
PlasmaCore.Svg {
id: lineSvg
imagePath: "widgets/line"
}
Timer {
id: clickTimer
property Item pendingButton
interval: 250
onTriggered: pendingButton.clicked()
}
Header {
id: header
anchors {
top: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return undefined;
default:
return parent.top;
}
}
bottom: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return parent.bottom;
default:
return undefined;
}
}
left: parent.left
right: parent.right
}
}
PlasmaComponents.TabGroup {
id: mainStack
anchors {
top: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
return tabBar.bottom;
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return parent.top;
default:
return header.bottom;
}
}
bottom: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return header.top;
default:
return tabBar.top;
}
}
left: plasmoid.location == PlasmaCore.Types.LeftEdge ? tabBar.right : parent.left
right: plasmoid.location == PlasmaCore.Types.RightEdge ? tabBar.left : parent.right
leftMargin: units.largeSpacing
rightMargin: units.largeSpacing
}
//pages
FavoritesView {
id: favoritesPage
}
PlasmaExtras.ConditionalLoader {
id: applicationsPage
when: mainStack.currentTab == applicationsPage
source: Qt.resolvedUrl("ApplicationsView.qml")
}
PlasmaExtras.ConditionalLoader {
id: systemPage
when: mainStack.currentTab == systemPage
source: Qt.resolvedUrl("SystemView.qml")
}
PlasmaExtras.ConditionalLoader {
id: recentlyUsedPage
when: mainStack.currentTab == recentlyUsedPage
source: Qt.resolvedUrl("RecentlyUsedView.qml")
}
PlasmaExtras.ConditionalLoader {
id: leavePage
when: mainStack.currentTab == leavePage
source: Qt.resolvedUrl("LeaveView.qml")
}
PlasmaExtras.ConditionalLoader {
id: searchPage
when: root.state == "Search"
//when: mainStack.currentTab == searchPage || root.state == "Search"
source: Qt.resolvedUrl("SearchView.qml")
}
} // mainStack
Kickoff.FavoritesModel {
id: favoritesModel
}
PlasmaComponents.TabBar {
id: tabBar
width: {
if (!visible) {
return 0;
}
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return units.gridUnit * 5;
default:
return 0;
}
}
height: {
if (!visible) {
return 0;
}
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return 0;
default:
return units.gridUnit * 5;
}
}
Behavior on width { NumberAnimation { duration: units.longDuration; easing.type: Easing.InQuad; } }
Behavior on height { NumberAnimation { duration: units.longDuration; easing.type: Easing.InQuad; } }
anchors {
top: {
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return parent.top;
default:
return undefined;
}
}
bottom: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
return undefined;
case PlasmaCore.Types.LeftEdge:
case PlasmaCore.Types.RightEdge:
return header.top;
default:
return parent.bottom;
}
}
left: {
switch (plasmoid.location) {
case PlasmaCore.Types.RightEdge:
return undefined;
default:
return parent.left;
}
}
right: {
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
return undefined;
default:
return parent.right;
}
}
}
tabPosition: {
switch (plasmoid.location) {
case PlasmaCore.Types.TopEdge:
return Qt.TopEdge;
case PlasmaCore.Types.LeftEdge:
return Qt.LeftEdge;
case PlasmaCore.Types.RightEdge:
return Qt.RightEdge;
default:
return Qt.BottomEdge;
}
}
currentTab: bookmarkButton
onCurrentTabChanged: root.forceActiveFocus();
KickoffButton {
id: bookmarkButton
tab: favoritesPage
iconSource: "bookmarks"
text: i18n("Favorites")
}
KickoffButton {
id: applicationButton
tab: applicationsPage
iconSource: "applications-other"
text: i18n("Applications")
}
KickoffButton {
id: computerButton
tab: systemPage
iconSource: "computer" // TODO: could also be computer-laptop
text: i18n("Computer")
}
KickoffButton {
id: usedButton
tab: recentlyUsedPage
iconSource: "document-open-recent"
text: i18n("Recently Used")
}
KickoffButton {
id: leaveButton
tab: leavePage
iconSource: "system-shutdown"
text: i18n("Leave")
}
} // tabBar
Keys.forwardTo: [tabBar.layout]
Keys.onPressed: {
if (mainStack.currentTab == applicationsPage) {
if (event.key != Qt.Key_Tab) {
root.state = "Applications";
}
}
switch(event.key) {
case Qt.Key_Up: {
currentView.decrementCurrentIndex();
event.accepted = true;
break;
}
case Qt.Key_Down: {
currentView.incrementCurrentIndex();
event.accepted = true;
break;
}
case Qt.Key_Left: {
if (header.input.focus) {
break;
}
if (!currentView.deactivateCurrentIndex()) {
// FIXME move to the previous tab immediately
root.state = "Normal"
}
event.accepted = true;
break;
}
case Qt.Key_Right: {
if (header.input.focus) {
break;
}
currentView.activateCurrentIndex();
event.accepted = true;
break;
}
case Qt.Key_Tab: {
root.state == "Applications" ? root.state = "Normal" : root.state = "Applications";
event.accepted = true;
break;
}
case Qt.Key_Enter:
case Qt.Key_Return: {
currentView.activateCurrentIndex(1);
event.accepted = true;
break;
}
case Qt.Key_Escape: {
if (header.query == "") {
plasmoid.expanded = false;
} else {
header.query = "";
}
event.accepted = true;
break;
}
default: { // forward key to searchView
if (event.text != "" && !header.input.focus) {
if (event.text == "v" && event.modifiers & Qt.ControlModifier) {
header.input.paste();
} else {
header.query = "";
header.query += event.text;
}
header.input.forceActiveFocus();
event.accepted = true;
}
}
}
}
states: [
State {
name: "Normal"
PropertyChanges {
target: root
Keys.forwardTo: [tabBar.layout]
}
},
State {
name: "Applications"
PropertyChanges {
target: root
Keys.forwardTo: [root]
}
},
State {
name: "Search"
PropertyChanges {
target: tabBar
visible: false
}
PropertyChanges {
target: mainStack
currentTab: searchPage
}
}
] // states
onStateChanged: {
print("root.state changed to : " + state);
}
}
} // root

View file

@ -0,0 +1,73 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.kquickcontrolsaddons 2.0
PlasmaComponents.TabButton {
id: button
property string iconSource
property alias text: labelElement.text
implicitHeight: iconElement.height + labelElement.implicitHeight + iconElement.anchors.topMargin + labelElement.anchors.topMargin + labelElement.anchors.bottomMargin
MouseArea {
enabled: root.switchTabsOnHover
anchors.fill: parent
hoverEnabled: root.switchTabsOnHover
onEntered: {
clickTimer.pendingButton = button
clickTimer.restart()
}
onExited: clickTimer.running = false
onClicked: button.clicked()
}
QIconItem {
id: iconElement
anchors {
topMargin: 5
top: parent.top
horizontalCenter: parent.horizontalCenter
}
width: units.iconSizes.medium
height: width
icon: iconSource
}
PlasmaComponents.Label {
id: labelElement
anchors {
bottom: parent.bottom
top: iconElement.bottom
left: parent.left
right: parent.right
topMargin: 5
bottomMargin: 5
}
horizontalAlignment: Text.AlignHCenter
elide: Text.ElideRight
font.pointSize: theme.smallestFont.pointSize
}
} // button

View file

@ -0,0 +1,171 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Gregor Taetzner <gregor@freenet.de>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.kquickcontrolsaddons 2.0
import org.kde.draganddrop 2.0
Item {
id: listItem
width: ListView.view.width
height: listItemDelegate.height // + listItemDelegate.anchors.margins*2
property bool dropEnabled: false
property bool modelChildren: hasModelChildren
property bool appView: false
property bool isCurrent: listItem.ListView.view.currentIndex === index;
property string url: model["url"]
function activate() {
if (hasModelChildren) {
listItem.ListView.view.addBreadcrumb(listItem.ListView.view.model.modelIndex(index), display);
listItem.ListView.view.model.rootIndex = listItem.ListView.view.model.modelIndex(index);
} else {
launcher.openUrl(model["url"]);
plasmoid.expanded = false;
}
}
Item {
id: listItemDelegate
anchors {
left: parent.left
right: parent.right
top: parent.top
bottom: parent.bottom
//margins: units.gridUnit / 2
}
//height: Math.max(elementIcon.height + units.gridUnit/2, titleElement.height + subTitleElement.height + units.gridUnit/2)
height: units.gridUnit * 3
DragArea {
anchors.fill: parent
supportedActions: Qt.MoveAction | Qt.LinkAction
delegateImage: decoration
mimeData {
url: "file://" + model["url"]
source: parent
text: index
}
MouseArea {
id: mouseArea
anchors.fill: parent
//anchors.margins: -8
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
onEntered: {
listItem.ListView.view.currentIndex = index;
}
onClicked: {
if (mouse.button == Qt.LeftButton) {
if (appView) {
appViewScrollArea.state = "OutgoingLeft";
}
else {
listItem.activate();
}
} else if (mouse.button == Qt.RightButton) {
// don't show a context menu for container
if (hasModelChildren || typeof(contextMenu) === "undefined") {
return;
}
contextMenu.visualParent = mouseArea
contextMenu.openAt(titleElement.text, model, mouse.x, mouse.y);
}
}
}
}
QIconItem {
id: elementIcon
anchors {
left: parent.left
leftMargin: (units.gridUnit * 3) - units.iconSizes.medium
verticalCenter: parent.verticalCenter
}
width: units.iconSizes.medium
height: width
icon: decoration
}
PlasmaComponents.Label {
id: titleElement
anchors {
top: elementIcon.top
left: elementIcon.right
right: parent.right
leftMargin: units.gridUnit
}
height: paintedHeight
// TODO: games should always show the by name!
text: {
if (hasModelChildren) {
return display;
} else {
plasmoid.configuration.showAppsByName || display.length == 0 ? (subtitle == undefined ? display : subtitle) :
display
}
}
}
PlasmaComponents.Label {
id: subTitleElement
anchors {
left: titleElement.left
right: parent.right
bottom: parent.bottom
top: titleElement.bottom
}
height: paintedHeight
text: {
if (hasModelChildren) {
return subtitle;
} else {
plasmoid.configuration.showAppsByName || subtitle == undefined ? (display.length != 0 ? display : subtitle) : subtitle;
}
}
opacity: isCurrent ? 0.6 : 0
Behavior on opacity { NumberAnimation { duration: units.longDuration /2 } }
font.pointSize: theme.smallestFont.pointSize
elide: Text.ElideMiddle
}
/*
PlasmaComponents.Highlight {
id: itemHighlight
anchors {
fill: parent
margins: -(units.gridUnit/2)
}
opacity: mouseArea.containsMouse ? 1 : 0
Behavior on opacity { NumberAnimation { duration: theme.shortDuration } }
}*/
} // listItemDelegate
} // listItem

View file

@ -0,0 +1,27 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.private.kickoff 0.1 as Kickoff
BaseView {
objectName: "LeaveView"
model: Kickoff.LeaveModel {}
}

View file

@ -0,0 +1,51 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.private.kickoff 0.1 as Kickoff
import org.kde.plasma.components 2.0 as PlasmaComponents
BaseView {
objectName: "RecentlyUsedView"
model: Kickoff.RecentlyUsedModel {
id: recentlyUsedModel
}
ContextMenu {
id: contextMenu
PlasmaComponents.MenuItem {
id: clearRecentApplications
text: i18n("Clear Recent Applications")
icon: QIcon("edit-clear-history")
onClicked: recentlyUsedModel.clearRecentApplications();
visible: contextMenu.isApp
}
PlasmaComponents.MenuItem {
id: clearRecentDocuments
text: i18n("Clear Recent Documents")
icon: QIcon("edit-clear-history")
onClicked: recentlyUsedModel.clearRecentDocuments();
visible: !contextMenu.isApp
}
}
}

View file

@ -0,0 +1,69 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Gregor Taetzner <gregor@freenet.de>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.private.kickoff 0.1 as Kickoff
Item {
id: searchViewContainer
anchors.fill: parent
objectName: "SearchView"
function decrementCurrentIndex() {
searchView.decrementCurrentIndex();
}
function incrementCurrentIndex() {
searchView.incrementCurrentIndex();
}
function activateCurrentIndex() {
searchView.currentItem.activate();
}
PlasmaExtras.ScrollArea {
anchors.fill: parent
ListView {
id: searchView
anchors.fill: parent
keyNavigationWraps: true
boundsBehavior: Flickable.StopAtBounds
delegate: KickoffItem {}
highlight: PlasmaComponents.Highlight {}
model: Kickoff.KRunnerModel{}
Connections {
target: header
onQueryChanged: {
searchView.model.setQuery(header.query)
}
}
} // searchView
} // ScrollArea
ContextMenu {
id: contextMenu
}
}

View file

@ -0,0 +1,64 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.extras 2.0 as PlasmaExtras
Item {
id: sectionDelegate
width: parent.width
height: childrenRect.height
// PlasmaCore.SvgItem {
// anchors {
// left: parent.left
// right: parent.right
// }
// height: lineSvg.elementSize("horizontal-line").height
//
// visible: sectionDelegate.y > 0
// svg: lineSvg
// elementId: "horizontal-line"
// }
PlasmaExtras.Heading {
id: sectionHeading
anchors {
// bottomMargin: units.gridUnit / 4
left: parent.left
right: parent.right
//leftMargin: units.gridUnit
}
y: units.gridUnit / 4
//height: paintedHeight + units.gridUnit / 4
//opacity: 0.6
level: 4
text: section
//horizontalAlignment: Text.AlignHCenter
}
Item {
width: parent.width
height: units.gridUnit / 4
anchors.left: parent.left
anchors.top: sectionHeading.bottom
}
} // sectionDelegate

View file

@ -0,0 +1,26 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
Copyright (C) 2012 Marco Martin <mart@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import QtQuick 2.0
import org.kde.plasma.private.kickoff 0.1 as Kickoff
BaseView {
objectName: "SystemView"
model: Kickoff.SystemModel {}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright 2013 David Edmundson <davidedmundson@kde.org>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 2.010-1301, USA.
*/
import QtQuick 2.0
import QtQuick.Controls 1.0 as QtControls
//FIXME this causes a crash in Oxygen style
//QtControls.GroupBox {
Item {
//FIXME i18n is broken currently
//when fixed delete this
function i18n(arg) {
return arg;
}
width: childrenRect.width
height: childrenRect.height
//FIXME enable when we're back to being a group box
// flat: true
// title: i18n("Appearance")
property alias cfg_switchTabsOnHover: switchTabsOnHoverCheckbox.checked
property alias cfg_showAppsByName: showApplicationsByNameCheckbox.checked
property alias cfg_showRecentlyInstalled: showRecentlyInstalledCheckbox.checked
Column {
QtControls.CheckBox {
id: switchTabsOnHoverCheckbox
text: i18n("Switch tabs on hover:")
}
QtControls.CheckBox {
id: showApplicationsByNameCheckbox
text: i18n("Show applications by name:")
}
QtControls.CheckBox {
id: showRecentlyInstalledCheckbox
text: i18n("Show 'Recently Installed':")
}
}
}

View file

@ -0,0 +1,184 @@
[Desktop Entry]
Name=Application Launcher
Name[af]=Programlanseerder
Name[ar]=مطلق التطبيقات
Name[ast]=Llanzador d'aplicaciones
Name[be]=Запуск праграмаў
Name[be@latin]=Uklučeńnie aplikacyi
Name[bg]=Стартиране на програми
Name[bn]=অ্যাপলিকেশন লঞ্চার
Name[bn_IN]=অ্যাপ্লিকেশন সঞ্চালনকারী
Name[bs]=pokretač programa
Name[ca]=Llançador d'aplicacions
Name[ca@valencia]=Llançador d'aplicacions
Name[cs]=Spouštěč aplikací
Name[csb]=Zrëszôcz programów
Name[da]=Startmenu
Name[de]=K-Menü
Name[el]=Εκτέλεση εφαρμογών
Name[en_GB]=Application Launcher
Name[eo]=Aplikaĵolanĉilo
Name[es]=Lanzador de aplicaciones
Name[et]=Rakenduste käivitaja
Name[eu]=Aplikazio-abiarazlea
Name[fa]=راه‌انداز برنامه
Name[fi]=Sovelluskäynnistin
Name[fr]=Lanceur d'application
Name[fy]=In applikaashe starter
Name[ga]=Tosaitheoir Feidhmchlár
Name[gl]=Iniciador de programas
Name[gu]=કાર્યક્રમ ચલાવનાર
Name[he]=משגר יישומים
Name[hi]=अनुप्रयोग चालक
Name[hne]=अनुपरयोग चालू करइया
Name[hr]=Pokretač aplikacija
Name[hsb]=Startowar za aplikacije
Name[hu]=Programindító
Name[ia]=Lanceator de application
Name[id]=Peluncur Aplikasi
Name[is]=Forrita-Ræsir
Name[it]=Avviatore di applicazioni
Name[ja]=Kickoff アプリケーションランチャー
Name[kk]=Қолданбаны жегу
Name[km]=កម្មវិធី​ចាប់ផ្ដើម​កម្មវិធី​
Name[kn]=ಅನ್ವಯ ಪ್ರಕ್ಷೇಪಕ (ಲಾಚರ್)
Name[ko]=프로그램 실행기
Name[ku]=Deskpêkerê Sepanan
Name[lt]=Programų paleidiklis
Name[lv]=Programmu palaidējs
Name[mai]=अनुप्रयोग चालक
Name[mk]=Стартувач на апликации
Name[ml]=പ്രയോഗവിക്ഷേപിണി
Name[mr]=अनुप्रयोग प्रक्षेपक
Name[nb]=Programstarter
Name[nds]=Programmoproper
Name[ne]=अनुप्रयोक सुरुआतकर्ता
Name[nl]=Programmastarter
Name[nn]=Programstartar
Name[or]=ପ୍ରୟୋଗ ଆରମ୍ଭକର୍ତ୍ତା
Name[pa]=ਐਪਲੀਕੇਸ਼ ਲਾਂਚਰ
Name[pl]=Aktywator programów
Name[pt]=Lançador de Aplicações
Name[pt_BR]=Lançador de aplicativos
Name[ro]=Lansator de aplicații
Name[ru]=Меню запуска приложений
Name[se]=Prográmmaálggaheaddji
Name[si]=යෙදුම් ඇරඹුම
Name[sk]=Spúšťač aplikácií
Name[sl]=Zaganjalnik programov
Name[sr]=покретач програма
Name[sr@ijekavian]=покретач програма
Name[sr@ijekavianlatin]=pokretač programa
Name[sr@latin]=pokretač programa
Name[sv]=Starta program
Name[ta]=பயன்பாடு ஏவி
Name[te]=అనువర్తనం దించునది
Name[tg]=Оғози барномаҳо
Name[th]=ตัวเรียกใช้งานโปรแกรม
Name[tr]=Uygulama Başlatıcısı
Name[ug]=پروگرامما ئىجرا قىلغۇچ
Name[uk]=Інструмент запуску програм
Name[uz]=Dasturlarni ishga tushiruvchi
Name[uz@cyrillic]=Дастурларни ишга туширувчи
Name[vi]=Trình chạy ứng dụng
Name[wa]=Enondeu di programe
Name[x-test]=xxApplication Launcherxx
Name[zh_CN]=程序启动器
Name[zh_TW]=應用程式啟動器
Comment=Launcher to start applications
Comment[af]=Lanseerder om programme te loop
Comment[ar]=مطلق لتشغيل التطبيقات
Comment[ast]=Llanzador pa entamar aplicaciones
Comment[be@latin]=Uklučeńnie aplikacyjaŭ
Comment[bg]=Стартиране на програми
Comment[bn]=বিভিন্ন অ্যাপলিকেশন চালু করার জন্য লঞ্চার
Comment[bs]=Pokretač za programe
Comment[ca]=Llançador per a iniciar aplicacions
Comment[ca@valencia]=Llançador per a iniciar aplicacions
Comment[cs]=Aplikace pro spouštění aplikací
Comment[da]=Til at starte programmer
Comment[de]=Ermöglicht den Aufruf verschiedenster Programme
Comment[el]=Εκτέλεση εφαρμογών
Comment[en_GB]=Launcher to start applications
Comment[eo]=Aplikaĵolanĉilo
Comment[es]=Lanzador para iniciar aplicaciones
Comment[et]=Rakenduste käivitaja
Comment[eu]=Aplikazioak abiarazteko abiarazlea
Comment[fi]=Sovellusten käynnistysvalikko
Comment[fr]=Lanceur pour démarrer des applications
Comment[fy]=Starter om applikaasjes útein te setten
Comment[ga]=Ríomhchlár a thosaíonn feidhmchláir
Comment[gl]=Iniciador para iniciar programas
Comment[gu]=કાર્યક્રમો શરૂ કરનાર
Comment[he]=משגר לפתיחת יישומים
Comment[hi]=अनुप्रयोग प्रारंभ करने के लिए चालक
Comment[hne]=अनुपरयोग ल चालू करे बर लांचर
Comment[hr]=Pokretač aplikacija
Comment[hsb]=Startowar, kiž aplikacije wuwjedźe
Comment[hu]=Alkalmazásindító
Comment[ia]=Lanceator pro initiar applicationes
Comment[id]=Peluncur untuk menjalankan aplikasi
Comment[is]=Flýtiræsing forrita
Comment[it]=Avviatore per far partire le applicazioni
Comment[ja]=アプリケーションを起動します
Comment[kk]=Қолданба жеккіші
Comment[km]=កម្មវិធី​ចាប់ផ្ដើម​ត្រូវ​ចាប់ផ្ដើម​កម្មវិធី
Comment[kn]=ಅನ್ವಯಗಳನ್ನು ಪ್ರಾರಂಭಿಸಲು ಒಂದು ಪ್ರಕ್ಷೇಪಕ (ಲಾಂಚರ್)
Comment[ko]=프로그램을 시작하는 실행기
Comment[lt]=Programų paleidiklis
Comment[lv]=Poga programmu palaišanai
Comment[mk]=Аплет за стартување апликации
Comment[ml]=പ്രയോഗങ്ങള്‍ ആരംഭിക്കുന്നതിനു് സഹായിക്കുന്ന സംവിധാനം
Comment[mr]=अनुप्रयोग सुरु करण्याकरिता प्रक्षेपक
Comment[nb]=Starter programmer som ikke hører til KDE
Comment[nds]=Röppt Programmen op
Comment[ne]=अनुप्रयोग सुरुआत गर्न सुरुआतकर्ता
Comment[nl]=Applet voor het starten van programma's
Comment[nn]=Moderne programstartar
Comment[pa]=ਐਪਲੀਕੇਸ਼ਨ ਚਲਾਉਣ ਲਈ ਲਾਂਚਰ
Comment[pl]=Aktywator do uruchamiania programów
Comment[pt]=Lançador para iniciar aplicações
Comment[pt_BR]=Lançador para iniciar aplicativos
Comment[ro]=Lansator pentru a porni aplicații
Comment[ru]=Современное меню запуска приложений
Comment[se]=Prográmmaálggaheaddji
Comment[si]=යෙදුම් ආරම්භ කිරීමට ආරම්භකය
Comment[sk]=Aplikácia na spúšťanie aplikácií
Comment[sl]=Zaganjalnik za zagon programov
Comment[sr]=Покретач за програме
Comment[sr@ijekavian]=Покретач за програме
Comment[sr@ijekavianlatin]=Pokretač za programe
Comment[sr@latin]=Pokretač za programe
Comment[sv]=Startprogram för att köra program
Comment[ta]=பயன்பாடுகளை ஏவிடத் தேவையான தளம்
Comment[te]=అనువర్తనాలను ప్రారంభించుటకు లాంచర్
Comment[tg]=Средство для запуска приложений
Comment[th]=ตัวเรียกใช้งานโปรแกรมให้ทำงาน
Comment[tr]=Uygulamaları başlatmak için çalıştırıcı
Comment[ug]=پروگراممىنى قوزغىتىدىغان ئىجراچى(Launcher)
Comment[uk]=Програма для запуску програм
Comment[uz]=Dasturlarni ishga tushiruvchi vosita
Comment[uz@cyrillic]=Дастурларни ишга туширувчи восита
Comment[vi]=Mục chạy để khởi động ứng dụng
Comment[wa]=Enondeu po lancî des programes
Comment[x-test]=xxLauncher to start applicationsxx
Comment[zh_CN]=应用程序的启动器
Comment[zh_TW]=應用程式啟動器
Icon=start-here-kde
Type=Service
X-KDE-ServiceTypes=Plasma/Applet,Plasma/PopupApplet
X-Plasma-API=declarativeappletscript
X-Plasma-MainScript=ui/Kickoff.qml
X-Plasma-RequiredExtensions=LaunchApp
X-KDE-PluginInfo-Author=Martin Graesslin
X-KDE-PluginInfo-Email=plasma-devel@kde.org
X-KDE-PluginInfo-Name=org.kde.plasma.kickoff
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=http://userbase.kde.org/Plasma/Kickoff
X-KDE-PluginInfo-Category=Application Launchers
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -0,0 +1,27 @@
plasma_install_package(package org.kde.plasma.pager)
set(pager_SRCS
plugin/model.cpp
plugin/pager.cpp
plugin/pagerplugin.cpp)
add_library(pagerplugin SHARED ${pager_SRCS})
target_link_libraries(pagerplugin
KF5::KIOCore
KF5::WindowSystem
KF5::Plasma
KF5::Activities
KF5::KDE4Support
Qt5::Core
Qt5::Qml
Qt5::Quick
Qt5::DBus
taskmanager)
if (X11_FOUND)
target_link_libraries(pagerplugin Qt5::X11Extras)
endif()
install(TARGETS pagerplugin DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/pager)
install(FILES plugin/qmldir DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/pager)

View file

@ -0,0 +1,3 @@
#! /usr/bin/env bash
$XGETTEXT `find . -name \*.js -o -name \*.qml -o -name \*.cpp` -o $podir/plasma_applet_org.kde.plasma.pager.pot
rm -f rc.cpp

View file

@ -0,0 +1,6 @@
.pragma library
function contains(item, point) {
return point.x >= item.x && point.x <= item.x + item.width
&& point.y >= item.y && point.y <= item.y + item.height;
}

View file

@ -0,0 +1,29 @@
/*
* Copyright 2013 Marco Martin <mart@kde.org>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 2.010-1301, USA.
*/
import QtQuick 2.0
import org.kde.plasma.configuration 2.0
ConfigModel {
ConfigCategory {
name: i18n("General")
icon: "user-desktop"
source: "configGeneral.qml"
}
}

View file

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="displayedText" type="Enum">
<choices>
<choice name="Number"/>
<choice name="Name"/>
<choice name="None"/>
</choices>
<default>2</default>
</entry>
<entry name="showWindowIcons" type="Bool">
<default>false</default>
</entry>
<entry name="currentDesktopSelected" type="Enum">
<choices>
<choice name="DoNothing"/>
<choice name="ShowDesktop"/>
<choice name="ShowDashboard"/>
</choices>
<default>0</default>
</entry>
</group>
</kcfg>

View file

@ -0,0 +1,143 @@
/*
* Copyright 2013 David Edmundson <davidedmundson@kde.org>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 2.010-1301, USA.
*/
import QtQuick 2.0
import QtQuick.Controls 1.0 as QtControls
import QtQuick.Layouts 1.0 as Layouts
//FIXME this causes a crash in Oxygen style
//QtControls.GroupBox {
Item {
width: childrenRect.width
height: childrenRect.height
//FIXME enable when we're back to being a group box
// flat: true
// title: i18n("Appearance")
property int cfg_displayedText
property alias cfg_showWindowIcons: showRecentlyInstalledCheckbox.checked
property int cfg_currentDesktopSelected
onCfg_displayedTextChanged: {
switch (cfg_displayedText) {
case 0:
displayedTextGroup.current = desktopNumberRadio;
break;
case 1:
displayedTextGroup.current = desktopNameRadio;
break;
default:
case 2:
displayedTextGroup.current = noTextRadio;
break;
}
}
onCfg_currentDesktopSelectedChanged: {
switch (cfg_currentDesktopSelected) {
case 0:
currentDesktopSelectedGroup.current = doesNothingRadio;
break;
case 1:
currentDesktopSelectedGroup.current = showsDesktopRadio;
break;
default:
case 2:
currentDesktopSelectedGroup.current = showsDashboardRadio;
break;
}
}
QtControls.ExclusiveGroup {
id: displayedTextGroup
}
QtControls.ExclusiveGroup {
id: currentDesktopSelectedGroup
}
Layouts.GridLayout {
columns: 2
QtControls.Label {
text: i18n("Display Text:")
Layouts.Layout.alignment: Qt.AlignVCenter|Qt.AlignRight
}
QtControls.RadioButton {
id: desktopNumberRadio
exclusiveGroup: displayedTextGroup
text: i18n("Desktop number")
onCheckedChanged: if (checked) cfg_displayedText = 0;
}
Item {
width: 2
height: 2
Layouts.Layout.rowSpan: 2
}
QtControls.RadioButton {
id: desktopNameRadio
exclusiveGroup: displayedTextGroup
text: i18n("Desktop name")
onCheckedChanged: if (checked) cfg_displayedText = 1;
}
QtControls.RadioButton {
id: noTextRadio
exclusiveGroup: displayedTextGroup
text: i18n("No text")
onCheckedChanged: if (checked) cfg_displayedText = 2;
}
QtControls.Label {
text: i18n("Display icons:")
Layouts.Layout.alignment: Qt.AlignVCenter|Qt.AlignRight
}
QtControls.CheckBox {
id: showRecentlyInstalledCheckbox
}
QtControls.Label {
text: i18n("Selecting current desktop:")
Layouts.Layout.alignment: Qt.AlignVCenter|Qt.AlignRight
}
QtControls.RadioButton {
id: doesNothingRadio
exclusiveGroup: currentDesktopSelectedGroup
text: i18n("Does nothing")
onCheckedChanged: if (checked) cfg_currentDesktopSelected = 0;
}
Item {
width: 2
height: 2
Layouts.Layout.rowSpan: 2
}
QtControls.RadioButton {
id: showsDesktopRadio
exclusiveGroup: currentDesktopSelectedGroup
text: i18n("Shows desktop")
onCheckedChanged: if (checked) cfg_currentDesktopSelected = 1;
}
QtControls.RadioButton {
id: showsDashboardRadio
exclusiveGroup: currentDesktopSelectedGroup
text: i18n("Shows the dashboard")
onCheckedChanged: if (checked) cfg_currentDesktopSelected = 2;
}
}
}

View file

@ -0,0 +1,329 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* 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 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import QtQuick 2.0
import QtQuick.Layouts 1.1
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddonsComponents
import org.kde.draganddrop 2.0
import org.kde.plasma.private.pager 2.0
import "utils.js" as Utils
Item {
id: root
property bool vertical: (plasmoid.formFactor == PlasmaCore.Types.Vertical)
Layout.minimumWidth: Layout.maximumWidth
Layout.minimumHeight: Layout.maximumHeight
Layout.maximumWidth: !root.vertical ? pager.preferredSize.width : undefined
Layout.maximumHeight: root.vertical ? pager.preferredSize.height : undefined
Plasmoid.preferredRepresentation: Plasmoid.fullRepresentation
Layout.fillWidth: root.vertical
Layout.fillHeight: !root.vertical
property bool dragging: false
property int dragId
property int dragSwitchDesktopId: -1
anchors.fill: parent
//visible: repeater.count > 1 // FIXME: re-enable and fix collapsing
property color windowActiveOnActiveDesktopColor: theme.textColor
property color windowInactiveOnActiveDesktopColor: theme.textColor
property color windowActiveColor: theme.textColor
property color windowActiveBorderColor: theme.textColor
property color windowInactiveColor: theme.textColor
property color windowInactiveBorderColor: theme.textColor
function action_addDesktop() {
pager.slotAddDesktop();
}
function action_removeDesktop() {
pager.slotRemoveDesktop();
}
Connections {
target: theme
onThemeChanged: {
windowActiveOnActiveDesktopColor = theme.textColor
windowActiveOnActiveDesktopColor.a = 0.6
windowActiveColor = theme.textColor
windowActiveColor.a = 0.5;
windowActiveBorderColor = theme.textColor
//windowActiveBorderColor = 1
windowInactiveOnActiveDesktopColor = theme.textColor
windowInactiveOnActiveDesktopColor.a = 0.35;
windowInactiveColor = theme.textColor
windowInactiveColor.a = 0.17;
windowInactiveBorderColor = theme.textColor
windowInactiveBorderColor.a = 0.5
}
}
Component.onCompleted: {
plasmoid.setAction("addDesktop", i18n("Add Virtual Desktop"), "list-add");
plasmoid.setAction("removeDesktop", i18n("Remove Virtual Desktop"), "list-remove");
windowActiveOnActiveDesktopColor = theme.textColor
windowActiveOnActiveDesktopColor.a = 0.6
windowActiveColor = theme.textColor
windowActiveColor.a = 0.5;
windowActiveBorderColor = theme.textColor
//windowActiveBorderColor = 1
windowInactiveOnActiveDesktopColor = theme.textColor
windowInactiveOnActiveDesktopColor.a = 0.35;
windowInactiveColor = theme.textColor
windowInactiveColor.a = 0.17;
windowInactiveBorderColor = theme.textColor
windowInactiveBorderColor.a = 0.5
}
Pager {
id: pager
orientation: plasmoid.formFactor == PlasmaCore.Types.Vertical ? Qt.Vertical : Qt.Horizontal
size: Qt.size(root.width, root.height)
showWindowIcons: plasmoid.configuration.showWindowIcons
currentDesktopSelected: plasmoid.configuration.currentDesktopSelected
displayedText: plasmoid.configuration.displayedText
}
Timer {
id: dragTimer
interval: 1000
onTriggered: {
if (dragSwitchDesktopId != -1 && dragSwitchDesktopId !== pager.currentDesktop-1) {
pager.changeDesktop(dragSwitchDesktopId);
}
}
}
Repeater {
id: repeater
model: pager.model
PlasmaCore.ToolTipArea {
id: desktop
property int desktopId: index
property string desktopName: model.desktopName ? model.desktopName : ""
property bool active: (desktopId === pager.currentDesktop-1)
mainText: desktopName
Component.onCompleted: {
console.log(model.windows)
}
x: model.x
y: model.y
width: model.width
height: model.height
PlasmaCore.FrameSvgItem {
anchors.fill: parent
z: 1 // to make sure that the FrameSvg will be placed on top of the windows
imagePath: "widgets/pager"
prefix: (desktopMouseArea.enabled && desktopMouseArea.containsMouse) || (root.dragging && root.dragId == desktopId) ?
"hover" : (desktop.active ? "active" : "normal")
}
DropArea {
id: droparea
anchors.fill: parent
onDragEnter: {
root.dragSwitchDesktopId = desktop.desktopId;
dragTimer.start();
}
onDragLeave: {
root.dragSwitchDesktopId = -1;
dragTimer.stop();
}
onDrop: {
pager.dropMimeData(event.mimeData, desktop.desktopId);
root.dragSwitchDesktopId = -1;
dragTimer.stop();
}
}
MouseArea {
id: desktopMouseArea
anchors.fill: parent
onClicked: pager.changeDesktop(desktopId);
}
Item {
id: clipRect
x: 1
y: 1
width: desktop.width - 2
height: desktop.height - 2
clip: true
PlasmaComponents.Label {
id: desktopText
anchors.centerIn: parent
text: pager.displayedText == Pager.Name ? desktop.desktopName
: (pager.displayedText == Pager.Number ? desktop.desktopId+1 : "")
}
Repeater {
model: windows
//update the tooltip whenever we add or remove a window
onCountChanged: {
var tooltipText = i18n("%1 windows", count)
var i;
for (i=0; i < Math.min(count,4); i++) {
tooltipText += "<li>"+ itemAt(i).visibleName +"</li>";
}
if (i < count) {
tooltipText += "<br/>"
tooltipText += i18n("and %1 other windows", count-i)
}
desktop.subText = tooltipText
}
Rectangle {
id: windowRect
property int windowId: model.windowId
property string visibleName: model.visibleName
/* since we move clipRect with 1, move it back */
x: model.x - 1
y: model.y - 1
width: model.width
height: model.height
color: {
if (desktop.active) {
if (model.active)
return windowActiveOnActiveDesktopColor;
else
return windowInactiveOnActiveDesktopColor;
} else {
if (model.active)
return windowActiveColor;
else
return windowInactiveColor;
}
}
border.width: 1
border.color: model.active ? windowActiveBorderColor
: windowInactiveBorderColor
KQuickControlsAddonsComponents.QPixmapItem {
id: icon
anchors.centerIn: parent
pixmap: model.icon
height: nativeHeight
width: nativeWidth
visible: pager.showWindowIcons && (windowRect.width >= icon.width) && (windowRect.height >= icon.height)
}
MouseArea {
id: windowMouseArea
anchors.fill: parent
drag.target: windowRect
drag.axis: Drag.XandYAxis
drag.minimumX: -windowRect.width/2
drag.maximumX: root.width - windowRect.width/2
drag.minimumY: -windowRect.height/2
drag.maximumY: root.height - windowRect.height/2
// used to save the state of some properties before the dragging
QtObject {
id: saveState
property int x: -1
property int y: -1
property variant parent
property int desktop: -1
property int mouseX: -1
property int mouseY: -1
}
drag.onActiveChanged: {
root.dragging = drag.active;
desktopMouseArea.enabled = !drag.active;
}
// reparent windowRect to enable the dragging for other desktops
onPressed: {
if (windowRect.parent == root)
return;
saveState.x = windowRect.x;
saveState.y = windowRect.y
saveState.parent = windowRect.parent;
saveState.desktop = desktop.desktopId;
saveState.mouseX = mouseX;
saveState.mouseY = mouseY;
var value = root.mapFromItem(clipRect, windowRect.x, windowRect.y);
windowRect.x = value.x;
windowRect.y = value.y
windowRect.parent = root;
}
onReleased: {
if (root.dragging) {
pager.moveWindow(windowRect.windowId, windowRect.x, windowRect.y,
root.dragId, saveState.desktop);
} else {
// when there is no dragging (just a click), the event is passed
// to the desktop mousearea
desktopMouseArea.clicked(mouse);
}
windowRect.x = saveState.x;
windowRect.y = saveState.y;
windowRect.parent = saveState.parent;
}
}
function checkDesktopHover() {
if (!windowMouseArea.drag.active)
return;
var mouse = root.mapFromItem(windowRect, saveState.mouseX, saveState.mouseY);
for (var i = 0; i < root.children.length; i++) {
var item = root.children[i];
if (item.desktopId != undefined && Utils.contains(item, mouse)) {
root.dragId = item.desktopId;
return;
}
}
}
onXChanged: checkDesktopHover();
onYChanged: checkDesktopHover();
}
}
}
}
}
}

View file

@ -0,0 +1,170 @@
[Desktop Entry]
Name=Pager
Name[af]=Pager
Name[ar]=المنادي
Name[ast]=Paxinador
Name[be@latin]=Stały
Name[bg]=Пейджър
Name[bn]=পেজার
Name[bn_IN]=পেজার
Name[bs]=pejdžer
Name[ca]=Paginador
Name[ca@valencia]=Paginador
Name[cs]=Přepínač ploch
Name[csb]=Pager
Name[da]=Skrivebordsvælger
Name[de]=Arbeitsflächen-Umschalter
Name[el]=Πίνακας σελίδων
Name[en_GB]=Pager
Name[eo]=Paĝilo
Name[es]=Paginador
Name[et]=Peiler
Name[eu]=Bilagailua
Name[fa]=پی‌جو
Name[fi]=Sivutin
Name[fr]=Gestionnaire de bureaux
Name[fy]=Semafoan
Name[ga]=Brabhsálaí Leathanach
Name[gl]=Paxinador
Name[gu]=પેજર
Name[hi]=पेजर
Name[hne]=पेजर
Name[hr]=Pager
Name[hsb]=Listowar
Name[hu]=Asztalváltó
Name[ia]=Pager
Name[id]=Pemisah
Name[is]=Flettir
Name[it]=Cambiadesktop
Name[ja]=ページャ
Name[kk]=Ақтарғыш
Name[km]=Pager
Name[kn]=ಪುಟವೀಕ್ಷಕ (ಪೇಜರ್)
Name[ko]=데스크톱 전환기
Name[ku]=Rûpelker
Name[lt]=Puslapiuotojas
Name[lv]=Lapotājs
Name[mai]=पेजर
Name[mk]=Пејџер
Name[ml]=പേജര്‍
Name[mr]=पेजर
Name[nb]=Skrivebordsbytter
Name[nds]=Schriefdisch-Översicht
Name[ne]=पेजर
Name[nl]=Pager
Name[nn]=Skrivebordsbytar
Name[oc]=Recebedor d'apèl
Name[or]=ପେଜର
Name[pa]=ਪੇਜ਼ਰ
Name[pl]=Pager
Name[pt]=Paginador
Name[pt_BR]=Paginador
Name[ro]=Paginator
Name[ru]=Переключение рабочих столов
Name[se]=Čállinbeavdemolsojeaddj
Name[si]=පේජරය
Name[sk]=Prepínač plôch
Name[sl]=Pozivnik
Name[sr]=листач
Name[sr@ijekavian]=листач
Name[sr@ijekavianlatin]=listač
Name[sr@latin]=listač
Name[sv]=Skrivbordsvisning
Name[ta]=Pager
Name[te]=పేజర్
Name[tg]=Пейҷер
Name[th]=สลับหน้าพื้นที่ทำงาน
Name[tr]=Sayfalayıcı
Name[ug]=چاقىرغۇ
Name[uk]=Пейджер
Name[wa]=Pager
Name[x-test]=xxPagerxx
Name[zh_CN]=分页器
Name[zh_TW]=虛擬桌面管理器
Comment=Switch between virtual desktops
Comment[ar]=يبدل بين أسطح المكتب الافتراضية
Comment[ast]=Camudar ente escritorios virtuales
Comment[be@latin]=Pieraklučeńnie virtualnych stałoŭ
Comment[bg]=Превключване между работните плотове
Comment[bs]=Prebacujte virtuelne površi
Comment[ca]=Commuta entre escriptoris virtuals
Comment[ca@valencia]=Commuta entre escriptoris virtuals
Comment[cs]=Přepínač mezi virtuálními plochami
Comment[da]=Skift mellem virtuelle skriveborde
Comment[de]=Ermöglicht Ihnen das Wechseln zwischen virtuellen Arbeitsflächen.
Comment[el]=Εναλλαγή μεταξύ εικονικών επιφανειών εργασίας
Comment[en_GB]=Switch between virtual desktops
Comment[eo]=Komuti inter virtualaj labortabloj
Comment[es]=Cambiar entre escritorios virtuales
Comment[et]=Lülitumine virtuaalsete töölaudade vahel
Comment[eu]=Aldatu alegiazko mahaigain batetik bestera
Comment[fi]=Vaihda virtuaalityöpöytää
Comment[fr]=Passe d'un bureau virtuel à l'autre
Comment[fy]=Wikselje tusken firuele buroblêden
Comment[ga]=Athraigh an deasc fhíorúil
Comment[gl]=Troca entre escritorios virtuais
Comment[gu]=વર્ચ્યુઅલ ડેસ્કટોપ્સની વચ્ચે બદલો
Comment[he]=משמש למעבר בין שולחנות עבודה וירטואלים
Comment[hi]=आभासी डेस्कटॉप्स के बीच स्विच करें
Comment[hne]=आभासी डेस्कटाप मं स्विच करव
Comment[hr]=Mijenjanje virtualnih radnih površina
Comment[hsb]=Mjez wirtuelnymi dźěłowymi powjerchami tam a sem skakać
Comment[hu]=Virtuális asztalok közötti váltásra szolgáló elem
Comment[ia]=Commuta inter scriptorios virtual
Comment[id]=Berpindah di antara desktop virtual
Comment[is]=Skiptir milli sýndarskjáborða
Comment[it]=Passa ad altri desktop virtuali
Comment[ja]=仮想デスクトップを切り替えます
Comment[kk]=Виртуалды үстелдерді ақтару
Comment[km]=ប្ដូរ​រវាង​ផ្ទៃតុ​និម្មិត
Comment[kn]=ವಾಸ್ತವಪ್ರಾಯ ಗಣಕತೆರೆಗಳ ನಡುವೆ ಅಂತರಿಸು
Comment[ko]=가상 데스크톱 사이를 전환합니다
Comment[lt]=Persijungti tarp virtualių darbastalių
Comment[lv]=Pārslēgties starp virtuālām darbvirsmām
Comment[mk]=Менување меѓу виртуелни раб. површини
Comment[ml]=വര്‍ച്ചുവല്‍ പണിയിടങ്ങള്‍ തമ്മില്‍ മാറുക
Comment[mr]=आभासी डेस्कटॉप बदला
Comment[nb]=Bytt mellom virtuelle skrivebord
Comment[nds]=Twischen Schriefdischen wesseln
Comment[nl]=Schakel tussen virtuele bureaubladen
Comment[nn]=Byt mellom virtuelle skrivebord
Comment[or]=ଆଭାସୀ ଡ଼େସ୍କଟପଗୁଡ଼ିକ ମଧ୍ଯରେ ଅଦଳ ବଦଳ କରନ୍ତୁ
Comment[pa]=ਵੁਰਚੁਅਲ ਡੈਸਕਟਾਪਾਂ ਵਿੱਚ ਸਵਿੱਚ ਕਰੋ
Comment[pl]=Przełączenie między wirtualnymi pulpitami
Comment[pt]=Mudar de ecrã virtual
Comment[pt_BR]=Alterna entre áreas de trabalho virtuais
Comment[ro]=Comută între birouri virtuale
Comment[ru]=Переключение между рабочими столами
Comment[si]=අතත්‍ය වැඩතල අතර මාරුවන්න
Comment[sk]=Prepínanie medzi virtuálnymi plochami
Comment[sl]=Preklapljajte med navideznimi namizji
Comment[sr]=Пребацујте виртуелне површи
Comment[sr@ijekavian]=Пребацујте виртуелне површи
Comment[sr@ijekavianlatin]=Prebacujte virtuelne površi
Comment[sr@latin]=Prebacujte virtuelne površi
Comment[sv]=Byt mellan virtuella skrivbord
Comment[ta]=Switch between virtual desktops
Comment[te]=వర్చ్యువల్ రంగస్థలముల మధ్యన మారుము
Comment[tg]=Переключение между рабочими столами
Comment[th]=สลับไปมาระหว่างพื้นที่ทำงานเสมือน
Comment[tr]=Sanal masaüstleri arasında gezin
Comment[ug]=مەۋھۇم ئۈستەلئۈستىلىرىنى ئالماشتۇر
Comment[uk]=Перемкніть віртуальні стільниці
Comment[wa]=Passer d' on forveyou scribanne a èn ôte
Comment[x-test]=xxSwitch between virtual desktopsxx
Comment[zh_CN]=在虚拟桌面间切换
Comment[zh_TW]=在虛擬桌面間切換
Icon=user-desktop
Type=Service
X-Plasma-API=declarativeappletscript
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-MainScript=ui/main.qml
X-KDE-PluginInfo-Author=The Plasma Team
X-KDE-PluginInfo-Email=plasma-devel@kde.org
X-KDE-PluginInfo-Name=org.kde.plasma.pager
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=http://userbase.kde.org/Plasma/Pager
X-KDE-PluginInfo-Category=Windows and Tasks
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -0,0 +1,250 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* 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 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "model.h"
RectangleModel::RectangleModel(QObject *parent)
: QAbstractListModel(parent)
{
setRoleNames(roles());
}
QHash<int, QByteArray> RectangleModel::roles() const
{
QHash<int, QByteArray> rectRoles;
rectRoles[WidthRole] = "width";
rectRoles[HeightRole] = "height";
rectRoles[XRole] = "x";
rectRoles[YRole] = "y";
return rectRoles;
}
void RectangleModel::clear()
{
m_rects.clear();
}
void RectangleModel::append(const QRectF &rect)
{
m_rects.append(rect);
}
QRectF &RectangleModel::rectAt(int index)
{
return m_rects[index];
}
int RectangleModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_rects.count();
}
QVariant RectangleModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() > m_rects.count())
return QVariant();
const QRectF &rect = m_rects[index.row()];
switch(role) {
case WidthRole:
return rect.width();
case HeightRole:
return rect.height();
case XRole:
return rect.x();
case YRole:
return rect.y();
default:
return QVariant();
}
}
WindowModel::WindowModel(QObject *parent)
: RectangleModel(parent)
{
setRoleNames(roles());
}
QHash<int, QByteArray> WindowModel::roles() const
{
QHash<int, QByteArray> rectRoles = RectangleModel::roles();
rectRoles[IdRole] = "windowId";
rectRoles[ActiveRole] = "active";
rectRoles[IconRole] = "icon";
rectRoles[VisibleNameRole] = "visibleName";
return rectRoles;
}
void WindowModel::clear()
{
beginResetModel();
RectangleModel::clear();
m_ids.clear();
m_active.clear();
m_icons.clear();
m_visibleNames.clear();
endResetModel();
}
void WindowModel::append(WId windowId, const QRectF &rect, bool active,
const QPixmap &icon, const QString &name)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_ids.append(windowId);
RectangleModel::append(rect);
m_active.append(active);
m_icons.append(icon);
m_visibleNames.append(name);
endInsertRows();
}
WId WindowModel::idAt(int index) const
{
return m_ids[index];
}
QString WindowModel::visibleNameAt(int index) const
{
return m_visibleNames[index];
}
QVariant WindowModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() >= rowCount())
return QVariant();
if (role >= RectangleModel::WidthRole && role < IdRole)
return RectangleModel::data(index, role);
switch (role) {
case IdRole:
return int(m_ids[index.row()]);
case ActiveRole:
return m_active[index.row()];
case IconRole:
return m_icons[index.row()];
case VisibleNameRole:
return m_visibleNames[index.row()];
default:
return QVariant();
}
}
PagerModel::PagerModel(QObject *parent)
: QAbstractListModel(parent)
{
setRoleNames(roles());
}
WindowModel *PagerModel::windowsAt(int index) const
{
if (index < 0 || index >= m_windows.count())
return 0;
return qobject_cast<WindowModel *>(m_windows[index]);
}
QHash<int, QByteArray> PagerModel::roles() const
{
QHash<int, QByteArray> rectRoles = m_desktops.roles();
rectRoles[WindowsRole] = "windows";
rectRoles[DesktopNameRole] = "desktopName";
return rectRoles;
}
void PagerModel::clearDesktopRects()
{
beginResetModel();
m_desktops.clear();
m_names.clear();
endResetModel();
}
void PagerModel::appendDesktopRect(const QRectF &rect, const QString &name)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_desktops.append(rect);
m_names.append(name);
endInsertRows();
}
QRectF& PagerModel::desktopRectAt(int index)
{
return m_desktops.rectAt(index);
}
void PagerModel::clearWindowRects()
{
int removeIndex = -1;
for (int i = 0; i < m_windows.count(); i++) {
windowsAt(i)->clear();
if (i >= rowCount())
removeIndex = (removeIndex == -1) ? i : -1;
}
if (removeIndex != -1) {
// remove the windows model if the number of desktop has decreased
for (int i = m_windows.count()-1; i >= removeIndex; i--) {
windowsAt(i)->deleteLater();
m_windows.removeAt(i);
}
}
// append more windows model if the number of desktop has increased
for (int i = m_windows.count(); i < rowCount(); i++)
m_windows.append(new WindowModel(this));
}
void PagerModel::appendWindowRect(int desktopId, WId windowId, const QRectF &rect,
bool active, const QPixmap &icon, const QString &name)
{
WindowModel *windows = windowsAt(desktopId);
if (!windows)
return;
windows->append(windowId, rect, active, icon, name);
QModelIndex i = index(desktopId);
emit dataChanged(i, i);
}
QVariant PagerModel::data(const QModelIndex &index, int role) const
{
if (role >= RectangleModel::WidthRole && role < WindowsRole)
return m_desktops.data(index, role);
if (index.row() < 0 || index.row() >= m_windows.count())
return QVariant();
switch (role) {
case WindowsRole:
return QVariant::fromValue(m_windows[index.row()]);
case DesktopNameRole:
return m_names[index.row()];
default:
return QVariant();
}
}
int PagerModel::rowCount(const QModelIndex &index) const
{
return m_desktops.rowCount(index);
}

View file

@ -0,0 +1,112 @@
/*
* Copyright 2012 Luís Gabriel Lima <lampih@gmail.com>
*
* 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 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODEL_H
#define MODEL_H
#include <QtCore/QAbstractListModel>
#include <QtCore/QRectF>
#include <QtGui/QWidgetList> // For WId
#include <QtGui/QPixmap>
class RectangleModel : public QAbstractListModel
{
Q_OBJECT
public:
enum RectangleRoles {
WidthRole = Qt::UserRole + 1,
HeightRole,
XRole,
YRole
};
RectangleModel(QObject *parent = 0);
virtual QHash<int, QByteArray> roles() const;
virtual void clear();
void append(const QRectF &rect);
QRectF &rectAt(int index);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
private:
QList<QRectF> m_rects;
};
class WindowModel : public RectangleModel
{
Q_OBJECT
public:
enum WindowRole {
IdRole = RectangleModel::YRole + 1,
ActiveRole,
IconRole,
VisibleNameRole
};
WindowModel(QObject *parent = 0);
QHash<int, QByteArray> roles() const;
void clear();
void append(WId, const QRectF &, bool active, const QPixmap &icon, const QString &name);
WId idAt(int index) const;
QString visibleNameAt(int index) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
private:
QList<WId> m_ids;
QList<bool> m_active;
QList<QPixmap> m_icons;
QStringList m_visibleNames;
};
class PagerModel : public QAbstractListModel
{
Q_OBJECT
public:
enum PagerRoles {
WindowsRole = RectangleModel::YRole + 1,
DesktopNameRole
};
PagerModel(QObject *parent = 0);
QHash<int, QByteArray> roles() const;
void clearDesktopRects();
void appendDesktopRect(const QRectF &rect, const QString &name);
QRectF &desktopRectAt(int index);
void clearWindowRects();
void appendWindowRect(int desktopId, WId, const QRectF &, bool active,
const QPixmap &icon, const QString &name);
WindowModel *windowsAt(int index) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
private:
RectangleModel m_desktops;
QList<QObject *> m_windows;
QStringList m_names;
};
#endif // MODEL_H

View file

@ -0,0 +1,601 @@
/***************************************************************************
* Copyright (C) 2007 by Daniel Laidig <d.laidig@gmx.de> *
* Copyright (C) 2012 by Luís Gabriel Lima <lampih@gmail.com> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include "pager.h"
#include <math.h>
#include <QAction>
#include <QApplication>
#include <QFont>
#include <QTimer>
#if HAVE_X11
#include <QX11Info>
#endif
#include <QDBusInterface>
#include <QTextDocument>
#include <QDesktopWidget>
#include <KColorScheme>
#include <KGlobalSettings>
#include <KIconLoader>
#include <KLocalizedString>
#include <KWindowSystem>
#if HAVE_X11
#include <netwm.h>
#endif
#include <Plasma/FrameSvg>
#include <Plasma/Package>
#include <kactivities/consumer.h>
#include <task.h>
const int FAST_UPDATE_DELAY = 100;
const int UPDATE_DELAY = 500;
const int MAXDESKTOPS = 20;
// random(), find a less magic one if you can. -sreich
const qreal MAX_TEXT_WIDTH = 800;
Pager::Pager(QObject *parent)
: QObject(parent),
m_displayedText(None),
m_currentDesktopSelected(DoNothing),
m_rows(2),
m_columns(0),
m_currentDesktop(0),
m_orientation(Qt::Horizontal),
m_addDesktopAction(0),
m_removeDesktopAction(0),
m_showWindowIcons(false),
m_desktopDown(false),
m_validSizes(false),
m_desktopWidget(QApplication::desktop())
#if HAVE_X11
, m_isX11(QX11Info::isPlatformX11())
#endif
{
// initialize with a decent default
m_desktopCount = qMax(1, KWindowSystem::numberOfDesktops());
m_pagerModel = new PagerModel(this);
createMenu();
m_timer = new QTimer(this);
m_timer->setSingleShot(true);
connect(m_timer, SIGNAL(timeout()), this, SLOT(recalculateWindowRects()));
connect(KWindowSystem::self(), SIGNAL(currentDesktopChanged(int)), this, SLOT(currentDesktopChanged(int)));
connect(KWindowSystem::self(), SIGNAL(windowAdded(WId)), this, SLOT(startTimerFast()));
connect(KWindowSystem::self(), SIGNAL(windowRemoved(WId)), this, SLOT(startTimerFast()));
connect(KWindowSystem::self(), SIGNAL(activeWindowChanged(WId)), this, SLOT(startTimerFast()));
connect(KWindowSystem::self(), SIGNAL(numberOfDesktopsChanged(int)), this, SLOT(numberOfDesktopsChanged(int)));
connect(KWindowSystem::self(), SIGNAL(desktopNamesChanged()), this, SLOT(desktopNamesChanged()));
connect(KWindowSystem::self(), SIGNAL(stackingOrderChanged()), this, SLOT(startTimerFast()));
connect(KWindowSystem::self(), SIGNAL(windowChanged(WId,const ulong*)), this, SLOT(windowChanged(WId,const ulong*)));
connect(KWindowSystem::self(), SIGNAL(showingDesktopChanged(bool)), this, SLOT(startTimer()));
connect(m_desktopWidget, SIGNAL(screenCountChanged(int)), SLOT(desktopsSizeChanged()));
connect(m_desktopWidget, SIGNAL(resized(int)), SLOT(desktopsSizeChanged()));
// connect to KWin's reloadConfig signal to get updates on the desktop layout
QDBusConnection dbus = QDBusConnection::sessionBus();
dbus.connect(QString(), "/KWin", "org.kde.KWin", "reloadConfig",
this, SLOT(configChanged()));
recalculateGridSizes(m_rows);
setCurrentDesktop(KWindowSystem::currentDesktop());
KActivities::Consumer *act = new KActivities::Consumer(this);
connect(act, SIGNAL(currentActivityChanged(QString)), this, SLOT(currentActivityChanged(QString)));
m_currentActivity = act->currentActivity();
}
Pager::~Pager()
{
}
void Pager::setCurrentDesktop(int desktop)
{
if (m_currentDesktop != desktop) {
m_currentDesktop = desktop;
emit currentDesktopChanged();
}
}
void Pager::setShowWindowIcons(bool show)
{
if (m_showWindowIcons != show) {
m_showWindowIcons = show;
emit showWindowIconsChanged();
}
}
Qt::Orientation Pager::orientation() const
{
return m_orientation;
}
void Pager::setOrientation(Qt::Orientation orientation)
{
if (m_orientation == orientation) {
return;
}
m_orientation = orientation;
emit orientationChanged();
// whenever we switch to/from vertical form factor, swap the rows and columns around
if (m_columns != m_rows) {
// pass in columns as the new rows
recalculateGridSizes(m_columns);
recalculateWindowRects();
}
}
QSizeF Pager::size() const
{
return m_size;
}
QSize Pager::preferredSize() const
{
return m_preferredSize;
}
void Pager::setSize(const QSizeF &size)
{
if (m_size == size) {
return;
}
m_size = size;
emit sizeChanged();
m_validSizes = false;
startTimer();
}
Pager::CurrentDesktopSelected Pager::currentDesktopSelected() const
{
return m_currentDesktopSelected;
}
void Pager::setCurrentDesktopSelected(CurrentDesktopSelected cur)
{
if (m_currentDesktopSelected == cur) {
return;
}
m_currentDesktopSelected = cur;
emit currentDesktopSelectedChanged();
}
Pager::DisplayedText Pager::displayedText() const
{
return m_displayedText;
}
void Pager::setDisplayedText(Pager::DisplayedText disp)
{
if (m_displayedText == disp) {
return;
}
m_displayedText = disp;
emit displayedTextChanged();
}
void Pager::createMenu()
{
#if HAVE_X11
m_addDesktopAction = new QAction(SmallIcon("list-add"),i18n("&Add Virtual Desktop"), this);
m_actions.append(m_addDesktopAction);
connect(m_addDesktopAction, SIGNAL(triggered(bool)), this , SLOT(slotAddDesktop()));
m_removeDesktopAction = new QAction(SmallIcon("list-remove"),i18n("&Remove Last Virtual Desktop"), this);
m_actions.append(m_removeDesktopAction);
connect(m_removeDesktopAction, SIGNAL(triggered(bool)), this , SLOT(slotRemoveDesktop()));
if (m_desktopCount <= 1) {
m_removeDesktopAction->setEnabled(false);
} else if (m_desktopCount >= MAXDESKTOPS) {
m_addDesktopAction->setEnabled(false);
}
#endif
}
QList<QAction*> Pager::contextualActions()
{
return m_actions;
}
#if HAVE_X11
void Pager::slotAddDesktop()
{
if (!m_isX11) {
return;
}
NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops);
info.setNumberOfDesktops(info.numberOfDesktops() + 1);
}
void Pager::slotRemoveDesktop()
{
if (!m_isX11) {
return;
}
NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops);
int desktops = info.numberOfDesktops();
if (desktops > 1) {
info.setNumberOfDesktops(info.numberOfDesktops() - 1);
}
}
#endif
void Pager::recalculateGridSizes(int rows)
{
// recalculate the number of rows and columns in the grid
rows = qBound(1, rows, m_desktopCount);
// avoid weird cases like having 3 rows for 4 desktops, where the last row is unused
int columns = m_desktopCount / rows;
if (m_desktopCount % rows > 0) {
columns++;
}
rows = m_desktopCount / columns;
if (m_desktopCount % columns > 0) {
rows++;
}
// update the grid size
m_rows = rows;
m_columns = columns;
updateSizes();
}
void Pager::updateSizes()
{
const int padding = 2; // Space between miniatures of desktops
const int textMargin = 3; // Space between name of desktop and border
const qreal leftMargin = 0;
const qreal topMargin = 0;
const qreal rightMargin = 0;
const qreal bottomMargin = 0;
QRect totalRect;
for (int x = 0; x < m_desktopWidget->screenCount(); x++) {
totalRect |= m_desktopWidget->screenGeometry(x);
}
const qreal ratio = (qreal) totalRect.width() /
(qreal) totalRect.height();
qreal itemHeight;
qreal itemWidth;
qreal preferredItemHeight;
qreal preferredItemWidth;
if (orientation() == Qt::Vertical) {
itemWidth = (m_size.width() - leftMargin - rightMargin -
padding * (m_columns - 1)) / m_columns;
itemHeight = itemWidth / ratio;
} else {
// work out the preferred size based on the height of the geometry
preferredItemHeight = (m_size.height() - topMargin - bottomMargin -
padding * (m_rows - 1)) / m_rows;
preferredItemWidth = preferredItemHeight * ratio;
if (m_displayedText == Name) {
// When containment is in this position we are not limited by low width and we can
// afford increasing width of applet to be able to display every name of desktops
for (int i = 0; i < m_desktopCount; i++) {
QFontMetricsF metrics(KGlobalSettings::taskbarFont());
QSizeF textSize = metrics.size(Qt::TextSingleLine, KWindowSystem::desktopName(i+1));
if (textSize.width() + textMargin * 2 > preferredItemWidth) {
preferredItemWidth = textSize.width() + textMargin * 2;
}
}
}
itemWidth = (m_size.width() - leftMargin - rightMargin -
padding * (m_columns - 1)) / m_columns;
if (itemWidth > preferredItemWidth) {
itemWidth = preferredItemWidth;
}
itemHeight = preferredItemHeight;
if (itemWidth < itemHeight * ratio) {
itemWidth = itemHeight * ratio;
}
}
m_widthScaleFactor = itemWidth / totalRect.width();
m_heightScaleFactor = itemHeight / totalRect.height();
m_pagerModel->clearDesktopRects();
int pw = (int)(leftMargin + (itemWidth + padding) * m_columns + rightMargin);
int ph = (int)(topMargin + (itemHeight + padding) * m_rows + bottomMargin);
if (orientation() == Qt::Vertical) {
pw = m_size.width();
} else {
ph = m_size.height();
}
m_preferredSize = QSize(pw, ph);
emit preferredSizeChanged();
QRectF itemRect(QPointF(leftMargin, topMargin) , QSizeF(itemWidth, itemHeight));
for (int i = 0; i < m_desktopCount; i++) {
itemRect.moveLeft(leftMargin + (i % m_columns) * (itemWidth + padding));
itemRect.moveTop(topMargin + (i / m_columns) * (itemHeight + padding));
QString name = KWindowSystem::desktopName(i + 1);
m_pagerModel->appendDesktopRect(itemRect, name);
}
m_validSizes = true;
}
void Pager::recalculateWindowRects()
{
if (!m_validSizes) {
updateSizes();
}
QList<WId> windows = KWindowSystem::stackingOrder();
m_pagerModel->clearWindowRects();
#if HAVE_X11
foreach (WId window, windows) {
KWindowInfo info = KWindowSystem::windowInfo(window, NET::WMGeometry | NET::WMFrameExtents |
NET::WMWindowType | NET::WMDesktop |
NET::WMState | NET::XAWMState | NET::WMVisibleName);
NET::WindowType type = info.windowType(NET::NormalMask | NET::DialogMask | NET::OverrideMask |
NET::UtilityMask | NET::DesktopMask | NET::DockMask |
NET::TopMenuMask | NET::SplashMask | NET::ToolbarMask |
NET::MenuMask);
// the reason we don't check for -1 or Net::Unknown here is that legitimate windows, such
// as some java application windows, may not have a type set for them.
// apparently sane defaults on properties is beyond the wisdom of x11.
if (type == NET::Desktop || type == NET::Dock || type == NET::TopMenu ||
type == NET::Splash || type == NET::Menu || type == NET::Toolbar ||
info.hasState(NET::SkipPager) || info.isMinimized()) {
continue;
}
//check activity
NETWinInfo netInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), 0, NET::WM2Activities);
QString result(netInfo.activities());
if (!result.isEmpty() && result != "00000000-0000-0000-0000-000000000000") {
QStringList activities = result.split(',');
if (!activities.contains(m_currentActivity)) {
continue;
}
}
for (int i = 0; i < m_desktopCount; i++) {
if (!info.isOnDesktop(i+1)) {
continue;
}
QRectF windowRect = info.frameGeometry();
if (KWindowSystem::mapViewport()) {
windowRect = fixViewportPosition(windowRect.toRect());
}
windowRect = QRectF(windowRect.x() * m_widthScaleFactor,
windowRect.y() * m_heightScaleFactor,
windowRect.width() * m_widthScaleFactor,
windowRect.height() * m_heightScaleFactor).toRect();
bool active = (window == KWindowSystem::activeWindow());
int windowIconSize = KIconLoader::global()->currentSize(KIconLoader::Small);
int windowRectSize = qMin(windowRect.width(), windowRect.height());
windowIconSize = qMax(windowIconSize, windowRectSize / 2);
QPixmap icon = KWindowSystem::icon(info.win(), windowIconSize, windowIconSize, true);
m_pagerModel->appendWindowRect(i, window, windowRect, active, icon, info.visibleName());
}
}
#endif
}
void Pager::currentDesktopChanged(int desktop)
{
if (desktop < 1) {
return; // bogus value, don't accept it
}
setCurrentDesktop(desktop);
m_desktopDown = false;
startTimerFast();
}
void Pager::currentActivityChanged(const QString &activity)
{
m_currentActivity = activity;
startTimerFast();
}
void Pager::numberOfDesktopsChanged(int num)
{
if (num < 1) {
return; // refuse to update to zero desktops
}
#if HAVE_X11
m_removeDesktopAction->setEnabled(num > 1);
m_addDesktopAction->setEnabled(num < MAXDESKTOPS);
#endif
m_desktopCount = num;
m_pagerModel->clearDesktopRects();
recalculateGridSizes(m_rows);
recalculateWindowRects();
}
void Pager::desktopNamesChanged()
{
m_pagerModel->clearDesktopRects();
m_validSizes = false;
startTimer();
}
void Pager::windowChanged(WId id, const unsigned long* dirty)
{
Q_UNUSED(id)
if (dirty[NETWinInfo::PROTOCOLS] & (NET::WMGeometry | NET::WMDesktop) ||
dirty[NETWinInfo::PROTOCOLS2] & NET::WM2Activities) {
startTimer();
}
}
void Pager::desktopsSizeChanged()
{
m_pagerModel->clearDesktopRects();
m_validSizes = false;
startTimer();
}
void Pager::startTimer()
{
if (!m_timer->isActive()) {
m_timer->start(UPDATE_DELAY);
}
}
void Pager::startTimerFast()
{
if (!m_timer->isActive()) {
m_timer->start(FAST_UPDATE_DELAY);
}
}
void Pager::moveWindow(int window, double x, double y, int targetDesktop, int sourceDesktop)
{
#if HAVE_X11
if (!m_isX11) {
return;
}
WId windowId = (WId) window;
QPointF dest = QPointF(x, y) - m_pagerModel->desktopRectAt(targetDesktop).topLeft();
dest = QPointF(dest.x()/m_widthScaleFactor, dest.y()/m_heightScaleFactor);
// don't move windows to negative positions
dest = QPointF(qMax(dest.x(), qreal(0.0)), qMax(dest.y(), qreal(0.0)));
// use _NET_MOVERESIZE_WINDOW rather than plain move, so that the WM knows this is a pager request
NETRootInfo info(QX11Info::connection(), 0);
int flags = (0x20 << 12) | (0x03 << 8) | 1; // from tool, x/y, northwest gravity
if (!KWindowSystem::mapViewport()) {
KWindowInfo windowInfo = KWindowSystem::windowInfo(windowId, NET::WMDesktop | NET::WMState);
if (!windowInfo.onAllDesktops()) {
KWindowSystem::setOnDesktop(windowId, targetDesktop+1);
}
// only move the window if it is not full screen and if it is kept within the same desktop
// moving when dropping between desktop is too annoying due to the small drop area.
if (!(windowInfo.state() & NET::FullScreen) &&
(targetDesktop == sourceDesktop || windowInfo.onAllDesktops())) {
QPoint d = dest.toPoint();
info.moveResizeWindowRequest(windowId, flags, d.x(), d.y(), 0, 0);
}
} else {
// setOnDesktop() with viewports is also moving a window, and since it takes a moment
// for the WM to do the move, there's a race condition with figuring out how much to move,
// so do it only as one move
dest += KWindowSystem::desktopToViewport(targetDesktop+1, false);
QPoint d = KWindowSystem::constrainViewportRelativePosition(dest.toPoint());
info.moveResizeWindowRequest(windowId, flags, d.x(), d.y(), 0, 0);
}
m_timer->start();
#else
Q_UNUSED(window)
Q_UNUSED(x)
Q_UNUSED(y)
Q_UNUSED(targetDesktop)
Q_UNUSED(sourceDesktop)
#endif
}
void Pager::changeDesktop(int newDesktop)
{
#if HAVE_X11
if (!m_isX11) {
return;
}
if (m_currentDesktop == newDesktop+1) {
// toogle the desktop or the dashboard
if (m_currentDesktopSelected == ShowDesktop) {
NETRootInfo info(QX11Info::connection(), 0);
m_desktopDown = !m_desktopDown;
info.setShowingDesktop(m_desktopDown);
} else if (m_currentDesktopSelected == ShowDashboard) {
QDBusInterface plasmaApp("org.kde.plasma-desktop", "/App");
plasmaApp.call("toggleDashboard");
}
} else {
KWindowSystem::setCurrentDesktop(newDesktop + 1);
setCurrentDesktop(newDesktop + 1);
}
#else
Q_UNUSED(newDesktop)
#endif
}
// KWindowSystem does not translate position when mapping viewports
// to virtual desktops (it'd probably break more things than fix),
// so the offscreen coordinates need to be fixed
QRect Pager::fixViewportPosition( const QRect& r )
{
QRect desktopGeom = m_desktopWidget->geometry();
int x = r.center().x() % desktopGeom.width();
int y = r.center().y() % desktopGeom.height();
if( x < 0 ) {
x = x + desktopGeom.width();
}
if( y < 0 ) {
y = y + desktopGeom.height();
}
return QRect( x - r.width() / 2, y - r.height() / 2, r.width(), r.height());
}
#include "moc_pager.cpp"

View file

@ -0,0 +1,168 @@
/***************************************************************************
* Copyright (C) 2007 by Daniel Laidig <d.laidig@gmx.de> *
* Copyright (C) 2012 by Luís Gabriel Lima <lampih@gmail.com> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#ifndef PAGER_H
#define PAGER_H
#include <QGraphicsSceneHoverEvent>
#include <QList>
#include <Plasma/Applet>
#include "model.h"
#include <config-X11.h>
class QDesktopWidget;
class KColorScheme;
class KWindowInfo;
class KCModuleProxy;
namespace Plasma
{
class FrameSvg;
}
class Pager : public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* model READ model CONSTANT)
Q_PROPERTY(int currentDesktop READ currentDesktop NOTIFY currentDesktopChanged)
Q_PROPERTY(bool showWindowIcons READ showWindowIcons WRITE setShowWindowIcons NOTIFY showWindowIconsChanged)
Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation NOTIFY orientationChanged)
Q_PROPERTY(QSizeF size READ size WRITE setSize NOTIFY sizeChanged)
Q_PROPERTY(QSize preferredSize READ preferredSize NOTIFY preferredSizeChanged)
Q_PROPERTY(Pager::CurrentDesktopSelected currentDesktopSelected READ currentDesktopSelected WRITE setCurrentDesktopSelected NOTIFY currentDesktopSelectedChanged)
Q_PROPERTY(Pager::DisplayedText displayedText READ displayedText WRITE setDisplayedText NOTIFY displayedTextChanged)
public:
enum CurrentDesktopSelected {
DoNothing = 0,
ShowDesktop,
ShowDashboard
};
Q_ENUMS(CurrentDesktopSelected)
enum DisplayedText {
Number = 0,
Name,
None
};
Q_ENUMS(DisplayedText)
Pager(QObject *parent = 0);
~Pager();
//void constraintsEvent(Plasma::Constraints);
virtual QList<QAction*> contextualActions();
QObject *model() const { return m_pagerModel; }
int currentDesktop() const { return m_currentDesktop; }
void setCurrentDesktop(int desktop);
bool showWindowIcons() const { return m_showWindowIcons; }
void setShowWindowIcons(bool show);
Qt::Orientation orientation() const;
void setOrientation(Qt::Orientation orientation);
QSizeF size() const;
void setSize(const QSizeF &size);
QSize preferredSize() const;
CurrentDesktopSelected currentDesktopSelected() const;
void setCurrentDesktopSelected(CurrentDesktopSelected cur);
DisplayedText displayedText() const;
void setDisplayedText(DisplayedText disp);
Q_INVOKABLE void moveWindow(int, double, double, int, int);
Q_INVOKABLE void changeDesktop(int desktopId);
Q_SIGNALS:
void currentDesktopChanged();
void showWindowIconsChanged();
void orientationChanged();
void sizeChanged();
void preferredSizeChanged();
void currentDesktopSelectedChanged();
void displayedTextChanged();
public Q_SLOTS:
void recalculateGridSizes(int rows);
void updateSizes();
void recalculateWindowRects();
protected Q_SLOTS:
void currentDesktopChanged(int desktop);
void currentActivityChanged(const QString &activity);
void desktopsSizeChanged();
void numberOfDesktopsChanged(int num);
void desktopNamesChanged();
void windowChanged(WId id, const unsigned long *dirty);
void startTimer();
void startTimerFast();
#if HAVE_X11
void slotAddDesktop();
void slotRemoveDesktop();
#endif
protected:
void createMenu();
QRect fixViewportPosition( const QRect& r );
private:
PagerModel *m_pagerModel;
QTimer* m_timer;
DisplayedText m_displayedText;
CurrentDesktopSelected m_currentDesktopSelected;
int m_rows;
int m_columns;
int m_desktopCount;
int m_currentDesktop;
QString m_currentActivity;
qreal m_widthScaleFactor;
qreal m_heightScaleFactor;
QSizeF m_size;
QSize m_preferredSize;
Qt::Orientation m_orientation;
//list of info about animations for each desktop
QList<QAction*> m_actions;
QAction *m_addDesktopAction;
QAction *m_removeDesktopAction;
bool m_showWindowIcons : 1;
bool m_desktopDown : 1;
bool m_validSizes : 1;
QDesktopWidget *m_desktopWidget;
#if HAVE_X11
bool m_isX11;
#endif
};
#endif

View file

@ -0,0 +1,29 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "pagerplugin.h"
#include "pager.h"
#include <QtQml>
void KickoffPlugin::registerTypes (const char *uri)
{
Q_ASSERT(uri == QLatin1String("org.kde.plasma.private.pager"));
qmlRegisterType<Pager>(uri, 2, 0, "Pager");
}

View file

@ -0,0 +1,35 @@
/*
Copyright (C) 2011 Martin Gräßlin <mgraesslin@kde.org>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef PAGERPLUGIN_H
#define PAGERPLUGIN_H
#include <QQmlEngine>
#include <QQmlExtensionPlugin>
class KickoffPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
public:
virtual void registerTypes(const char *uri);
};
#endif // PAGERPLUGIN_H

View file

@ -0,0 +1 @@
plugin pagerplugin

View file

@ -0,0 +1 @@
plasma_install_package(package org.kde.plasma.showActivityManager)

View file

@ -0,0 +1,4 @@
#! /usr/bin/env bash
$EXTRACTRC `find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` >> rc.cpp
$XGETTEXT `find . -name \*.qml -o -name \*.cpp` -o $podir/plasma_applet_org.kde.plasma.showActivityManager.pot
rm -f rc.cpp

View file

@ -0,0 +1,61 @@
/*
* Copyright 2012 Gregor Taetzner <gregor@freenet.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import QtQuick 2.0
import QtQuick.Layouts 1.1
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
MouseArea {
id: iconContainer
property string activeSource: "Status"
height: 16
width: 16
Layout.minimumWidth: 16
Layout.minimumHeight: 16
implicitWidth: units.iconSizes["panel"]
implicitHeight: implicitWidth
onClicked: {
var service = dataSource.serviceForSource(activeSource)
var operation = service.operationDescription("toggleActivityManager")
service.startOperationCall(operation)
}
PlasmaCore.DataSource {
id: dataSource
engine: "org.kde.activities"
connectedSources: [activeSource]
}
PlasmaCore.ToolTipArea {
id: tooltip
mainText: i18n("Show Activity Manager")
subText: i18n("Click to show the activity manager")
anchors.fill: parent
image: "preferences-activities"
}
PlasmaCore.IconItem {
id: icon
source: "preferences-activities"
width: parent.width
height: parent.height
}
}

View file

@ -0,0 +1,127 @@
[Desktop Entry]
Name=Activities
Name[ar]=الأنشطة
Name[bg]=Дейности
Name[bs]=motor aktivnosti
Name[ca]=Activitats
Name[ca@valencia]=Activitats
Name[cs]=Aktivity
Name[da]=Aktiviteter
Name[de]=Aktivitäten
Name[el]=Δραστηριότητες
Name[es]=Actividades
Name[et]=Tegevused
Name[eu]=Jarduerak
Name[fa]=فعالیتها
Name[fi]=Aktiviteetit
Name[fr]=Activités
Name[ga]=Gníomhaíochtaí
Name[gl]=Actividades
Name[he]=עילויות
Name[hr]=Aktivnosti
Name[hu]=Aktivitások
Name[ia]=Activitates
Name[is]=Virknistjóri
Name[it]=Attività
Name[ja]=アクティビティ
Name[kk]=Белсенділіктер
Name[km]=សកម្មភាព
Name[ko]=활동
Name[lt]=Veiklos
Name[lv]=Aktivitātes
Name[mr]=कार्यपध्दती
Name[nb]=Aktiviteter
Name[nds]=Aktiviteten
Name[nl]=Activiteiten
Name[pa]=ਸਰਗਰਮੀਆਂ
Name[pl]=Działania
Name[pt]=Actividades
Name[pt_BR]=Atividades
Name[ro]=Activități
Name[ru]=Комнаты
Name[sk]=Aktivity
Name[sl]=Dejavnosti
Name[sr]=активности
Name[sr@ijekavian]=активности
Name[sr@ijekavianlatin]=aktivnosti
Name[sr@latin]=aktivnosti
Name[sv]=Aktiviteter
Name[tr]=Etkinlikler
Name[ug]=پائالىيەتلەر
Name[uk]=Простори дій
Name[vi]=Hoạt động
Name[wa]=Activités
Name[x-test]=xxActivitiesxx
Name[zh_CN]=活动
Name[zh_TW]=活動
Comment=Shows the activity manager
Comment[bg]=Управление на дейностите
Comment[bs]=Prikazuje menadžer aktivnosti
Comment[ca]=Mostra el gestor d'activitats
Comment[ca@valencia]=Mostra el gestor d'activitats
Comment[cs]=Zobrazí správce aktivit
Comment[da]=Vis aktivitetshåndtering
Comment[de]=Zeigt die Aktivitätenverwaltung an
Comment[el]=Εμφανίζει το διαχειριστή δραστηριοτήτων
Comment[es]=Muestra el gestor de actividades
Comment[et]=Tegevuste halduri näitamine
Comment[eu]=Jarduera-kudeatzailea erakusten du
Comment[fi]=Näyttää aktiviteettienhallinnan
Comment[fr]=Affiche le gestionnaire d'activités
Comment[ga]=Taispeáin an bainisteoir gníomhaíochta
Comment[gl]=Mostra o xestor da actividade
Comment[he]=מציג את מנהל פעילויות
Comment[hr]=Prikazuje upravitelja aktivnosti
Comment[hu]=Aktivitáskezelő megjelenítése
Comment[ia]=Monstra le gerente de activitate
Comment[is]=Birtir virknistjóra
Comment[it]=Mostra il gestore delle attività
Comment[kk]=Белсенділік менеджері көрсетеді
Comment[km]=បង្ហាញ​កម្មវិធី​គ្រប់គ្រង​សកម្មភាព​
Comment[ko]=활동 관리자 보이기
Comment[lt]=Rodo veiklų tvarkyklę
Comment[lv]=Rāda aktivitāšu pārvaldnieku
Comment[mr]=कार्यपध्दती व्यवस्थापक दर्शवितो
Comment[nb]=Viser aktivitetshåndtereren
Comment[nds]=Wiest den Aktivitetenpleger
Comment[nl]=Toont de activiteitenbeheerder
Comment[pa]=ਸਰਗਰਮੀ ਮੈਨੇਜਰ ਵੇਖਾਉਂਦਾ ਹੈ
Comment[pl]=Pokazuje menadżera działań
Comment[pt]=Mostra o gestor de actividades
Comment[pt_BR]=Mostra o gerenciador de atividades
Comment[ro]=Arată Gestionarul de activități
Comment[ru]=Показывает диспетчер комнат
Comment[sk]=Ukáže správcu aktivít
Comment[sl]=Prikaže upravljalnika dejavnosti
Comment[sr]=Приказује менаџер активности
Comment[sr@ijekavian]=Приказује менаџер активности
Comment[sr@ijekavianlatin]=Prikazuje menadžer aktivnosti
Comment[sr@latin]=Prikazuje menadžer aktivnosti
Comment[sv]=Visar Aktivitetshanteraren
Comment[tr]=Etkinlik yöneticisini gösterir
Comment[ug]=پائالىيەت باشقۇرغۇچنى كۆرسىتىدۇ
Comment[uk]=Показує вікно керування просторами дій
Comment[wa]=Mostrer l' manaedjeu des activités
Comment[x-test]=xxShows the activity managerxx
Comment[zh_CN]=显示活动管理器
Comment[zh_TW]=顯示活動管理員
Icon=preferences-activities
Type=Service
X-Plasma-API=declarativeappletscript
X-Plasma-MainScript=ui/main.qml
X-Plasma-Requires-FileDialog=Unused
X-Plasma-Requires-LaunchApp=Unused
X-KDE-PluginInfo-Author=Gregor Tätzner
X-KDE-PluginInfo-Email=plasma-devel@kde.org
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=Windows and Tasks
X-KDE-PluginInfo-Name=org.kde.plasma.showActivityManager
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true
X-KDE-ServiceTypes=Plasma/Applet

View file

@ -0,0 +1,26 @@
plasma_install_package(package org.kde.plasma.taskmanager)
set(taskmanagerplugin_SRCS
plugin/backend.cpp
plugin/draghelper.cpp
plugin/taskmanagerplugin.cpp
plugin/textlabel.cpp
)
install(FILES plugin/qmldir DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/taskmanager)
add_library(taskmanagerplugin SHARED ${taskmanagerplugin_SRCS})
# FIXME TODO HACK: The last two are temp, see comment in Backend::activateItem().
target_link_libraries(taskmanagerplugin
PW::LibTaskManager
Qt5::Core
Qt5::Qml
Qt5::Quick
Qt5::Widgets
KF5::KIOCore
KF5::WindowSystem
Qt5::X11Extras
${X11_LIBRARIES})
install(TARGETS taskmanagerplugin DESTINATION ${QML_INSTALL_DIR}/org/kde/plasma/private/taskmanager)

View file

@ -0,0 +1,4 @@
#! /usr/bin/env bash
$EXTRACTRC `find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` >> rc.cpp
$XGETTEXT `find . -name \*.js -o -name \*.qml -o -name \*.cpp` -o $podir/plasma_applet_tasks.pot
rm -f rc.cpp

View file

@ -0,0 +1,172 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
function horizontalMargins() {
return taskFrame.margins.left + taskFrame.margins.right;
}
function verticalMargins() {
return taskFrame.margins.top + taskFrame.margins.bottom;
}
function launcherLayoutTasks() {
return Math.round(backend.tasksModel.launcherCount / Math.floor(preferredMinWidth() / launcherWidth()));
}
function launcherLayoutWidthDiff() {
return (launcherLayoutTasks() * taskWidth()) - (backend.tasksModel.launcherCount * launcherWidth());
}
function logicalTaskCount() {
var count = (backend.tasksModel.count - backend.tasksModel.launcherCount) + launcherLayoutTasks();
return Math.max(backend.tasksModel.count ? 1 : 0, count);
}
function maxStripes() {
var length = tasks.vertical ? taskList.width : taskList.height;
var minimum = tasks.vertical ? preferredMinWidth() : preferredMinHeight();
return Math.min(plasmoid.configuration.maxStripes, Math.max(1, Math.floor(length / minimum)));
}
function tasksPerStripe() {
if (plasmoid.configuration.forceStripes) {
return Math.ceil(logicalTaskCount() / maxStripes());
} else {
var length = tasks.vertical ? taskList.height : taskList.width;
var minimum = tasks.vertical ? preferredMinHeight() : preferredMinWidth();
return Math.floor(length / minimum);
}
}
function calculateStripes() {
var stripes = plasmoid.configuration.forceStripes ? plasmoid.configuration.maxStripes : Math.min(plasmoid.configuration.maxStripes, Math.ceil(logicalTaskCount() / tasksPerStripe()));
return Math.min(stripes, maxStripes());
}
function full() {
return (maxStripes() == calculateStripes());
}
function optimumCapacity(width, height) {
var length = tasks.vertical ? height : width - (backend.tasksModel.launcherCount * launcherWidth());
var maximum = tasks.vertical ? preferredMaxHeight() : preferredMaxWidth();
return (Math.ceil(length / maximum) * maxStripes()) + backend.tasksModel.launcherCount;
}
function layoutWidth() {
if (plasmoid.configuration.forceStripes && !tasks.vertical) {
return Math.min(tasks.width, Math.max(preferredMaxWidth(), tasksPerStripe() * preferredMaxWidth()));
} else {
return tasks.width;
}
}
function layoutHeight() {
if (plasmoid.configuration.forceStripes && tasks.vertical) {
return Math.min(tasks.height, Math.max(preferredMaxHeight(), tasksPerStripe() * preferredMaxHeight()));
} else {
return tasks.height;
}
}
function preferredMinWidth() {
if (tasks.vertical) {
return horizontalMargins() + units.iconSizes.small;
} else {
return horizontalMargins() + units.iconSizes.small + 3 + (theme.mSize(theme.defaultFont).width * 12);
}
}
function preferredMaxWidth() {
return Math.floor(preferredMinWidth() * 1.8);
}
function preferredMinHeight() {
// TODO FIXME UPSTREAM: Port to proper font metrics for descenders once we have access to them.
return theme.mSize(theme.defaultFont).height + 4;
}
function preferredMaxHeight() {
return verticalMargins() + Math.min(units.iconSizes.small * 3, theme.mSize(theme.defaultFont).height * 3);
}
function taskWidth() {
if (tasks.vertical) {
return Math.floor(taskList.width / calculateStripes());
} else {
if (full() && Math.max(1, logicalTaskCount()) > tasksPerStripe()) {
return Math.floor(taskList.width / Math.ceil(logicalTaskCount() / maxStripes()));
} else {
return Math.min(preferredMaxWidth(), Math.floor(taskList.width / Math.min(logicalTaskCount(), tasksPerStripe())));
}
}
}
function taskHeight() {
if (tasks.vertical) {
if (full() && Math.max(1, logicalTaskCount()) > tasksPerStripe()) {
return Math.floor(taskList.height / Math.ceil(logicalTaskCount() / maxStripes()));
} else {
return Math.min(preferredMaxHeight(), Math.floor(taskList.height / Math.min(logicalTaskCount(), tasksPerStripe())));
}
} else {
return Math.floor(taskList.height / calculateStripes());
}
}
function launcherWidth() {
return horizontalMargins() + units.iconSizes.small;
}
function layout(container) {
var item;
var stripes = calculateStripes();
var taskCount = backend.tasksModel.count - backend.tasksModel.launcherCount;
var width = taskWidth();
var adjustedWidth = width;
var height = taskHeight();
if (!tasks.vertical && stripes == 1 && taskCount)
{
width = Math.min(width + Math.floor(launcherLayoutWidthDiff() / taskCount), preferredMaxWidth());
}
for (var i = 0; i < container.count; ++i) {
item = container.itemAt(i);
item.visible = true;
adjustedWidth = width;
if (!tasks.vertical) {
if (item.isLauncher) {
adjustedWidth = launcherWidth();
} else if (stripes > 1 && i == backend.tasksModel.launcherCount) {
adjustedWidth += launcherLayoutWidthDiff();
}
}
item.width = adjustedWidth;
item.height = height;
}
}

View file

@ -0,0 +1,118 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
function activateNextPrevTask(parentItem, next) {
var taskIdList;
if (parentItem && parentItem.isGroupParent) {
taskIdList = backend.tasksModel.taskIdList(visualModel.modelIndex(parentItem.itemIndex));
} else {
taskIdList = backend.tasksModel.taskIdList();
}
if (!taskIdList.length) {
return;
}
var activeTaskId = backend.tasksModel.activeTaskId();
var target = taskIdList[0];
for (var i = 0; i < taskIdList.length; ++i) {
if (taskIdList[i] == activeTaskId)
{
if (next && i < (taskIdList.length - 1)) {
target = taskIdList[i + 1];
} else if (!next)
{
if (i) {
target = taskIdList[i - 1];
} else {
target = taskIdList[taskIdList.length - 1];
}
}
break;
}
}
activateItem(target, false);
}
function insertionIndexAt(sourceIndex, x, y) {
var above = target.childAt(x, y);
if (above) {
var index = above.itemIndex;
if (index > sourceIndex) {
++index;
}
return index;
} else {
var distance = tasks.vertical ? x : y;
var step = tasks.vertical ? Layout.taskWidth() : Layout.taskHeight();
var stripe = Math.ceil(distance / step);
if (stripe == Layout.calculateStripes()) {
return -1;
} else {
return stripe * Layout.tasksPerStripe();
}
}
}
function publishIconGeometries(taskItems) {
for (var i = 0; i < taskItems.length - 1; ++i) {
var task = taskItems[i];
if (task.isGroupParent) {
var taskIdList = backend.tasksModel.taskIdList(visualModel.modelIndex(task.itemIndex));
for (var j = 0; j < taskIdList.length; ++j) {
tasks.itemGeometryChanged(task, taskIdList[j].itemId);
}
} else if (!task.isLauncher) {
tasks.itemGeometryChanged(task, task.itemId);
}
}
}
function taskPrefix(prefix) {
var effectivePrefix;
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
effectivePrefix = "west-" + prefix;
break;
case PlasmaCore.Types.TopEdge:
effectivePrefix = "north-" + prefix;
break;
case PlasmaCore.Types.RightEdge:
effectivePrefix = "east-" + prefix;
break;
default:
effectivePrefix = "south-" + prefix;
}
if (!frame.hasElementPrefix(effectivePrefix)) {
return prefix;
}
return effectivePrefix;
}

View file

@ -0,0 +1,30 @@
/***************************************************************************
* Copyright (C) 2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import org.kde.plasma.configuration 2.0
ConfigModel {
ConfigCategory {
name: "General"
icon: "preferences-system-windows"
source: "ConfigGeneral.qml"
}
}

View file

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="showOnlyCurrentScreen" type="Bool">
<default>true</default>
</entry>
<entry name="showOnlyCurrentDesktop" type="Bool">
<default>false</default>
</entry>
<entry name="showOnlyCurrentActivity" type="Bool">
<default>true</default>
</entry>
<entry name="showOnlyMinimized" type="Int">
<default>false</default>
</entry>
<entry name="groupingStrategy" type="Enum">
<default>2</default>
</entry>
<entry name="onlyGroupWhenFull" type="Bool">
<default>true</default>
</entry>
<entry name="sortingStrategy" type="Int">
<default>2</default>
</entry>
<entry name="maxStripes" type="Int">
<default>2</default>
</entry>
<entry name="forceStripes" type="Bool">
<default>false</default>
</entry>
<entry name="showToolTips" type="Bool">
<default>true</default>
</entry>
<entry name="highlightWindows" type="Bool">
<default>false</default>
</entry>
<entry name="launchers" type="String">
<default></default>
</entry>
</group>
</kcfg>

View file

@ -0,0 +1,137 @@
/***************************************************************************
* Copyright (C) 2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import QtQuick.Controls 1.0 as QtControls
import QtQuick.Layouts 1.0 as QtLayouts
QtControls.GroupBox {
width: childrenRect.width
height: childrenRect.height
flat: true
title: i18n("General")
property alias cfg_forceStripes: forceStripes.checked
property alias cfg_showToolTips: showToolTips.checked
property alias cfg_highlightWindows: highlightWindows.checked
property alias cfg_maxStripes: maxStripes.value
property alias cfg_groupingStrategy: groupingStrategy.currentIndex
property alias cfg_onlyGroupWhenFull: onlyGroupWhenFull.checked
property alias cfg_sortingStrategy: sortingStrategy.currentIndex
property alias cfg_showOnlyCurrentScreen: showOnlyCurrentScreen.checked
property alias cfg_showOnlyCurrentDesktop: showOnlyCurrentDesktop.checked
property alias cfg_showOnlyCurrentActivity: showOnlyCurrentActivity.checked
property alias cfg_showOnlyMinimized: showOnlyMinimized.checked
QtLayouts.ColumnLayout {
QtControls.GroupBox {
title: i18n("Appearance")
flat: true
QtLayouts.ColumnLayout {
QtControls.CheckBox {
id: forceStripes
text: i18n("Force row settings")
}
QtControls.CheckBox {
id: showToolTips
text: i18n("Show tooltips")
}
QtControls.CheckBox {
id: highlightWindows
text: i18n("Highlight windows")
}
QtLayouts.RowLayout {
QtControls.Label {
text: i18n("Maximum rows:")
}
QtControls.SpinBox {
id: maxStripes
}
}
}
}
QtControls.GroupBox {
title: i18n("Grouping and Sorting")
flat: true
QtLayouts.ColumnLayout {
QtLayouts.RowLayout {
QtControls.Label {
text: i18n("Grouping:")
}
QtControls.ComboBox {
id: groupingStrategy
model: [i18n("Do Not Group"), i18n("Manually"), i18n("By Program Name")]
}
}
QtControls.CheckBox {
id: onlyGroupWhenFull
text: i18n("Only when the task manager is full")
}
QtLayouts.RowLayout {
QtControls.Label {
text: i18n("Sorting:")
}
QtControls.ComboBox {
id: sortingStrategy
model: [i18n("Do Not Sort"), i18n("Manually"), i18n("Alphabetically"), i18n("By Desktop"), i18n("By Activity")]
}
}
}
}
QtControls.GroupBox {
title: i18n("Filters")
flat: true
QtLayouts.ColumnLayout {
QtControls.CheckBox {
id: showOnlyCurrentScreen
text: i18n("Show only tasks from the current screen")
}
QtControls.CheckBox {
id: showOnlyCurrentDesktop
text: i18n("Show only tasks from the current desktop")
}
QtControls.CheckBox {
id: showOnlyCurrentActivity
text: i18n("Show only tasks from the current activity")
}
QtControls.CheckBox {
id: showOnlyMinimized
text: i18n("Show only tasks that are minimized")
}
}
}
}
}

View file

@ -0,0 +1,115 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.draganddrop 2.0
import "../code/layout.js" as LayoutManager
PlasmaCore.Dialog {
visible: false
type: PlasmaCore.Dialog.PopupMenu
flags: Qt.WindowStaysOnTopHint
hideOnWindowDeactivate: true
location: plasmoid.location
mainItem: Item {
MouseHandler {
anchors.fill: parent
id: mouseHandler
target: taskList
}
TaskList {
id: taskList
anchors.fill: parent
Repeater {
id: groupRepeater
onCountChanged: updateSize()
}
}
}
data: [
VisualDataModel {
id: groupFilter
delegate: Task {
visible: true
inPopup: true
}
}
]
onVisualParentChanged: {
if (!visualParent) {
visible = false;
}
}
onVisibleChanged: {
if (visible && visualParent) {
groupFilter.model = backend.tasksModel;
groupFilter.rootIndex = groupFilter.modelIndex(visualParent.itemIndex);
groupRepeater.model = groupFilter;
} else {
visualParent = null;
groupRepeater.model = undefined;
groupFilter.model = undefined;
groupFilter.rootIndex = undefined;
}
}
function updateSize() {
if (!visible || !visualParent) {
return;
}
if (!groupRepeater.count) {
visible = false;
} else {
var task;
var maxWidth = 0;
for (var i = 0; i < taskList.children.length - 1; ++i) {
task = taskList.children[i];
if (task.textWidth > maxWidth) {
maxWidth = task.textWidth;
}
task.textWidthChanged.connect(updateSize);
}
maxWidth += LayoutManager.horizontalMargins() + units.iconSizes.small + 6;
// TODO: Properly derive limits from work area size (screen size sans struts).
mainItem.width = Math.min(maxWidth, (tasks.vertical ? 640 - tasks.width : Math.max(tasks.width, 640)) - 20);
mainItem.height = groupRepeater.count * (LayoutManager.verticalMargins() + units.iconSizes.small);
}
}
}

View file

@ -0,0 +1,98 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
PlasmaCore.SvgItem {
id: arrow
anchors {
bottom: {
if (plasmoid.location != PlasmaCore.Types.TopEdge && plasmoid.location != PlasmaCore.Types.LeftEdge && plasmoid.location != PlasmaCore.Types.RightEdge) {
return parent.bottom;
} else {
return undefined;
}
}
horizontalCenter: {
if (plasmoid.location != PlasmaCore.Types.LeftEdge && plasmoid.location != PlasmaCore.Types.RightEdge) {
return iconBox.horizontalCenter;
} else {
return undefined;
}
}
verticalCenter: {
if (plasmoid.location == PlasmaCore.Types.LeftEdge || plasmoid.location == PlasmaCore.Types.RightEdge) {
return iconBox.verticalCenter;
} else {
return undefined;
}
}
top: {
if (plasmoid.location == PlasmaCore.Types.TopEdge) {
return parent.top;
} else {
return undefined;
}
}
left: {
if (plasmoid.location == PlasmaCore.Types.LeftEdge) {
return parent.left;
} else {
return undefined;
}
}
right: {
if (plasmoid.location == PlasmaCore.Types.RightEdge) {
return parent.right;
} else {
return undefined;
}
}
}
implicitWidth: Math.min(units.iconSizes.small, iconBox.width)
implicitHeight: implicitWidth
svg: arrows
elementId: elementForLocation()
function elementForLocation() {
switch (plasmoid.location) {
case PlasmaCore.Types.LeftEdge:
return "right-arrow";
case PlasmaCore.Types.TopEdge:
return "down-arrow";
case PlasmaCore.Types.RightEdge:
return "left-arrow";
case PlasmaCore.Types.BottomEdge:
default:
return "up-arrow";
}
}
Connections {
target: plasmoid.configuration
onLocationChanged: {
arrow.width = arrow.implicitWidth
arrow.height = arrow.implicitHeight
}
}
}

View file

@ -0,0 +1,92 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import org.kde.draganddrop 2.0
import org.kde.kquickcontrolsaddons 2.0
import "../code/layout.js" as LayoutManager
import "../code/tools.js" as TaskTools
Item {
property Item target
DropArea {
id: dropHandler
anchors.fill: parent
property Item hoveredItem
onDragMove: {
if (target.animating) {
return;
}
var above = target.childAt(event.x, event.y);
// HACK: plasmoid.configuration.sortingStrategy is an integer representation
// of the TaskManager::GroupManager::TaskSortingStrategy enum.
if (tasks.dragSource && plasmoid.configuration.sortingStrategy == 1) {
if (tasks.dragSource != above && !tasks.dragSource.isLauncher
&& !(above && "isLauncher" in above && above.isLauncher)) {
itemMove(tasks.dragSource.itemId,
TaskTools.insertionIndexAt(tasks.dragSource.itemIndex,
event.x, event.y));
}
} else if (!tasks.dragSource && above && hoveredItem != above) {
hoveredItem = above;
activationTimer.restart();
} else if (!above) {
hoveredItem = null;
activationTimer.stop();
}
}
onDragLeave: {
hoveredItem = null;
activationTimer.stop();
}
Timer {
id: activationTimer
interval: 250
repeat: false
onTriggered: {
if (parent.hoveredItem.isGroupParent) {
groupDialog.target = parent.hoveredItem;
groupDialog.visible = true;
} else if (!parent.hoveredItem.isLauncher) {
tasks.activateItem(parent.hoveredItem.itemId, false);
}
}
}
}
MouseEventListener {
id: wheelHandler
anchors.fill: parent
onWheelMoved: TaskTools.activateNextPrevTask(false, wheel.delta < 0)
}
}

View file

@ -0,0 +1,340 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.draganddrop 2.0
import org.kde.kquickcontrolsaddons 2.0
import org.kde.plasma.private.taskmanager 0.1 as TaskManager
import "../code/layout.js" as LayoutManager
import "../code/tools.js" as TaskTools
MouseEventListener {
id: task
width: groupDialog.mainItem.width
height: units.iconSizes.small + LayoutManager.verticalMargins()
visible: false
LayoutMirroring.enabled: (Qt.application.layoutDirection == Qt.RightToLeft)
LayoutMirroring.childrenInherit: (Qt.application.layoutDirection == Qt.RightToLeft)
property int itemIndex: index
property int itemId: model.Id
property bool inPopup: false
property bool isGroupParent: model.hasModelChildren
property bool isLauncher: model.IsLauncher
property bool isStartup: model.IsStartup
property bool demandsAttention: model.DemandsAttention
property int textWidth: label.implicitWidth
property bool pressed: false
property int pressX: -1
property int pressY: -1
property Item busyIndicator
acceptedButtons: Qt.LeftButton | Qt.RightButton
hoverEnabled: true
onItemIndexChanged: {
if (!inPopup && !tasks.vertical && LayoutManager.calculateStripes() > 1) {
var newWidth = LayoutManager.taskWidth();
if (index == backend.tasksModel.launcherCount) {
newWidth += LayoutManager.launcherLayoutWidthDiff();
}
width = newWidth;
}
}
onIsStartupChanged: {
if (!isStartup) {
tasks.itemGeometryChanged(itemId, x, y, width, height);
}
}
onDemandsAttentionChanged: {
tasks.updateStatus(demandsAttention);
}
onContainsMouseChanged: {
if (!containsMouse) {
pressed = false;
}
tasks.itemHovered(model.Id, containsMouse);
}
onPressed: {
if (mouse.buttons & Qt.LeftButton) {
pressed = true;
pressX = mouse.x;
pressY = mouse.y;
} else if (mouse.buttons & Qt.RightButton) {
if (plasmoid.configuration.showToolTips) {
toolTip.hideToolTip();
}
tasks.itemContextMenu(task, plasmoid.action("configure"));
}
}
onReleased: {
if (pressed) {
if (!mouse.button == Qt.LeftButton) {
return;
}
if (isGroupParent) {
if (groupDialog.visible) {
groupDialog.visible = false;
} else {
groupDialog.visualParent = task;
groupDialog.visible = true;
}
} else {
tasks.activateItem(model.Id, true);
}
}
pressed = false;
pressX = -1;
pressY = -1;
}
onPositionChanged: {
if (pressX != -1 && dragHelper.isDrag(pressX, pressY, mouse.x, mouse.y)) {
tasks.dragSource = task;
dragHelper.startDrag(task, model.MimeType, model.MimeData,
model.LauncherUrl, model.DecorationRole);
pressX = -1;
pressY = -1;
return;
}
}
onWheelMoved: TaskTools.activateNextPrevTask(task, wheel.delta < 0)
PlasmaCore.FrameSvgItem {
id: frame
anchors.fill: parent
imagePath: "widgets/tasks"
prefix: TaskTools.taskPrefix("normal")
PlasmaCore.ToolTipArea {
id: toolTip
anchors.fill: parent
property variant windows: model.WindowList
active: !inPopup && plasmoid.configuration.showToolTips
interactive: true
location: plasmoid.location
mainItem: toolTipDelegate
//FIXME TODO: highlightWindows: plasmoid.configuration.highlightWindows
onContainsMouseChanged: {
if (containsMouse) {
toolTip.windows = model.WindowList;
toolTip.mainText = model.DisplayRole;
toolTip.icon = model.DecorationRole;
toolTip.subText = model.IsLauncher ? model.GenericName
: toolTip.generateSubText(model);
}
}
function generateSubText(task) {
var subTextEntries = new Array();
if (!plasmoid.configuration.showOnlyCurrentDesktop) {
subTextEntries.push(i18n("On %1", task.DesktopName));
}
if (task.OnAllActivities) {
subTextEntries.push(i18nc("Which virtual desktop a window is currently on",
"Available on all activities"));
} else if (plasmoid.configuration.showOnlyCurrentActivity) {
if (task.OtherActivityNames.length > 0) {
subTextEntries.push(i18nc("Activities a window is currently on (apart from the current one)",
"Also available on %1",
task.OtherActivityNames.join(", ")));
}
} else if (task.ActivityNames.length > 0) {
subTextEntries.push(i18nc("Which activities a window is currently on",
"Available on %1",
task.ActivityNames.join(", ")));
}
return subTextEntries.join("<br />");
}
}
}
Item {
id: iconBox
anchors {
left: parent.left
leftMargin: taskFrame.margins.left
verticalCenter: parent.verticalCenter
}
width: inPopup ? units.iconSizes.small : Math.min(height, parent.width - LayoutManager.horizontalMargins())
height: Math.min(units.iconSizes.huge,
parent.height - (parent.height - LayoutManager.verticalMargins() < units.iconSizes.small ?
Math.min(9, LayoutManager.verticalMargins()) : LayoutManager.verticalMargins()))
PlasmaCore.IconItem {
id: icon
anchors.fill: parent
visible: !model.IsStartup
active: task.containsMouse
enabled: !(model.Minimized && !plasmoid.configuration.showOnlyMinimized)
source: model.DecorationRole
onVisibleChanged: {
if (visible && busyIndicator) {
busyIndicator.destroy();
}
}
}
states: [
// Using a state transition avoids a binding loop between label.visible and
// the text label margin, which derives from the icon width.
State {
name: "standalone"
when: !label.visible
AnchorChanges {
target: iconBox
anchors.left: undefined
anchors.horizontalCenter: parent.horizontalCenter
}
PropertyChanges {
target: iconBox
anchors.leftMargin: 0
}
}
]
}
TaskManager.TextLabel {
id: label
anchors {
left: parent.left
right: parent.right
leftMargin: taskFrame.margins.left + icon.width + 4
rightMargin: taskFrame.margins.right
verticalCenter: parent.verticalCenter
}
height: Math.max(theme.mSize(theme.defaultFont).height, parent.height - taskFrame.margins.top - taskFrame.margins.bottom)
visible: !model.IsLauncher && (parent.width - anchors.leftMargin - anchors.rightMargin) >= (theme.mSize(theme.defaultFont).width * 3)
enabled: !model.Minimized
text: model.DisplayRole
color: theme.textColor
elide: !inPopup
}
states: [
State {
name: "launcher"
when: model.IsLauncher
PropertyChanges {
target: frame
prefix: ""
}
},
State {
name: "hovered"
when: containsMouse
PropertyChanges {
target: frame
prefix: TaskTools.taskPrefix("hover");
}
},
State {
name: "attention"
when: model.DemandsAttention
PropertyChanges {
target: frame
prefix: TaskTools.taskPrefix("attention");
}
},
State {
name: "minimized"
when: model.Minimized && !(groupDialog.visible && groupDialog.target == task)
PropertyChanges {
target: frame
prefix: TaskTools.taskPrefix("minimized");
}
},
State {
name: "active"
when: model.Active || groupDialog.visible && groupDialog.target == task
PropertyChanges {
target: frame
prefix: TaskTools.taskPrefix("focus");
}
}
]
Component.onCompleted: {
if (model.IsStartup) {
busyIndicator = Qt.createQmlObject('import org.kde.plasma.components 2.0 as PlasmaComponents; ' +
'PlasmaComponents.BusyIndicator { anchors.fill: parent; running: true }', iconBox);
}
if (model.hasModelChildren) {
var component = Qt.createComponent("GroupExpanderOverlay.qml");
component.createObject(task);
}
}
/*
Component.onDestruction: {
if (groupDialog.visible && groupDialog.groupItemId == model.Id) {
groupDialog.visible = false;
}
}
*/
}

View file

@ -0,0 +1,42 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
Flow {
property bool animating: false
layoutDirection: Qt.application.layoutDirection
property int rows: Math.floor(height / children[0].height)
property int columns: Math.floor(width / children[0].width)
move: Transition {
SequentialAnimation {
PropertyAction { target: taskList; property: "animating"; value: true }
NumberAnimation {
properties: "x, y"
easing.type: Easing.OutQuad
}
PropertyAction { target: taskList; property: "animating"; value: false }
}
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright 2013 by Sebastian Kügler <sebas@kde.org>
* Copyright 2014 by Martin Gräßlin <mgraesslin@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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 Library General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 2.010-1301, USA.
*/
import QtQuick 2.0
import QtQuick.Layouts 1.1
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.components 2.0 as PlasmaComponents
import org.kde.plasma.extras 2.0 as PlasmaExtras
import org.kde.kquickcontrolsaddons 2.0 as KQuickControlsAddons
Column {
id: tooltipContentItem
property Item toolTip
property int preferredTextWidth: theme.mSize(theme.defaultFont).width * 40
property int _s: units.largeSpacing / 2
Layout.minimumWidth: childrenRect.width + _s
Layout.minimumHeight: childrenRect.height + units.largeSpacing
Layout.maximumWidth: childrenRect.width + _s
Layout.maximumHeight: childrenRect.height + units.largeSpacing
width: childrenRect.width + _s
height: childrenRect.height + units.largeSpacing
spacing: units.largeSpacing
Row {
anchors.horizontalCenter: parent.horizontalCenter
width: childrenRect.width
height: childrenRect.height
spacing: units.largeSpacing
Repeater {
model: toolTip.windows
PlasmaCore.WindowThumbnail {
// hardcoded values from old implementation
width: 200
height: 150
winId: modelData
}
}
}
Row {
width: childrenRect.width + _s
height: childrenRect.height + units.largeSpacing
spacing: units.largeSpacing
Item {
id: imageContainer
visible: toolTip != null && toolTip.icon != null
width: tooltipIcon.width
height: tooltipIcon.height
x: _s
y: _s
PlasmaCore.IconItem {
id: tooltipIcon
x: _s
width: toolTip != undefined && toolTip.icon != null ? units.iconSizes.desktop : 0
height: width
source: toolTip != undefined && toolTip.icon != null ? toolTip.icon : ""
}
}
Column {
id: mainColumn
x: _s
y: _s
//This instance is purely for metrics
PlasmaExtras.Heading {
id: tooltipMaintextPlaceholder
visible: false
level: 3
text: toolTip ? toolTip.mainText : ""
}
PlasmaExtras.Heading {
id: tooltipMaintext
level: 3
width: Math.min(tooltipMaintextPlaceholder.width, preferredTextWidth)
//width: 400
elide: Text.ElideRight
text: toolTip ? toolTip.mainText : ""
}
PlasmaComponents.Label {
id: tooltipSubtext
width: tooltipContentItem.preferredTextWidth
wrapMode: Text.WordWrap
text: toolTip ? toolTip.subText : ""
opacity: 0.5
}
}
}
}

View file

@ -0,0 +1,236 @@
/***************************************************************************
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
import QtQuick 2.0
import QtQuick.Layouts 1.1
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.private.taskmanager 0.1 as TaskManager
import "../code/layout.js" as LayoutManager
import "../code/tools.js" as TaskTools
Item {
id: tasks
anchors.fill: parent
property bool vertical: (plasmoid.formFactor == PlasmaCore.Types.Vertical)
Plasmoid.preferredRepresentation: Plasmoid.fullRepresentation
Layout.fillWidth: true
Layout.fillHeight:true
Layout.minimumWidth: tasks.vertical ? 0 : LayoutManager.preferredMinWidth()
Layout.minimumHeight: !tasks.vertical ? 0 : LayoutManager.preferredMinHeight()
//BEGIN TODO: this is not precise enough: launchers are smaller than full tasks
Layout.preferredWidth: tasks.vertical ? units.gridUnit * 10 : Math.min(taskList.columns, taskList.children.length) * units.gridUnit * 10;
Layout.preferredHeight: tasks.vertical ? Math.min(taskList.rows, taskList.children.length) * units.gridUnit * 2 : units.gridUnit * 2;
//END TODO
property Item dragSource: null
signal activateItem(int id, bool toggle)
signal itemContextMenu(Item item, QtObject configAction)
signal itemHovered(int id, bool hovered)
signal itemMove(int id, int newIndex)
signal itemGeometryChanged(Item item, int id)
onWidthChanged: {
taskList.width = LayoutManager.layoutWidth();
if (plasmoid.configuration.forceStripes) {
taskList.height = LayoutManager.layoutHeight();
}
}
onHeightChanged: {
if (plasmoid.configuration.forceStripes) {
taskList.width = LayoutManager.layoutWidth();
}
taskList.height = LayoutManager.layoutHeight();
}
TaskManager.Backend {
id: backend
taskManagerItem: tasks
highlightWindows: plasmoid.configuration.highlightWindows
groupingStrategy: plasmoid.configuration.groupingStrategy
sortingStrategy: plasmoid.configuration.sortingStrategy
onLaunchersChanged: plasmoid.configuration.launchers = launchers
Component.onCompleted: {
launchers = plasmoid.configuration.launchers;
}
}
Connections {
target: plasmoid.configuration
onLaunchersChanged: backend.launchers = plasmoid.configuration.launchers
}
Binding {
target: backend.groupManager
property: "screen"
value: plasmoid.screen
}
Binding {
target: backend.groupManager
property: "onlyGroupWhenFull"
value: plasmoid.configuration.onlyGroupWhenFull
}
Binding {
target: backend.groupManager
property: "fullLimit"
value: LayoutManager.optimumCapacity(width, height) + 1
}
Binding {
target: backend.groupManager
property: "showOnlyCurrentScreen"
value: plasmoid.configuration.showOnlyCurrentScreen
}
Binding {
target: backend.groupManager
property: "showOnlyCurrentDesktop"
value: plasmoid.configuration.showOnlyCurrentDesktop
}
Binding {
target: backend.groupManager
property: "showOnlyCurrentActivity"
value: plasmoid.configuration.showOnlyCurrentActivity
}
Binding {
target: backend.groupManager
property: "showOnlyMinimized"
value: plasmoid.configuration.showOnlyMinimized
}
TaskManager.DragHelper { id: dragHelper }
PlasmaCore.FrameSvgItem {
id: taskFrame
visible: false;
imagePath: "widgets/tasks";
prefix: "normal"
}
PlasmaCore.Svg {
id: arrows
imagePath: "widgets/arrows"
size: "16x16"
}
MouseHandler {
id: mouseHandler
anchors.fill: parent
target: taskList
}
VisualDataModel {
id: visualModel
model: backend.tasksModel
delegate: Task {}
}
ToolTipDelegate {
id: toolTipDelegate
}
TaskList {
id: taskList
anchors {
left: parent.left
top: parent.top
}
onWidthChanged: LayoutManager.layout(taskRepeater)
onHeightChanged: LayoutManager.layout(taskRepeater)
flow: tasks.vertical ? Flow.TopToBottom : Flow.LeftToRight
onAnimatingChanged: {
if (!animating) {
TaskTools.publishIconGeometries(children);
}
}
Repeater {
id: taskRepeater
model: visualModel
onCountChanged: {
taskList.width = LayoutManager.layoutWidth();
taskList.height = LayoutManager.layoutHeight();
LayoutManager.layout(taskRepeater);
}
function modelWasReset() {
LayoutManager.layout(taskRepeater);
}
Component.onCompleted: {
backend.tasksModel.modelReset.connect(modelWasReset);
}
}
}
GroupDialog { id: groupDialog }
function updateStatus(demandsAttention) {
if (demandsAttention) {
plasmoid.status = PlasmaCore.Types.NeedsAttentionStatus;
} else if (!backend.anyTaskNeedsAttention) {
plasmoid.status = PlasmaCore.Types.PassiveStatus;
}
}
function resetDragSource() {
dragSource = null;
}
Component.onCompleted: {
tasks.activateItem.connect(backend.activateItem);
tasks.itemContextMenu.connect(backend.itemContextMenu);
tasks.itemHovered.connect(backend.itemHovered);
tasks.itemMove.connect(backend.itemMove);
tasks.itemGeometryChanged.connect(backend.itemGeometryChanged);
dragHelper.dropped.connect(resetDragSource);
}
}

View file

@ -0,0 +1,172 @@
[Desktop Entry]
Name=Task Manager
Name[af]=Taakbestuurder
Name[ar]=مدير المهام
Name[ast]=Xestor de xeres
Name[be]=Кіраванне заданнямі
Name[be@latin]=Kiraŭnik zadańniaŭ
Name[bg]=Управление на задачи
Name[bn]=টাস্ক ম্যানেজার
Name[bs]=menadžer zadataka
Name[ca]=Gestor de tasques
Name[ca@valencia]=Gestor de tasques
Name[cs]=Správce úloh
Name[csb]=Menedżer dzejaniów
Name[da]=Opgavelinje
Name[de]=Fensterleiste
Name[el]=Διαχειριστής εργασιών
Name[en_GB]=Task Manager
Name[eo]=Taskadministrilo
Name[es]=Gestor de tareas
Name[et]=Tegumihaldur
Name[eu]=Ataza-kudeatzailea
Name[fi]=Tehtävienhallinta
Name[fr]=Gestionnaire de tâches
Name[fy]=Taakbehearder
Name[ga]=Bainisteoir na dTascanna
Name[gl]=Xestor de tarefas
Name[gu]=ટાસ્ક વ્યવસ્થાપક
Name[he]=מנהל משימות
Name[hi]=कार्य प्रबंधक
Name[hne]=काम प्रबंधक
Name[hr]=Upravljanje zadacima
Name[hsb]=Rjadowar nadawkow
Name[hu]=Feladatkezelő
Name[ia]=Gerente de carga
Name[id]=Manajer Tugas
Name[is]=Verkefnastjóri
Name[it]=Gestore dei processi
Name[ja]=タスクマネージャ
Name[kk]=Тапсырмалар менеджері
Name[km]=កម្មវិធី​គ្រប់គ្រង​ភារកិច្ច
Name[kn]=ಕಾರ್ಯ ವ್ಯವಸ್ಥಾಪಕ (ಟಾಸ್ಕ್ ಮ್ಯಾನೇಜರ್)
Name[ko]=작업 관리자
Name[lt]=Užduočių tvarkyklė
Name[lv]=Uzdevumu pārvaldnieks
Name[mk]=Менаџер на апликации
Name[ml]=ടാസ്ക് മാനേജര്‍
Name[mr]=कार्य व्यवस्थापक
Name[nb]=Oppgavebehandler
Name[nds]=Opgavenpleger
Name[ne]=कार्य प्रबन्धक
Name[nl]=Takenbeheer
Name[nn]=Oppgåvehandsamar
Name[or]=କାର୍ଯ୍ୟ ପରିଚାଳକ
Name[pa]=ਟਾਸਕ ਮੈਨੇਜਰ
Name[pl]=Zarządzanie zadaniami
Name[pt]=Gestor de Tarefas
Name[pt_BR]=Gerenciador de tarefas
Name[ro]=Gestionar de sarcini
Name[ru]=Панель задач
Name[se]=Bargogieđahalli
Name[si]=කාර්‍යය කළමණාකරු
Name[sk]=Správca úloh
Name[sl]=Upravljalnik opravil
Name[sr]=менаџер задатака
Name[sr@ijekavian]=менаџер задатака
Name[sr@ijekavianlatin]=menadžer zadataka
Name[sr@latin]=menadžer zadataka
Name[sv]=Aktivitetshanterare
Name[ta]=பணி மேலாளர்
Name[te]=కర్తవ్య నిర్వాహకి
Name[tg]=Мудири вазифаҳо
Name[th]=จัดการงาน
Name[tr]=Görev Yöneticisi
Name[ug]=ۋەزىپە باشقۇرغۇچ
Name[uk]=Менеджер задач
Name[uz]=Vazifa boshqaruvchisi
Name[uz@cyrillic]=Вазифа бошқарувчиси
Name[wa]=Manaedjeu des bouyes
Name[x-test]=xxTask Managerxx
Name[zh_CN]=任务管理器
Name[zh_TW]=工作管理員
Comment=Switch between running applications
Comment[ar]=بدّل بين التطبيقات التي تعمل
Comment[ast]=Camudar ente aplicaciones n'execución
Comment[be@latin]=Pieraklučeńnie dziejnych aplikacyjaŭ
Comment[bg]=Превключване между стартирани програми
Comment[bs]=Prebacujte između programa u radu
Comment[ca]=Commuta entre aplicacions en execució
Comment[ca@valencia]=Commuta entre aplicacions en execució
Comment[cs]=Přepínač mezi běžícími aplikacemi
Comment[da]=Skift mellem kørende programmer
Comment[de]=Ermöglicht den wechselnden Zugriff auf laufende Programme.
Comment[el]=Εναλλαγή μεταξύ εκτελούμενων εφαρμογών
Comment[en_GB]=Switch between running applications
Comment[eo]=Komuti inter funkciantaj aplikaĵoj
Comment[es]=Cambiar entre aplicaciones en ejecución
Comment[et]=Lülitumine töötavate rakenduste vahel
Comment[eu]=Aldatu abian dauden aplikazio batetik bestera
Comment[fi]=Vaihda avoinna olevien ohjelmien välillä
Comment[fr]=Passe d'une application à l'autre
Comment[fy]=Wikselje tusken rinnende programma's
Comment[ga]=Athraigh idir feidhmchláir atá ag rith
Comment[gl]=Troca entre programas en execución
Comment[gu]=ચાલતાં કાર્યક્રમો વચ્ચે ફેરબદલી કરો
Comment[he]=מעבר בין יישומים פעילים
Comment[hi]=चल रहे अनुप्रयोगों के बीच स्विच करें
Comment[hne]=चलत अनुपरयोग मं स्विच करव
Comment[hr]=Promjena među pokrenutim aplikacijama
Comment[hsb]=Šaltuje mjez běžacymi aplikacijemi
Comment[hu]=A futó alkalmazások között lehet vele váltani
Comment[ia]=Commuta inter applicationes que on exeque
Comment[id]=Berpindah di antara aplikasi yang berjalan
Comment[is]=Skipta á milli forrita sem eru í gangi
Comment[it]=Passa ad altre applicazioni in esecuzione
Comment[ja]=実行中のアプリケーションを切り替えます
Comment[kk]=Жегілген қолданбаларды ақтару
Comment[km]=ប្ដូរ​រវាង​កម្មវិធី​ដែល​កំពុង​រត់
Comment[kn]=ಚಾಲ್ತಿಯಲ್ಲಿರುವ ಅನ್ವಯಗಳ ನಡುವೆ ಅಂತರಿಸು
Comment[ko]=실행 중인 프로그램을 전환합니다
Comment[lt]=Perjungimas tarp veikiančių programų
Comment[lv]=Pārslēdzas starp palaistajām programmām
Comment[mk]=Движете се низ активните апликации
Comment[ml]=പ്രവര്‍ത്തിക്കുന്ന പ്രവര്‍ത്തങ്ങള്‍ തമ്മില്‍ മാറുക
Comment[mr]=कार्यरत अनुप्रयोग अंतर्गत बदल करा
Comment[nb]=Bytt mellom kjørende programmer
Comment[nds]=Twischen lopen Programmen wesseln
Comment[nl]=Schakel tussen draaiende programma's
Comment[nn]=Byt mellom program som køyrer
Comment[or]=ଚାଲୁଥିବା ପ୍ରୟୋଗଗୁଡ଼ିକ ମଧ୍ଯରେ ଅଦଳ ବଦଳ କରନ୍ତୁ
Comment[pa]=ਚੱਲਦੀਆਂ ਐਪਲੀਕੇਸ਼ਨਾਂ ਬਦਲੋ
Comment[pl]=Przełączanie między działającymi programami
Comment[pt]=Mudar de aplicações em execução
Comment[pt_BR]=Alterna entre os aplicativos em execução
Comment[ro]=Comută printre aplicațiile ce rulează
Comment[ru]=Переключение между запущенными приложениями
Comment[si]=ක්‍රියාත්මක වන යෙදුම් අතරේ මාරුවන්න
Comment[sk]=Prepínanie medzi bežiacimi aplikáciami
Comment[sl]=Preklapljajte med zagnanimi programi
Comment[sr]=Пребацујте између програма у раду
Comment[sr@ijekavian]=Пребацујте између програма у раду
Comment[sr@ijekavianlatin]=Prebacujte između programa u radu
Comment[sr@latin]=Prebacujte između programa u radu
Comment[sv]=Byt mellan program som kör
Comment[ta]=Switch between running applications
Comment[te]=నడుస్తున్న అనువర్తనముల మద్యన మారుము
Comment[tg]=Переключение между рабочими столами
Comment[th]=สลับการทำงานระหว่างโปรแกรมต่าง ๆ
Comment[tr]=Çalışan uygulamalar arasında gezin
Comment[ug]=ئىجرا بولۇۋاتقان پروگراممىلارنى ئالماشتۇر
Comment[uk]=Перемкніть запущені програми
Comment[wa]=Passer d' on programe ovrant a èn ôte
Comment[x-test]=xxSwitch between running applicationsxx
Comment[zh_CN]=在已运行的程序间切换
Comment[zh_TW]=在執行中的應用程式間切換
Type=Service
Icon=preferences-system-windows
X-KDE-ServiceTypes=Plasma/Applet
X-Plasma-API=declarativeappletscript
X-Plasma-MainScript=ui/main.qml
X-KDE-PluginInfo-Author=Eike Hein
X-KDE-PluginInfo-Email=hein@kde.org
X-KDE-PluginInfo-Name=org.kde.plasma.taskmanager
X-KDE-PluginInfo-Version=3.0
X-KDE-PluginInfo-Website=http://userbase.kde.org/Plasma/Tasks
X-KDE-PluginInfo-Category=Windows and Tasks
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL v2+
X-KDE-PluginInfo-EnabledByDefault=true

View file

@ -0,0 +1,272 @@
/***************************************************************************
* Copyright (C) 2007 by Robert Knight <robertknight@gmail.com> *
* Copyright (C) 2008 by Alexis Ménard <darktears31@gmail.com> *
* Copyright (C) 2012-2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#include "backend.h"
#include <groupmanager.h>
#include <taskactions.h>
#include <taskgroup.h>
#include <tasksmodel.h>
#include <QCursor>
#include <QQuickItem>
#include <QQuickWindow>
#include <QScreen>
//FIXME TODO HACK See comment in Backend::activateItem().
#include <QX11Info>
#include <X11/Xlib.h>
#include <KAuthorized>
#include <kwindoweffects.h>
Backend::Backend(QObject* parent) : QObject(parent),
m_groupManager(new TaskManager::GroupManager(this)),
m_tasksModel(new TaskManager::TasksModel(m_groupManager, this)),
m_lastWindowId(0),
m_highlightWindows(false)
{
connect(m_groupManager, SIGNAL(launcherListChanged()), this, SLOT(updateLaunchersCache()));
}
Backend::~Backend()
{
}
TaskManager::GroupManager* Backend::groupManager() const
{
return m_groupManager;
}
TaskManager::TasksModel* Backend::tasksModel() const
{
return m_tasksModel;
}
QQuickItem* Backend::taskManagerItem() const
{
return m_taskManagerItem;
}
void Backend::setTaskManagerItem(QQuickItem* item)
{
if (item != m_taskManagerItem) {
m_taskManagerItem = item;
emit taskManagerItemChanged(item);
}
}
bool Backend::anyTaskNeedsAttention() const
{
return groupManager()->rootGroup()->demandsAttention();
}
bool Backend::highlightWindows() const
{
return m_highlightWindows;
}
void Backend::setHighlightWindows(bool highlight)
{
if (highlight != m_highlightWindows) {
m_highlightWindows = highlight;
emit highlightWindowsChanged(highlight);
}
}
int Backend::groupingStrategy() const
{
return m_groupManager->groupingStrategy();
}
void Backend::setGroupingStrategy(int groupingStrategy)
{
// FIXME TODO: This is fucking terrible.
m_groupManager->setGroupingStrategy(static_cast<TaskManager::GroupManager::TaskGroupingStrategy>(groupingStrategy));
}
int Backend::sortingStrategy() const
{
return m_groupManager->sortingStrategy();
}
void Backend::setSortingStrategy(int sortingStrategy)
{
// FIXME TODO: This is fucking terrible.
m_groupManager->setSortingStrategy(static_cast<TaskManager::GroupManager::TaskSortingStrategy>(sortingStrategy));
}
void Backend::updateLaunchersCache()
{
const QList<QUrl> launcherList = m_groupManager->launcherList();
QStringList launchers;
foreach(const QUrl& launcher, launcherList) {
launchers.append(launcher.toString());
}
QString joined(launchers.join(','));
if (joined != m_launchers) {
m_launchers = joined;
emit launchersChanged();
}
}
QString Backend::launchers() const
{
return m_launchers;
}
void Backend::setLaunchers(const QString& launchers)
{
if (launchers == m_launchers) {
return;
}
m_launchers = launchers;
QList<QUrl> launcherList;
foreach(const QString& launcher, launchers.split(',')) {
launcherList.append(launcher);
}
disconnect(m_groupManager, SIGNAL(launcherListChanged()), this, SLOT(updateLaunchersCache()));
m_groupManager->setLauncherList(launcherList);
connect(m_groupManager, SIGNAL(launcherListChanged()), this, SLOT(updateLaunchersCache()));
emit launchersChanged();
}
void Backend::activateItem(int id, bool toggle)
{
TaskManager::AbstractGroupableItem* item = m_groupManager->rootGroup()->getMemberById(id);
if (!item) {
return;
}
if (item->itemType() == TaskManager::TaskItemType && !item->isStartupItem()) {
TaskManager::TaskItem* taskItem = static_cast<TaskManager::TaskItem*>(item);
if (toggle) {
taskItem->task()->activateRaiseOrIconify();
} else {
taskItem->task()->activate();
}
//FIXME TODO HACK This papers over XSendEvent() calls lacking an explicit flush in
//KWindowSystem; not addressed there due to pending xcb port.
XFlush(QX11Info::display());
} else if (item->itemType() == TaskManager::LauncherItemType) {
static_cast<TaskManager::LauncherItem*>(item)->launch();
}
}
void Backend::itemContextMenu(QQuickItem *item, QObject *configAction)
{
TaskManager::AbstractGroupableItem* agItem = m_groupManager->rootGroup()->getMemberById(item->property("itemId").toInt());
if (!KAuthorized::authorizeKAction("kwin_rmb") || !item || !item->window() || !agItem) {
return;
}
QList <QAction*> actionList;
QAction *action = static_cast<QAction *>(configAction);
if (action && action->isEnabled()) {
actionList << action;
}
TaskManager::BasicMenu* menu = 0;
if (agItem->itemType() == TaskManager::TaskItemType && !agItem->isStartupItem()) {
TaskManager::TaskItem* taskItem = static_cast<TaskManager::TaskItem*>(agItem);
menu = new TaskManager::BasicMenu(0, taskItem, m_groupManager, actionList);
} else if (agItem->itemType() == TaskManager::GroupItemType) {
TaskManager::TaskGroup* taskGroup = static_cast<TaskManager::TaskGroup*>(agItem);
const int maxWidth = 0.8 * item->window()->screen()->size().width();
menu = new TaskManager::BasicMenu(0, taskGroup, m_groupManager, actionList, QList <QAction*>(), maxWidth);
} else if (agItem->itemType() == TaskManager::LauncherItemType) {
menu = new TaskManager::BasicMenu(0, static_cast<TaskManager::LauncherItem*>(agItem),
m_groupManager, actionList);
}
if (!menu) {
return;
}
menu->adjustSize();
if (!taskManagerItem()->property("vertical").toBool()) {
menu->setMinimumWidth(item->width());
}
menu->exec(QCursor::pos());
menu->deleteLater();
}
void Backend::itemHovered(int id, bool hovered)
{
TaskManager::AbstractGroupableItem* item = m_groupManager->rootGroup()->getMemberById(id);
if (!item) {
return;
}
if (hovered && m_highlightWindows && m_taskManagerItem->window()) {
m_lastWindowId = m_taskManagerItem->window()->winId();
KWindowEffects::highlightWindows(m_lastWindowId, QList<WId>::fromSet(item->winIds()));
} else if (m_highlightWindows && m_lastWindowId) {
KWindowEffects::highlightWindows(m_lastWindowId, QList<WId>());
}
}
void Backend::itemMove(int id, int newIndex)
{
m_groupManager->manualSortingRequest(m_groupManager->rootGroup()->getMemberById(id), newIndex);
}
void Backend::itemGeometryChanged(QQuickItem *item, int id)
{
TaskManager:: AbstractGroupableItem *agItem = m_groupManager->rootGroup()->getMemberById(id);
if (!item || !item->window() || !agItem || agItem->itemType() != TaskManager::TaskItemType)
{
return;
}
TaskManager::TaskItem *taskItem = static_cast<TaskManager::TaskItem *>(agItem);
if (!taskItem->task()) {
return;
}
QRect iconRect(item->x(), item->y(), item->width(), item->height());
iconRect.moveTopLeft(item->parentItem()->mapToScene(iconRect.topLeft()).toPoint());
iconRect.moveTopLeft(item->window()->mapToGlobal(iconRect.topLeft()));
taskItem->task()->publishIconGeometry(iconRect);
}

View file

@ -0,0 +1,91 @@
/***************************************************************************
* Copyright (C) 2013 by Eike Hein <hein@kde.org> *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . *
***************************************************************************/
#ifndef BACKEND_H
#define BACKEND_H
#include <QObject>
#include <groupmanager.h>
#include <tasksmodel.h>
class QQuickItem;
class Backend : public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* groupManager READ groupManager CONSTANT)
Q_PROPERTY(QObject* tasksModel READ tasksModel CONSTANT)
Q_PROPERTY(QQuickItem* taskManagerItem READ taskManagerItem WRITE setTaskManagerItem NOTIFY taskManagerItemChanged)
Q_PROPERTY(bool anyTaskNeedsAttention READ anyTaskNeedsAttention)
Q_PROPERTY(bool highlightWindows READ highlightWindows WRITE setHighlightWindows NOTIFY highlightWindowsChanged)
Q_PROPERTY(int groupingStrategy READ groupingStrategy WRITE setGroupingStrategy)
Q_PROPERTY(int sortingStrategy READ sortingStrategy WRITE setSortingStrategy)
Q_PROPERTY(QString launchers READ launchers WRITE setLaunchers NOTIFY launchersChanged)
public:
Backend(QObject *parent = 0);
~Backend();
TaskManager::GroupManager *groupManager() const;
TaskManager::TasksModel *tasksModel() const;
QQuickItem* taskManagerItem() const;
void setTaskManagerItem(QQuickItem *item);
bool anyTaskNeedsAttention() const;
bool highlightWindows() const;
void setHighlightWindows(bool highlight);
int groupingStrategy() const;
void setGroupingStrategy(int groupingStrategy);
int sortingStrategy() const;
void setSortingStrategy(int sortingStrategy);
QString launchers() const;
void setLaunchers(const QString& launchers);
public Q_SLOTS:
void activateItem(int id, bool toggle);
void itemContextMenu(QQuickItem *item, QObject *configAction);
void itemHovered(int id, bool hovered);
void itemMove(int id, int newIndex);
void itemGeometryChanged(QQuickItem *item, int id);
private Q_SLOTS:
void updateLaunchersCache();
Q_SIGNALS:
void taskManagerItemChanged(QQuickItem*);
void highlightWindowsChanged(bool);
void launchersChanged();
private:
TaskManager::GroupManager *m_groupManager;
TaskManager::TasksModel *m_tasksModel;
QQuickItem* m_taskManagerItem;
WId m_lastWindowId;
bool m_highlightWindows;
QString m_launchers;
};
#endif

View file

@ -0,0 +1,154 @@
#ifndef BLUR_CPP
#define BLUR_CPP
/*
* Copyright 2007 Jani Huhtanen <jani.huhtanen@tut.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License version 2 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <cmath>
// Exponential blur, Jani Huhtanen, 2006
//
template<int aprec, int zprec>
static inline void blurinner(unsigned char *bptr, int &zR, int &zG, int &zB, int &zA, int alpha);
template<int aprec,int zprec>
static inline void blurrow(QImage &im, int line, int alpha);
template<int aprec, int zprec>
static inline void blurcol(QImage &im, int col, int alpha);
/*
* expblur(QImage &img, int radius)
*
* In-place blur of image 'img' with kernel
* of approximate radius 'radius'.
*
* Blurs with two sided exponential impulse
* response.
*
* aprec = precision of alpha parameter
* in fixed-point format 0.aprec
*
* zprec = precision of state parameters
* zR,zG,zB and zA in fp format 8.zprec
*/
template<int aprec,int zprec>
void expblur(QImage &img, int radius)
{
if (radius < 1) {
return;
}
img = img.convertToFormat(QImage::Format_ARGB32_Premultiplied);
/* Calculate the alpha such that 90% of
the kernel is within the radius.
(Kernel extends to infinity)
*/
int alpha = (int)((1 << aprec) * (1.0f - std::exp(-2.3f / (radius + 1.f))));
int height = img.height();
int width = img.width();
for (int row=0; row<height; row++) {
blurrow<aprec,zprec>(img, row, alpha);
}
for (int col=0; col<width; col++) {
blurcol<aprec,zprec>(img, col, alpha);
}
return;
}
template<int aprec, int zprec>
static inline void blurinner(unsigned char *bptr, int &zR, int &zG, int &zB, int &zA, int alpha)
{
int R, G, B, A;
R = *bptr;
G = *(bptr + 1);
B = *(bptr + 2);
A = *(bptr + 3);
zR += (alpha * ((R << zprec) - zR)) >> aprec;
zG += (alpha * ((G << zprec) - zG)) >> aprec;
zB += (alpha * ((B << zprec) - zB)) >> aprec;
zA += (alpha * ((A << zprec) - zA)) >> aprec;
*bptr = zR >> zprec;
*(bptr+1) = zG >> zprec;
*(bptr+2) = zB >> zprec;
*(bptr+3) = zA >> zprec;
}
template<int aprec,int zprec>
static inline void blurrow(QImage &im, int line, int alpha)
{
int zR, zG, zB, zA;
QRgb *ptr = (QRgb *)im.scanLine(line);
int width = im.width();
zR = *((unsigned char *)ptr ) << zprec;
zG = *((unsigned char *)ptr + 1) << zprec;
zB = *((unsigned char *)ptr + 2) << zprec;
zA = *((unsigned char *)ptr + 3) << zprec;
for (int index=1; index<width; index++) {
blurinner<aprec,zprec>((unsigned char *)&ptr[index],zR,zG,zB,zA,alpha);
}
for (int index=width-2; index>=0; index--) {
blurinner<aprec,zprec>((unsigned char *)&ptr[index],zR,zG,zB,zA,alpha);
}
}
template<int aprec, int zprec>
static inline void blurcol(QImage &im, int col, int alpha)
{
int zR, zG, zB, zA;
QRgb *ptr = (QRgb *)im.bits();
ptr += col;
int height = im.height();
int width = im.width();
zR = *((unsigned char *)ptr ) << zprec;
zG = *((unsigned char *)ptr + 1) << zprec;
zB = *((unsigned char *)ptr + 2) << zprec;
zA = *((unsigned char *)ptr + 3) << zprec;
for (int index=width; index<(height-1)*width; index+=width) {
blurinner<aprec,zprec>((unsigned char *)&ptr[index], zR, zG, zB, zA, alpha);
}
for (int index=(height-2)*width; index>=0; index-=width) {
blurinner<aprec,zprec>((unsigned char *)&ptr[index], zR, zG, zB, zA, alpha);
}
}
template<class T>
inline const T &qClamp(const T &x, const T &low, const T &high)
{
if (x < low) {
return low;
} else if (x > high) {
return high;
} else {
return x;
}
}
#endif

Some files were not shown because too many files have changed in this diff Show more