python: remove python demos and help docs from repository
This commit is contained in:
parent
0293e83c3b
commit
ad6ad6fa89
@ -1,34 +0,0 @@
|
||||
|
||||
<h1>Welcome to ToaruOS!</h1>
|
||||
|
||||
<img src="/usr/share/logo_login.png"></img>
|
||||
とあるOS (ToaruOS) is a hobby operating system built mostly from scratch, including both a kernel and userspace.
|
||||
|
||||
<h2>Introduction</h2>
|
||||
|
||||
This <link target="help_browser.trt"><i>Help Browser</i></link> is intended to provide guidance and assistance in using ToaruOS.
|
||||
|
||||
For a listing of topics, see the <link target="special:contents">Table of Contents</link>.
|
||||
|
||||
<h2>History</h2>
|
||||
|
||||
ToaruOS started as a side project at the University of Illinois at Urbana-Champaign. For several months in late 2011 and early 2012, the University's SIGOps chapter managed development efforts focused on building the original compositing GUI. Since then, the project has mostly been a one-man effort with a handful of third party contributions.
|
||||
|
||||
<h2>Kernel</h2>
|
||||
|
||||
The Toaru kernel provides a basic Unix-like environment. The kernel uses a hybrid modular architecture, with loadable modules providing most device driver support. The core kernel includes support for Unix pipes and TTYs, a virtual file system, multitasking, ELF binary support, and various core platform features on x86 systems.
|
||||
Modules provide support for disk drives, ext2 filesystems, serial, keyboards and mice, a <mono>/proc</mono> filesystem similar to the one found in Linux, as well as an expanding collection of other device drivers.
|
||||
|
||||
<h2>Userspace</h2>
|
||||
|
||||
ToaruOS's userspace is focused on a rich graphical environment, backed by an in-house compositing window manager. ToaruOS's terminal emulator supports xterm-compatible 256-color modes, as well as Konsole 24-bit color modes and anti-aliased text with basic Unicode support. Program binaries are dynamically linked. Several graphical demos are provided, alongside a number of command-line applications. A port of SDL targetting the native graphical environment is also available.
|
||||
|
||||
<h2>Third-Party Software</h2>
|
||||
|
||||
The userspace depends on a number of third-party libraries which are outside of the development scope of the project. Additionally, several third-party applications and libraries have been integrated into ToaruOS's core userspace, or otherwise ported to ToaruOS.
|
||||
|
||||
Please see the <link target="special:contents">Table of Contents</link> for a listing of licenses for included third-party software.
|
||||
|
||||
<h2>Community</h2>
|
||||
|
||||
You can join us through IRC in <mono>#toaruos</mono> on Freenode (<mono>irc.freenode.net</mono>).
|
@ -1,11 +0,0 @@
|
||||
|
||||
<h1>Calculator</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/calculator.png"></img>
|
||||
A simple four-function calculator.
|
||||
|
||||
<h2>Technical Details</h2>
|
||||
|
||||
The calculator uses Python's integrated parsing and AST to format mathematical expressions. As such, some functions are different from a normal calculator. For example, you can use <mono>**</mono> as an exponent operator, parenthesis do not imply multiplication (<mono>2(4)</mono> is a syntax error; use <mono>2*(4)</mono> or similar instead), etc.
|
||||
|
||||
|
@ -1,5 +0,0 @@
|
||||
|
||||
<h1>File Browser</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/folder.png"></img>
|
||||
The <i>File Browser</i> allows visual navigation of the file system.
|
@ -1,50 +0,0 @@
|
||||
|
||||
<h1>Help Browser</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/help.png"></img>
|
||||
The <i>Help Browser</i> provides rich text documentation for ToaruOS. Documentation is written in a markup language similar to HTML, but with some notable differences due to nature of the rendering engine. This markup language supports three heading levels, bold, italic, and colored text, links to other help documents, and images. Whitespace is generally significant and line feeds in a source document will be rendered as such in the final document. Text is expected to be encoded in UTF-8, and the renderer will select between several fallback fonts to find characters if they are not in the base font. This same rendering engine is used to display labels and button text in most applications in ToaruOS, so these formatting hints can be applied if you are writing your own applications.
|
||||
|
||||
<h2>Oddities and Differences from HTML</h2>
|
||||
|
||||
The most important difference between the documentation markup language and HTML is the name of the link tag. Link tags are called <mono><link></mono>. They accept a <mono>target</mono> parameter with the target of the link.
|
||||
|
||||
Another significant difference is that images appear on lines by themselves.
|
||||
|
||||
All lines have the same line height. In this help browser, the default is <mono>18</mono>.
|
||||
|
||||
<h2>Examples</h2>
|
||||
|
||||
This document itself may serve as an example. It can be found in <mono>/usr/share/help/help_browser.trt</mono>.
|
||||
|
||||
<h3>Headings</h3>
|
||||
|
||||
There are three levels of heading tags available:
|
||||
<mono>
|
||||
<h1>H1</h1>
|
||||
<h2>H2</h2>
|
||||
<h3>H3</h3>
|
||||
</mono>
|
||||
These headings will produce text as follows:
|
||||
<h1>H1</h1>
|
||||
<h2>H2</h2>
|
||||
<h3>H3</h3>
|
||||
|
||||
<h3>Formatting</h3>
|
||||
|
||||
You can also format <b>bold</b> and <i>italic</i> text as well combinations of <b><i>bold and italic</i></b> and <color 0x00FF00>different colors</color>
|
||||
<mono>
|
||||
You can also format <b>bold</b> and <i>italic</i> text as well combinations of <b><i>bold and italic</i></b> and <color 0x00FF00>different colors</color>
|
||||
</mono>
|
||||
|
||||
<h3>Images</h3>
|
||||
|
||||
Images may be relative to the documentation root directory (<mono>/usr/share/help</mono>) or absolute paths.
|
||||
|
||||
Images look like this:
|
||||
<mono>
|
||||
<img src="/usr/share/logo_login.png"></img>
|
||||
</mono>
|
||||
<img src="/usr/share/logo_login.png"></img>
|
||||
You can also make links out of images, like this:
|
||||
<link target="special:contents"><img src="/usr/share/icons/48/help.png"></img></link>
|
||||
|
@ -1,56 +0,0 @@
|
||||
|
||||
<h1>ToaruOS</h1>
|
||||
<mono>
|
||||
Copyright (c) 2011-2018 K. Lange. All rights reserved.
|
||||
|
||||
Dedicated to the memory of
|
||||
Dennis Ritchie
|
||||
1941-2011
|
||||
|
||||
Developed by: ToAruOS Kernel Development Team
|
||||
http://toaruos.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to
|
||||
deal with the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimers.
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimers in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the names of the ToAruOS Kernel Development Team, K. Lange,
|
||||
nor the names of its contributors may be used to endorse
|
||||
or promote products derived from this Software without specific prior
|
||||
written permission.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
WITH THE SOFTWARE.
|
||||
</mono>
|
||||
<h2>Authors</h2>
|
||||
|
||||
- K. Lange
|
||||
- Markus Schober
|
||||
- Tianyi Wang
|
||||
- Josh Kilmer
|
||||
- Patrick Lucas
|
||||
- Steve Jenson
|
||||
- Tyler Bindon
|
||||
- Mat "Lioncash" M.
|
||||
- Ivailo Monev
|
||||
- Dale Weiler
|
||||
- Mike Gerow
|
||||
- Matt White
|
||||
- Mike Gerow
|
||||
- Fabien Siron
|
||||
- Gil Mendes
|
||||
- Peter Harliman Liem
|
||||
- Shawn Anastasio
|
||||
|
@ -1,39 +0,0 @@
|
||||
|
||||
<h1>Cairo</h1>
|
||||
|
||||
A copy of the LGPL v2.1 may be found <link target="licenses/lgpl-2.1.trt">here</link>.
|
||||
<mono>
|
||||
Cairo is free software.
|
||||
|
||||
Every source file in the implementation[*] of cairo is available to be
|
||||
redistributed and/or modified under the terms of either the GNU Lesser
|
||||
General Public License (LGPL) version 2.1 or the Mozilla Public
|
||||
License (MPL) version 1.1. Some files are available under more
|
||||
liberal terms, but we believe that in all cases, each file may be used
|
||||
under either the LGPL or the MPL.
|
||||
|
||||
See the following files in this directory for the precise terms and
|
||||
conditions of either license:
|
||||
|
||||
COPYING-LGPL-2.1
|
||||
COPYING-MPL-1.1
|
||||
|
||||
Please see each file in the implementation for copyright and licensing
|
||||
information, (in the opening comment of each file).
|
||||
|
||||
[*] The implementation of cairo is contained entirely within the "src"
|
||||
directory of the cairo source distribution. There are other components
|
||||
of the cairo source distribution (such as the "test", "util", and "perf")
|
||||
that are auxiliary to the library itself. None of the source code in these
|
||||
directories contributes to a build of the cairo library itself, (libcairo.so
|
||||
or cairo.dll or similar).
|
||||
|
||||
These auxiliary components are also free software, but may be under
|
||||
different license terms than cairo itself. For example, most of the
|
||||
test cases in the perf and test directories are made available under
|
||||
an MIT license to simplify any use of this code for reference purposes
|
||||
in using cairo itself. Other files might be available under the GNU
|
||||
General Public License (GPL), for example. Again, please see the COPYING
|
||||
file under each directory and the opening comment of each file for copyright
|
||||
and licensing information.
|
||||
</mono>
|
@ -1,49 +0,0 @@
|
||||
|
||||
<h1>DejaVu / Bitstream Vera</h1>
|
||||
<mono>
|
||||
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream
|
||||
Vera is a trademark of Bitstream, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of the fonts accompanying this license ("Fonts") and associated
|
||||
documentation files (the "Font Software"), to reproduce and distribute
|
||||
the Font Software, including without limitation the rights to use,
|
||||
copy, merge, publish, distribute, and/or sell copies of the Font
|
||||
Software, and to permit persons to whom the Font Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright and trademark notices and this permission notice
|
||||
shall be included in all copies of one or more of the Font Software
|
||||
typefaces.
|
||||
|
||||
The Font Software may be modified, altered, or added to, and in
|
||||
particular the designs of glyphs or characters in the Fonts may be
|
||||
modified and additional glyphs or characters may be added to the Fonts,
|
||||
only if the fonts are renamed to names not containing either the words
|
||||
"Bitstream" or the word "Vera".
|
||||
|
||||
This License becomes null and void to the extent applicable to Fonts or
|
||||
Font Software that has been modified and is distributed under the
|
||||
"Bitstream Vera" names.
|
||||
|
||||
The Font Software may be sold as part of a larger software package but
|
||||
no copy of one or more of the Font Software typefaces may be sold by
|
||||
itself.
|
||||
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
|
||||
BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL,
|
||||
OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT
|
||||
SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
||||
Except as contained in this notice, the names of Gnome, the Gnome
|
||||
Foundation, and Bitstream Inc., shall not be used in advertising or
|
||||
otherwise to promote the sale, use or other dealings in this Font
|
||||
Software without prior written authorization from the Gnome Foundation
|
||||
or Bitstream Inc., respectively. For further information, contact:
|
||||
fonts at gnome dot org.
|
||||
</mono>
|
@ -1,8 +0,0 @@
|
||||
|
||||
<h1>Symbola</h1>
|
||||
<mono>
|
||||
In lieu of a license
|
||||
Fonts in this site are offered free for any use; they may be installed,
|
||||
embedded, opened, edited, modified, regenerated, posted,
|
||||
packaged and redistributed. - George Douros
|
||||
</mono>
|
@ -1,35 +0,0 @@
|
||||
|
||||
<h1>VL Gothic</h1>
|
||||
<mono>
|
||||
Copyright (c) 1990-2003 Wada Laboratory, the University of Tokyo.
|
||||
Copyright (c) 2003-2004 Electronic Font Open Laboratory (/efont/).
|
||||
Copyright (C) 2002-2010 M+ FONTS PROJECT Copyright (C) 2006-2010
|
||||
Daisuke SUZUKI . Copyright (C) 2006-2010 Project Vine . All rights
|
||||
reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the Wada Laboratory, the University of Tokyo nor
|
||||
the names of its contributors may be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY WADA LABORATORY, THE UNIVERSITY OF TOKYO
|
||||
AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
IN NO EVENT SHALL THE LABORATORY OR CONTRIBUTORS BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
||||
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
|
||||
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
</mono>
|
@ -1,170 +0,0 @@
|
||||
|
||||
<h1>Freetype</h1>
|
||||
<mono>
|
||||
The FreeType Project LICENSE
|
||||
----------------------------
|
||||
|
||||
2006-Jan-27
|
||||
|
||||
Copyright 1996-2002, 2006 by
|
||||
David Turner, Robert Wilhelm, and Werner Lemberg
|
||||
|
||||
|
||||
|
||||
Introduction
|
||||
============
|
||||
|
||||
The FreeType Project is distributed in several archive packages;
|
||||
some of them may contain, in addition to the FreeType font engine,
|
||||
various tools and contributions which rely on, or relate to, the
|
||||
FreeType Project.
|
||||
|
||||
This license applies to all files found in such packages, and
|
||||
which do not fall under their own explicit license. The license
|
||||
affects thus the FreeType font engine, the test programs,
|
||||
documentation and makefiles, at the very least.
|
||||
|
||||
This license was inspired by the BSD, Artistic, and IJG
|
||||
(Independent JPEG Group) licenses, which all encourage inclusion
|
||||
and use of free software in commercial and freeware products
|
||||
alike. As a consequence, its main points are that:
|
||||
|
||||
o We don't promise that this software works. However, we will be
|
||||
interested in any kind of bug reports. (`as is' distribution)
|
||||
|
||||
o You can use this software for whatever you want, in parts or
|
||||
full form, without having to pay us. (`royalty-free' usage)
|
||||
|
||||
o You may not pretend that you wrote this software. If you use
|
||||
it, or only parts of it, in a program, you must acknowledge
|
||||
somewhere in your documentation that you have used the
|
||||
FreeType code. (`credits')
|
||||
|
||||
We specifically permit and encourage the inclusion of this
|
||||
software, with or without modifications, in commercial products.
|
||||
We disclaim all warranties covering The FreeType Project and
|
||||
assume no liability related to The FreeType Project.
|
||||
|
||||
|
||||
Finally, many people asked us for a preferred form for a
|
||||
credit/disclaimer to use in compliance with this license. We thus
|
||||
encourage you to use the following text:
|
||||
|
||||
"""
|
||||
Portions of this software are copyrigh © <year> The FreeType
|
||||
Project (www.freetype.org). All rights reserved.
|
||||
"""
|
||||
|
||||
Please replace <year> with the value from the FreeType version you
|
||||
actually use.
|
||||
|
||||
|
||||
Legal Terms
|
||||
===========
|
||||
|
||||
0. Definitions
|
||||
--------------
|
||||
|
||||
Throughout this license, the terms `package', `FreeType Project',
|
||||
and `FreeType archive' refer to the set of files originally
|
||||
distributed by the authors (David Turner, Robert Wilhelm, and
|
||||
Werner Lemberg) as the `FreeType Project', be they named as alpha,
|
||||
beta or final release.
|
||||
|
||||
`You' refers to the licensee, or person using the project, where
|
||||
`using' is a generic term including compiling the project's source
|
||||
code as well as linking it to form a `program' or `executable'.
|
||||
This program is referred to as `a program using the FreeType
|
||||
engine'.
|
||||
|
||||
This license applies to all files distributed in the original
|
||||
FreeType Project, including all source code, binaries and
|
||||
documentation, unless otherwise stated in the file in its
|
||||
original, unmodified form as distributed in the original archive.
|
||||
If you are unsure whether or not a particular file is covered by
|
||||
this license, you must contact us to verify this.
|
||||
|
||||
The FreeType Project is copyright (C) 1996-2000 by David Turner,
|
||||
Robert Wilhelm, and Werner Lemberg. All rights reserved except as
|
||||
specified below.
|
||||
|
||||
1. No Warranty
|
||||
--------------
|
||||
|
||||
THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
|
||||
BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO
|
||||
USE, OF THE FREETYPE PROJECT.
|
||||
|
||||
2. Redistribution
|
||||
-----------------
|
||||
|
||||
This license grants a worldwide, royalty-free, perpetual and
|
||||
irrevocable right and license to use, execute, perform, compile,
|
||||
display, copy, create derivative works of, distribute and
|
||||
sublicense the FreeType Project (in both source and object code
|
||||
forms) and derivative works thereof for any purpose; and to
|
||||
authorize others to exercise some or all of the rights granted
|
||||
herein, subject to the following conditions:
|
||||
|
||||
o Redistribution of source code must retain this license file
|
||||
(`FTL.TXT') unaltered; any additions, deletions or changes to
|
||||
the original files must be clearly indicated in accompanying
|
||||
documentation. The copyright notices of the unaltered,
|
||||
original files must be preserved in all copies of source
|
||||
files.
|
||||
|
||||
o Redistribution in binary form must provide a disclaimer that
|
||||
states that the software is based in part of the work of the
|
||||
FreeType Team, in the distribution documentation. We also
|
||||
encourage you to put an URL to the FreeType web page in your
|
||||
documentation, though this isn't mandatory.
|
||||
|
||||
These conditions apply to any software derived from or based on
|
||||
the FreeType Project, not just the unmodified files. If you use
|
||||
our work, you must acknowledge us. However, no fee need be paid
|
||||
to us.
|
||||
|
||||
3. Advertising
|
||||
--------------
|
||||
|
||||
Neither the FreeType authors and contributors nor you shall use
|
||||
the name of the other for commercial, advertising, or promotional
|
||||
purposes without specific prior written permission.
|
||||
|
||||
We suggest, but do not require, that you use one or more of the
|
||||
following phrases to refer to this software in your documentation
|
||||
or advertising materials: `FreeType Project', `FreeType Engine',
|
||||
`FreeType library', or `FreeType Distribution'.
|
||||
|
||||
As you have not signed this license, you are not required to
|
||||
accept it. However, as the FreeType Project is copyrighted
|
||||
material, only this license, or another one contracted with the
|
||||
authors, grants you the right to use, distribute, and modify it.
|
||||
Therefore, by using, distributing, or modifying the FreeType
|
||||
Project, you indicate that you understand and accept all the terms
|
||||
of this license.
|
||||
|
||||
4. Contacts
|
||||
-----------
|
||||
|
||||
There are two mailing lists related to FreeType:
|
||||
|
||||
o freetype@nongnu.org
|
||||
|
||||
Discusses general use and applications of FreeType, as well as
|
||||
future and wanted additions to the library and distribution.
|
||||
If you are looking for support, start in this list if you
|
||||
haven't found anything to help you in the documentation.
|
||||
|
||||
o freetype-devel@nongnu.org
|
||||
|
||||
Discusses bugs, as well as engine internals, design issues,
|
||||
specific licenses, porting, etc.
|
||||
|
||||
Our home page can be found at
|
||||
|
||||
http://www.freetype.org
|
||||
</mono>
|
@ -1,506 +0,0 @@
|
||||
|
||||
<h1>GNU Lesser General Public License (LGPL) 2.1</h1>
|
||||
<mono>
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 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.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
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 and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, 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 library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete 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 distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
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 Library or any portion
|
||||
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
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 Library, 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 Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you 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.
|
||||
|
||||
If distribution of 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 satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be 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.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library 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.
|
||||
|
||||
9. 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 Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
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 with
|
||||
this License.
|
||||
|
||||
11. 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 Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library 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 Library.
|
||||
|
||||
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.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library 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.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser 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 Library
|
||||
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 Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
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
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "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
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. 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 LIBRARY 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
|
||||
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. 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 library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 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
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; 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.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
</mono>
|
@ -1,169 +0,0 @@
|
||||
|
||||
<h1>GNU Lesser General Public License (LGPL) 3.0</h1>
|
||||
<mono>
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser 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
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
</mono>
|
@ -1,7 +0,0 @@
|
||||
|
||||
|
||||
<h1>PyCairo</h1>
|
||||
|
||||
<mono>pycairo</mono> is licensed under the GNU Lesser General Public License (LGPL) version 3.
|
||||
|
||||
A copy of the LGPL v3 may be found <link target="licenses/lgpl-3.0.trt">here</link>.
|
@ -1,8 +0,0 @@
|
||||
|
||||
<h1>Python</h1>
|
||||
|
||||
The license for Python may be viewed by running the following command:
|
||||
<mono>
|
||||
python -c "license()"
|
||||
</mono>
|
||||
|
@ -1,8 +0,0 @@
|
||||
|
||||
<h1>Mines</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/mines.png"></img>
|
||||
Implementation of the classic logic game.
|
||||
|
||||
Click to reveal, ctrl+click to flag / unflag.
|
||||
|
@ -1,5 +0,0 @@
|
||||
|
||||
<h1>Package Manager</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/package.png"></img>
|
||||
The <i>Package Manager</i> can be used to browse and install available packages.
|
@ -1,14 +0,0 @@
|
||||
|
||||
<h1>ToaruPaint</h1>
|
||||
|
||||
<img src="/usr/share/icons/48/applications-painting.png"></img>
|
||||
Draw things with this simple painting tool.
|
||||
|
||||
<h2>Controls</h2>
|
||||
|
||||
Select colors using the color picker (Tools > Color).
|
||||
|
||||
Change the brush size by scrolling the mouse wheel up and down.
|
||||
|
||||
Drag the viewport with the middle mouse button.
|
||||
|
@ -48,12 +48,3 @@ popd
|
||||
echo "Installing readline hook..."
|
||||
cp util/readline._py $HDD_PATH/usr/python/lib/python3.6/
|
||||
|
||||
echo "Installing demos..."
|
||||
mkdir -p base/usr/share/python-demos
|
||||
cp util/python-demos/*.py base/usr/share/python-demos/
|
||||
|
||||
echo "Installing Help Browser files..."
|
||||
mkdir -p base/usr/share/help
|
||||
mkdir -p base/usr/share/help/licenses
|
||||
cp util/extra-help/*.trt base/usr/share/help/
|
||||
cp util/extra-help/licenses/*.trt base/usr/share/help/licenses/
|
||||
|
@ -1,82 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Generic "About" applet provider.
|
||||
"""
|
||||
import sys
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
|
||||
class AboutAppletWindow(yutani.Window):
|
||||
|
||||
base_width = 350
|
||||
base_height = 250
|
||||
|
||||
text_offset = 110
|
||||
|
||||
def __init__(self, decorator, title, logo, text, icon="star",on_close=None):
|
||||
super(AboutAppletWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, flags=yutani.WindowFlag.FLAG_DISALLOW_RESIZE, icon=icon, doublebuffer=True)
|
||||
self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
|
||||
self.decorator = decorator
|
||||
if logo.endswith('.png'):
|
||||
logo = logo.replace('.png','.bmp') # Hope that works
|
||||
self.logo = yutani.Sprite.from_file(logo).get_cairo_surface()
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)
|
||||
self.tr = text_region.TextRegion(0,0,self.base_width-30,self.base_height-self.text_offset,font=self.font)
|
||||
self.tr.set_alignment(2)
|
||||
self.tr.set_richtext(text)
|
||||
self.on_close = on_close
|
||||
self.draw()
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
ctx.set_source_surface(self.logo,int((WIDTH-self.logo.get_width())/2),10+int((84-self.logo.get_height())/2))
|
||||
ctx.paint()
|
||||
|
||||
self.tr.resize(WIDTH-30,HEIGHT-self.text_offset)
|
||||
self.tr.move(self.decorator.left_width(self) + 15,self.decorator.top_height(self)+self.text_offset)
|
||||
self.tr.draw(self)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def close_window(self):
|
||||
self.close()
|
||||
if self.on_close:
|
||||
self.on_close()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
if self.decorator.handle_event(msg) == yutani.Decor.EVENT_CLOSE:
|
||||
self.close_window()
|
||||
return
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.key == b"q":
|
||||
self.close_window()
|
||||
|
||||
|
@ -1,101 +0,0 @@
|
||||
import math
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
def rounded_rectangle(ctx,x,y,w,h,r):
|
||||
degrees = math.pi / 180
|
||||
ctx.new_sub_path()
|
||||
|
||||
ctx.arc(x + w - r, y + r, r, -90 * degrees, 0 * degrees)
|
||||
ctx.arc(x + w - r, y + h - r, r, 0 * degrees, 90 * degrees)
|
||||
ctx.arc(x + r, y + h - r, r, 90 * degrees, 180 * degrees)
|
||||
ctx.arc(x + r, y + r, r, 180 * degrees, 270 * degrees)
|
||||
ctx.close_path()
|
||||
|
||||
def draw_button(ctx,x,y,w,h,hilight):
|
||||
"""Theme definition for drawing a button."""
|
||||
ctx.save()
|
||||
|
||||
ctx.set_line_cap(cairo.LINE_CAP_ROUND)
|
||||
ctx.set_line_join(cairo.LINE_JOIN_ROUND)
|
||||
|
||||
if hilight == 2:
|
||||
rounded_rectangle(ctx, 2 + x, 2 + y, w - 4, h - 4, 2.0)
|
||||
ctx.set_source_rgba(134/255,173/255,201/255,1.0)
|
||||
ctx.set_line_width(2)
|
||||
ctx.stroke()
|
||||
|
||||
rounded_rectangle(ctx, 2 + x, 2 + y, w - 4, h - 4, 2.0)
|
||||
ctx.set_source_rgba(202/255,211/255,232/255,1.0)
|
||||
ctx.fill()
|
||||
else:
|
||||
rounded_rectangle(ctx, 2 + x, 2 + y, w - 4, h - 4, 2.0)
|
||||
ctx.set_source_rgba(44/255,71/255,91/255,29/255)
|
||||
ctx.set_line_width(4)
|
||||
ctx.stroke()
|
||||
|
||||
rounded_rectangle(ctx, 2 + x, 2 + y, w - 4, h - 4, 2.0)
|
||||
ctx.set_source_rgba(158/255,169/255,177/255,1.0)
|
||||
ctx.set_line_width(2)
|
||||
ctx.stroke()
|
||||
|
||||
if hilight == 1:
|
||||
pat = cairo.LinearGradient(2+x,2+y,2+x,2+y+h-4)
|
||||
pat.add_color_stop_rgba(0,1,1,1,1)
|
||||
pat.add_color_stop_rgba(1,229/255,229/255,246/255,1)
|
||||
rounded_rectangle(ctx,2+x,2+y,w-4,h-4,2.0)
|
||||
ctx.set_source(pat)
|
||||
ctx.fill()
|
||||
|
||||
pat = cairo.LinearGradient(3+x,3+y,3+x,3+y+h-4)
|
||||
pat.add_color_stop_rgba(0,252/255,252/255,254/255,1)
|
||||
pat.add_color_stop_rgba(1,212/255,223/255,251/255,1)
|
||||
rounded_rectangle(ctx,3+x,3+y,w-5,h-5,2.0)
|
||||
ctx.set_source(pat)
|
||||
ctx.fill()
|
||||
|
||||
else:
|
||||
pat = cairo.LinearGradient(2+x,2+y,2+x,2+y+h-4)
|
||||
pat.add_color_stop_rgba(0,1,1,1,1)
|
||||
pat.add_color_stop_rgba(1,241/255,241/255,244/255,1)
|
||||
rounded_rectangle(ctx,2+x,2+y,w-4,h-4,2.0)
|
||||
ctx.set_source(pat)
|
||||
ctx.fill()
|
||||
|
||||
pat = cairo.LinearGradient(3+x,3+y,3+x,3+y+h-4)
|
||||
pat.add_color_stop_rgba(0,252/255,252/255,254/255,1)
|
||||
pat.add_color_stop_rgba(1,223/255,225/255,230/255,1)
|
||||
rounded_rectangle(ctx,3+x,3+y,w-5,h-5,2.0)
|
||||
ctx.set_source(pat)
|
||||
ctx.fill()
|
||||
|
||||
ctx.restore()
|
||||
|
||||
class Button(object):
|
||||
|
||||
def __init__(self, text, callback):
|
||||
self.text = text
|
||||
self.callback = callback
|
||||
self.hilight = 0
|
||||
self.x, self.y, self.width, self.height = 0,0,0,0
|
||||
|
||||
def draw(self, window, ctx, x, y, w, h):
|
||||
self.x, self.y, self.width, self.height = x, y, w, h
|
||||
draw_button(ctx,x,y,w,h,self.hilight)
|
||||
|
||||
x_, y_ = ctx.user_to_device(x,y)
|
||||
tr = text_region.TextRegion(int(x_),int(y_),w,h)
|
||||
tr.set_alignment(2)
|
||||
tr.set_valignment(2)
|
||||
tr.set_text(self.text)
|
||||
tr.draw(window)
|
||||
|
||||
def focus_enter(self):
|
||||
self.hilight = 1
|
||||
|
||||
def focus_leave(self):
|
||||
self.hilight = 0
|
@ -1,284 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Calculator for ToaruOS
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
from button import Button
|
||||
from menu_bar import MenuBarWidget, MenuEntryAction, MenuEntrySubmenu, MenuEntryDivider, MenuWindow
|
||||
from about_applet import AboutAppletWindow
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
import ast
|
||||
import operator as op
|
||||
|
||||
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
|
||||
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
|
||||
ast.USub: op.neg}
|
||||
|
||||
app_name = "Calculator"
|
||||
version = "1.0.0"
|
||||
_description = f"<b>{app_name} {version}</b>\n© 2017-2018 K. Lange\n\nSimple four-function calculator using Python.\n\n<color 0x0000FF>http://github.com/klange/toaruos</color>"
|
||||
|
||||
def eval_expr(expr):
|
||||
"""
|
||||
>>> eval_expr('2^6')
|
||||
4
|
||||
>>> eval_expr('2**6')
|
||||
64
|
||||
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
|
||||
-5.0
|
||||
"""
|
||||
return eval_(ast.parse(expr, mode='eval').body)
|
||||
|
||||
def eval_(node):
|
||||
if isinstance(node, ast.Num): # <number>
|
||||
return node.n
|
||||
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
|
||||
return operators[type(node.op)](eval_(node.left), eval_(node.right))
|
||||
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
|
||||
return operators[type(node.op)](eval_(node.operand))
|
||||
else:
|
||||
raise TypeError("invalid operation")
|
||||
|
||||
|
||||
class CalculatorWindow(yutani.Window):
|
||||
|
||||
base_width = 200
|
||||
base_height = 240
|
||||
|
||||
def __init__(self, decorator):
|
||||
super(CalculatorWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=app_name, icon="calculator", doublebuffer=True)
|
||||
self.move(100,100)
|
||||
self.decorator = decorator
|
||||
|
||||
def add_string(button):
|
||||
self.add_string(button.text)
|
||||
|
||||
def clear(button):
|
||||
self.clear_text()
|
||||
|
||||
def calculate(button):
|
||||
self.calculate()
|
||||
|
||||
self.buttons = [
|
||||
[Button("C",clear), None, Button("(",add_string), Button(")",add_string)],
|
||||
[Button("7",add_string), Button("8",add_string), Button("9",add_string), Button("/",add_string)],
|
||||
[Button("4",add_string), Button("5",add_string), Button("6",add_string), Button("*",add_string)],
|
||||
[Button("1",add_string), Button("2",add_string), Button("3",add_string), Button("-",add_string)],
|
||||
[Button("0",add_string), Button(".",add_string), Button("=",calculate), Button("+",add_string)],
|
||||
]
|
||||
|
||||
def exit_app(action):
|
||||
menus = [x for x in self.menus.values()]
|
||||
for x in menus:
|
||||
x.definitely_close()
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
def about_window(action):
|
||||
AboutAppletWindow(self.decorator,f"About {app_name}","/usr/share/icons/48/calculator.png",_description,"calculator")
|
||||
def help_browser(action):
|
||||
subprocess.Popen(["help-browser.py","calculator.trt"])
|
||||
menus = [
|
||||
("File", [
|
||||
MenuEntryAction("Exit","exit",exit_app,None),
|
||||
]),
|
||||
("Help", [
|
||||
MenuEntryAction("Contents","help",help_browser,None),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction(f"About {app_name}","star",about_window,None),
|
||||
]),
|
||||
]
|
||||
|
||||
self.menubar = MenuBarWidget(self,menus)
|
||||
|
||||
self.tr = text_region.TextRegion(self.decorator.left_width(self)+5,self.decorator.top_height(self)+self.menubar.height,self.base_width-10,40)
|
||||
self.tr.set_font(toaru_fonts.Font(toaru_fonts.FONT_MONOSPACE,18))
|
||||
self.tr.set_text("")
|
||||
self.tr.set_alignment(1)
|
||||
self.tr.set_valignment(2)
|
||||
self.tr.set_one_line()
|
||||
self.tr.set_ellipsis()
|
||||
|
||||
self.error = False
|
||||
|
||||
self.hover_widget = None
|
||||
self.down_button = None
|
||||
|
||||
self.menus = {}
|
||||
self.hovered_menu = None
|
||||
|
||||
|
||||
def calculate(self):
|
||||
if self.error or len(self.tr.text) == 0:
|
||||
self.tr.set_text("0")
|
||||
self.error = False
|
||||
try:
|
||||
self.tr.set_text(str(eval_expr(self.tr.text)))
|
||||
except Exception as e:
|
||||
error = str(e)
|
||||
if "(" in error:
|
||||
error = error[:error.find("(")-1]
|
||||
self.tr.set_richtext(f"<i><color 0xFF0000>{e.__class__.__name__}</color>: {error}</i>")
|
||||
self.error = True
|
||||
self.draw()
|
||||
self.flip()
|
||||
|
||||
def add_string(self, text):
|
||||
if self.error:
|
||||
self.tr.text = ""
|
||||
self.error = False
|
||||
self.tr.set_text(self.tr.text + text)
|
||||
self.draw()
|
||||
self.flip()
|
||||
|
||||
def clear_text(self):
|
||||
self.error = False
|
||||
self.tr.set_text("")
|
||||
self.draw()
|
||||
self.flip()
|
||||
|
||||
def clear_last(self):
|
||||
if self.error:
|
||||
self.error = False
|
||||
self.tr.set_text("")
|
||||
if len(self.tr.text):
|
||||
self.tr.set_text(self.tr.text[:-1])
|
||||
self.draw()
|
||||
self.flip()
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
ctx.rectangle(0,5+self.menubar.height,WIDTH,self.tr.height-10)
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
self.tr.move(self.decorator.left_width(self)+5,self.decorator.top_height(self)+self.menubar.height)
|
||||
self.tr.resize(WIDTH-10, self.tr.height)
|
||||
self.tr.draw(self)
|
||||
|
||||
offset_x = 0
|
||||
offset_y = self.tr.height + self.menubar.height
|
||||
button_height = int((HEIGHT - self.tr.height - self.menubar.height) / len(self.buttons))
|
||||
for row in self.buttons:
|
||||
button_width = int(WIDTH / len(row))
|
||||
for button in row:
|
||||
if button:
|
||||
button.draw(self,ctx,offset_x,offset_y,button_width,button_height)
|
||||
offset_x += button_width
|
||||
offset_x = 0
|
||||
offset_y += button_height
|
||||
|
||||
self.menubar.draw(ctx,0,0,WIDTH)
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
if msg.width < 200 or msg.height < 200:
|
||||
self.resize_offer(max(msg.width,200),max(msg.height,200))
|
||||
return
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
decor_event = d.handle_event(msg)
|
||||
if decor_event == yutani.Decor.EVENT_CLOSE:
|
||||
window.close()
|
||||
sys.exit(0)
|
||||
elif decor_event == yutani.Decor.EVENT_RIGHT:
|
||||
d.show_menu(self, msg)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
if x >= 0 and x < w and y >= 0 and y < self.menubar.height:
|
||||
self.menubar.mouse_event(msg, x, y)
|
||||
return
|
||||
|
||||
redraw = False
|
||||
if self.down_button:
|
||||
if msg.command == yutani.MouseEvent.RAISE or msg.command == yutani.MouseEvent.CLICK:
|
||||
if not (msg.buttons & yutani.MouseButton.BUTTON_LEFT):
|
||||
if x >= self.down_button.x and \
|
||||
x < self.down_button.x + self.down_button.width and \
|
||||
y >= self.down_button.y and \
|
||||
y < self.down_button.y + self.down_button.height:
|
||||
self.down_button.focus_enter()
|
||||
self.down_button.callback(self.down_button)
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
else:
|
||||
self.down_button.focus_leave()
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
|
||||
else:
|
||||
if y > self.tr.height + self.menubar.height and y < h and x >= 0 and x < w:
|
||||
row = int((y - self.tr.height - self.menubar.height) / (self.height - self.decorator.height() - self.tr.height - self.menubar.height) * len(self.buttons))
|
||||
col = int(x / (self.width - self.decorator.width(self)) * len(self.buttons[row]))
|
||||
button = self.buttons[row][col]
|
||||
if button != self.hover_widget:
|
||||
if button:
|
||||
button.focus_enter()
|
||||
redraw = True
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = button
|
||||
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if button:
|
||||
button.hilight = 2
|
||||
self.down_button = button
|
||||
redraw = True
|
||||
else:
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = None
|
||||
|
||||
if redraw:
|
||||
self.draw()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action != 0x01:
|
||||
return # Ignore anything that isn't a key down.
|
||||
if msg.event.key in b"0123456789.+-/*()":
|
||||
self.add_string(msg.event.key.decode('utf-8'))
|
||||
if msg.event.key == b"\n":
|
||||
self.calculate()
|
||||
if msg.event.key == b"c":
|
||||
self.clear_text()
|
||||
if msg.event.keycode == 8:
|
||||
self.clear_last()
|
||||
if msg.event.key == b"q":
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
window = CalculatorWindow(d)
|
||||
window.draw()
|
||||
|
||||
yutani_mainloop.mainloop()
|
@ -1,310 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Fancy clock.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import toaru_fonts
|
||||
import fswait
|
||||
|
||||
from menu_bar import MenuBarWidget, MenuEntryAction, MenuEntrySubmenu, MenuEntryDivider, MenuWindow
|
||||
from about_applet import AboutAppletWindow
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
app_name = "Clock"
|
||||
version = "1.0.0"
|
||||
_description = f"<b>{app_name} {version}</b>\n© 2017-2018 K. Lange\n\nAnalog clock widget.\n\n<color 0x0000FF>http://github.com/klange/toaruos</color>"
|
||||
|
||||
class BasicWatchFace(object):
|
||||
|
||||
def __init__(self):
|
||||
self.font = toaru_fonts.get_cairo_face()
|
||||
|
||||
def draw_background(self, ctx, t):
|
||||
ctx.set_line_width(9)
|
||||
ctx.set_source_rgb(0,0,0)
|
||||
ctx.arc(0,0,100 - 10, 0, 2 * math.pi)
|
||||
ctx.stroke_preserve()
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
r2 = 100 - 9
|
||||
ctx.set_source_rgb(0,0,0)
|
||||
for i in range(12*5):
|
||||
theta = 2 * math.pi * (i / (12*5))
|
||||
if i % 5 == 0:
|
||||
ctx.set_line_width(2)
|
||||
r1 = 100 - 20
|
||||
else:
|
||||
ctx.set_line_width(0.5)
|
||||
r1 = 100 - 14
|
||||
ctx.move_to(math.sin(theta) * r1, -r1 * math.cos(theta))
|
||||
ctx.line_to(math.sin(theta) * r2, -r2 * math.cos(theta))
|
||||
ctx.stroke()
|
||||
|
||||
def setup_labels(self, ctx, t):
|
||||
ctx.set_font_face(self.font)
|
||||
ctx.set_font_size(12)
|
||||
ctx.set_source_rgb(0,0,0)
|
||||
|
||||
def draw_labels(self, ctx, t):
|
||||
ctx.save()
|
||||
label = "12"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-e[2]/2,-72+e[3])
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "3"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(75-e[2],e[3]/2)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "9"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-75,e[3]/2)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "6"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-e[2]/2,72)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
|
||||
label = "1"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(39-e[2],-63+e[3])
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "11"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-39,-63+e[3])
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
|
||||
label = "5"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(39-e[2],63)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "7"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-39,63)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
|
||||
label = "2"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(63-e[2],-37+e[3])
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "10"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-63,-37+e[3])
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
|
||||
label = "4"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(63-e[2],37)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
label = "8"
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-63,37)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
|
||||
def draw_date(self, ctx, t):
|
||||
ctx.save()
|
||||
ctx.set_font_size(10)
|
||||
label = time.strftime('%B %e',t[0])
|
||||
e = ctx.text_extents(label)
|
||||
ctx.move_to(-e[2]/2,-30)
|
||||
ctx.show_text(label)
|
||||
ctx.fill()
|
||||
|
||||
def draw_line(self, ctx, thickness, color, a, b, r1, r2):
|
||||
theta = (a / b) * 2 * math.pi
|
||||
ctx.set_line_width(thickness)
|
||||
ctx.set_source_rgb(*color)
|
||||
ctx.move_to(math.sin(theta) * r1, -r1 * math.cos(theta))
|
||||
ctx.line_to(math.sin(theta) * r2, -r2 * math.cos(theta))
|
||||
ctx.stroke()
|
||||
|
||||
def tick(self,t):
|
||||
ts = t*t
|
||||
tc = ts*t
|
||||
return (0.5*tc*ts + -8*ts*ts + 20*tc + -19*ts + 7.5*t);
|
||||
|
||||
def draw_hands(self, ctx, t):
|
||||
_,h,m,s = t
|
||||
self.draw_line(ctx,3,(0,0,0),h%12+(m+s/60)/60,12,52,-5)
|
||||
self.draw_line(ctx,2,(0,0,0),m+s/60,60,86,-10)
|
||||
|
||||
_s = int(60+s-1)+self.tick(s%1)
|
||||
self.draw_line(ctx,1,(1,0,0),_s,60,86,-20)
|
||||
self.draw_line(ctx,3,(1,0,0),_s,60,-4,-16)
|
||||
|
||||
def draw(self, ctx, t):
|
||||
self.draw_background(ctx,t)
|
||||
self.setup_labels(ctx,t)
|
||||
self.draw_labels(ctx,t)
|
||||
self.draw_date(ctx,t)
|
||||
self.draw_hands(ctx,t)
|
||||
|
||||
class DarkWatchFace(BasicWatchFace):
|
||||
def draw_background(self, ctx, t):
|
||||
ctx.set_line_width(9)
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.arc(0,0,100 - 10, 0, 2 * math.pi)
|
||||
ctx.stroke_preserve()
|
||||
ctx.set_source_rgb(0,0,0)
|
||||
ctx.fill()
|
||||
|
||||
r2 = 100 - 9
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
for i in range(12*5):
|
||||
theta = 2 * math.pi * (i / (12*5))
|
||||
if i % 5 == 0:
|
||||
ctx.set_line_width(2)
|
||||
r1 = 100 - 20
|
||||
else:
|
||||
ctx.set_line_width(0.5)
|
||||
r1 = 100 - 14
|
||||
ctx.move_to(math.sin(theta) * r1, -r1 * math.cos(theta))
|
||||
ctx.line_to(math.sin(theta) * r2, -r2 * math.cos(theta))
|
||||
ctx.stroke()
|
||||
|
||||
def draw_hands(self, ctx, t):
|
||||
_,h,m,s = t
|
||||
self.draw_line(ctx,3,(1,1,1),h%12+(m+s/60)/60,12,52,-5)
|
||||
self.draw_line(ctx,2,(1,1,1),m+s/60,60,86,-10)
|
||||
|
||||
_s = int(60+s-1)+self.tick(s%1)
|
||||
self.draw_line(ctx,1,(1,0,0),_s,60,86,-20)
|
||||
self.draw_line(ctx,3,(1,0,0),_s,60,-4,-16)
|
||||
|
||||
def setup_labels(self, ctx, t):
|
||||
ctx.set_font_face(self.font)
|
||||
ctx.set_font_size(12)
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
|
||||
|
||||
class ClockWindow(yutani.Window):
|
||||
|
||||
base_width = 200
|
||||
base_height = 200
|
||||
|
||||
def __init__(self):
|
||||
super(ClockWindow, self).__init__(self.base_width, self.base_height, title="Clock", icon="clock", doublebuffer=True)
|
||||
self.move(100,100)
|
||||
self.update_shape(yutani.WindowShape.THRESHOLD_CLEAR)
|
||||
|
||||
self.menus = {}
|
||||
|
||||
self.watchfaces = {
|
||||
'Default': BasicWatchFace(),
|
||||
'Dark': DarkWatchFace(),
|
||||
}
|
||||
|
||||
self.watchface = self.watchfaces['Default']
|
||||
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
ctx = cairo.Context(surface)
|
||||
|
||||
# Clear
|
||||
ctx.set_operator(cairo.OPERATOR_SOURCE)
|
||||
ctx.rectangle(0,0,self.width,self.height)
|
||||
ctx.set_source_rgba(0,0,0,0)
|
||||
ctx.fill()
|
||||
|
||||
ctx.set_operator(cairo.OPERATOR_OVER)
|
||||
ctx.translate(self.width / 2, self.height / 2)
|
||||
ctx.scale(self.width / 200, self.height / 200)
|
||||
|
||||
current_time = time.time()
|
||||
t = time.localtime(int(current_time))
|
||||
s = current_time % 60
|
||||
m = t.tm_min
|
||||
h = t.tm_hour
|
||||
|
||||
self.watchface.draw(ctx,(t,h,m,s))
|
||||
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
if msg.width != msg.height:
|
||||
s = min(msg.width,msg.height)
|
||||
self.resize_offer(s,s)
|
||||
return
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def exit(self, data):
|
||||
sys.exit(0)
|
||||
|
||||
def about(self, data=None):
|
||||
AboutAppletWindow(d,f"About {app_name}","/usr/share/icons/48/clock.bmp",_description,"clock")
|
||||
|
||||
def mouse_event(self, msg):
|
||||
# drag start
|
||||
if msg.command == yutani.MouseEvent.DOWN and msg.buttons & yutani.MouseButton.BUTTON_LEFT:
|
||||
self.drag_start()
|
||||
|
||||
if msg.buttons & yutani.MouseButton.BUTTON_RIGHT:
|
||||
if not self.menus:
|
||||
def set_face(x):
|
||||
self.watchface = self.watchfaces[x]
|
||||
faces = [MenuEntryAction(x,None,set_face,x) for x in self.watchfaces.keys()]
|
||||
menu_entries = [
|
||||
MenuEntrySubmenu("Watchface",faces,icon='clock'),
|
||||
MenuEntryAction(f"About {app_name}","star",self.about,None),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction("Exit","exit",self.exit,None),
|
||||
]
|
||||
menu = MenuWindow(menu_entries,(self.x+msg.new_x,self.y+msg.new_y),root=self)
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action != yutani.KeyAction.ACTION_DOWN:
|
||||
return
|
||||
if msg.event.key == b'q':
|
||||
self.exit(None)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor() # Just in case.
|
||||
|
||||
window = ClockWindow()
|
||||
window.draw()
|
||||
|
||||
fds = [yutani.yutani_ctx]
|
||||
while 1:
|
||||
# Poll for events.
|
||||
fd = fswait.fswait(fds,20)
|
||||
if fd == 0:
|
||||
msg = yutani.yutani_ctx.poll()
|
||||
while msg:
|
||||
yutani_mainloop.handle_event(msg)
|
||||
msg = yutani.yutani_ctx.poll(False)
|
||||
window.draw()
|
||||
elif fd == 1:
|
||||
# Tick
|
||||
window.draw()
|
||||
|
||||
|
@ -1,456 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Simple okay/cancel dialog.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
import fnmatch
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
from button import Button
|
||||
from icon_cache import get_icon
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
_default_text = "This is a dialog. <b>Formatting is available.</b>"
|
||||
|
||||
hilight_border_top = (54/255,128/255,205/255)
|
||||
hilight_gradient_top = (93/255,163/255,236/255)
|
||||
hilight_gradient_bottom = (56/255,137/255,220/55)
|
||||
hilight_border_bottom = (47/255,106/255,167/255)
|
||||
|
||||
class DialogButtons(object):
|
||||
|
||||
OKAY_CANCEL = 1
|
||||
YES_NO_CANCEL = 2
|
||||
|
||||
class DialogWindow(yutani.Window):
|
||||
|
||||
base_width = 500
|
||||
base_height = 150
|
||||
|
||||
text_offset = 40
|
||||
|
||||
okay_label = "Okay"
|
||||
cancel_label = "Cancel"
|
||||
|
||||
def __init__(self, decorator, title, text, icon='help', buttons=DialogButtons.OKAY_CANCEL, callback=None, cancel_callback=None,window=None,cancel_label=True,close_is_cancel=True):
|
||||
super(DialogWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, icon=icon, doublebuffer=True)
|
||||
|
||||
if window:
|
||||
# Center window
|
||||
self.move(window.x+int((window.width-self.width)/2),window.y+int((window.height-self.height)/2))
|
||||
else:
|
||||
# Center screen
|
||||
self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
|
||||
self.decorator = decorator
|
||||
self.logo = get_icon(icon,48,'help')
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)
|
||||
self.tr = text_region.TextRegion(0,0,self.base_width-60,self.base_height-self.text_offset,font=self.font)
|
||||
self.tr.set_richtext(text)
|
||||
|
||||
if cancel_label is not True:
|
||||
self.cancel_label = cancel_label
|
||||
|
||||
self.button_ok = Button(self.okay_label,self.ok_click)
|
||||
self.button_cancel = Button(self.cancel_label,self.cancel_click)
|
||||
self.buttons = [self.button_ok]
|
||||
if self.cancel_label:
|
||||
self.buttons.append(self.button_cancel)
|
||||
|
||||
self.close_is_cancel = close_is_cancel
|
||||
|
||||
self.hover_widget = None
|
||||
self.down_button = None
|
||||
|
||||
self.callback = callback
|
||||
self.cancel_callback = cancel_callback
|
||||
self.draw()
|
||||
|
||||
def ok_click(self, button):
|
||||
self.close()
|
||||
if self.callback:
|
||||
self.callback()
|
||||
return False
|
||||
|
||||
def cancel_click(self, button):
|
||||
self.close()
|
||||
if self.cancel_callback:
|
||||
self.cancel_callback()
|
||||
return False
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
ctx.set_source_surface(self.logo,30,30)
|
||||
ctx.paint()
|
||||
|
||||
self.tr.resize(WIDTH-90,HEIGHT-self.text_offset)
|
||||
self.tr.move(self.decorator.left_width(self) + 90,self.decorator.top_height(self)+self.text_offset)
|
||||
self.tr.draw(self)
|
||||
|
||||
self.button_ok.draw(self,ctx,WIDTH-130,HEIGHT-60,100,30)
|
||||
if self.cancel_label:
|
||||
self.button_cancel.draw(self,ctx,WIDTH-240,HEIGHT-60,100,30)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
decor_event = self.decorator.handle_event(msg)
|
||||
if decor_event == yutani.Decor.EVENT_CLOSE:
|
||||
if self.close_is_cancel:
|
||||
self.cancel_click(None)
|
||||
else:
|
||||
self.ok_click(None)
|
||||
return
|
||||
elif decor_event == yutani.Decor.EVENT_RIGHT:
|
||||
self.decorator.show_menu(self, msg)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
redraw = False
|
||||
if self.down_button:
|
||||
if msg.command == yutani.MouseEvent.RAISE or msg.command == yutani.MouseEvent.CLICK:
|
||||
if not (msg.buttons & yutani.MouseButton.BUTTON_LEFT):
|
||||
if x >= self.down_button.x and \
|
||||
x < self.down_button.x + self.down_button.width and \
|
||||
y >= self.down_button.y and \
|
||||
y < self.down_button.y + self.down_button.height:
|
||||
self.down_button.focus_enter()
|
||||
if self.down_button.callback(self.down_button):
|
||||
redraw = True
|
||||
self.down_button = None
|
||||
else:
|
||||
self.down_button.focus_leave()
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
|
||||
else:
|
||||
button = None
|
||||
for b in self.buttons:
|
||||
if x >= b.x and x < b.x + b.width and y >= b.y and y < b.y + b.height:
|
||||
button = b
|
||||
break
|
||||
if button != self.hover_widget:
|
||||
if button:
|
||||
button.focus_enter()
|
||||
redraw = True
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = button
|
||||
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if button:
|
||||
button.hilight = 2
|
||||
self.down_button = button
|
||||
redraw = True
|
||||
if not button:
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = None
|
||||
|
||||
if redraw:
|
||||
self.draw()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action == yutani.KeyAction.ACTION_DOWN:
|
||||
if msg.event.key == b'\n':
|
||||
self.ok_click(None)
|
||||
|
||||
|
||||
class File(object):
|
||||
|
||||
def __init__(self, path,name=None):
|
||||
if not name:
|
||||
self.name = os.path.basename(path)
|
||||
else:
|
||||
self.name = name
|
||||
self.path = os.path.normpath(path)
|
||||
self.stat = os.stat(path)
|
||||
self.y = 0
|
||||
self.x = 0
|
||||
self.hilight = False
|
||||
self.tr = text_region.TextRegion(0,0,400,20)
|
||||
self.tr.set_one_line()
|
||||
self.tr.set_ellipsis()
|
||||
self.tr.set_text(self.name)
|
||||
|
||||
def do_action(self, dialog):
|
||||
if self.is_directory:
|
||||
dialog.load_directory(self.path)
|
||||
dialog.redraw_buf()
|
||||
return True
|
||||
else:
|
||||
dialog.path = self.path
|
||||
dialog.ok_click(None)
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_directory(self):
|
||||
return stat.S_ISDIR(self.stat.st_mode)
|
||||
|
||||
@property
|
||||
def is_executable(self):
|
||||
return stat.S_IXUSR & self.stat.st_mode and not self.is_directory
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
if self.is_directory: return get_icon('folder',16)
|
||||
if self.is_executable: return get_icon('applications-generic',16)
|
||||
return get_icon('file',16) # Need file icon
|
||||
|
||||
@property
|
||||
def sortkey(self):
|
||||
if self.is_directory: return "___" + self.name
|
||||
else: return "zzz" + self.name
|
||||
|
||||
|
||||
class OpenFileDialog(DialogWindow):
|
||||
|
||||
base_width = 500
|
||||
base_height = 450
|
||||
okay_label = "Open"
|
||||
|
||||
buf = None
|
||||
path = None
|
||||
icon_width = 16
|
||||
unit_height = 20
|
||||
|
||||
def __init__(self, decorator, title, glob=None, callback=None, cancel_callback=None,window=None):
|
||||
self.buf = None
|
||||
self.path = None
|
||||
if glob:
|
||||
self.matcher = re.compile(fnmatch.translate(glob))
|
||||
else:
|
||||
self.matcher = None
|
||||
self.tr = None
|
||||
self.load_directory(os.getcwd())
|
||||
self.redraw_buf()
|
||||
self.hilighted = None
|
||||
super(OpenFileDialog, self).__init__(decorator,title,"Open...",icon="open",callback=callback,cancel_callback=cancel_callback,window=window)
|
||||
self.tr.set_text(self.directory)
|
||||
|
||||
def ok_click(self, button):
|
||||
self.close()
|
||||
if self.callback:
|
||||
self.callback(self.path)
|
||||
return False
|
||||
|
||||
def load_directory(self, directory):
|
||||
self.directory = os.path.normpath(directory)
|
||||
if self.tr:
|
||||
self.tr.set_text(self.directory)
|
||||
self.files = sorted([File(os.path.join(self.directory,f)) for f in os.listdir(self.directory)],key=lambda x: x.sortkey)
|
||||
if self.matcher:
|
||||
self.files = [x for x in self.files if x.is_directory or self.matcher.match(x.name)]
|
||||
if directory != '/':
|
||||
self.files.insert(0,File(os.path.join(self.directory,'..'),'(Go up)'))
|
||||
self.scroll_y = 0
|
||||
|
||||
def redraw_buf(self,clips=None):
|
||||
if self.buf:
|
||||
self.buf.destroy()
|
||||
w = 450
|
||||
height = self.unit_height
|
||||
self.buf = yutani.GraphicsBuffer(w,len(self.files)*height)
|
||||
|
||||
surface = self.buf.get_cairo_surface()
|
||||
ctx = cairo.Context(surface)
|
||||
|
||||
if clips:
|
||||
for clip in clips:
|
||||
ctx.rectangle(clip.x,clip.y,w,height)
|
||||
ctx.clip()
|
||||
|
||||
ctx.rectangle(0,0,surface.get_width(),surface.get_height())
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
offset_y = 0
|
||||
|
||||
i = 0
|
||||
for f in self.files:
|
||||
f.y = offset_y
|
||||
if not clips or f in clips:
|
||||
tr = f.tr
|
||||
tr.move(26,offset_y+2)
|
||||
if f.hilight:
|
||||
gradient = cairo.LinearGradient(0,0,0,height-2)
|
||||
gradient.add_color_stop_rgba(0.0,*hilight_gradient_top,1.0)
|
||||
gradient.add_color_stop_rgba(1.0,*hilight_gradient_bottom,1.0)
|
||||
ctx.rectangle(0,offset_y,w,1)
|
||||
ctx.set_source_rgb(*hilight_border_top)
|
||||
ctx.fill()
|
||||
ctx.rectangle(0,offset_y+height-1,w,1)
|
||||
ctx.set_source_rgb(*hilight_border_bottom)
|
||||
ctx.fill()
|
||||
ctx.save()
|
||||
ctx.translate(0,offset_y+1)
|
||||
ctx.rectangle(0,0,w,height-2)
|
||||
ctx.set_source(gradient)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
tr.font.font_color = 0xFFFFFFFF
|
||||
else:
|
||||
ctx.rectangle(0,offset_y,w,height)
|
||||
if i % 2:
|
||||
ctx.set_source_rgb(0.9,0.9,0.9)
|
||||
else:
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
tr.font.font_color = 0xFF000000
|
||||
ctx.set_source_surface(f.icon,4,offset_y+2)
|
||||
ctx.paint()
|
||||
tr.draw(self.buf)
|
||||
offset_y += height
|
||||
i += 1
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
#ctx.set_source_surface(self.logo,30,30)
|
||||
#ctx.paint()
|
||||
|
||||
self.tr.resize(WIDTH,30)
|
||||
self.tr.move(self.decorator.left_width(self),self.decorator.top_height(self)+10)
|
||||
self.tr.set_alignment(2)
|
||||
self.tr.draw(self)
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(20, 40)
|
||||
ctx.rectangle(0,0,450,HEIGHT-130)
|
||||
ctx.set_line_width(2)
|
||||
ctx.set_source_rgb(0.7,0.7,0.7)
|
||||
ctx.stroke_preserve()
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
ctx.rectangle(0,0,450,HEIGHT-130)
|
||||
ctx.clip()
|
||||
text = self.buf.get_cairo_surface()
|
||||
ctx.set_source_surface(text,0,self.scroll_y)
|
||||
ctx.paint()
|
||||
ctx.restore()
|
||||
|
||||
self.button_cancel.draw(self,ctx,WIDTH-130,HEIGHT-60,100,30)
|
||||
self.button_ok.draw(self,ctx,WIDTH-240,HEIGHT-60,100,30)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def scroll(self, amount):
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
self.scroll_y += amount
|
||||
if self.scroll_y > 0:
|
||||
self.scroll_y = 0
|
||||
top = min(-(self.buf.height - (h-130)),0)
|
||||
if self.scroll_y < top:
|
||||
self.scroll_y = top
|
||||
|
||||
|
||||
def mouse_event(self, msg):
|
||||
super(OpenFileDialog,self).mouse_event(msg)
|
||||
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
if y < 0: return
|
||||
if x < 0 or x >= w: return
|
||||
|
||||
if msg.buttons & yutani.MouseButton.SCROLL_UP:
|
||||
self.scroll(30)
|
||||
self.draw()
|
||||
return
|
||||
elif msg.buttons & yutani.MouseButton.SCROLL_DOWN:
|
||||
self.scroll(-30)
|
||||
self.draw()
|
||||
return
|
||||
|
||||
offset_y = self.scroll_y + 40
|
||||
|
||||
redraw = []
|
||||
hit = False
|
||||
|
||||
if x >= 20 and x < 450+20:
|
||||
for f in self.files:
|
||||
if offset_y > h: break
|
||||
if y >= offset_y and y < offset_y + self.unit_height:
|
||||
if not f.hilight:
|
||||
redraw.append(f)
|
||||
if self.hilighted:
|
||||
redraw.append(self.hilighted)
|
||||
self.hilighted.hilight = False
|
||||
f.hilight = True
|
||||
self.hilighted = f
|
||||
hit = True
|
||||
break
|
||||
offset_y += self.unit_height
|
||||
|
||||
if not hit:
|
||||
if self.hilighted:
|
||||
redraw.append(self.hilighted)
|
||||
self.hilighted.hilight = False
|
||||
self.hilighted = None
|
||||
|
||||
if self.hilighted:
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if self.hilighted.do_action(self):
|
||||
redraw = []
|
||||
self.redraw_buf()
|
||||
self.draw()
|
||||
|
||||
if redraw:
|
||||
self.redraw_buf(redraw)
|
||||
self.draw()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
def okay(path):
|
||||
print("You hit Okay!",path)
|
||||
sys.exit(0)
|
||||
|
||||
def cancel():
|
||||
print("You hit Cancel!")
|
||||
sys.exit(0)
|
||||
|
||||
#window = DialogWindow(d,"Okay/Cancel Dialog","A thing happend!",cancel_callback=cancel,callback=okay)
|
||||
window = OpenFileDialog(d,"Open...",glob="*.png",cancel_callback=cancel,callback=okay)
|
||||
|
||||
yutani_mainloop.mainloop()
|
||||
|
@ -1,332 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
File Browser
|
||||
"""
|
||||
import os
|
||||
import math
|
||||
import stat
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
from menu_bar import MenuBarWidget, MenuEntryAction, MenuEntrySubmenu, MenuEntryDivider, MenuWindow
|
||||
from icon_cache import get_icon
|
||||
from about_applet import AboutAppletWindow
|
||||
from input_box import TextInputWindow
|
||||
from dialog import DialogWindow
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
app_name = "File Browser"
|
||||
version = "1.0.0"
|
||||
_description = f"<b>{app_name} {version}</b>\n© 2017-2018 K. Lange\n\nFile system navigator.\n\n<color 0x0000FF>http://github.com/klange/toaruos</color>"
|
||||
|
||||
class File(object):
|
||||
|
||||
def __init__(self, path, window):
|
||||
self.path = path
|
||||
self.name = os.path.basename(path)
|
||||
self.stat = os.stat(path)
|
||||
self.hilight = False
|
||||
self.window = window
|
||||
self.tr = text_region.TextRegion(0,0,100,20)
|
||||
self.tr.set_alignment(2)
|
||||
self.tr.set_ellipsis()
|
||||
self.tr.set_text(self.name)
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
|
||||
@property
|
||||
def is_directory(self):
|
||||
return stat.S_ISDIR(self.stat.st_mode)
|
||||
|
||||
@property
|
||||
def is_executable(self):
|
||||
return stat.S_IXUSR & self.stat.st_mode and not self.is_directory
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
if self.is_directory: return get_icon('folder',48)
|
||||
if self.is_executable: return get_icon(self.name,48)
|
||||
return get_icon('file',48) # Need file icon
|
||||
|
||||
def do_action(self):
|
||||
if self.is_directory:
|
||||
self.window.load_directory(self.path)
|
||||
self.window.draw()
|
||||
elif self.is_executable:
|
||||
subprocess.Popen([self.path])
|
||||
elif self.name.endswith('.png'):
|
||||
subprocess.Popen(['painting.py',self.path])
|
||||
elif self.name.endswith('.pdf') and os.path.exists('/usr/bin/pdfviewer.py'):
|
||||
subprocess.Popen(['pdfviewer.py',self.path])
|
||||
elif self.name.endswith('.pdf') and os.path.exists('/usr/bin/pdfviewer'):
|
||||
subprocess.Popen(['pdfviewer',self.path])
|
||||
# Nothing to do.
|
||||
|
||||
@property
|
||||
def sortkey(self):
|
||||
if self.is_directory: return "___" + self.name
|
||||
else: return "zzz" + self.name
|
||||
|
||||
|
||||
class FileBrowserWindow(yutani.Window):
|
||||
|
||||
base_width = 400
|
||||
base_height = 300
|
||||
|
||||
def __init__(self, decorator, path):
|
||||
super(FileBrowserWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=app_name, icon="folder", doublebuffer=True)
|
||||
self.move(100,100)
|
||||
self.decorator = decorator
|
||||
|
||||
def exit_app(action):
|
||||
menus = [x for x in self.menus.values()]
|
||||
for x in menus:
|
||||
x.definitely_close()
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
def about_window(action):
|
||||
AboutAppletWindow(self.decorator,f"About {app_name}","/usr/share/icons/48/folder.png",_description,"folder")
|
||||
def help_browser(action):
|
||||
subprocess.Popen(["help-browser.py","file_browser.trt"])
|
||||
|
||||
def input_path(action):
|
||||
def input_callback(input_window):
|
||||
text = input_window.tr.text
|
||||
input_window.close()
|
||||
self.load_directory(text)
|
||||
TextInputWindow(self.decorator,"Open directory...","open",text=self.path,callback=input_callback,window=self)
|
||||
|
||||
menus = [
|
||||
("File", [
|
||||
MenuEntryAction("Exit","exit",exit_app,None),
|
||||
]),
|
||||
("Go", [
|
||||
MenuEntryAction("Path...","open",input_path,None),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction("Home","home",self.load_directory,os.environ.get("HOME")),
|
||||
MenuEntryAction("File System",None,self.load_directory,"/"),
|
||||
MenuEntryAction("Up","up",self.go_up,None),
|
||||
]),
|
||||
("Help", [
|
||||
MenuEntryAction("Contents","help",help_browser,None),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction(f"About {app_name}","star",about_window,None),
|
||||
]),
|
||||
]
|
||||
|
||||
self.menubar = MenuBarWidget(self,menus)
|
||||
|
||||
self.hover_widget = None
|
||||
self.down_button = None
|
||||
|
||||
self.menus = {}
|
||||
self.hovered_menu = None
|
||||
|
||||
self.buf = None
|
||||
self.load_directory(path)
|
||||
self.hilighted = None
|
||||
|
||||
def go_up(self, action):
|
||||
self.load_directory(os.path.abspath(os.path.join(self.path,'..')))
|
||||
self.draw()
|
||||
|
||||
def load_directory(self, path):
|
||||
if not os.path.exists(path):
|
||||
DialogWindow(self.decorator,app_name,f"The path <mono>{path}</mono> could not be opened. (Not found)",window=self,icon='folder')
|
||||
return
|
||||
if not os.path.isdir(path):
|
||||
DialogWindow(self.decorator,app_name,f"The path <mono>{path}</mono> could not be opened. (Not a directory)",window=self,icon='folder')
|
||||
return
|
||||
path = os.path.normpath(path)
|
||||
self.path = path
|
||||
title = "/" if path == "/" else os.path.basename(path)
|
||||
self.set_title(f"{title} - {app_name}",'folder')
|
||||
|
||||
self.files = sorted([File(os.path.join(path,f), self) for f in os.listdir(path)], key=lambda x: x.sortkey)
|
||||
self.scroll_y = 0
|
||||
self.hilighted = None
|
||||
self.redraw_buf()
|
||||
|
||||
def redraw_buf(self,icons=None):
|
||||
if self.buf:
|
||||
self.buf.destroy()
|
||||
w = self.width - self.decorator.width(self)
|
||||
files_per_row = int(w / 100)
|
||||
self.buf = yutani.GraphicsBuffer(w,math.ceil(len(self.files)/files_per_row)*100)
|
||||
|
||||
surface = self.buf.get_cairo_surface()
|
||||
ctx = cairo.Context(surface)
|
||||
|
||||
if icons:
|
||||
for icon in icons:
|
||||
ctx.rectangle(icon.x,icon.y,100,100)
|
||||
ctx.clip()
|
||||
|
||||
|
||||
ctx.rectangle(0,0,surface.get_width(),surface.get_height())
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
offset_x = 0
|
||||
offset_y = 0
|
||||
|
||||
for f in self.files:
|
||||
if not icons or f in icons:
|
||||
x_, y_ = ctx.user_to_device(0,0)
|
||||
f.tr.move(offset_x,offset_y+60)
|
||||
f.tr.draw(self.buf)
|
||||
ctx.set_source_surface(f.icon,offset_x + 26,offset_y+10)
|
||||
ctx.paint_with_alpha(1.0 if not f.hilight else 0.7)
|
||||
f.x = offset_x
|
||||
f.y = offset_y
|
||||
offset_x += 100
|
||||
if offset_x + 100 > surface.get_width():
|
||||
offset_x = 0
|
||||
offset_y += 100
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(0,self.menubar.height)
|
||||
text = self.buf.get_cairo_surface()
|
||||
ctx.set_source_surface(text,0,self.scroll_y)
|
||||
ctx.paint()
|
||||
ctx.restore()
|
||||
|
||||
self.menubar.draw(ctx,0,0,WIDTH)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
if msg.width < 120 or msg.height < 120:
|
||||
self.resize_offer(max(msg.width,120),max(msg.height,120))
|
||||
return
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.redraw_buf()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def scroll(self, amount):
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
files_per_row = int(w / 100)
|
||||
rows_total = math.ceil(len(self.files) / files_per_row)
|
||||
rows_visible = int((h - 24) / 100)
|
||||
rows = rows_total - rows_visible
|
||||
if rows < 0: rows = 0
|
||||
self.scroll_y += amount
|
||||
if self.scroll_y > 0:
|
||||
self.scroll_y = 0
|
||||
if self.scroll_y < -100 * rows:
|
||||
self.scroll_y = -100 * rows
|
||||
|
||||
def mouse_event(self, msg):
|
||||
decor_event = d.handle_event(msg)
|
||||
if decor_event == yutani.Decor.EVENT_CLOSE:
|
||||
window.close()
|
||||
sys.exit(0)
|
||||
elif decor_event == yutani.Decor.EVENT_RIGHT:
|
||||
d.show_menu(self, msg)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
if x >= 0 and x < w and y >= 0 and y < self.menubar.height:
|
||||
self.menubar.mouse_event(msg, x, y)
|
||||
return
|
||||
|
||||
if x >= 0 and x < w and y >= self.menubar.height and y < h:
|
||||
if msg.buttons & yutani.MouseButton.SCROLL_UP:
|
||||
self.scroll(30)
|
||||
self.draw()
|
||||
return
|
||||
elif msg.buttons & yutani.MouseButton.SCROLL_DOWN:
|
||||
self.scroll(-30)
|
||||
self.draw()
|
||||
return
|
||||
|
||||
if msg.buttons & yutani.MouseButton.BUTTON_RIGHT:
|
||||
if not self.menus:
|
||||
menu_entries = [
|
||||
MenuEntryAction("Up","up",self.go_up,None),
|
||||
]
|
||||
menu = MenuWindow(menu_entries,(self.x+msg.new_x,self.y+msg.new_y),root=self)
|
||||
return
|
||||
|
||||
if y < 0: return
|
||||
|
||||
offset_x = 0
|
||||
offset_y = self.scroll_y + self.menubar.height
|
||||
|
||||
redraw = []
|
||||
|
||||
files_per_row = int(w / 100)
|
||||
rows_total = math.ceil(len(self.files) / files_per_row)
|
||||
skip_files = files_per_row * (int(-offset_y / 100))
|
||||
offset_y += int(-offset_y/100) * 100
|
||||
|
||||
hit = False
|
||||
for f in self.files[skip_files:]:
|
||||
if offset_y > h: break
|
||||
if offset_y > -100:
|
||||
if x >= offset_x and x < offset_x + 100 and y >= offset_y and y < offset_y + 100:
|
||||
if not f.hilight:
|
||||
redraw.append(f)
|
||||
if self.hilighted:
|
||||
redraw.append(self.hilighted)
|
||||
self.hilighted.hilight = False
|
||||
f.hilight = True
|
||||
self.hilighted = f
|
||||
hit = True
|
||||
break
|
||||
offset_x += 100
|
||||
if offset_x + 100 > w:
|
||||
offset_x = 0
|
||||
offset_y += 100
|
||||
if not hit:
|
||||
if self.hilighted:
|
||||
redraw.append(self.hilighted)
|
||||
self.hilighted.hilight = False
|
||||
self.hilighted = None
|
||||
|
||||
if self.hilighted:
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
self.hilighted.do_action()
|
||||
|
||||
if redraw:
|
||||
self.redraw_buf(redraw)
|
||||
self.draw()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action != yutani.KeyAction.ACTION_DOWN:
|
||||
return # Ignore anything that isn't a key down.
|
||||
if msg.event.key == b"q":
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
window = FileBrowserWindow(d,os.environ.get('HOME','/') if len(sys.argv) < 2 else sys.argv[1])
|
||||
window.draw()
|
||||
|
||||
yutani_mainloop.mainloop()
|
@ -1,20 +0,0 @@
|
||||
import ctypes
|
||||
|
||||
_lib = None
|
||||
|
||||
if not _lib:
|
||||
_lib = ctypes.CDLL('libc.so')
|
||||
_lib.syscall_fswait.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_int)]
|
||||
_lib.syscall_fswait.restype = ctypes.c_int
|
||||
_lib.syscall_fswait2.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_int),ctypes.c_int]
|
||||
_lib.syscall_fswait2.restype = ctypes.c_int
|
||||
|
||||
def fswait(files,timeout=None):
|
||||
fds = (ctypes.c_int * len(files))()
|
||||
for i in range(len(files)):
|
||||
fds[i] = files[i].fileno()
|
||||
if timeout is None:
|
||||
return _lib.syscall_fswait(len(fds),fds)
|
||||
else:
|
||||
return _lib.syscall_fswait2(len(fds),fds,timeout)
|
||||
|
@ -1,508 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Help Documentation Browser
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import toaru_fonts
|
||||
import text_region
|
||||
|
||||
from menu_bar import MenuBarWidget, MenuEntryAction, MenuEntrySubmenu, MenuEntryDivider, MenuWindow
|
||||
from about_applet import AboutAppletWindow
|
||||
from dialog import DialogWindow
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
app_name = "Help Browser"
|
||||
version = "1.0.0"
|
||||
_description = f"<b>{app_name} {version}</b>\n© 2017 Kevin Lange\n\nRich text help document viewer.\n\n<color 0x0000FF>http://github.com/klange/toaruos</color>"
|
||||
|
||||
class ScrollableText(object):
|
||||
|
||||
def __init__(self):
|
||||
self.tr = None
|
||||
self.width = 0
|
||||
self.height_ext = 0
|
||||
self.height_int = 0
|
||||
self.text_buffer = None
|
||||
self.background = (1,1,1)
|
||||
self.pad = 10
|
||||
|
||||
def destroy(self):
|
||||
if self.text_buffer:
|
||||
self.text_buffer.destroy()
|
||||
|
||||
def update(self, width):
|
||||
|
||||
needs_resize = False
|
||||
|
||||
if width != self.width:
|
||||
needs_resize = True
|
||||
self.width = width
|
||||
|
||||
self.tr.resize(self.width-self.pad*2, self.tr.line_height)
|
||||
h = self.tr.line_height * len(self.tr.lines) + self.pad*2
|
||||
if h != self.height_int:
|
||||
needs_resize = True
|
||||
self.height_int = h
|
||||
|
||||
if self.height_int - self.pad * 2 > 30000:
|
||||
# Shit...
|
||||
self.height_int = 30000 - self.pad * 2
|
||||
|
||||
self.tr.resize(self.width-self.pad*2, self.height_int-self.pad*2)
|
||||
self.tr.move(self.pad,self.pad)
|
||||
|
||||
if needs_resize or not self.text_buffer:
|
||||
if self.text_buffer:
|
||||
self.text_buffer.destroy()
|
||||
self.text_buffer = yutani.GraphicsBuffer(self.width,self.height_int)
|
||||
|
||||
surface = self.text_buffer.get_cairo_surface()
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.rectangle(0,0,surface.get_width(),surface.get_height())
|
||||
ctx.set_source_rgb(*self.background)
|
||||
ctx.fill()
|
||||
|
||||
self.tr.draw(self.text_buffer)
|
||||
|
||||
def scroll_max(self):
|
||||
if self.height_ext > self.height_int:
|
||||
return 0
|
||||
|
||||
return self.height_int - self.height_ext
|
||||
|
||||
|
||||
def draw(self,ctx,x,y,height,scroll):
|
||||
self.height_ext = height
|
||||
surface = self.text_buffer.get_cairo_surface()
|
||||
ctx.rectangle(x,y,self.width,height)
|
||||
ctx.set_source_surface(surface,x,y-scroll)
|
||||
ctx.fill()
|
||||
|
||||
class HelpBrowserWindow(yutani.Window):
|
||||
|
||||
base_width = 800
|
||||
base_height = 600
|
||||
|
||||
def __init__(self, decorator):
|
||||
super(HelpBrowserWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=app_name, icon="help", doublebuffer=True)
|
||||
self.move(100,100)
|
||||
self.decorator = decorator
|
||||
self.current_topic = "0_index.trt"
|
||||
self.text_buffer = None
|
||||
self.text_offset = 0
|
||||
self.tr = None
|
||||
self.size_changed = True
|
||||
self.text_scroller = ScrollableText()
|
||||
|
||||
self.special = {}
|
||||
self.special['contents'] = self.special_contents
|
||||
self.special['demo'] = self.special_demo
|
||||
self.down_text = None
|
||||
self.cache = {}
|
||||
self.history = []
|
||||
self.history_index = 0
|
||||
self.title_cache = {}
|
||||
|
||||
def herp(action):
|
||||
print(action)
|
||||
|
||||
self.history_menu = MenuEntrySubmenu('History...',[MenuEntryDivider()])
|
||||
|
||||
def exit_app(action):
|
||||
menus = [x for x in self.menus.values()]
|
||||
for x in menus:
|
||||
x.definitely_close()
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
|
||||
def about_window(action):
|
||||
AboutAppletWindow(self.decorator,f"About {app_name}","/usr/share/icons/48/help.png",_description,"help")
|
||||
|
||||
menus = [
|
||||
("File", [
|
||||
#MenuEntryAction("Open...",None,print_derp,None),
|
||||
#MenuEntryDivider(),
|
||||
MenuEntryAction("Exit","exit",exit_app,None),
|
||||
]),
|
||||
("Go", [
|
||||
MenuEntryAction("Home","home",self.go_page,"0_index.trt"),
|
||||
MenuEntryAction("Topics","bookmark",self.go_page,"special:contents"),
|
||||
MenuEntryDivider(),
|
||||
self.history_menu,
|
||||
MenuEntryAction("Back","back",self.go_back,None),
|
||||
MenuEntryAction("Forward","forward",self.go_forward,None),
|
||||
]),
|
||||
("Help", [
|
||||
MenuEntryAction("Contents","help",self.go_page,"help_browser.trt"),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction(f"About {app_name}","star",about_window,None),
|
||||
]),
|
||||
]
|
||||
|
||||
self.menubar = MenuBarWidget(self,menus)
|
||||
|
||||
self.menus = {}
|
||||
self.hovered_menu = None
|
||||
|
||||
self.update_text_buffer()
|
||||
self.navigate("0_index.trt")
|
||||
|
||||
|
||||
def get_title(self, document):
|
||||
if document.startswith("special:"):
|
||||
if document[8:] in self.special:
|
||||
return self.special[document[8:]].__doc__
|
||||
return "???"
|
||||
elif document.startswith("http:") or document.startswith('https:'):
|
||||
if document in self.title_cache:
|
||||
return self.title_cache[document]
|
||||
if document in self.cache:
|
||||
lines = self.cache[document].split('\n')
|
||||
for x in lines:
|
||||
x = x.strip()
|
||||
if x.startswith('<h1>') and x.endswith('</h1>'):
|
||||
return x[4:-5]
|
||||
return document.split('/')[-1].replace('.trt','').title()
|
||||
else:
|
||||
return document
|
||||
elif document.startswith("file:"):
|
||||
path = document.replace("file:","")
|
||||
else:
|
||||
path = f'/usr/share/help/{document}'
|
||||
if not os.path.exists(path):
|
||||
return "(file not found)"
|
||||
with open(path,'r') as f:
|
||||
lines = f.readlines()
|
||||
for x in lines:
|
||||
x = x.strip()
|
||||
if x.startswith('<h1>') and x.endswith('</h1>'):
|
||||
return x[4:-5]
|
||||
return document.replace('.trt','').title()
|
||||
|
||||
def special_contents(self):
|
||||
"""Table of Contents"""
|
||||
# List all things.
|
||||
output = "\n<h1>Table of Contents</h1>\n\nThis table of contents is automatically generated.\n\n"
|
||||
output += "<h2>Special Pages</h2>\n\n"
|
||||
for k in self.special:
|
||||
output += f"➤ <link target=\"special:{k}\">{self.special[k].__doc__}</link>\n"
|
||||
output += "\n<h2>Documentation</h2>\n\n"
|
||||
for k in sorted(os.listdir('/usr/share/help')):
|
||||
if k.endswith('.trt'):
|
||||
output += f"➤ <link target=\"{k}\">{self.get_title(k)}</link>\n"
|
||||
for directory,_,files in os.walk('/usr/share/help'):
|
||||
if directory == '/usr/share/help':
|
||||
continue
|
||||
files = sorted([x for x in files if not x.startswith('.')])
|
||||
if files:
|
||||
d = directory.replace('/usr/share/help/','')
|
||||
output += "\n<h3>" + d.title() + "</h3>\n\n"
|
||||
for k in files:
|
||||
if k.endswith('.trt'):
|
||||
k = d + '/' + k
|
||||
output += f"➤ <link target=\"{k}\">{self.get_title(k)}</link>\n"
|
||||
return output
|
||||
|
||||
def special_demo(self):
|
||||
"""Formatting demo"""
|
||||
return f"""
|
||||
|
||||
<h1>This is a big header</h1>
|
||||
This is text below that.
|
||||
<h2>This is a medium header</h2>
|
||||
|
||||
<h3>This is a small header</h3>
|
||||
|
||||
This is normal text. <b>This is bold text.</b> <i>This is italic text.</i> <b><i>This is both.</i></b>
|
||||
<link target=\"0_index.trt\">go home</link>"""
|
||||
|
||||
def get_cache(self, url):
|
||||
if url in self.cache:
|
||||
return self.cache[url]
|
||||
else:
|
||||
try:
|
||||
text = subprocess.check_output(['fetch',url])
|
||||
if text.startswith(b'\x89PNG'):
|
||||
text = f"<html><body><img src=\"{url}\"></body></html>"
|
||||
else:
|
||||
text = text.decode('utf-8')
|
||||
except:
|
||||
text = '\n<h1>Error</h1>\n\nThere was an error obtaining this file.'
|
||||
self.cache[url] = text
|
||||
return text
|
||||
|
||||
def get_document_text(self):
|
||||
if self.current_topic.startswith("special:"):
|
||||
if self.current_topic[8:] in self.special:
|
||||
return self.special[self.current_topic[8:]]()
|
||||
elif self.current_topic.startswith("http:") or self.current_topic.startswith('https:'):
|
||||
# Good luck
|
||||
return self.get_cache(self.current_topic)
|
||||
elif self.current_topic.startswith("file:"):
|
||||
path = self.current_topic.replace("file:","")
|
||||
else:
|
||||
path = f'/usr/share/help/{self.current_topic}'
|
||||
if os.path.exists(path):
|
||||
with open(path,'r') as f:
|
||||
return f.read()
|
||||
return f"""
|
||||
<h1>Document Not Found</h1>
|
||||
|
||||
Uh oh, looks like the help document you tried to open ({self.current_topic}) wasn't available. Do you want to <link target=\"0_index.trt\">return to the index</link>?
|
||||
|
||||
You can also <link target=\"special:contents\">check the Table of Contents</link>.
|
||||
|
||||
"""
|
||||
|
||||
def is_html(self):
|
||||
if self.current_topic.endswith('.html') or self.current_topic.endswith('.htm'): return True
|
||||
if self.current_topic.startswith('http') and not self.current_topic.endswith('.trt'): return True
|
||||
if '<html' in self.get_document_text(): return True
|
||||
return False
|
||||
|
||||
def update_history(self):
|
||||
def go_history(action):
|
||||
self.navigate(self.history[action],touch_history=False)
|
||||
self.history_index = action
|
||||
self.update_history()
|
||||
entries = []
|
||||
for x in range(len(self.history)):
|
||||
t = self.get_title(self.history[x])
|
||||
e = MenuEntryAction(t,None,go_history,x)
|
||||
if x == self.history_index:
|
||||
e.title = f'<b>{t}</b>'
|
||||
e.rich = True
|
||||
e.update_text()
|
||||
entries.append(e)
|
||||
entries.reverse()
|
||||
self.history_menu.entries = entries
|
||||
|
||||
def navigate(self, target, touch_history=True):
|
||||
#if target.startswith('https:'):
|
||||
# DialogWindow(self.decorator,app_name,f"<mono>https</mono> is not supported. Could not load the URL <mono>{target}</mono>",callback=lambda: None,window=self,cancel_label=False)
|
||||
# return
|
||||
if touch_history:
|
||||
del self.history[self.history_index+1:]
|
||||
self.history.append(target)
|
||||
self.history_index = len(self.history)-1
|
||||
self.current_topic = target
|
||||
self.text_offset = 0
|
||||
if self.is_html():
|
||||
self.tr.base_dir = os.path.dirname(target) + '/'
|
||||
else:
|
||||
self.tr.base_dir = '/usr/share/help/'
|
||||
self.tr.set_richtext(self.get_document_text(),html=self.is_html())
|
||||
self.update_text_buffer()
|
||||
if self.tr.title:
|
||||
self.set_title(f"{self.tr.title} - {app_name}","help")
|
||||
self.title_cache[target] = self.tr.title
|
||||
else:
|
||||
self.set_title(f"{self.get_title(self.current_topic)} - {app_name}","help")
|
||||
self.update_history()
|
||||
|
||||
def update_text_buffer(self):
|
||||
if not self.tr:
|
||||
self.tr = text_region.TextRegion(0,0,100,100)
|
||||
self.tr.set_line_height(18)
|
||||
self.tr.base_dir = '/usr/share/help/'
|
||||
self.tr.set_richtext(self.get_document_text(),html=self.is_html())
|
||||
self.text_scroller.tr = self.tr
|
||||
|
||||
if self.size_changed:
|
||||
self.text_scroller.update(self.width - self.decorator.width())
|
||||
|
||||
#self.tr.scroll = self.scroll_offset
|
||||
#self.tr.draw(self.text_buffer)
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(), self.height - self.decorator.height()
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(), self.decorator.top_height())
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
#ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(0,self.menubar.height)
|
||||
"""
|
||||
text = self.text_buffer.get_cairo_surface()
|
||||
ctx.set_source_surface(text,0,-self.text_offset)
|
||||
ctx.paint()
|
||||
"""
|
||||
self.text_scroller.draw(ctx,0,0,HEIGHT-self.menubar.height,self.text_offset)
|
||||
ctx.restore()
|
||||
|
||||
self.menubar.draw(ctx,0,0,WIDTH)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
if msg.width < 100 or msg.height < 100:
|
||||
self.resize_offer(max(msg.width,100),max(msg.height,100))
|
||||
return
|
||||
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.size_changed = True
|
||||
self.update_text_buffer()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def scroll(self, amount):
|
||||
self.text_offset += amount
|
||||
if self.text_offset < 0:
|
||||
self.text_offset = 0
|
||||
if self.text_offset > self.text_scroller.scroll_max():
|
||||
self.text_offset = self.text_scroller.scroll_max()
|
||||
|
||||
def text_under_cursor(self, msg):
|
||||
"""Get the text unit under the cursor."""
|
||||
x = msg.new_x - self.decorator.left_width()
|
||||
y = msg.new_y - self.decorator.top_height() + self.text_offset - self.menubar.height
|
||||
return self.tr.click(x,y)
|
||||
|
||||
|
||||
def go_page(self, action):
|
||||
"""Navigate to a page."""
|
||||
self.navigate(action)
|
||||
self.draw()
|
||||
|
||||
def go_back(self,action):
|
||||
"""Go back."""
|
||||
if self.history and self.history_index > 0:
|
||||
self.history_index -= 1
|
||||
self.navigate(self.history[self.history_index], touch_history=False)
|
||||
self.update_history()
|
||||
self.draw()
|
||||
|
||||
def go_forward(self,action):
|
||||
"""Go forward."""
|
||||
if self.history and self.history_index < len(self.history)-1:
|
||||
self.history_index += 1
|
||||
self.navigate(self.history[self.history_index], touch_history=False)
|
||||
self.update_history()
|
||||
self.draw()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
if self.mouse_check(msg):
|
||||
self.draw()
|
||||
|
||||
def mouse_check(self, msg):
|
||||
if d.handle_event(msg) == yutani.Decor.EVENT_CLOSE:
|
||||
window.close()
|
||||
sys.exit(0)
|
||||
x,y = msg.new_x - self.decorator.left_width(), msg.new_y - self.decorator.top_height()
|
||||
w,h = self.width - self.decorator.width(), self.height - self.decorator.height()
|
||||
if x >= 0 and x < w and y >= 0 and y < self.menubar.height:
|
||||
self.menubar.mouse_event(msg, x, y)
|
||||
|
||||
if x >= 0 and x < w and y >= self.menubar.height and y < h:
|
||||
if msg.buttons & yutani.MouseButton.BUTTON_RIGHT:
|
||||
if not self.menus:
|
||||
menu_entries = [
|
||||
MenuEntryAction("Back","back",self.go_back,None),
|
||||
MenuEntryAction("Forward","forward",self.go_forward,None),
|
||||
]
|
||||
menu = MenuWindow(menu_entries,(self.x+msg.new_x,self.y+msg.new_y),root=self)
|
||||
if msg.buttons & yutani.MouseButton.SCROLL_UP:
|
||||
self.scroll(-30)
|
||||
return True
|
||||
elif msg.buttons & yutani.MouseButton.SCROLL_DOWN:
|
||||
self.scroll(30)
|
||||
return True
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
e = self.text_under_cursor(msg)
|
||||
r = False
|
||||
if self.down_text and e != self.down_text:
|
||||
for u in self.down_text.tag_group:
|
||||
if u.unit_type == 4:
|
||||
u.set_extra('hilight',False)
|
||||
else:
|
||||
u.set_font(self.down_font[u])
|
||||
del self.down_font
|
||||
self.down_text = None
|
||||
self.update_text_buffer()
|
||||
r = True
|
||||
if e and 'link' in e.extra and e.tag_group:
|
||||
self.down_font = {}
|
||||
for u in e.tag_group:
|
||||
if u.unit_type == 4:
|
||||
u.set_extra('hilight',True)
|
||||
else:
|
||||
new_font = toaru_fonts.Font(u.font.font_number,u.font.font_size,0xFFFF0000)
|
||||
self.down_font[u] = u.font
|
||||
u.set_font(new_font)
|
||||
self.update_text_buffer()
|
||||
r = True
|
||||
self.down_text = e
|
||||
else:
|
||||
self.down_text = None
|
||||
return r
|
||||
if msg.command == yutani.MouseEvent.CLICK or msg.command == yutani.MouseEvent.RAISE:
|
||||
e = self.text_under_cursor(msg)
|
||||
if self.down_text and e == self.down_text:
|
||||
self.navigate(e.extra['link'])
|
||||
return True
|
||||
elif self.down_text:
|
||||
for u in self.down_text.tag_group:
|
||||
if u.unit_type == 4:
|
||||
u.set_extra('hilight',False)
|
||||
else:
|
||||
u.set_font(self.down_font[u])
|
||||
del self.down_font
|
||||
self.down_text = None
|
||||
self.update_text_buffer()
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if self.keyboard_check(msg):
|
||||
self.draw()
|
||||
|
||||
def keyboard_check(self,msg):
|
||||
if msg.event.action != 0x01:
|
||||
return False # Ignore anything that isn't a key down.
|
||||
if msg.event.keycode == yutani.Keycode.HOME:
|
||||
self.text_offset = 0
|
||||
return True
|
||||
elif msg.event.keycode == yutani.Keycode.END:
|
||||
n = (len(self.tr.lines)-self.tr.visible_lines())+5
|
||||
self.text_offset = self.text_scroller.scroll_max()
|
||||
return True
|
||||
elif msg.event.keycode == yutani.Keycode.PAGE_UP:
|
||||
self.scroll(int(-self.height/2))
|
||||
return True
|
||||
elif msg.event.keycode == yutani.Keycode.PAGE_DOWN:
|
||||
self.scroll(int(self.height/2))
|
||||
return True
|
||||
elif msg.event.key == b"q":
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
window = HelpBrowserWindow(d)
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
window.navigate(sys.argv[-1])
|
||||
|
||||
window.draw()
|
||||
|
||||
yutani_mainloop.mainloop()
|
@ -1,54 +0,0 @@
|
||||
"""
|
||||
Library for caching Cairo surfaces for icons by name and size.
|
||||
"""
|
||||
import os
|
||||
import cairo
|
||||
import yutani
|
||||
|
||||
icon_directories = {
|
||||
16: [
|
||||
"/usr/share/icons/16",
|
||||
"/usr/share/icons/external/16",
|
||||
"/usr/share/icons/24",
|
||||
"/usr/share/icons/external/24",
|
||||
"/usr/share/icons/48",
|
||||
"/usr/share/icons/external/48",
|
||||
"/usr/share/icons",
|
||||
"/usr/share/icons/external",
|
||||
],
|
||||
24: [
|
||||
"/usr/share/icons/24",
|
||||
"/usr/share/icons/external/24",
|
||||
"/usr/share/icons/48",
|
||||
"/usr/share/icons/external/48",
|
||||
"/usr/share/icons",
|
||||
"/usr/share/icons/external",
|
||||
],
|
||||
48: [
|
||||
"/usr/share/icons/48",
|
||||
"/usr/share/icons/external/48",
|
||||
"/usr/share/icons",
|
||||
"/usr/share/icons/external",
|
||||
"/usr/share/icons/24",
|
||||
"/usr/share/icons/external/24",
|
||||
],
|
||||
}
|
||||
|
||||
icon_cache = {24:{},48:{},16:{}}
|
||||
def get_icon(name,size=24,fallback='applications-generic'):
|
||||
"""Find an icon in the icon cache or fetch it if possible."""
|
||||
if not name:
|
||||
return get_icon(fallback,size)
|
||||
|
||||
if not name in icon_cache[size]:
|
||||
for directory in icon_directories[size]:
|
||||
path = f"{directory}/{name}.bmp"
|
||||
if os.access(path,os.R_OK):
|
||||
#icon = cairo.ImageSurface.create_from_png(f"{directory}/{name}.png")
|
||||
icon = yutani.Sprite.from_file(f"{directory}/{name}.bmp").get_cairo_surface()
|
||||
icon_cache[size][name] = icon
|
||||
return icon
|
||||
return get_icon(fallback,size)
|
||||
else:
|
||||
return icon_cache[size][name]
|
||||
|
@ -1,439 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Shows an input box.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
import fswait
|
||||
|
||||
from button import Button
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
def rounded_rectangle(ctx,x,y,w,h,r):
|
||||
degrees = math.pi / 180
|
||||
ctx.new_sub_path()
|
||||
|
||||
ctx.arc(x + w - r, y + r, r, -90 * degrees, 0 * degrees)
|
||||
ctx.arc(x + w - r, y + h - r, r, 0 * degrees, 90 * degrees)
|
||||
ctx.arc(x + r, y + h - r, r, 90 * degrees, 180 * degrees)
|
||||
ctx.arc(x + r, y + r, r, 180 * degrees, 270 * degrees)
|
||||
ctx.close_path()
|
||||
|
||||
def draw_input_box(ctx,x,y,w,h,focused):
|
||||
# Outer
|
||||
rounded_rectangle(ctx,x,y,w,h,4)
|
||||
if focused:
|
||||
ctx.set_source_rgb(0x8E/0xFF,0xD8/0xFF,1)
|
||||
else:
|
||||
ctx.set_source_rgb(192/255,192/255,192/255)
|
||||
ctx.fill()
|
||||
|
||||
# Inner
|
||||
rounded_rectangle(ctx,x+1,y+1,w-2,h-2,4)
|
||||
if focused:
|
||||
ctx.set_source_rgb(246/255,246/255,246/255)
|
||||
else:
|
||||
ctx.set_source_rgb(234/255,234/255,234/255)
|
||||
ctx.fill()
|
||||
|
||||
class InputBox(object):
|
||||
|
||||
padding = 5
|
||||
cursor_height = 15
|
||||
text_offset = 2
|
||||
color = 0xFF000000
|
||||
ph_color = 0x88000000
|
||||
ctrl_chars = [' ','/']
|
||||
|
||||
def __init__(self,text="",password=False,placeholder="",width=200,height=20):
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, self.color)
|
||||
self.tr = text_region.TextRegion(0,0,200,20,font=self.font)
|
||||
self.width = width
|
||||
self.height = height
|
||||
|
||||
self.placeholder = placeholder
|
||||
self.ph_font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, self.ph_color)
|
||||
self.ph_tr = text_region.TextRegion(0,0,200,20,font=self.ph_font)
|
||||
self.ph_tr.set_text(placeholder)
|
||||
|
||||
self.is_password = password
|
||||
self.tr.set_one_line()
|
||||
self.tr.break_all = True
|
||||
self.update_text(text)
|
||||
self.is_focused = False
|
||||
self.cursor_index = len(self.text)
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
|
||||
if password:
|
||||
self.ctrl_chars = []
|
||||
|
||||
self.x = 0
|
||||
self.y = 0
|
||||
|
||||
self.text_changed = None
|
||||
|
||||
self.submit = None
|
||||
self.tab_handler = None
|
||||
|
||||
def draw(self,window,ctx):
|
||||
self.parent = window
|
||||
x_, y_ = ctx.user_to_device(0,0)
|
||||
|
||||
self.x = int(x_)
|
||||
self.y = int(y_)
|
||||
|
||||
draw_input_box(ctx,0,0,self.width,self.height,self.is_focused)
|
||||
|
||||
self.tr.resize(self.width - self.padding * 2, self.height)
|
||||
self.tr.move(self.x + self.padding,self.y + self.text_offset)
|
||||
|
||||
if not self.is_focused and not self.text and self.placeholder:
|
||||
self.ph_tr.resize(self.width - self.padding * 2, self.height)
|
||||
self.ph_tr.move(self.x + self.padding,self.y + self.text_offset)
|
||||
self.ph_tr.draw(window)
|
||||
else:
|
||||
self.tr.draw(window)
|
||||
|
||||
if self.cursor_x is not None and self.is_focused:
|
||||
ctx.rectangle(self.cursor_x + self.padding, self.text_offset, 1, self.cursor_height)
|
||||
ctx.set_source_rgb(0,0,0)
|
||||
ctx.fill()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if msg.new_x >= self.x and msg.new_x < self.x + self.width and \
|
||||
msg.new_y >= self.y and msg.new_y < self.y + self.height:
|
||||
self.focus_enter()
|
||||
changed = False
|
||||
u,l = self.tr.pick(msg.new_x,msg.new_y)
|
||||
if u:
|
||||
changed = True
|
||||
self.cursor_x = l[1]
|
||||
self.cursor_index = l[3]
|
||||
if (l[2]-l[1]) > u.width / 2:
|
||||
self.cursor_x += u.width
|
||||
self.cursor_index += 1
|
||||
elif l:
|
||||
changed = True
|
||||
self.cursor_x = l[1]
|
||||
self.cursor_index = l[3]
|
||||
if changed:
|
||||
self.update()
|
||||
return True
|
||||
return False
|
||||
|
||||
def update(self):
|
||||
self.parent.draw()
|
||||
|
||||
def update_text(self, new_text):
|
||||
self.text = new_text
|
||||
if self.is_password:
|
||||
self.tr.set_text("●" * len(new_text))
|
||||
else:
|
||||
self.tr.set_text(new_text)
|
||||
|
||||
def reset_cursor(self):
|
||||
self.cursor_index = 0
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
|
||||
def focus_enter(self):
|
||||
if not self.is_focused:
|
||||
self.is_focused = True
|
||||
self.update()
|
||||
|
||||
def focus_leave(self):
|
||||
if self.is_focused:
|
||||
self.is_focused = False
|
||||
self.update()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action == yutani.KeyAction.ACTION_DOWN:
|
||||
if self.cursor_x is not None:
|
||||
if msg.event.key == b'\x08':
|
||||
if msg.event.modifiers & yutani.Modifier.MOD_LEFT_CTRL:
|
||||
new_c = self.cursor_index
|
||||
while new_c > 0 and self.text[new_c-1] in self.ctrl_chars:
|
||||
new_c -= 1
|
||||
while new_c > 0 and self.text[new_c-1] not in self.ctrl_chars:
|
||||
new_c -= 1
|
||||
text = self.text
|
||||
before = text[:new_c]
|
||||
after = text[self.cursor_index:]
|
||||
self.update_text(before + after)
|
||||
self.cursor_index = new_c
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
if self.text_changed:
|
||||
self.text_changed(self)
|
||||
self.update()
|
||||
else:
|
||||
if self.cursor_index > 0:
|
||||
text = self.text
|
||||
before = text[:self.cursor_index-1]
|
||||
after = text[self.cursor_index:]
|
||||
self.update_text(before + after)
|
||||
self.cursor_index -= 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
if self.text_changed:
|
||||
self.text_changed(self)
|
||||
self.update()
|
||||
elif msg.event.key == b'\t':
|
||||
if self.tab_handler:
|
||||
self.tab_handler()
|
||||
elif msg.event.keycode == yutani.Keycode.ARROW_LEFT:
|
||||
if msg.event.modifiers & yutani.Modifier.MOD_LEFT_CTRL:
|
||||
while self.cursor_index > 0 and self.text[self.cursor_index-1] in self.ctrl_chars:
|
||||
self.cursor_index -= 1
|
||||
while self.cursor_index > 0 and self.text[self.cursor_index-1] not in self.ctrl_chars:
|
||||
self.cursor_index -= 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
else:
|
||||
if self.cursor_index > 0:
|
||||
self.cursor_index -= 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
elif msg.event.keycode == yutani.Keycode.ARROW_RIGHT:
|
||||
if msg.event.modifiers & yutani.Modifier.MOD_LEFT_CTRL:
|
||||
while self.cursor_index < len(self.text) and self.text[self.cursor_index] in self.ctrl_chars:
|
||||
self.cursor_index += 1
|
||||
while self.cursor_index < len(self.text) and self.text[self.cursor_index] not in self.ctrl_chars:
|
||||
self.cursor_index += 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
else:
|
||||
if self.cursor_index < len(self.text):
|
||||
self.cursor_index += 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
elif msg.event.keycode == yutani.Keycode.END:
|
||||
self.cursor_index = len(self.text)
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
elif msg.event.keycode == yutani.Keycode.HOME:
|
||||
self.cursor_index = 0
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
self.update()
|
||||
elif msg.event.keycode == yutani.Keycode.DEL:
|
||||
if msg.event.modifiers & yutani.Modifier.MOD_LEFT_CTRL:
|
||||
new_c = self.cursor_index
|
||||
while new_c < len(self.text) and self.text[new_c] in self.ctrl_chars:
|
||||
new_c += 1
|
||||
while new_c < len(self.text) and self.text[new_c] not in self.ctrl_chars:
|
||||
new_c += 1
|
||||
text = self.text
|
||||
before = text[:self.cursor_index]
|
||||
after = text[new_c+1:]
|
||||
self.update_text(before + after)
|
||||
if self.text_changed:
|
||||
self.text_changed(self)
|
||||
self.update()
|
||||
else:
|
||||
if self.cursor_index < len(self.text):
|
||||
text = self.text
|
||||
before = text[:self.cursor_index]
|
||||
after = text[self.cursor_index+1:]
|
||||
self.update_text(before + after)
|
||||
if self.text_changed:
|
||||
self.text_changed(self)
|
||||
self.update()
|
||||
elif msg.event.key == b'\n':
|
||||
if self.submit:
|
||||
self.submit()
|
||||
elif msg.event.key != b'\x00':
|
||||
text = self.text
|
||||
before = text[:self.cursor_index]
|
||||
after = text[self.cursor_index:]
|
||||
self.update_text(before + msg.event.key.decode('utf-8') + after)
|
||||
self.cursor_index += 1
|
||||
self.cursor_x = self.tr.get_offset_at_index(self.cursor_index)[1][1]
|
||||
if self.text_changed:
|
||||
self.text_changed(self)
|
||||
self.update()
|
||||
|
||||
|
||||
class TextInputWindow(yutani.Window):
|
||||
|
||||
base_width = 500
|
||||
base_height = 120
|
||||
|
||||
text_offset = 22
|
||||
|
||||
okay_label = "Okay"
|
||||
cancel_label = "Cancel"
|
||||
|
||||
def __init__(self, decorator, title, icon, text="", text_changed=None, callback=None,window=None,cancel_callback=None):
|
||||
super(TextInputWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, icon=icon, doublebuffer=True)
|
||||
if window:
|
||||
# Center window
|
||||
self.move(window.x+int((window.width-self.width)/2),window.y+int((window.height-self.height)/2))
|
||||
else:
|
||||
# Center screen
|
||||
self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
|
||||
self.decorator = decorator
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)
|
||||
|
||||
# Initialize here
|
||||
self.input = InputBox(text=text)
|
||||
self.input.text_changed = text_changed
|
||||
self.input.submit = self.ok_click
|
||||
self.input.is_focused = True
|
||||
|
||||
self.text_changed = text_changed
|
||||
self.callback = callback
|
||||
self.cancel_callback = cancel_callback
|
||||
|
||||
self.button_ok = Button(self.okay_label,self.ok_click)
|
||||
self.button_cancel = Button(self.cancel_label,self.cancel_click)
|
||||
self.buttons = [self.button_ok, self.button_cancel]
|
||||
|
||||
self.hover_widget = None
|
||||
self.down_button = None
|
||||
|
||||
# For backwards compatibility with old API
|
||||
self.tr = lambda: None
|
||||
|
||||
def text(self):
|
||||
return self.input.text
|
||||
|
||||
|
||||
def cancel_click(self, button):
|
||||
self.close()
|
||||
if __name__ == '__main__':
|
||||
sys.exit(0)
|
||||
if self.cancel_callback:
|
||||
self.cancel_callback()
|
||||
|
||||
def ok_click(self, button=None):
|
||||
self.tr.text = self.text()
|
||||
if self.callback:
|
||||
self.callback(self)
|
||||
|
||||
def draw(self):
|
||||
if self.closed: return
|
||||
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
# XXX draw here
|
||||
ctx.save()
|
||||
ctx.translate(15,self.text_offset)
|
||||
self.input.width = WIDTH-30
|
||||
self.input.draw(self,ctx)
|
||||
ctx.restore()
|
||||
|
||||
self.button_ok.draw(self,ctx,WIDTH-130,HEIGHT-60,100,30)
|
||||
self.button_cancel.draw(self,ctx,WIDTH-240,HEIGHT-60,100,30)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.int_width = msg.width - self.decorator.width(self)
|
||||
self.int_height = msg.height - self.decorator.height(self)
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
if self.closed: return
|
||||
if self.decorator.handle_event(msg) == yutani.Decor.EVENT_CLOSE:
|
||||
self.cancel_click(None)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
redraw = False
|
||||
if self.down_button:
|
||||
if msg.command == yutani.MouseEvent.RAISE or msg.command == yutani.MouseEvent.CLICK:
|
||||
if not (msg.buttons & yutani.MouseButton.BUTTON_LEFT):
|
||||
if x >= self.down_button.x and \
|
||||
x < self.down_button.x + self.down_button.width and \
|
||||
y >= self.down_button.y and \
|
||||
y < self.down_button.y + self.down_button.height:
|
||||
self.down_button.focus_enter()
|
||||
if self.down_button.callback(self.down_button):
|
||||
redraw = True
|
||||
self.down_button = None
|
||||
else:
|
||||
self.down_button.focus_leave()
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
|
||||
else:
|
||||
button = None
|
||||
for b in self.buttons:
|
||||
if x >= b.x and x < b.x + b.width and y >= b.y and y < b.y + b.height:
|
||||
button = b
|
||||
break
|
||||
if button != self.hover_widget:
|
||||
if button:
|
||||
button.focus_enter()
|
||||
redraw = True
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = button
|
||||
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if button:
|
||||
button.hilight = 2
|
||||
self.down_button = button
|
||||
redraw = True
|
||||
if not button:
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = None
|
||||
|
||||
if not self.closed:
|
||||
if self.input.mouse_event(msg):
|
||||
changed = True
|
||||
elif msg.command == yutani.MouseEvent.DOWN:
|
||||
changed = self.input.focus_leave()
|
||||
# Do unfocus stuff here
|
||||
else:
|
||||
changed = False
|
||||
|
||||
if changed or redraw:
|
||||
self.draw()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
if msg.event.action == yutani.KeyAction.ACTION_DOWN:
|
||||
if not self.input.is_focused:
|
||||
self.input.focus_enter()
|
||||
self.input.keyboard_event(msg)
|
||||
# Do keyboard stuff here
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
title = "Input Box" if len(sys.argv) < 2 else sys.argv[1]
|
||||
icon = "default" if len(sys.argv) < 3 else sys.argv[2]
|
||||
|
||||
def print_text(text_box):
|
||||
print(text_box.text())
|
||||
sys.exit(0)
|
||||
|
||||
window = TextInputWindow(d,title,icon,callback=print_text)
|
||||
window.draw()
|
||||
|
||||
yutani_mainloop.mainloop()
|
||||
|
@ -1,429 +0,0 @@
|
||||
"""
|
||||
Provides basic nested menus.
|
||||
"""
|
||||
import cairo
|
||||
import math
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
from icon_cache import get_icon
|
||||
|
||||
menu_windows = {}
|
||||
|
||||
def close_enough(msg):
|
||||
return msg.command == yutani.MouseEvent.RAISE and \
|
||||
math.sqrt((msg.new_x - msg.old_x) ** 2 + (msg.new_y - msg.old_y) ** 2) < 10
|
||||
|
||||
class MenuBarWidget(object):
|
||||
"""Widget for display multiple menus."""
|
||||
|
||||
height = 24
|
||||
hilight_gradient_top = (93/255,163/255,236/255)
|
||||
hilight_gradient_bottom = (56/255,137/255,220/255)
|
||||
|
||||
def __init__(self, window, entries):
|
||||
self.window = window
|
||||
self.entries = entries
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF,13,0xFFFFFFFF)
|
||||
self.active_menu = None
|
||||
self.active_entry = None
|
||||
self.gradient = cairo.LinearGradient(0,0,0,self.height)
|
||||
self.gradient.add_color_stop_rgba(0.0,*self.hilight_gradient_top,1.0)
|
||||
self.gradient.add_color_stop_rgba(1.0,*self.hilight_gradient_bottom,1.0)
|
||||
|
||||
def draw(self, cr, x, y, width):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.width = width
|
||||
|
||||
cr.save()
|
||||
cr.set_source_rgb(59/255,59/255,59/255)
|
||||
cr.rectangle(0,0,width,self.height)
|
||||
cr.fill()
|
||||
cr.restore()
|
||||
|
||||
menus = self.window.menus
|
||||
|
||||
x_, y_ = cr.user_to_device(x,y)
|
||||
offset = 0
|
||||
for e in self.entries:
|
||||
title, _ = e
|
||||
w = self.font.width(title) + 10
|
||||
if self.active_menu in menus.values() and e == self.active_entry:
|
||||
cr.rectangle(offset+2,0,w+2,self.height)
|
||||
cr.set_source(self.gradient)
|
||||
cr.fill()
|
||||
tr = text_region.TextRegion(int(x_)+8+offset,int(y_)+2,w,self.height,self.font)
|
||||
tr.set_one_line()
|
||||
tr.set_text(title)
|
||||
tr.draw(self.window)
|
||||
offset += w
|
||||
|
||||
def mouse_event(self, msg, x, y):
|
||||
offset = 0
|
||||
for e in self.entries:
|
||||
title, menu = e
|
||||
w = self.font.width(title) + 10
|
||||
if x >= offset and x < offset + w:
|
||||
if msg.command == yutani.MouseEvent.CLICK or close_enough(msg):
|
||||
menu = MenuWindow(menu,(self.window.x+self.window.decorator.left_width(self.window)+offset,self.window.y+self.window.decorator.top_height(self.window)+self.height),root=self.window)
|
||||
self.active_menu = menu
|
||||
self.active_entry = e
|
||||
elif self.active_menu and self.active_menu in self.window.menus.values() and e != self.active_entry:
|
||||
self.active_menu.definitely_close()
|
||||
menu = MenuWindow(menu,(self.window.x+self.window.decorator.left_width(self.window)+offset,self.window.y+self.window.decorator.top_height(self.window)+self.height),root=self.window)
|
||||
self.active_menu = menu
|
||||
self.active_entry = e
|
||||
self.window.draw()
|
||||
break
|
||||
offset += w
|
||||
|
||||
|
||||
class MenuEntryAction(object):
|
||||
"""Menu entry class for describing a menu entry with an action."""
|
||||
|
||||
# This should be calculated from the space necessary for the icon,
|
||||
# but we're going to be lazy for now and just assume they're all this big.
|
||||
height = 20
|
||||
|
||||
hilight_border_top = (54/255,128/255,205/255)
|
||||
hilight_gradient_top = (93/255,163/255,236/255)
|
||||
hilight_gradient_bottom = (56/255,137/255,220/55)
|
||||
hilight_border_bottom = (47/255,106/255,167/255)
|
||||
|
||||
right_margin = 50
|
||||
|
||||
def __init__(self, title, icon, action=None, data=None, rich=False):
|
||||
self.title = title
|
||||
self.icon = get_icon(icon,16) if icon else None
|
||||
self.action = action
|
||||
self.data = data
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF,13,0xFF000000)
|
||||
self.font_hilight = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF,13,0xFFFFFFFF)
|
||||
self.rich = rich
|
||||
|
||||
self.width = self.font.width(self.title) + self.right_margin # Arbitrary bit of extra space.
|
||||
# Fit width to hold title?
|
||||
self.tr = text_region.TextRegion(0,0,self.width - 22, 20, self.font)
|
||||
self.update_text()
|
||||
self.hilight = False
|
||||
self.window = None
|
||||
self.gradient = cairo.LinearGradient(0,0,0,self.height-2)
|
||||
self.gradient.add_color_stop_rgba(0.0,*self.hilight_gradient_top,1.0)
|
||||
self.gradient.add_color_stop_rgba(1.0,*self.hilight_gradient_bottom,1.0)
|
||||
|
||||
def update_text(self):
|
||||
if self.rich:
|
||||
self.tr.set_richtext(self.title)
|
||||
else:
|
||||
self.tr.set_text(self.title)
|
||||
self.width = self.font.width(self.title) + self.right_margin # Arbitrary bit of extra space.
|
||||
if self.rich:
|
||||
try:
|
||||
self.width = self.tr.get_offset_at_index(-1)[1][1] + self.right_margin
|
||||
except:
|
||||
pass # uh, fallback to the original width
|
||||
self.tr.resize(self.width - 22, 20)
|
||||
|
||||
def focus_enter(self,keyboard=False):
|
||||
if self.window and self.window.child:
|
||||
self.window.child.definitely_close()
|
||||
self.tr.set_font(self.font_hilight)
|
||||
self.update_text()
|
||||
self.hilight = True
|
||||
|
||||
def focus_leave(self):
|
||||
self.tr.set_font(self.font)
|
||||
self.update_text()
|
||||
self.hilight = False
|
||||
|
||||
def draw(self, window, offset, ctx):
|
||||
# Here, offset = y offset, not x like in panel widgets
|
||||
# eventually, this all needs to be made generic with containers and calculated window coordinates...
|
||||
# but for now, as always, we're being lazy
|
||||
self.window = window
|
||||
self.offset = offset
|
||||
if self.hilight:
|
||||
ctx.rectangle(1,offset,window.width-2,1)
|
||||
ctx.set_source_rgb(*self.hilight_border_top)
|
||||
ctx.fill()
|
||||
ctx.rectangle(1,offset+self.height-1,window.width-2,1)
|
||||
ctx.set_source_rgb(*self.hilight_border_bottom)
|
||||
ctx.fill()
|
||||
ctx.save()
|
||||
ctx.translate(0,offset+1)
|
||||
ctx.rectangle(1,0,window.width-2,self.height-2)
|
||||
ctx.set_source(self.gradient)
|
||||
ctx.fill()
|
||||
ctx.restore()
|
||||
if self.icon:
|
||||
ctx.save()
|
||||
ctx.translate(4,offset+2)
|
||||
if self.icon.get_width != 16:
|
||||
ctx.scale(16/self.icon.get_width(),16/self.icon.get_width())
|
||||
ctx.set_source_surface(self.icon,0,0)
|
||||
ctx.paint()
|
||||
ctx.restore()
|
||||
self.tr.move(22,offset+2)
|
||||
self.tr.draw(window)
|
||||
|
||||
def activate(self):
|
||||
if self.action:
|
||||
self.action(self.data) # Probably like launch_app("terminal")
|
||||
self.window.root.hovered_menu = None
|
||||
self.focus_leave()
|
||||
m = [m for m in self.window.root.menus.values()]
|
||||
for k in m:
|
||||
k.definitely_close()
|
||||
self.window.root.draw()
|
||||
|
||||
def close_enough(self, msg):
|
||||
return close_enough(msg) and msg.old_y >= self.offset and msg.old_y < self.offset + self.height
|
||||
|
||||
def mouse_action(self, msg):
|
||||
if msg.command == yutani.MouseEvent.CLICK or self.close_enough(msg):
|
||||
self.activate()
|
||||
|
||||
return False
|
||||
|
||||
class MenuEntrySubmenu(MenuEntryAction):
|
||||
"""A menu entry which opens a nested submenu."""
|
||||
|
||||
def __init__(self, title, entries, icon="folder"):
|
||||
super(MenuEntrySubmenu,self).__init__(title,icon,None,None)
|
||||
self.entries = entries
|
||||
self.tick = get_icon('menu-tick', 16)
|
||||
self.tick_hilight = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.tick.get_width(), self.tick.get_height())
|
||||
tmp = cairo.Context(self.tick_hilight)
|
||||
tmp.set_operator(cairo.OPERATOR_SOURCE)
|
||||
tmp.set_source_surface(self.tick,0,0)
|
||||
tmp.paint()
|
||||
tmp.set_operator(cairo.OPERATOR_ATOP)
|
||||
tmp.rectangle(0,0,16,16)
|
||||
tmp.set_source_rgb(1,1,1)
|
||||
tmp.paint()
|
||||
|
||||
def draw(self, window, offset, ctx):
|
||||
super(MenuEntrySubmenu,self).draw(window, offset, ctx)
|
||||
ctx.save()
|
||||
ctx.set_source_surface(self.tick if not self.hilight else self.tick_hilight,window.width-16, self.offset + 2)
|
||||
ctx.paint()
|
||||
ctx.restore()
|
||||
|
||||
def focus_enter(self,keyboard=False):
|
||||
self.tr.set_font(self.font_hilight)
|
||||
self.tr.set_text(self.title)
|
||||
self.hilight = True
|
||||
if not keyboard:
|
||||
self.activate()
|
||||
|
||||
def activate(self):
|
||||
if self.window:
|
||||
menu = MenuWindow(self.entries, (self.window.x + self.window.width - 2, self.window.y + self.offset - self.window.top_height), self.window, root=self.window.root)
|
||||
def mouse_action(self, msg):
|
||||
return False
|
||||
|
||||
class MenuEntryDivider(object):
|
||||
"""A visible separator between menu entries. Does nothing."""
|
||||
|
||||
height = 6
|
||||
width = 0
|
||||
|
||||
def draw(self, window, offset, ctx):
|
||||
self.window = window
|
||||
ctx.rectangle(2,offset+3,window.width-4,1)
|
||||
ctx.set_source_rgb(0.7,0.7,0.7)
|
||||
ctx.fill()
|
||||
ctx.rectangle(2,offset+4,window.width-5,1)
|
||||
ctx.set_source_rgb(0.98,0.98,0.98)
|
||||
ctx.fill()
|
||||
|
||||
def focus_enter(self,keyboard=False):
|
||||
if self.window and self.window.child:
|
||||
self.window.child.definitely_close()
|
||||
pass
|
||||
|
||||
def focus_leave(self):
|
||||
pass
|
||||
|
||||
def mouse_action(self,msg):
|
||||
return False
|
||||
|
||||
class MenuWindow(yutani.Window):
|
||||
"""Nested menu window."""
|
||||
|
||||
# These should be part of some theming functionality, but for now we'll
|
||||
# just embed them here in the MenuWindow class.
|
||||
top_height = 4
|
||||
bottom_height = 4
|
||||
base_background = (239/255,238/255,232/255)
|
||||
base_border = (109/255,111/255,112/255)
|
||||
|
||||
def __init__(self, entries, origin=(0,0), parent=None, root=None):
|
||||
self.parent = parent
|
||||
if self.parent:
|
||||
self.parent.child = self
|
||||
self.entries = entries
|
||||
required_width = max([e.width for e in entries])
|
||||
required_height = sum([e.height for e in entries]) + self.top_height + self.bottom_height
|
||||
flags = yutani.WindowFlag.FLAG_ALT_ANIMATION
|
||||
super(MenuWindow, self).__init__(required_width,required_height,doublebuffer=True,flags=flags)
|
||||
menu_windows[self.wid] = self
|
||||
self.move(*origin)
|
||||
self.focused_widget = None
|
||||
self.child = None
|
||||
self.closed = False
|
||||
self.root = root
|
||||
self.root.menus[self.wid] = self
|
||||
self.draw()
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
ctx = cairo.Context(surface)
|
||||
|
||||
ctx.set_operator(cairo.OPERATOR_SOURCE)
|
||||
ctx.rectangle(0,0,self.width,self.height)
|
||||
ctx.set_line_width(2)
|
||||
ctx.set_source_rgb(*self.base_background)
|
||||
ctx.fill_preserve()
|
||||
ctx.set_source_rgb(*self.base_border)
|
||||
ctx.stroke()
|
||||
ctx.set_operator(cairo.OPERATOR_OVER)
|
||||
|
||||
offset = self.top_height
|
||||
for entry in self.entries:
|
||||
entry.draw(self,offset,ctx)
|
||||
offset += entry.height
|
||||
|
||||
|
||||
self.flip()
|
||||
|
||||
def mouse_action(self, msg):
|
||||
if msg.new_y < self.top_height or msg.new_y >= self.height - self.bottom_height or \
|
||||
msg.new_x < 0 or msg.new_x >= self.width:
|
||||
if self.focused_widget:
|
||||
self.focused_widget.focus_leave()
|
||||
self.focused_widget = None
|
||||
self.draw()
|
||||
return
|
||||
# We must have focused something
|
||||
x = (msg.new_y - self.top_height)
|
||||
offset = 0
|
||||
new_widget = None
|
||||
for entry in self.entries:
|
||||
if x >= offset and x < offset + entry.height:
|
||||
new_widget = entry
|
||||
break
|
||||
offset += entry.height
|
||||
|
||||
redraw = False
|
||||
if new_widget:
|
||||
if self.focused_widget != new_widget:
|
||||
if self.focused_widget:
|
||||
self.focused_widget.focus_leave()
|
||||
new_widget.focus_enter(keyboard=False)
|
||||
self.focused_widget = new_widget
|
||||
redraw = True
|
||||
if new_widget.mouse_action(msg):
|
||||
redraw = True
|
||||
if redraw:
|
||||
self.draw()
|
||||
|
||||
def has_eventual_child(self, child):
|
||||
"""Does this menu have the given menu as a child, or a child of a child, etc.?"""
|
||||
if child is self: return True
|
||||
if not self.child: return False
|
||||
return self.child.has_eventual_child(child)
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
"""Handle keyboard."""
|
||||
if msg.event.action != yutani.KeyAction.ACTION_DOWN:
|
||||
return
|
||||
if msg.event.keycode == yutani.Keycode.ESCAPE:
|
||||
self.root.hovered_menu = None
|
||||
self.root.menus[msg.wid].leave_menu()
|
||||
return
|
||||
|
||||
self.root.hovered_menu = self
|
||||
|
||||
if msg.event.keycode == yutani.Keycode.ARROW_DOWN:
|
||||
if not self.focused_widget and self.entries:
|
||||
self.focused_widget = self.entries[0]
|
||||
self.focused_widget.focus_enter(keyboard=True)
|
||||
self.draw()
|
||||
return
|
||||
i = 0
|
||||
for entry in self.entries:
|
||||
if entry == self.focused_widget:
|
||||
break
|
||||
i += 1
|
||||
i += 1
|
||||
if i >= len(self.entries):
|
||||
i = 0
|
||||
self.focused_widget.focus_leave()
|
||||
self.focused_widget = self.entries[i]
|
||||
self.focused_widget.focus_enter(keyboard=True)
|
||||
self.draw()
|
||||
|
||||
if msg.event.keycode == yutani.Keycode.ARROW_UP:
|
||||
if not self.focused_widget and self.entries:
|
||||
self.focused_widget = self.entries[0]
|
||||
self.focused_widget.focus_enter(keyboard=True)
|
||||
self.draw()
|
||||
return
|
||||
i = 0
|
||||
for entry in self.entries:
|
||||
if entry == self.focused_widget:
|
||||
break
|
||||
i += 1
|
||||
i -= 1
|
||||
if i < 0:
|
||||
i = len(self.entries)-1
|
||||
self.focused_widget.focus_leave()
|
||||
self.focused_widget = self.entries[i]
|
||||
self.focused_widget.focus_enter(keyboard=True)
|
||||
self.draw()
|
||||
|
||||
if msg.event.keycode == yutani.Keycode.ARROW_LEFT:
|
||||
self.root.hovered_menu = self.parent
|
||||
self.definitely_close()
|
||||
return
|
||||
|
||||
if msg.event.keycode == yutani.Keycode.ARROW_RIGHT:
|
||||
if self.focused_widget and isinstance(self.focused_widget, MenuEntrySubmenu):
|
||||
self.focused_widget.activate()
|
||||
|
||||
if msg.event.key == b'\n':
|
||||
if self.focused_widget:
|
||||
self.focused_widget.activate()
|
||||
|
||||
def close(self):
|
||||
if self.wid in menu_windows:
|
||||
del menu_windows[self.wid]
|
||||
super(MenuWindow,self).close()
|
||||
|
||||
def definitely_close(self):
|
||||
"""Close this menu and all of its submenus."""
|
||||
if self.child:
|
||||
self.child.definitely_close()
|
||||
self.child = None
|
||||
if self.closed:
|
||||
return
|
||||
if self.focused_widget:
|
||||
self.focused_widget.focus_leave()
|
||||
self.closed = True
|
||||
wid = self.wid
|
||||
self.close()
|
||||
del self.root.menus[wid]
|
||||
|
||||
def leave_menu(self):
|
||||
"""Focus has left this menu. If it is not a parent of the currently active menu, close it."""
|
||||
if self.has_eventual_child(self.root.hovered_menu):
|
||||
pass
|
||||
else:
|
||||
m = [m for m in self.root.menus.values()]
|
||||
for k in m:
|
||||
if not self.root.hovered_menu or (k is not self.root.hovered_menu.child and not k.has_eventual_child(self.root.hovered_menu)):
|
||||
k.definitely_close()
|
||||
|
@ -1,381 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Minesweeper clone
|
||||
"""
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
|
||||
from button import Button, rounded_rectangle
|
||||
from menu_bar import MenuBarWidget, MenuEntryAction, MenuEntrySubmenu, MenuEntryDivider, MenuWindow
|
||||
from about_applet import AboutAppletWindow
|
||||
from input_box import TextInputWindow
|
||||
from dialog import DialogWindow
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
version = "1.0.0"
|
||||
app_name = "Mines"
|
||||
_description = f"<b>{app_name} {version}</b>\n© 2017-2018 K. Lange\n\nClassic logic game.\n\n<color 0x0000FF>http://github.com/klange/toaruos</color>"
|
||||
|
||||
class MineButton(Button):
|
||||
|
||||
def __init__(self,action,r,c,is_mine,neighbor_mines):
|
||||
super(MineButton,self).__init__("",action)
|
||||
self.row = r
|
||||
self.col = c
|
||||
self.tr = text_region.TextRegion(0,0,10,10)
|
||||
self.is_mine = is_mine
|
||||
self.tr.set_text("")
|
||||
self.tr.set_alignment(2)
|
||||
self.tr.set_valignment(2)
|
||||
self.width = None
|
||||
self.revealed = False
|
||||
self.mines = neighbor_mines
|
||||
self.flagged = False
|
||||
|
||||
def reveal(self):
|
||||
if self.revealed: return
|
||||
self.revealed = True
|
||||
if self.is_mine:
|
||||
self.tr.set_text("X")
|
||||
elif self.mines == 0:
|
||||
self.tr.set_text("")
|
||||
else:
|
||||
self.tr.set_text(str(self.mines))
|
||||
|
||||
def set_flagged(self):
|
||||
self.flagged = not self.flagged
|
||||
|
||||
def draw(self, window, ctx, x, y, w, h):
|
||||
if self.width != w:
|
||||
self.x, self.y, self.width, self.height = x, y, w, h
|
||||
x_, y_ = ctx.user_to_device(x,y)
|
||||
self.tr.move(int(x_)+2,int(y_)+2)
|
||||
self.tr.resize(w-4,h-4)
|
||||
rounded_rectangle(ctx,x+2,y+2,w-4,h-4,3)
|
||||
if self.revealed:
|
||||
ctx.set_source_rgb(0.6,0.6,0.6)
|
||||
elif self.flagged:
|
||||
ctx.set_source_rgb(0.6,0.1,0.1)
|
||||
elif self.hilight == 1:
|
||||
ctx.set_source_rgb(0.7,0.7,0.7)
|
||||
elif self.hilight == 2:
|
||||
ctx.set_source_rgb(0.3,0.3,0.3)
|
||||
else:
|
||||
ctx.set_source_rgb(1,1,1)
|
||||
ctx.fill()
|
||||
|
||||
if self.tr.text:
|
||||
self.tr.draw(window)
|
||||
|
||||
class MinesWindow(yutani.Window):
|
||||
|
||||
base_width = 400
|
||||
base_height = 440
|
||||
|
||||
def __init__(self, decorator):
|
||||
super(MinesWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=app_name, icon="mines", doublebuffer=True)
|
||||
self.move(100,100)
|
||||
self.decorator = decorator
|
||||
self.button_width = {}
|
||||
self.button_height = 0
|
||||
|
||||
def exit_app(action):
|
||||
menus = [x for x in self.menus.values()]
|
||||
for x in menus:
|
||||
x.definitely_close()
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
def about_window(action):
|
||||
AboutAppletWindow(self.decorator,f"About {app_name}","/usr/share/icons/48/mines.png",_description,"mines")
|
||||
def help_browser(action):
|
||||
subprocess.Popen(["help-browser.py","mines.trt"])
|
||||
def custom_game(action):
|
||||
def input_callback(input_window):
|
||||
size = int(input_window.tr.text)
|
||||
input_window.close()
|
||||
def second_callback(input_window):
|
||||
mines = int(input_window.tr.text)
|
||||
input_window.close()
|
||||
self.new_game((size,mines))
|
||||
|
||||
TextInputWindow(self.decorator,"How many mines?","mines",text="90",callback=second_callback,window=self)
|
||||
TextInputWindow(self.decorator,"How wide/tall?","mines",text="20",callback=input_callback,window=self)
|
||||
|
||||
menus = [
|
||||
("File", [
|
||||
MenuEntrySubmenu("New Game...",[
|
||||
MenuEntryAction("9×9, 10 mines",None,self.new_game,(9,10)),
|
||||
MenuEntryAction("16×16, 40 mines",None,self.new_game,(16,40)),
|
||||
MenuEntryAction("20×20, 90 mines",None,self.new_game,(20,90)),
|
||||
MenuEntryAction("Custom...",None,custom_game,None),
|
||||
],icon="new"),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction("Exit","exit",exit_app,None),
|
||||
]),
|
||||
("Help", [
|
||||
MenuEntryAction("Contents","help",help_browser,None),
|
||||
MenuEntryDivider(),
|
||||
MenuEntryAction(f"About {app_name}","star",about_window,None),
|
||||
]),
|
||||
]
|
||||
|
||||
self.menubar = MenuBarWidget(self,menus)
|
||||
|
||||
self.tr = text_region.TextRegion(self.decorator.left_width(self)+5,self.decorator.top_height(self)+self.menubar.height,self.base_width-10,40)
|
||||
self.tr.set_font(toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF,18))
|
||||
self.tr.set_alignment(2)
|
||||
self.tr.set_valignment(2)
|
||||
self.tr.set_one_line()
|
||||
self.tr.set_ellipsis()
|
||||
|
||||
|
||||
self.error = False
|
||||
|
||||
self.hover_widget = None
|
||||
self.down_button = None
|
||||
|
||||
self.menus = {}
|
||||
self.hovered_menu = None
|
||||
self.modifiers = 0
|
||||
|
||||
self.new_game((9,10))
|
||||
|
||||
def basic_game(self):
|
||||
self.new_game((9,10))
|
||||
|
||||
def new_game(self,action):
|
||||
def mine_func(b):
|
||||
button = b
|
||||
if self.first_click:
|
||||
i = 0
|
||||
while button.is_mine or button.mines:
|
||||
if i > 30:
|
||||
DialogWindow(self.decorator,app_name,"Failed to generate a board.",callback=self.basic_game,window=self,icon='mines')
|
||||
return
|
||||
self.new_game(action)
|
||||
button = self.buttons[button.row][button.col]
|
||||
i += 1
|
||||
self.first_click = False
|
||||
if button.flagged:
|
||||
return
|
||||
if button.is_mine and not button.revealed:
|
||||
self.tr.set_text("You lose.")
|
||||
for row in self.buttons:
|
||||
for b in row:
|
||||
b.reveal()
|
||||
self.draw()
|
||||
def new():
|
||||
self.new_game(action)
|
||||
DialogWindow(self.decorator,app_name,"Oops, you clicked a mine! Play another game?",callback=new,window=self,icon='mines')
|
||||
return
|
||||
else:
|
||||
if not button.revealed:
|
||||
button.reveal()
|
||||
if button.mines == 0:
|
||||
n = [x for x in check_neighbor_buttons(button.row,button.col) if not x.revealed]
|
||||
while n:
|
||||
b = n.pop()
|
||||
b.reveal()
|
||||
if b.mines == 0:
|
||||
n.extend([x for x in check_neighbor_buttons(b.row,b.col) if not x.revealed and not x in n])
|
||||
self.check_win()
|
||||
|
||||
self.field_size, self.mine_count = action
|
||||
self.first_click = True
|
||||
self.tr.set_text(f"There are {self.mine_count} mines.")
|
||||
|
||||
self.mines = []
|
||||
i = 0
|
||||
while len(self.mines) < self.mine_count:
|
||||
x,y = random.randrange(self.field_size),random.randrange(self.field_size)
|
||||
i += 1
|
||||
if not (x,y) in self.mines:
|
||||
i = 0
|
||||
self.mines.append((x,y))
|
||||
if i > 50:
|
||||
DialogWindow(self.decorator,app_name,"Failed to generate a board.",callback=self.basic_game,window=self,icon='mines')
|
||||
return
|
||||
|
||||
def check_neighbors(r,c):
|
||||
n = []
|
||||
if r > 0:
|
||||
if c > 0: n.append((r-1,c-1))
|
||||
n.append((r-1,c))
|
||||
if c < self.field_size-1: n.append((r-1,c+1))
|
||||
if r < self.field_size-1:
|
||||
if c > 0: n.append((r+1,c-1))
|
||||
n.append((r+1,c))
|
||||
if c < self.field_size-1: n.append((r+1,c+1))
|
||||
if c > 0: n.append((r,c-1))
|
||||
if c < self.field_size-1: n.append((r,c+1))
|
||||
return n
|
||||
|
||||
def check_neighbor_buttons(r,c):
|
||||
return [self.buttons[x][y] for x,y in check_neighbors(r,c)]
|
||||
|
||||
self.buttons = []
|
||||
for row in range(self.field_size):
|
||||
r = []
|
||||
for col in range(self.field_size):
|
||||
is_mine = (row,col) in self.mines
|
||||
neighbor_mines = len([x for x in check_neighbors(row,col) if x in self.mines])
|
||||
r.append(MineButton(mine_func,row,col,is_mine,neighbor_mines))
|
||||
self.buttons.append(r)
|
||||
|
||||
|
||||
def check_win(self):
|
||||
buttons = []
|
||||
for row in self.buttons:
|
||||
buttons.extend(row)
|
||||
n_flagged = len([x for x in buttons if x.flagged and not x.revealed])
|
||||
n_revealed = len([x for x in buttons if x.revealed])
|
||||
if n_flagged == self.mine_count and n_revealed + n_flagged == self.field_size ** 2:
|
||||
self.tr.set_text("You win!")
|
||||
for b in buttons:
|
||||
b.reveal()
|
||||
def new():
|
||||
self.new_game((self.field_size,self.mine_count))
|
||||
DialogWindow(self.decorator,app_name,"You won! Play another game?",callback=new,window=self,icon='mines')
|
||||
|
||||
def flag(self,button):
|
||||
button.set_flagged()
|
||||
self.check_win()
|
||||
self.draw()
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
self.tr.resize(WIDTH-10, self.tr.height)
|
||||
self.tr.draw(self)
|
||||
|
||||
offset_x = 0
|
||||
offset_y = self.tr.height + self.menubar.height
|
||||
self.button_height = int((HEIGHT - self.tr.height - self.menubar.height) / len(self.buttons))
|
||||
i = 0
|
||||
for row in self.buttons:
|
||||
self.button_width[i] = int(WIDTH / len(row))
|
||||
for button in row:
|
||||
if button:
|
||||
button.draw(self,ctx,offset_x,offset_y,self.button_width[i],self.button_height)
|
||||
offset_x += self.button_width[i]
|
||||
offset_x = 0
|
||||
offset_y += self.button_height
|
||||
i += 1
|
||||
|
||||
self.menubar.draw(ctx,0,0,WIDTH)
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
if msg.width < 400 or msg.height < 400:
|
||||
self.resize_offer(max(msg.width,400),max(msg.height,400))
|
||||
return
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
decor_event = d.handle_event(msg)
|
||||
if decor_event == yutani.Decor.EVENT_CLOSE:
|
||||
window.close()
|
||||
sys.exit(0)
|
||||
elif decor_event == yutani.Decor.EVENT_RIGHT:
|
||||
d.show_menu(self, msg)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
if x >= 0 and x < w and y >= 0 and y < self.menubar.height:
|
||||
self.menubar.mouse_event(msg, x, y)
|
||||
return
|
||||
|
||||
redraw = False
|
||||
if self.down_button:
|
||||
if msg.command == yutani.MouseEvent.RAISE or msg.command == yutani.MouseEvent.CLICK:
|
||||
if not (msg.buttons & yutani.MouseButton.BUTTON_LEFT):
|
||||
if x >= self.down_button.x and \
|
||||
x < self.down_button.x + self.down_button.width and \
|
||||
y >= self.down_button.y and \
|
||||
y < self.down_button.y + self.down_button.height:
|
||||
self.down_button.focus_enter()
|
||||
if self.modifiers & yutani.Modifier.MOD_LEFT_CTRL:
|
||||
self.flag(self.down_button)
|
||||
else:
|
||||
self.down_button.callback(self.down_button)
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
else:
|
||||
self.down_button.focus_leave()
|
||||
self.down_button = None
|
||||
redraw = True
|
||||
|
||||
else:
|
||||
if y > self.tr.height + self.menubar.height and y < h and x >= 0 and x < w:
|
||||
xh = self.button_height * len(self.buttons)
|
||||
row = int((y - self.tr.height - self.menubar.height) / (xh) * len(self.buttons))
|
||||
if row < len(self.buttons):
|
||||
xw = self.button_width[row] * len(self.buttons[row])
|
||||
col = int(x / (xw) * len(self.buttons[row]))
|
||||
if col < len(self.buttons[row]):
|
||||
button = self.buttons[row][col]
|
||||
else:
|
||||
button = None
|
||||
else:
|
||||
button = None
|
||||
if button != self.hover_widget:
|
||||
if button:
|
||||
button.focus_enter()
|
||||
redraw = True
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = button
|
||||
|
||||
if msg.command == yutani.MouseEvent.DOWN:
|
||||
if button:
|
||||
button.hilight = 2
|
||||
self.down_button = button
|
||||
redraw = True
|
||||
else:
|
||||
if self.hover_widget:
|
||||
self.hover_widget.focus_leave()
|
||||
redraw = True
|
||||
self.hover_widget = None
|
||||
|
||||
if redraw:
|
||||
self.draw()
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
self.modifiers = msg.event.modifiers
|
||||
if msg.event.action != 0x01:
|
||||
return # Ignore anything that isn't a key down.
|
||||
if msg.event.key == b"q":
|
||||
self.close()
|
||||
sys.exit(0)
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
window = MinesWindow(d)
|
||||
window.draw()
|
||||
|
||||
yutani_mainloop.mainloop()
|
File diff suppressed because it is too large
Load Diff
@ -1,128 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Shows a progress bar.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
||||
import cairo
|
||||
|
||||
import yutani
|
||||
import text_region
|
||||
import toaru_fonts
|
||||
import fswait
|
||||
|
||||
import yutani_mainloop
|
||||
|
||||
def rounded_rectangle(ctx,x,y,w,h,r):
|
||||
degrees = math.pi / 180
|
||||
ctx.new_sub_path()
|
||||
|
||||
ctx.arc(x + w - r, y + r, r, -90 * degrees, 0 * degrees)
|
||||
ctx.arc(x + w - r, y + h - r, r, 0 * degrees, 90 * degrees)
|
||||
ctx.arc(x + r, y + h - r, r, 90 * degrees, 180 * degrees)
|
||||
ctx.arc(x + r, y + r, r, 180 * degrees, 270 * degrees)
|
||||
ctx.close_path()
|
||||
|
||||
def draw_progress_bar(ctx,x,y,w,h,percent):
|
||||
# Outer
|
||||
rounded_rectangle(ctx,x,y,w,h,4)
|
||||
ctx.set_source_rgb(192/255,192/255,192/255)
|
||||
ctx.fill()
|
||||
|
||||
# Inner
|
||||
rounded_rectangle(ctx,x+1,y+1,w-2,h-2,4)
|
||||
ctx.set_source_rgb(217/255,217/255,217/255)
|
||||
ctx.fill()
|
||||
|
||||
rounded_rectangle(ctx,x+2,y+2,(w-4) * percent,h-4,4)
|
||||
ctx.set_source_rgb(0,92/255,229/255)
|
||||
ctx.fill()
|
||||
|
||||
class ProgressBarWindow(yutani.Window):
|
||||
|
||||
base_width = 350
|
||||
base_height = 80
|
||||
text_offset = 50
|
||||
|
||||
def __init__(self, decorator, title, icon):
|
||||
super(ProgressBarWindow, self).__init__(self.base_width + decorator.width(), self.base_height + decorator.height(), title=title, icon=icon, doublebuffer=True)
|
||||
self.move(int((yutani.yutani_ctx._ptr.contents.display_width-self.width)/2),int((yutani.yutani_ctx._ptr.contents.display_height-self.height)/2))
|
||||
self.decorator = decorator
|
||||
self.font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13, 0xFF000000)
|
||||
self.tr = text_region.TextRegion(0,0,self.base_width-30,self.base_height-self.text_offset,font=self.font)
|
||||
self.tr.set_alignment(2)
|
||||
self.progress = 0
|
||||
self.total = 1
|
||||
|
||||
def draw(self):
|
||||
surface = self.get_cairo_surface()
|
||||
|
||||
WIDTH, HEIGHT = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
ctx = cairo.Context(surface)
|
||||
ctx.translate(self.decorator.left_width(self), self.decorator.top_height(self))
|
||||
ctx.rectangle(0,0,WIDTH,HEIGHT)
|
||||
ctx.set_source_rgb(204/255,204/255,204/255)
|
||||
ctx.fill()
|
||||
|
||||
draw_progress_bar(ctx,10,20,WIDTH-20,20,self.progress / self.total)
|
||||
|
||||
percent = int(100 * self.progress / self.total)
|
||||
self.tr.set_text(f"{percent}%")
|
||||
self.tr.resize(WIDTH-30,HEIGHT-self.text_offset)
|
||||
self.tr.move(self.decorator.left_width(self) + 15,self.decorator.top_height(self)+self.text_offset)
|
||||
self.tr.draw(self)
|
||||
|
||||
self.decorator.render(self)
|
||||
self.flip()
|
||||
|
||||
def finish_resize(self, msg):
|
||||
"""Accept a resize."""
|
||||
self.resize_accept(msg.width, msg.height)
|
||||
self.reinit()
|
||||
self.int_width = msg.width - self.decorator.width(self)
|
||||
self.int_height = msg.height - self.decorator.height(self)
|
||||
self.draw()
|
||||
self.resize_done()
|
||||
self.flip()
|
||||
|
||||
def mouse_event(self, msg):
|
||||
if d.handle_event(msg) == yutani.Decor.EVENT_CLOSE:
|
||||
window.close()
|
||||
sys.exit(0)
|
||||
x,y = msg.new_x - self.decorator.left_width(self), msg.new_y - self.decorator.top_height(self)
|
||||
w,h = self.width - self.decorator.width(self), self.height - self.decorator.height(self)
|
||||
|
||||
def keyboard_event(self, msg):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
title = "Progress" if len(sys.argv) < 2 else sys.argv[1]
|
||||
icon = "default" if len(sys.argv) < 3 else sys.argv[2]
|
||||
|
||||
window = ProgressBarWindow(d,title,icon)
|
||||
window.draw()
|
||||
|
||||
fds = [yutani.yutani_ctx,sys.stdin]
|
||||
while 1:
|
||||
# Poll for events.
|
||||
fd = fswait.fswait(fds)
|
||||
|
||||
if fd < 0:
|
||||
print("? fswait error.")
|
||||
elif fd == 0:
|
||||
msg = yutani.yutani_ctx.poll()
|
||||
yutani_mainloop.handle_event(msg)
|
||||
elif fd == 1:
|
||||
status = sys.stdin.readline().strip()
|
||||
if status == "done":
|
||||
window.close()
|
||||
break
|
||||
window.progress, window.total = map(int,status.split(" "))
|
||||
window.draw()
|
||||
|
@ -1,589 +0,0 @@
|
||||
import hashlib
|
||||
import subprocess
|
||||
from urllib.parse import urlparse
|
||||
import unicodedata
|
||||
from html.parser import HTMLParser
|
||||
import math
|
||||
import os
|
||||
|
||||
import cairo
|
||||
import toaru_fonts
|
||||
import yutani
|
||||
|
||||
def create_from_bmp(path):
|
||||
if os.path.exists(path) and path.endswith('.bmp'):
|
||||
return yutani.Sprite.from_file(path).get_cairo_surface()
|
||||
return None
|
||||
|
||||
_emoji_available = os.path.exists('/usr/share/emoji')
|
||||
|
||||
if _emoji_available:
|
||||
_emoji_values = [int(x.replace('.png',''),16) for x in os.listdir('/usr/share/emoji') if x.endswith('.png') and not '-' in x]
|
||||
|
||||
_emoji_table = {}
|
||||
def get_emoji(emoji):
|
||||
if not emoji in _emoji_table:
|
||||
_emoji_table[emoji] = cairo.ImageSurface.create_from_png('/usr/share/emoji/' + hex(ord(emoji)).replace('0x','')+'.png')
|
||||
return _emoji_table[emoji]
|
||||
|
||||
class TextUnit(object):
|
||||
def __init__(self, string, unit_type, font):
|
||||
self.string = string
|
||||
self.unit_type = unit_type
|
||||
self.font = font
|
||||
self.width = font.width(self.string) if font else 0
|
||||
self.extra = {}
|
||||
self.tag_group = None
|
||||
if self.unit_type == 2 and _emoji_available:
|
||||
if ord(self.string) > 0x1000 and ord(self.string) in _emoji_values:
|
||||
self.extra['emoji'] = True
|
||||
self.extra['img'] = get_emoji(self.string)
|
||||
self.extra['offset'] = font.font_size
|
||||
self.string = ""
|
||||
self.width = font.font_size
|
||||
|
||||
def set_tag_group(self, tag_group):
|
||||
self.tag_group = tag_group
|
||||
self.tag_group.append(self)
|
||||
|
||||
def set_font(self, font):
|
||||
if 'img' in self.extra: return
|
||||
self.font = font
|
||||
self.width = font.width(self.string) if font else 0
|
||||
|
||||
def set_extra(self, key, data):
|
||||
self.extra[key] = data
|
||||
|
||||
def __repr__(self):
|
||||
return "(" + self.string + "," + str(self.unit_type) + "," + str(self.width) + ")"
|
||||
|
||||
|
||||
class TextRegion(object):
|
||||
|
||||
def __init__(self, x, y, width, height, font=None):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.width = width
|
||||
self.height = height
|
||||
if not font:
|
||||
font = toaru_fonts.Font(toaru_fonts.FONT_SANS_SERIF, 13)
|
||||
self.font = font
|
||||
self.text = ""
|
||||
self.lines = []
|
||||
self.align = 0
|
||||
self.valign = 0
|
||||
self.line_height = self.font.font_size
|
||||
self.text_units = []
|
||||
self.scroll = 0
|
||||
self.ellipsis = ""
|
||||
self.one_line = False
|
||||
self.base_dir = ""
|
||||
self.break_all = False
|
||||
self.title = None
|
||||
self.max_lines = None
|
||||
|
||||
def set_alignment(self, align):
|
||||
self.align = align
|
||||
|
||||
def set_valignment(self, align):
|
||||
self.valign = align
|
||||
|
||||
def set_max_lines(self, max_lines):
|
||||
self.max_lines = max_lines
|
||||
self.reflow()
|
||||
|
||||
def visible_lines(self):
|
||||
return int(self.height / self.line_height)
|
||||
|
||||
def reflow(self):
|
||||
self.lines = []
|
||||
|
||||
current_width = 0
|
||||
current_units = []
|
||||
leftover = None
|
||||
|
||||
i = 0
|
||||
while i < len(self.text_units):
|
||||
if leftover:
|
||||
unit = leftover
|
||||
leftover = None
|
||||
else:
|
||||
unit = self.text_units[i]
|
||||
if unit.unit_type == 3:
|
||||
self.lines.append(current_units)
|
||||
current_units = []
|
||||
current_width = 0
|
||||
i += 1
|
||||
continue
|
||||
if unit.unit_type == 4:
|
||||
if current_units:
|
||||
self.lines.append(current_units)
|
||||
i += 1
|
||||
self.lines.append([unit])
|
||||
current_units = []
|
||||
current_width = 0
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if current_width + unit.width > self.width:
|
||||
if not current_units or self.one_line or (self.max_lines is not None and len(self.lines) == self.max_lines - 1):
|
||||
# We need to split the current unit.
|
||||
k = len(unit.string)-1
|
||||
while k and current_width + unit.font.width(unit.string[:k] + self.ellipsis) > self.width:
|
||||
k -= 1
|
||||
ellipsis = self.ellipsis
|
||||
if not k and self.ellipsis:
|
||||
ellipsis = ""
|
||||
if not k and (self.one_line or (self.max_lines is not None and len(self.lines) == self.max_lines - 1)):
|
||||
added_ellipsis = False
|
||||
while len(current_units) and sum([unit.width for unit in current_units]) + unit.font.width(self.ellipsis) > self.width:
|
||||
this_unit = current_units[-1]
|
||||
current_units = current_units[:-1]
|
||||
current_width = sum([unit.width for unit in current_units])
|
||||
k = len(this_unit.string)-1
|
||||
while k and current_width + unit.font.width(this_unit.string[:k] + self.ellipsis) > self.width:
|
||||
k -= 1
|
||||
if k:
|
||||
current_units.append(TextUnit(this_unit.string[:k] + self.ellipsis,this_unit.unit_type,this_unit.font))
|
||||
added_ellipsis = True
|
||||
break
|
||||
if not added_ellipsis:
|
||||
current_units.append(TextUnit(self.ellipsis,0,unit.font))
|
||||
|
||||
else:
|
||||
current_units.append(TextUnit(unit.string[:k]+ellipsis,unit.unit_type,unit.font))
|
||||
leftover = TextUnit(unit.string[k:],unit.unit_type,unit.font)
|
||||
self.lines.append(current_units)
|
||||
current_units = []
|
||||
current_width = 0
|
||||
if self.one_line or (self.max_lines is not None and len(self.lines) == self.max_lines):
|
||||
return
|
||||
else:
|
||||
self.lines.append(current_units)
|
||||
current_units = []
|
||||
current_width = 0
|
||||
if unit.unit_type == 1:
|
||||
i += 1
|
||||
else:
|
||||
current_units.append(unit)
|
||||
current_width += unit.width
|
||||
i += 1
|
||||
if current_units:
|
||||
self.lines.append(current_units)
|
||||
|
||||
def units_from_text(self, text, font=None, whitespace=True):
|
||||
if not font:
|
||||
font = self.font
|
||||
|
||||
def char_width(char):
|
||||
if _emoji_available and ord(char) in _emoji_values:
|
||||
return 2
|
||||
x = unicodedata.east_asian_width(char)
|
||||
if x == 'Na': return 1 # Narrow
|
||||
if x == 'N': return 1 # Narrow
|
||||
if x == 'A': return 1 # Ambiguous
|
||||
if x == 'W': return 2 # Wide
|
||||
if x == 'F': return 1 # Fullwidth (treat as normal)
|
||||
if x == 'H': return 1 # Halfwidth
|
||||
print(f"Don't know how wide {x} is, assuming 1")
|
||||
return 1
|
||||
|
||||
def classify(char):
|
||||
if char == '\n': return 3 # break on line feed
|
||||
if unicodedata.category(char) == 'Zs': return 1 # break on space
|
||||
if char_width(char) > 1: return 2 # allow break on CJK characters (TODO: only really valid for Chinese and Japanese; Korean doesn't work this way
|
||||
if self.break_all: return 2
|
||||
return 0
|
||||
|
||||
units = []
|
||||
offset = 0
|
||||
current_unit = ""
|
||||
while offset < len(text):
|
||||
c = text[offset]
|
||||
if not whitespace and c.isspace():
|
||||
if current_unit:
|
||||
units.append(TextUnit(current_unit,0,font))
|
||||
current_unit = ""
|
||||
units.append(TextUnit(' ',1,font))
|
||||
offset += 1
|
||||
continue
|
||||
x = classify(c)
|
||||
if x == 0:
|
||||
current_unit += c
|
||||
offset += 1
|
||||
else:
|
||||
if not current_unit:
|
||||
units.append(TextUnit(c,x,font))
|
||||
offset += 1
|
||||
else:
|
||||
units.append(TextUnit(current_unit,0,font))
|
||||
current_unit = ""
|
||||
if current_unit:
|
||||
units.append(TextUnit(current_unit,0,font))
|
||||
return units
|
||||
|
||||
def set_one_line(self, one_line=True):
|
||||
self.one_line = one_line
|
||||
self.reflow()
|
||||
|
||||
def set_ellipsis(self, ellipsis="…"):
|
||||
self.ellipsis = ellipsis
|
||||
self.reflow()
|
||||
|
||||
def set_text(self, text):
|
||||
self.text = text
|
||||
self.text_units = self.units_from_text(text)
|
||||
self.reflow()
|
||||
|
||||
def set_richtext(self, text, html=False):
|
||||
f = self.font
|
||||
self.text = text
|
||||
tr = self
|
||||
|
||||
class RichTextParser(HTMLParser):
|
||||
|
||||
def __init__(self, html=False):
|
||||
super(RichTextParser,self).__init__()
|
||||
self.font_stack = []
|
||||
self.tag_stack = []
|
||||
self.current_font = f
|
||||
self.units = []
|
||||
self.link_stack = []
|
||||
self.current_link = None
|
||||
self.tag_group = None
|
||||
self.is_html = html
|
||||
self.whitespace_sensitive = not html
|
||||
self.autoclose = ['br','meta','input']
|
||||
self.title = ''
|
||||
if self.is_html:
|
||||
self.autoclose.extend(['img','link'])
|
||||
self.surface_cache = {}
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
def make_bold(n):
|
||||
if n == 0: return 1
|
||||
if n == 2: return 3
|
||||
if n == 4: return 5
|
||||
if n == 6: return 7
|
||||
return n
|
||||
def make_italic(n):
|
||||
if n == 0: return 2
|
||||
if n == 1: return 3
|
||||
if n == 4: return 6
|
||||
if n == 5: return 7
|
||||
return n
|
||||
def make_monospace(n):
|
||||
if n == 0: return 4
|
||||
if n == 1: return 5
|
||||
if n == 2: return 6
|
||||
if n == 3: return 7
|
||||
return n
|
||||
|
||||
if tag not in self.autoclose:
|
||||
self.tag_stack.append(tag)
|
||||
|
||||
if tag in ['p','div','h1','h2','h3','li','tr','pre'] and not self.whitespace_sensitive: # etc?
|
||||
if self.units and self.units[-1].unit_type != 3:
|
||||
self.units.append(TextUnit('\n',3,self.current_font))
|
||||
|
||||
if tag == "b":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_bold(self.current_font.font_number),self.current_font.font_size,self.current_font.font_color)
|
||||
elif tag == "i":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_italic(self.current_font.font_number),self.current_font.font_size,self.current_font.font_color)
|
||||
elif tag == "color":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(self.current_font.font_number,self.current_font.font_size,int(attrs[0][0],16) | 0xFF000000)
|
||||
elif tag == "mono":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_monospace(self.current_font.font_number),self.current_font.font_size,self.current_font.font_color)
|
||||
elif tag == "pre":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_monospace(self.current_font.font_number),self.current_font.font_size,self.current_font.font_color)
|
||||
elif tag == "link" and not self.is_html:
|
||||
target = None
|
||||
for attr in attrs:
|
||||
if attr[0] == "target":
|
||||
target = attr[1]
|
||||
self.tag_group = []
|
||||
self.link_stack.append(self.current_link)
|
||||
self.current_link = target
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(self.current_font.font_number,self.current_font.font_size,0xFF0000FF)
|
||||
elif tag == "a":
|
||||
target = None
|
||||
for attr in attrs:
|
||||
if attr[0] == "href":
|
||||
target = attr[1]
|
||||
self.tag_group = []
|
||||
self.link_stack.append(self.current_link)
|
||||
if target and self.is_html and not target.startswith('http:') and not target.startswith('https:'):
|
||||
# This is actually more complicated than this check - protocol-relative stuff can work without full URLs
|
||||
if target.startswith('/'):
|
||||
base = urlparse(tr.base_dir)
|
||||
target = f"{base.scheme}://{base.netloc}{target}"
|
||||
else:
|
||||
target = tr.base_dir + target
|
||||
self.current_link = target
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(self.current_font.font_number,self.current_font.font_size,0xFF0000FF)
|
||||
elif tag == "h1":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_bold(self.current_font.font_number),20)
|
||||
elif tag == "h2":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_bold(self.current_font.font_number),18)
|
||||
elif tag == "h3":
|
||||
self.font_stack.append(self.current_font)
|
||||
self.current_font = toaru_fonts.Font(make_bold(self.current_font.font_number),16)
|
||||
elif tag == "img":
|
||||
self.handle_img(tag,attrs)
|
||||
elif tag == "br":
|
||||
units = tr.units_from_text('\n', self.current_font)
|
||||
self.units.extend(units)
|
||||
else:
|
||||
pass
|
||||
|
||||
def handle_startendtag(self, tag, attrs):
|
||||
if tag == "img":
|
||||
self.handle_img(tag,attrs)
|
||||
elif tag == "br":
|
||||
units = tr.units_from_text('\n', self.current_font)
|
||||
self.units.extend(units)
|
||||
elif tag in ['p','div','h1','h2','h3','tr','pre'] and not self.whitespace_sensitive: # etc?
|
||||
units = tr.units_from_text('\n', self.current_font)
|
||||
self.units.extend(units)
|
||||
else:
|
||||
# Unknown start/end tag.
|
||||
pass
|
||||
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if not self.tag_stack:
|
||||
print(f"No stack when trying to close {tag}?")
|
||||
if self.tag_stack[-1] != tag:
|
||||
print(f"unclosed tag {self.tag_stack[-1]} when closing tag {tag}")
|
||||
else:
|
||||
self.tag_stack.pop()
|
||||
if tag in ["b","i","color","mono","link","h1","h2","h3","a","pre"]:
|
||||
self.current_font = self.font_stack.pop()
|
||||
if tag in ['p','div','h1','h2','h3','li','tr','pre'] and not self.whitespace_sensitive: # etc?
|
||||
units = tr.units_from_text('\n', self.current_font)
|
||||
self.units.extend(units)
|
||||
if tag in ["link","a"]:
|
||||
self.current_link = self.link_stack.pop()
|
||||
self.tag_group = None
|
||||
|
||||
def handle_data(self, data):
|
||||
if 'title' in self.tag_stack:
|
||||
self.title += data
|
||||
if 'head' in self.tag_stack or 'script' in self.tag_stack: return
|
||||
if 'pre' in self.tag_stack:
|
||||
units = tr.units_from_text(data, self.current_font, whitespace=True)
|
||||
else:
|
||||
units = tr.units_from_text(data, self.current_font, whitespace=self.whitespace_sensitive)
|
||||
if self.current_link:
|
||||
for u in units:
|
||||
u.set_extra('link',self.current_link)
|
||||
if self.tag_group is not None:
|
||||
for u in units:
|
||||
u.set_tag_group(self.tag_group)
|
||||
self.units.extend(units)
|
||||
|
||||
def handle_img(self, tag, attrs):
|
||||
target = None
|
||||
for attr in attrs:
|
||||
if attr[0] == "src":
|
||||
target = attr[1]
|
||||
if target and self.is_html and not target.startswith('http:') and not target.startswith('https:'):
|
||||
# This is actually more complicated than this check - protocol-relative stuff can work without full URLs
|
||||
if target.startswith('/'):
|
||||
base = urlparse(tr.base_dir)
|
||||
target = f"{base.scheme}://{base.netloc}{target}"
|
||||
else:
|
||||
target = tr.base_dir + target
|
||||
else:
|
||||
if target and not self.is_html and not target.startswith('/'):
|
||||
target = tr.base_dir + target
|
||||
if target and self.is_html and not target.startswith('http:'):
|
||||
target = tr.base_dir + target
|
||||
if target and target.startswith('http:'):
|
||||
x = hashlib.sha512(target.encode('utf-8')).hexdigest()
|
||||
p = f'/tmp/.browser-cache.{x}'
|
||||
if not os.path.exists(p):
|
||||
try:
|
||||
subprocess.check_output(['fetch','-o',p,target])
|
||||
except:
|
||||
print(f"Failed to download image: {target}")
|
||||
pass
|
||||
target = p
|
||||
if target and os.path.exists(target):
|
||||
try:
|
||||
img = self.img_from_path(target)
|
||||
except:
|
||||
print(f"Failed to load image {target}, going to show backup image.")
|
||||
img = None
|
||||
if not img:
|
||||
img = self.img_from_path('/usr/share/icons/16/missing.bmp')
|
||||
chop = math.ceil(img.get_height() / tr.line_height)
|
||||
group = []
|
||||
for i in range(chop):
|
||||
u = TextUnit("",4,self.current_font)
|
||||
u.set_extra('img',img)
|
||||
u.set_extra('offset',i * tr.line_height)
|
||||
if self.current_link:
|
||||
u.set_extra('link',self.current_link)
|
||||
u.set_tag_group(group)
|
||||
u.width = img.get_width()
|
||||
self.units.append(u)
|
||||
|
||||
def fix_whitespace(self):
|
||||
out_units = []
|
||||
last_was_whitespace = False
|
||||
for unit in self.units:
|
||||
if unit.unit_type == 3:
|
||||
last_was_whitespace = True
|
||||
out_units.append(unit)
|
||||
elif unit.unit_type == 1 and unit.string == ' ':
|
||||
if last_was_whitespace:
|
||||
continue
|
||||
last_was_whitespace = True
|
||||
out_units.append(unit)
|
||||
else:
|
||||
last_was_whitespace = False
|
||||
out_units.append(unit)
|
||||
self.units = out_units
|
||||
|
||||
def img_from_path(self, path):
|
||||
if not path in self.surface_cache:
|
||||
s = create_from_bmp(path)
|
||||
self.surface_cache[path] = s
|
||||
return s
|
||||
else:
|
||||
return self.surface_cache[path]
|
||||
|
||||
parser = RichTextParser(html=html)
|
||||
parser.feed(text)
|
||||
self.title = parser.title
|
||||
if html:
|
||||
parser.fix_whitespace()
|
||||
self.text_units = parser.units
|
||||
self.reflow()
|
||||
|
||||
def set_font(self, new_font):
|
||||
self.font = new_font
|
||||
self.line_height = self.font.font_size
|
||||
self.reflow()
|
||||
|
||||
def set_line_height(self, new_line_height):
|
||||
self.line_height = new_line_height
|
||||
self.reflow()
|
||||
|
||||
def resize(self, new_width, new_height):
|
||||
needs_reflow = self.width != new_width
|
||||
self.width = new_width
|
||||
self.height = new_height
|
||||
if needs_reflow:
|
||||
self.reflow()
|
||||
|
||||
def move(self, new_x, new_y):
|
||||
self.x = new_x
|
||||
self.y = new_y
|
||||
|
||||
def get_offset_at_index(self, index):
|
||||
""" Only works for one-liners... """
|
||||
if not self.lines:
|
||||
return None, (0, 0, 0, 0)
|
||||
left_align = 0
|
||||
xline = self.lines[0]
|
||||
if self.align == 1: # right align
|
||||
left_align = self.width - sum([u.width for u in xline])
|
||||
elif self.align == 2: # center
|
||||
left_align = int((self.width - sum([u.width for u in xline])) / 2)
|
||||
i = 0
|
||||
for unit in xline:
|
||||
if i == index:
|
||||
return unit, (0, left_align, left_align, i)
|
||||
left_align += unit.width
|
||||
i += 1
|
||||
return None, (0, left_align, left_align, i)
|
||||
|
||||
def pick(self, x, y):
|
||||
# Determine which line this click belongs in
|
||||
if x < self.x or x > self.x + self.width or y < self.y or y > self.y + self.height:
|
||||
return None, None
|
||||
top_align = 0
|
||||
if len(self.lines) < int(self.height / self.line_height):
|
||||
if self.valign == 1: # bottom
|
||||
top_align = self.height - len(self.lines) * self.line_height
|
||||
elif self.valign == 2: # middle
|
||||
top_align = int((self.height - len(self.lines) * self.line_height) / 2)
|
||||
new_y = y - top_align - self.y - 2 # fuzz factor
|
||||
line = int(new_y / self.line_height)
|
||||
if line < len(self.lines[self.scroll:]):
|
||||
left_align = 0
|
||||
xline = self.lines[self.scroll+line]
|
||||
if self.align == 1: # right align
|
||||
left_align = self.width - sum([u.width for u in xline])
|
||||
elif self.align == 2: # center
|
||||
left_align = int((self.width - sum([u.width for u in xline])) / 2)
|
||||
i = 0
|
||||
for unit in xline:
|
||||
if x >= self.x + left_align and x < self.x + left_align + unit.width:
|
||||
return unit, (line, left_align, x - self.x, i)
|
||||
left_align += unit.width
|
||||
i += 1
|
||||
return None, (line, left_align, x - self.x, i)
|
||||
return None, None
|
||||
|
||||
def click(self, x, y):
|
||||
unit, _ = self.pick(x,y)
|
||||
return unit
|
||||
|
||||
def draw(self, context):
|
||||
current_height = self.line_height
|
||||
top_align = 0
|
||||
if len(self.lines) < int(self.height / self.line_height):
|
||||
if self.valign == 1: # bottom
|
||||
top_align = self.height - len(self.lines) * self.line_height
|
||||
elif self.valign == 2: # middle
|
||||
top_align = int((self.height - len(self.lines) * self.line_height) / 2)
|
||||
su = context.get_cairo_surface() if 'get_cairo_surface' in dir(context) else None
|
||||
cr = cairo.Context(su) if su else None
|
||||
for line in self.lines[self.scroll:]:
|
||||
if current_height > self.height:
|
||||
break
|
||||
left_align = 0
|
||||
if self.align == 1: # right align
|
||||
left_align = self.width - sum([u.width for u in line])
|
||||
elif self.align == 2: # center
|
||||
left_align = int((self.width - sum([u.width for u in line])) / 2)
|
||||
for unit in line:
|
||||
if unit.unit_type == 4:
|
||||
cr.save()
|
||||
extra = 3
|
||||
cr.translate(self.x + left_align, self.y + current_height + top_align)
|
||||
if 'hilight' in unit.extra and unit.extra['hilight']:
|
||||
cr.rectangle(0,-self.line_height+extra,unit.extra['img'].get_width(),self.line_height)
|
||||
cr.set_source_rgb(1,0,0)
|
||||
cr.fill()
|
||||
cr.rectangle(0,-self.line_height+extra,unit.extra['img'].get_width(),self.line_height)
|
||||
cr.set_source_surface(unit.extra['img'],0,-unit.extra['offset']-self.line_height+extra)
|
||||
cr.fill()
|
||||
cr.restore()
|
||||
elif unit.unit_type == 2 and 'emoji' in unit.extra:
|
||||
cr.save()
|
||||
extra = 3
|
||||
cr.translate(self.x + left_align, self.y + current_height + top_align -self.line_height+extra)
|
||||
if unit.extra['img'].get_height() > self.line_height - 3:
|
||||
scale = (self.line_height - 3) / unit.extra['img'].get_height()
|
||||
cr.scale(scale,scale)
|
||||
cr.rectangle(0,0,unit.extra['img'].get_width(),unit.extra['img'].get_height())
|
||||
cr.set_source_surface(unit.extra['img'],0,0)
|
||||
cr.fill()
|
||||
cr.restore()
|
||||
elif unit.font:
|
||||
unit.font.write(context, self.x + left_align, self.y + current_height + top_align, unit.string)
|
||||
left_align += unit.width
|
||||
current_height += self.line_height
|
@ -1,92 +0,0 @@
|
||||
import ctypes
|
||||
import importlib
|
||||
|
||||
_cairo_lib = None
|
||||
_cairo_module = None
|
||||
_cairo_module_lib = None
|
||||
|
||||
_lib = None
|
||||
|
||||
if not _lib:
|
||||
_lib = ctypes.CDLL('libtoaru_ext_freetype_fonts.so')
|
||||
#_lib.init_shmemfonts() # No init call in new library
|
||||
_lib.freetype_draw_string_width.argtypes = [ctypes.c_char_p]
|
||||
_lib.freetype_draw_string_width.restype = ctypes.c_uint32
|
||||
_lib.freetype_font_name.restype = ctypes.c_char_p
|
||||
_lib.freetype_draw_string.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint32, ctypes.c_char_p]
|
||||
_lib.freetype_draw_string_shadow.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_uint32, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_double]
|
||||
_lib.freetype_get_active_font_face.restype = ctypes.c_void_p
|
||||
|
||||
FONT_SANS_SERIF = 0
|
||||
FONT_SANS_SERIF_BOLD = 1
|
||||
FONT_SANS_SERIF_ITALIC = 2
|
||||
FONT_SANS_SERIF_BOLD_ITALIC = 3
|
||||
FONT_MONOSPACE = 4
|
||||
FONT_MONOSPACE_BOLD = 5
|
||||
FONT_MONOSPACE_ITALIC = 6
|
||||
FONT_MONOSPACE_BOLD_ITALIC = 7
|
||||
FONT_JAPANESE = 8
|
||||
FONT_SYMBOLA = 9
|
||||
|
||||
def get_active_font():
|
||||
return _lib.freetype_get_active_font_face()
|
||||
|
||||
def get_cairo_face():
|
||||
global _cairo_lib
|
||||
global _cairo_module
|
||||
global _cairo_module_lib
|
||||
if not _cairo_lib:
|
||||
_cairo_lib = ctypes.CDLL('libcairo.so')
|
||||
_cairo_module = importlib.import_module('_cairo')
|
||||
_cairo_module_lib = ctypes.CDLL(_cairo_module.__file__)
|
||||
|
||||
cfffcfff = _cairo_lib.cairo_ft_font_face_create_for_ft_face
|
||||
cfffcfff.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
cfffcfff.restype = ctypes.c_void_p
|
||||
ft_face = cfffcfff(get_active_font(),0)
|
||||
|
||||
pcfffff = _cairo_module_lib.PycairoFontFace_FromFontFace
|
||||
pcfffff.argtypes = [ctypes.c_void_p]
|
||||
pcfffff.restype = ctypes.py_object
|
||||
return pcfffff(ft_face)
|
||||
|
||||
class Font(object):
|
||||
|
||||
def __init__(self, font_number, font_size=10, font_color=0xFF000000):
|
||||
self.font_number = font_number
|
||||
self.font_size = font_size
|
||||
self.font_color = font_color
|
||||
self.shadow = None
|
||||
|
||||
def set_shadow(self, shadow):
|
||||
self.shadow = shadow
|
||||
|
||||
def _use(self):
|
||||
_lib.freetype_set_font_face(self.font_number)
|
||||
_lib.freetype_set_font_size(self.font_size)
|
||||
|
||||
def width(self, string):
|
||||
self._use()
|
||||
string = string.encode('utf-8')
|
||||
return _lib.freetype_draw_string_width(string)
|
||||
|
||||
def write(self, ctx, x, y, string, shadow=None):
|
||||
if self.shadow:
|
||||
shadow = self.shadow
|
||||
self._use()
|
||||
foreground = self.font_color
|
||||
string = string.encode('utf-8')
|
||||
if hasattr(ctx,"_gfx"):
|
||||
# Allow a yutani.Window to be passed to this instead of a real graphics context
|
||||
ctx = ctx._gfx
|
||||
if shadow:
|
||||
color, darkness, offset_x, offset_y, radius = shadow
|
||||
_lib.freetype_draw_string_shadow(ctx,x,y,foreground,string,color,darkness,offset_x,offset_y,radius)
|
||||
else:
|
||||
_lib.freetype_draw_string(ctx,x,y,foreground,string)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return _lib.freetype_font_name(self.font_number).decode('utf-8')
|
||||
|
||||
|
@ -1,42 +0,0 @@
|
||||
#!/usr/bin/python3.6
|
||||
"""
|
||||
Toaru OS UI theming.
|
||||
"""
|
||||
|
||||
panel_widget_foreground = 0xFFE6E6E6
|
||||
panel_widget_hilight = 0xFF8EDBFF
|
||||
|
||||
menu_entry_text = 0xFF000000
|
||||
|
||||
panel_window_shadow = (0xFF000000, 2, 1, 1, 3.0)
|
||||
panel_window_gradient_top = (0.0,72/255,167/255,255/255,0.7)
|
||||
panel_window_gradient_low = (1.0,72/255,167/255,255/255,0.0)
|
||||
|
||||
panel_window_divider_top = (0.1,1,1,1,0.0)
|
||||
panel_window_divider_mid = (0.5,1,1,1,1.0)
|
||||
panel_window_divider_low = (0.9,1,1,1,0.0)
|
||||
|
||||
desktop_icon_hilight = (0x8E/0xFF,0xD8/0xFF,1,0.3)
|
||||
desktop_icon_shadow = (0xFF000000, 2, 1, 1, 3.0)
|
||||
desktop_icon_text = 0xFFFFFFFF
|
||||
|
||||
alt_tab_text = 0xFFE6E6E6
|
||||
alt_tab_background = (0,0,0,0.7)
|
||||
alt_tab_extra_text = '0x888888'
|
||||
|
||||
|
||||
def as_rgb_tuple(color):
|
||||
r = ((color & 0xFF0000) >> 16) / 0xFF
|
||||
g = ((color & 0xFF00) >> 8) / 0xFF
|
||||
b = ((color & 0xFF)) / 0xFF
|
||||
return (r,g,b)
|
||||
|
||||
def as_rgba_tuple(color):
|
||||
a = ((color & 0xFF000000) >> 24) / 0xFF
|
||||
r = ((color & 0xFF0000) >> 16) / 0xFF
|
||||
g = ((color & 0xFF00) >> 8) / 0xFF
|
||||
b = ((color & 0xFF)) / 0xFF
|
||||
return (r,g,b,a)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("...")
|
@ -1,115 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Tool to asynchronously fetch weather data from OpenWeatherMap.org
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
|
||||
with open('/etc/weather.json','r') as f:
|
||||
config = json.loads(f.read())
|
||||
|
||||
home = os.environ['HOME']
|
||||
if os.path.exists(f'{home}/.weather.json'):
|
||||
with open(f'{home}/.weather.json','r') as f:
|
||||
x_config = json.loads(f.read())
|
||||
for k in x_config:
|
||||
config[k] = x_config[k]
|
||||
else:
|
||||
x_config = {}
|
||||
|
||||
|
||||
key = config['key']
|
||||
city = config['city']
|
||||
units = config['units']
|
||||
|
||||
def write_config():
|
||||
with open(f'{home}/.weather.json','w') as f:
|
||||
f.write(json.dumps(x_config))
|
||||
|
||||
def write_out(data):
|
||||
with open('/tmp/weather.json','w') as f:
|
||||
f.write(data)
|
||||
try:
|
||||
os.chmod('/tmp/weather.json',0o666) # Ensure users can write this, too, for now.
|
||||
# Obviously a better approach would be a per-user file, but whatever.
|
||||
except:
|
||||
pass
|
||||
|
||||
def update_weather():
|
||||
|
||||
with open('/proc/netif','r') as f:
|
||||
lines = f.readlines()
|
||||
if len(lines) < 4 or "no network" in lines[0]:
|
||||
with open('/tmp/weather.json','w') as f:
|
||||
f.write("")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}&units={units}"
|
||||
data = subprocess.check_output(['fetch',url]).decode('utf-8').strip()
|
||||
weather = json.loads(data)
|
||||
if 'weather' in weather and len(weather['weather']) >= 1:
|
||||
conditions = weather['weather'][0]
|
||||
else:
|
||||
conditions = None
|
||||
temp = round(weather['main']['temp'])
|
||||
|
||||
output = {
|
||||
'temp': weather['main']['temp'],
|
||||
'temp_r': round(weather['main']['temp']),
|
||||
'conditions': conditions['main'] if conditions else None,
|
||||
'icon': conditions['icon'] if conditions else None,
|
||||
'humidity': weather['main']['humidity'],
|
||||
'clouds': weather['clouds']['all'] if 'all' in weather['clouds'] else None,
|
||||
'city': city,
|
||||
}
|
||||
|
||||
with open('/tmp/weather.json','w') as f:
|
||||
f.write(json.dumps(output))
|
||||
return True
|
||||
except:
|
||||
with open('/tmp/weather.json','w') as f:
|
||||
f.write("")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if "--config" in sys.argv:
|
||||
import yutani
|
||||
import yutani_mainloop
|
||||
from input_box import TextInputWindow
|
||||
|
||||
if __name__ == '__main__':
|
||||
yutani.Yutani()
|
||||
d = yutani.Decor()
|
||||
|
||||
def quit():
|
||||
sys.exit(0)
|
||||
|
||||
def set_units(inputbox):
|
||||
global units
|
||||
x_config['units'] = inputbox.text()
|
||||
units = x_config['units']
|
||||
inputbox.close()
|
||||
write_config()
|
||||
update_weather()
|
||||
quit()
|
||||
|
||||
def set_city(inputbox):
|
||||
global city
|
||||
x_config['city'] = inputbox.text()
|
||||
city = x_config['city']
|
||||
inputbox.close()
|
||||
TextInputWindow(d,"What units would you like? (metric, imperial, kelvin)","",text=units,callback=set_units, cancel_callback=quit)
|
||||
|
||||
TextInputWindow(d,"What city are you in?","",text=city,callback=set_city,cancel_callback=quit)
|
||||
|
||||
yutani_mainloop.mainloop()
|
||||
sys.exit(0)
|
||||
|
||||
else:
|
||||
if not update_weather():
|
||||
sys.exit(1)
|
||||
|
@ -1,889 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
"""
|
||||
Bindings for the Yutani graphics libraries, including the core Yutani protocol,
|
||||
general graphics routines, and the system decoration library.
|
||||
"""
|
||||
|
||||
from ctypes import *
|
||||
import importlib
|
||||
|
||||
yutani_lib = None
|
||||
yutani_gfx_lib = None
|
||||
yutani_ctx = None
|
||||
yutani_menu_lib = None
|
||||
yutani_windows = {}
|
||||
|
||||
_cairo_lib = None
|
||||
_cairo_module = None
|
||||
_cairo_module_lib = None
|
||||
|
||||
_libc = CDLL('libc.so')
|
||||
|
||||
def usleep(microseconds):
|
||||
_libc.usleep(microseconds)
|
||||
|
||||
class Message(object):
|
||||
"""A generic event message from the Yutani server."""
|
||||
class _yutani_msg_t(Structure):
|
||||
_fields_ = [
|
||||
('magic', c_uint32),
|
||||
('type', c_uint32),
|
||||
('size', c_uint32),
|
||||
('data', c_char*0),
|
||||
]
|
||||
|
||||
MSG_HELLO = 0x00000001
|
||||
MSG_WINDOW_NEW = 0x00000002
|
||||
MSG_FLIP = 0x00000003
|
||||
MSG_KEY_EVENT = 0x00000004
|
||||
MSG_MOUSE_EVENT = 0x00000005
|
||||
MSG_WINDOW_MOVE = 0x00000006
|
||||
MSG_WINDOW_CLOSE = 0x00000007
|
||||
MSG_WINDOW_SHOW = 0x00000008
|
||||
MSG_WINDOW_HIDE = 0x00000009
|
||||
MSG_WINDOW_STACK = 0x0000000A
|
||||
MSG_WINDOW_FOCUS_CHANGE = 0x0000000B
|
||||
MSG_WINDOW_MOUSE_EVENT = 0x0000000C
|
||||
MSG_FLIP_REGION = 0x0000000D
|
||||
MSG_WINDOW_NEW_FLAGS = 0x0000000E
|
||||
MSG_RESIZE_REQUEST = 0x00000010
|
||||
MSG_RESIZE_OFFER = 0x00000011
|
||||
MSG_RESIZE_ACCEPT = 0x00000012
|
||||
MSG_RESIZE_BUFID = 0x00000013
|
||||
MSG_RESIZE_DONE = 0x00000014
|
||||
MSG_WINDOW_ADVERTISE = 0x00000020
|
||||
MSG_SUBSCRIBE = 0x00000021
|
||||
MSG_UNSUBSCRIBE = 0x00000022
|
||||
MSG_NOTIFY = 0x00000023
|
||||
MSG_QUERY_WINDOWS = 0x00000024
|
||||
MSG_WINDOW_FOCUS = 0x00000025
|
||||
MSG_WINDOW_DRAG_START = 0x00000026
|
||||
MSG_WINDOW_WARP_MOUSE = 0x00000027
|
||||
MSG_WINDOW_SHOW_MOUSE = 0x00000028
|
||||
MSG_WINDOW_RESIZE_START = 0x00000029
|
||||
MSG_SESSION_END = 0x00000030
|
||||
MSG_KEY_BIND = 0x00000040
|
||||
MSG_WINDOW_UPDATE_SHAPE = 0x00000050
|
||||
MSG_GOODBYE = 0x000000F0
|
||||
MSG_TIMER_REQUEST = 0x00000100 # XXX deprecated
|
||||
MSG_TIMER_TICK = 0x00000101 # xxx deprecated
|
||||
MSG_WELCOME = 0x00010001
|
||||
MSG_WINDOW_INIT = 0x00010002
|
||||
|
||||
def __init__(self, msg):
|
||||
self._ptr = msg
|
||||
|
||||
def free(self):
|
||||
if self._ptr:
|
||||
_libc.free(self._ptr)
|
||||
self._ptr = None
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
return self._ptr.contents.type
|
||||
|
||||
_message_types = {}
|
||||
|
||||
class MessageBuilder(type):
|
||||
|
||||
def __new__(cls, name, bases, dct):
|
||||
global _message_types
|
||||
new_cls = super(MessageBuilder, cls).__new__(cls, name, bases, dct)
|
||||
if 'type_val' in dct:
|
||||
_message_types[dct['type_val']] = new_cls
|
||||
return new_cls
|
||||
|
||||
class MessageEx(Message, metaclass=MessageBuilder):
|
||||
"""An event message with extra data available."""
|
||||
type_val = None
|
||||
data_struct = None
|
||||
|
||||
def __init__(self, msg):
|
||||
Message.__init__(self, msg)
|
||||
self._data_ptr = cast(byref(self._ptr.contents,Message._yutani_msg_t.data.offset), POINTER(self.data_struct))
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in dir(self._data_ptr.contents):
|
||||
return getattr(self._data_ptr.contents, name)
|
||||
raise AttributeError(name)
|
||||
|
||||
class MessageWelcome(MessageEx):
|
||||
"""Message sent by the server on display size changes."""
|
||||
type_val = Message.MSG_WELCOME
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('display_width', c_uint32),
|
||||
('display_height', c_uint32),
|
||||
]
|
||||
|
||||
class Keycode(object):
|
||||
"""Keycodes."""
|
||||
NONE = 0
|
||||
BACKSPACE = 8
|
||||
CTRL_A = 1
|
||||
CTRL_B = 2
|
||||
CTRL_C = 3
|
||||
CTRL_D = 4
|
||||
CTRL_E = 5
|
||||
CTRL_F = 6
|
||||
CTRL_G = 7
|
||||
CTRL_H = 8
|
||||
CTRL_I = 9
|
||||
CTRL_J = 10
|
||||
CTRL_K = 11
|
||||
CTRL_L = 12
|
||||
CTRL_M = 13
|
||||
CTRL_N = 14
|
||||
CTRL_O = 15
|
||||
CTRL_P = 16
|
||||
CTRL_Q = 17
|
||||
CTRL_R = 18
|
||||
CTRL_S = 19
|
||||
CTRL_T = 20
|
||||
CTRL_U = 21
|
||||
CTRL_V = 22
|
||||
CTRL_W = 23
|
||||
CTRL_X = 24
|
||||
CTRL_Y = 25
|
||||
CTRL_Z = 26
|
||||
ESCAPE = 27
|
||||
NORMAL_MAX = 256
|
||||
ARROW_UP = 257
|
||||
ARROW_DOWN = 258
|
||||
ARROW_RIGHT = 259
|
||||
ARROW_LEFT = 260
|
||||
BAD_STATE = -1
|
||||
|
||||
CTRL_ARROW_UP = 261
|
||||
CTRL_ARROW_DOWN = 262
|
||||
CTRL_ARROW_RIGHT = 263
|
||||
CTRL_ARROW_LEFT = 264
|
||||
|
||||
SHIFT_ARROW_UP = 265
|
||||
SHIFT_ARROW_DOWN = 266
|
||||
SHIFT_ARROW_RIGHT = 267
|
||||
SHIFT_ARROW_LEFT = 268
|
||||
|
||||
LEFT_CTRL = 1001
|
||||
LEFT_SHIFT = 1002
|
||||
LEFT_ALT = 1003
|
||||
LEFT_SUPER = 1004
|
||||
|
||||
RIGHT_CTRL = 1011
|
||||
RIGHT_SHIFT = 1012
|
||||
RIGHT_ALT = 1013
|
||||
RIGHT_SUPER = 1014
|
||||
|
||||
F1 = 2001
|
||||
F2 = 2002
|
||||
F3 = 2003
|
||||
F4 = 2004
|
||||
F5 = 2005
|
||||
F6 = 2006
|
||||
F7 = 2007
|
||||
F8 = 2008
|
||||
F9 = 2009
|
||||
F10 = 2010
|
||||
F11 = 2011
|
||||
F12 = 2012
|
||||
|
||||
PAGE_DOWN = 2013
|
||||
PAGE_UP = 2014
|
||||
|
||||
HOME = 2015
|
||||
END = 2016
|
||||
DEL = 2017
|
||||
INSERT = 2018
|
||||
|
||||
class Modifier(object):
|
||||
"""Modifier key flags."""
|
||||
MOD_LEFT_CTRL = 0x01
|
||||
MOD_LEFT_SHIFT = 0x02
|
||||
MOD_LEFT_ALT = 0x04
|
||||
MOD_LEFT_SUPER = 0x08
|
||||
MOD_RIGHT_CTRL = 0x10
|
||||
MOD_RIGHT_SHIFT = 0x20
|
||||
MOD_RIGHT_ALT = 0x40
|
||||
MOD_RIGHT_SUPER = 0x80
|
||||
|
||||
class KeyAction(object):
|
||||
"""Keyboard action (up or down)"""
|
||||
ACTION_DOWN = 1
|
||||
ACTION_UP = 2
|
||||
|
||||
class MessageKeyEvent(MessageEx):
|
||||
"""Message containing key event information."""
|
||||
type_val = Message.MSG_KEY_EVENT
|
||||
class data_struct(Structure):
|
||||
class key_event_t(Structure):
|
||||
_fields_ = [
|
||||
('keycode', c_uint),
|
||||
('modifiers', c_uint),
|
||||
('action', c_ubyte),
|
||||
('key', c_char),
|
||||
]
|
||||
class key_event_state_t(Structure):
|
||||
_fields = [
|
||||
("kbd_state", c_int),
|
||||
("kbd_s_state", c_int),
|
||||
|
||||
("k_ctrl", c_int),
|
||||
("k_shift", c_int),
|
||||
("k_alt", c_int),
|
||||
("k_super", c_int),
|
||||
|
||||
("kl_ctrl", c_int),
|
||||
("kl_shift", c_int),
|
||||
("kl_alt", c_int),
|
||||
("kl_super", c_int),
|
||||
|
||||
("kr_ctrl", c_int),
|
||||
("kr_shift", c_int),
|
||||
("kr_alt", c_int),
|
||||
("kr_super", c_int),
|
||||
|
||||
("kbd_esc_buf", c_int),
|
||||
]
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('event', key_event_t),
|
||||
('state', key_event_state_t),
|
||||
]
|
||||
|
||||
class MessageWindowMouseEvent(MessageEx):
|
||||
"""Message containing window-relative mouse event information."""
|
||||
type_val = Message.MSG_WINDOW_MOUSE_EVENT
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('new_x', c_int32),
|
||||
('new_y', c_int32),
|
||||
('old_x', c_int32),
|
||||
('old_y', c_int32),
|
||||
('buttons', c_ubyte),
|
||||
('command', c_ubyte),
|
||||
]
|
||||
|
||||
class MessageWindowFocusChange(MessageEx):
|
||||
"""Message indicating the focus state of a window has changed."""
|
||||
type_val = Message.MSG_WINDOW_FOCUS_CHANGE
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('focused', c_int),
|
||||
]
|
||||
|
||||
class MessageWindowResize(MessageEx):
|
||||
"""Message indicating the server wishes to resize this window."""
|
||||
type_val = Message.MSG_RESIZE_OFFER
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('width', c_uint32),
|
||||
('height', c_uint32),
|
||||
('bufid', c_uint32),
|
||||
]
|
||||
|
||||
class MessageWindowAdvertisement(MessageEx):
|
||||
"""Message containing information about a foreign window."""
|
||||
type_val = Message.MSG_WINDOW_ADVERTISE
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('flags', c_uint32),
|
||||
('offsets', c_uint16 * 5),
|
||||
('size', c_uint32),
|
||||
('strings', c_byte * 0),
|
||||
]
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return string_at(addressof(self.strings) + self.offsets[0]).decode('utf-8')
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
return string_at(addressof(self.strings) + self.offsets[1]).decode('utf-8')
|
||||
|
||||
class MessageWindowMove(MessageEx):
|
||||
"""Message received when a window has moved containing its new coordinates."""
|
||||
type_val = Message.MSG_WINDOW_MOVE
|
||||
class data_struct(Structure):
|
||||
_fields_ = [
|
||||
('wid', c_uint32),
|
||||
('x', c_int32),
|
||||
('y', c_int32),
|
||||
]
|
||||
|
||||
class Yutani(object):
|
||||
"""Base Yutani communication class. Must be initialized to start a connection."""
|
||||
class _yutani_t(Structure):
|
||||
_fields_ = [
|
||||
("sock", c_void_p), # File pointer
|
||||
("display_width", c_size_t),
|
||||
("display_height", c_size_t),
|
||||
("windows", c_void_p), # hashmap
|
||||
("queued", c_void_p), # list
|
||||
("server_ident", c_char_p),
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
global yutani_lib
|
||||
global yutani_ctx
|
||||
global yutani_gfx_lib
|
||||
global yutani_menu_lib
|
||||
if not yutani_lib:
|
||||
yutani_lib = CDLL("libtoaru_yutani.so")
|
||||
if not yutani_gfx_lib:
|
||||
yutani_gfx_lib = CDLL("libtoaru_graphics.so")
|
||||
if not yutani_menu_lib:
|
||||
yutani_menu_lib = CDLL("libtoaru_menu.so")
|
||||
self._ptr = cast(yutani_lib.yutani_init(), POINTER(self._yutani_t))
|
||||
if not self._ptr:
|
||||
raise ConnectionRefusedError("Could not connect to compositor.")
|
||||
yutani_ctx = self
|
||||
self._fileno = _libc.fileno(self._ptr.contents.sock)
|
||||
|
||||
def process_menus(self, event):
|
||||
return yutani_menu_lib.menu_process_event(self._ptr, event._ptr)
|
||||
|
||||
def poll(self, sync=True):
|
||||
"""Poll for an event message."""
|
||||
if sync:
|
||||
result = yutani_lib.yutani_poll(self._ptr)
|
||||
else:
|
||||
result = yutani_lib.yutani_poll_async(self._ptr)
|
||||
if not result:
|
||||
return None
|
||||
msg_ptr = cast(result, POINTER(Message._yutani_msg_t))
|
||||
msg_class = _message_types.get(msg_ptr.contents.type, Message)
|
||||
return msg_class(msg_ptr)
|
||||
|
||||
def wait_for(self, message):
|
||||
"""Wait for a particular kind of message to be delivered."""
|
||||
result = yutani_lib.yutani_wait_for(self._ptr, message)
|
||||
msg_ptr = cast(result, POINTER(Message._yutani_msg_t))
|
||||
msg_class = _message_types.get(msg_ptr.contents.type, Message)
|
||||
return msg_class(msg_ptr)
|
||||
|
||||
def subscribe(self):
|
||||
"""Subscribe to window information changes."""
|
||||
yutani_lib.yutani_subscribe_windows(self._ptr)
|
||||
|
||||
def unsubscribe(self):
|
||||
"""Unsubscribe from window information changes."""
|
||||
yutani_lib.yutani_unsubscribe_windows(self._ptr)
|
||||
|
||||
def query_windows(self):
|
||||
"""Request a window subsription list."""
|
||||
yutani_lib.yutani_query_windows(self._ptr)
|
||||
|
||||
def focus_window(self, wid):
|
||||
"""Request that the server change the focused window to the window with the specified wid."""
|
||||
yutani_lib.yutani_focus_window(self._ptr, wid)
|
||||
|
||||
def session_end(self):
|
||||
"""Request the end of the user session."""
|
||||
yutani_lib.yutani_session_end(self._ptr)
|
||||
|
||||
def key_bind(self, keycode, modifiers, flags):
|
||||
"""Set global key binding."""
|
||||
yutani_lib.yutani_key_bind(self._ptr, keycode, modifiers, flags)
|
||||
|
||||
def fileno(self):
|
||||
"""Act file-like and return our file descriptor number."""
|
||||
return self._fileno
|
||||
|
||||
def query(self):
|
||||
"""Asynchronously check if data is available."""
|
||||
return yutani_lib.yutani_query(self._ptr)
|
||||
|
||||
class KeybindFlag(object):
|
||||
"""Flags for global key bindings."""
|
||||
BIND_PASSTHROUGH = 0 # The key bind should be received by other clients.
|
||||
BIND_STEAL = 1 # The key bind should stop after being processed here.
|
||||
|
||||
class WindowShape(object):
|
||||
"""Window shaping modes for Window.update_shape."""
|
||||
# These are actually values representing the minimum required
|
||||
# alpha value for a pixel to be registered as part of the given window.
|
||||
# 256 is more than the maximum alpha value, so all clicks will pass through.
|
||||
# 0 will catch every pixel, even if it is entirely transparent.
|
||||
THRESHOLD_NONE = 0
|
||||
THRESHOLD_CLEAR = 1
|
||||
THRESHOLD_HALF = 127
|
||||
THRESHOLD_ANY = 255
|
||||
THRESHOLD_PASSTHROUGH = 256
|
||||
|
||||
class WindowStackOrder(object):
|
||||
"""Window stack order options."""
|
||||
ZORDER_MAX = 0xFFFF
|
||||
ZORDER_TOP = 0xFFFF
|
||||
ZORDER_BOTTOM = 0x0000
|
||||
|
||||
class WindowFlag(object):
|
||||
"""Flags for window creation."""
|
||||
FLAG_NO_STEAL_FOCUS = (1 << 0) # Don't steal focus on window creation.
|
||||
FLAG_DISALLOW_DRAG = (1 << 1) # Don't allow this window to be dragged.
|
||||
FLAG_DISALLOW_RESIZE = (1 << 2) # Don't allow this window to be resized.
|
||||
FLAG_ALT_ANIMATION = (1 << 3) # Use the alternate animation when mapping and unmapping.
|
||||
|
||||
class MouseButton(object):
|
||||
"""Mouse button flags."""
|
||||
BUTTON_LEFT = 0x01
|
||||
BUTTON_RIGHT = 0x02
|
||||
BUTTON_MIDDLE = 0x04
|
||||
SCROLL_UP = 0x10
|
||||
SCROLL_DOWN = 0x20
|
||||
|
||||
class MouseEvent(object):
|
||||
"""Mouse event types."""
|
||||
CLICK = 0
|
||||
DRAG = 1
|
||||
RAISE = 2
|
||||
DOWN = 3
|
||||
MOVE = 4
|
||||
LEAVE = 5
|
||||
ENTER = 6
|
||||
|
||||
class CursorType(object):
|
||||
"""Cursor types for show_mouse."""
|
||||
RESET = -1
|
||||
HIDE = 0
|
||||
NORMAL = 1
|
||||
DRAG = 2
|
||||
RESIZE_VERTICAL = 3
|
||||
RESIZE_HORIZONTAL = 4
|
||||
RESIZE_UP_DOWN = 5
|
||||
RESIZE_DOWN_UP = 6
|
||||
|
||||
class Sprite(object):
|
||||
class _sprite_t(Structure):
|
||||
_fields_ = [
|
||||
('width', c_uint16),
|
||||
('height', c_uint16),
|
||||
('bitmap', POINTER(c_char)),
|
||||
('masks', POINTER(c_char)),
|
||||
('blank', c_uint32),
|
||||
('alpha', c_uint8),
|
||||
]
|
||||
|
||||
@property
|
||||
def width(self):
|
||||
return self._ptr.contents.width
|
||||
|
||||
@property
|
||||
def height(self):
|
||||
return self._ptr.contents.height
|
||||
|
||||
@property
|
||||
def buffer(self):
|
||||
return self._ptr.contents.bitmap
|
||||
|
||||
def get_cairo_surface(self):
|
||||
class Derp(object):
|
||||
pass
|
||||
self._gfx = Derp()
|
||||
self._gfx.contents = Derp()
|
||||
self._gfx.contents.backbuffer = self._ptr.contents.bitmap
|
||||
self._cairo_surface = Window.get_cairo_surface(self)
|
||||
return self._cairo_surface
|
||||
|
||||
def from_file(path):
|
||||
global yutani_gfx_lib
|
||||
if not yutani_gfx_lib:
|
||||
yutani_gfx_lib = CDLL("libtoaru_graphics.so")
|
||||
s = Sprite()
|
||||
s._contents = create_string_buffer(sizeof(Sprite._sprite_t))
|
||||
s._ptr = cast(addressof(s._contents), POINTER(Sprite._sprite_t))
|
||||
yutani_gfx_lib.load_sprite.argtypes = [c_void_p, c_char_p]
|
||||
yutani_gfx_lib.load_sprite(s._ptr, path.encode('utf-8'))
|
||||
return s
|
||||
|
||||
def create(width, height):
|
||||
s = Sprite()
|
||||
s._ptr = yutani_gfx_lib.create_sprite(width, height)
|
||||
return s
|
||||
|
||||
def free(self):
|
||||
yutani_gfx_lib.sprite_free(self._ptr)
|
||||
|
||||
|
||||
class GraphicsBuffer(object):
|
||||
"""Generic buffer for rendering."""
|
||||
|
||||
def __init__(self, width, height):
|
||||
self.width = width
|
||||
self.height = height
|
||||
|
||||
self._sprite = yutani_gfx_lib.create_sprite(width,height,2)
|
||||
self._gfx = cast(yutani_gfx_lib.init_graphics_sprite(self._sprite),POINTER(Window._gfx_context_t))
|
||||
|
||||
def get_cairo_surface(self):
|
||||
return Window.get_cairo_surface(self)
|
||||
|
||||
def get_value(self,x,y):
|
||||
return cast(self._gfx.contents.backbuffer,POINTER(c_uint32))[self.width * y + x]
|
||||
|
||||
def destroy(self):
|
||||
yutani_gfx_lib.sprite_free(self._sprite)
|
||||
_libc.free(self._gfx)
|
||||
|
||||
|
||||
class Window(object):
|
||||
"""Yutani Window object."""
|
||||
class _yutani_window_t(Structure):
|
||||
_fields_ = [
|
||||
("wid", c_uint),
|
||||
("width", c_uint32),
|
||||
("height", c_uint32),
|
||||
("buffer", POINTER(c_uint8)),
|
||||
("bufid", c_uint32),
|
||||
("focused", c_uint8),
|
||||
("oldbufid", c_uint32),
|
||||
("userdata", c_void_p),
|
||||
("x", c_int32),
|
||||
("y", c_int32),
|
||||
("decorator_flags", c_uint32),
|
||||
("ctx", c_void_p),
|
||||
]
|
||||
|
||||
class _gfx_context_t(Structure):
|
||||
_fields_ = [
|
||||
('width', c_uint16),
|
||||
('height', c_uint16),
|
||||
('depth', c_uint16),
|
||||
('size', c_uint32),
|
||||
('buffer', POINTER(c_char)),
|
||||
('backbuffer', POINTER(c_char)),
|
||||
]
|
||||
|
||||
def __init__(self, width, height, flags=0, title=None, icon=None, doublebuffer=False):
|
||||
if not yutani_ctx:
|
||||
raise ValueError("Not connected.")
|
||||
|
||||
self._ptr = cast(yutani_lib.yutani_window_create_flags(yutani_ctx._ptr, width, height, flags), POINTER(self._yutani_window_t))
|
||||
|
||||
yutani_windows[self.wid] = self
|
||||
|
||||
self.doublebuffer = doublebuffer
|
||||
|
||||
if doublebuffer:
|
||||
self._gfx = cast(yutani_lib.init_graphics_yutani_double_buffer(self._ptr), POINTER(self._gfx_context_t))
|
||||
else:
|
||||
self._gfx = cast(yutani_lib.init_graphics_yutani(self._ptr), POINTER(self._gfx_context_t))
|
||||
|
||||
if title:
|
||||
self.set_title(title, icon)
|
||||
|
||||
self.closed = False
|
||||
|
||||
def get_cairo_surface(self):
|
||||
"""Obtain a pycairo.ImageSurface representing the window backbuffer."""
|
||||
global _cairo_lib
|
||||
global _cairo_module
|
||||
global _cairo_module_lib
|
||||
if not _cairo_lib:
|
||||
_cairo_lib = CDLL('libcairo.so')
|
||||
_cairo_module = importlib.import_module('_cairo')
|
||||
_cairo_module_lib = CDLL(_cairo_module.__file__)
|
||||
buffer = self._gfx.contents.backbuffer
|
||||
width = self.width
|
||||
height = self.height
|
||||
format = _cairo_module.FORMAT_ARGB32
|
||||
# int cairo_format_stride_for_width(cairo_format_t format, int width)
|
||||
cfsfw = _cairo_lib.cairo_format_stride_for_width
|
||||
cfsfw.argtypes = [c_int, c_int]
|
||||
cfsfw.restype = c_int
|
||||
# stride = cairo_format_stride_for_width(format, width)
|
||||
stride = cfsfw(format, width)
|
||||
# cairo_surface_t * cairo_image_surface_create_for_data(unsigned char * data, cairo_format_t format, int ...)
|
||||
ciscfd = _cairo_lib.cairo_image_surface_create_for_data
|
||||
ciscfd.argtypes = [POINTER(c_char), c_int, c_int, c_int, c_int]
|
||||
ciscfd.restype = c_void_p
|
||||
# surface = cairo_image_surface_create_for_data(buffer,format,width,height,stride)
|
||||
surface = ciscfd(buffer,format,width,height,stride)
|
||||
# PyObject * PycairoSurface_FromSurface(cairo_surface_t * surface, PyObject * base)
|
||||
pcsfs = _cairo_module_lib.PycairoSurface_FromSurface
|
||||
pcsfs.argtypes = [c_void_p, c_int]
|
||||
pcsfs.restype = py_object
|
||||
# return PycairoSurface_FromSurface(surface, NULL)
|
||||
return pcsfs(surface, 0)
|
||||
|
||||
|
||||
def set_title(self, title, icon=None):
|
||||
"""Advertise this window with the given title and optional icon string."""
|
||||
self.title = title
|
||||
self.icon = icon
|
||||
title_string = title.encode('utf-8') if title else None
|
||||
icon_string = icon.encode('utf-8') if icon else None
|
||||
|
||||
if not icon:
|
||||
yutani_lib.yutani_window_advertise(yutani_ctx._ptr, self._ptr, title_string)
|
||||
else:
|
||||
yutani_lib.yutani_window_advertise_icon(yutani_ctx._ptr, self._ptr, title_string, icon_string)
|
||||
|
||||
def buffer(self):
|
||||
"""Obtain a reference to the graphics backbuffer representing this window's canvas."""
|
||||
return cast(self._gfx.contents.backbuffer, POINTER(c_uint32))
|
||||
|
||||
def flip(self, region=None):
|
||||
"""Flip the window buffer when double buffered and inform the server of updates."""
|
||||
if self.doublebuffer:
|
||||
yutani_gfx_lib.flip(self._gfx)
|
||||
yutani_lib.yutani_flip(yutani_ctx._ptr, self._ptr)
|
||||
|
||||
def close(self):
|
||||
"""Close the window."""
|
||||
if self.wid in yutani_windows:
|
||||
del yutani_windows[self.wid]
|
||||
self.closed = True
|
||||
yutani_lib.yutani_close(yutani_ctx._ptr, self._ptr)
|
||||
yutani_lib.release_graphics_yutani(self._gfx)
|
||||
|
||||
def move(self, x, y):
|
||||
"""Move the window to the requested location."""
|
||||
yutani_lib.yutani_window_move(yutani_ctx._ptr, self._ptr, x, y)
|
||||
|
||||
def resize_accept(self, w, h):
|
||||
"""Inform the server that we have accepted the offered resize."""
|
||||
yutani_lib.yutani_window_resize_accept(yutani_ctx._ptr, self._ptr, w, h)
|
||||
|
||||
def resize_done(self):
|
||||
"""Inform the server that we are done resizing and the new window may be displayed."""
|
||||
yutani_lib.yutani_window_resize_done(yutani_ctx._ptr, self._ptr)
|
||||
|
||||
def resize_offer(self, width, height):
|
||||
"""Offer alternative dimensions in response to a server offer."""
|
||||
yutani_lib.yutani_window_resize_offer(yutani_ctx._ptr, self._ptr, width, height)
|
||||
|
||||
def resize(self, width, height):
|
||||
"""Request that a window be resized to the given dimensions."""
|
||||
yutani_lib.yutani_window_resize(yutani_ctx._ptr, self._ptr, width, height)
|
||||
|
||||
def reinit(self):
|
||||
"""Reinitialize the internal graphics context for the window. Should be done after a resize_accept."""
|
||||
yutani_lib.reinit_graphics_yutani(self._gfx, self._ptr)
|
||||
|
||||
def fill(self, color):
|
||||
"""Fill the entire window with a given color."""
|
||||
yutani_gfx_lib.draw_fill(self._gfx, color)
|
||||
|
||||
def update_shape(self, mode):
|
||||
"""Set the mouse passthrough / window shaping mode. Does not affect appearance of window."""
|
||||
yutani_lib.yutani_window_update_shape(yutani_ctx._ptr, self._ptr, mode)
|
||||
|
||||
def set_stack(self, stack):
|
||||
"""Set the stack layer for the window."""
|
||||
yutani_lib.yutani_set_stack(yutani_ctx._ptr, self._ptr, stack)
|
||||
|
||||
def drag_start(self):
|
||||
"""Begin window drag."""
|
||||
yutani_lib.yutani_window_drag_start(yutani_ctx._ptr, self._ptr)
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
return self._ptr.contents.x
|
||||
|
||||
@property
|
||||
def y(self):
|
||||
return self._ptr.contents.y
|
||||
|
||||
@property
|
||||
def width(self):
|
||||
return self._ptr.contents.width
|
||||
|
||||
@property
|
||||
def height(self):
|
||||
return self._ptr.contents.height
|
||||
|
||||
# TODO: setters for width/height call resize?
|
||||
|
||||
@property
|
||||
def wid(self):
|
||||
"""The identifier of the window."""
|
||||
return self._ptr.contents.wid
|
||||
|
||||
@property
|
||||
def focused(self):
|
||||
"""Whether the window is current focused."""
|
||||
return self._ptr.contents.focused
|
||||
|
||||
@focused.setter
|
||||
def focused(self, value):
|
||||
self._ptr.contents.focused = value
|
||||
|
||||
class Decor(object):
|
||||
"""Class for rendering decorations with the system decorator library."""
|
||||
|
||||
EVENT_OTHER = 1
|
||||
EVENT_CLOSE = 2
|
||||
EVENT_RESIZE = 3
|
||||
EVENT_MAXIMIZE = 4
|
||||
EVENT_RIGHT = 5
|
||||
|
||||
class decor_bound(Structure):
|
||||
_fields_ = [
|
||||
("top_height", c_int),
|
||||
("bottom_height", c_int),
|
||||
("left_width", c_int),
|
||||
("right_width", c_int),
|
||||
("width", c_int),
|
||||
("height", c_int),
|
||||
]
|
||||
|
||||
def __init__(self):
|
||||
self.lib = CDLL("libtoaru_decorations.so")
|
||||
self.lib.init_decorations()
|
||||
self._bounds = self.decor_bound()
|
||||
|
||||
self._decor_get_bounds = cast(c_void_p.in_dll(self.lib, "decor_get_bounds").value, CFUNCTYPE(c_int, c_void_p, c_void_p))
|
||||
|
||||
def _get_bounds(self, window):
|
||||
self._decor_get_bounds(window._ptr if window else None, byref(self._bounds))
|
||||
|
||||
def bounds(self,window=None):
|
||||
self._get_bounds(window)
|
||||
return self._bounds
|
||||
|
||||
def width(self,window=None):
|
||||
"""The complete width of the left and right window borders."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.width)
|
||||
|
||||
def height(self,window=None):
|
||||
"""The complete height of the top and bottom window borders."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.height)
|
||||
|
||||
def top_height(self,window=None):
|
||||
"""The height of the top edge of the decorations."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.top_height)
|
||||
|
||||
def bottom_height(self,window=None):
|
||||
"""The height of the bottom edge of the decorations."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.bottom_height)
|
||||
|
||||
def left_width(self,window=None):
|
||||
"""The width of the left edge of the decorations."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.left_width)
|
||||
|
||||
def right_width(self,window=None):
|
||||
"""The width of the right edge of the decorations."""
|
||||
self._get_bounds(window)
|
||||
return int(self._bounds.right_width)
|
||||
|
||||
def render(self, window, title=None):
|
||||
"""Render decorations on this window. If a title is not provided, it will be retreived from the window object."""
|
||||
if not title:
|
||||
title = window.title
|
||||
title_string = title.encode('utf-8') if title else None
|
||||
self.lib.render_decorations(window._ptr, window._gfx, title_string)
|
||||
|
||||
def handle_event(self, msg):
|
||||
"""Let the decorator library handle an event. Usually passed mouse events."""
|
||||
return self.lib.decor_handle_event(yutani_ctx._ptr, msg._ptr)
|
||||
|
||||
def show_menu(self, window, event):
|
||||
self.lib.decor_show_default_menu(window._ptr, window.x + event.new_x, window.y + event.new_y)
|
||||
|
||||
# Demo follows.
|
||||
if __name__ == '__main__':
|
||||
# Connect to the server.
|
||||
Yutani()
|
||||
|
||||
# Initialize the decoration library.
|
||||
d = Decor()
|
||||
|
||||
# Create a new window.
|
||||
w = Window(300+d.width(),300+d.height(),title="Python Demo")
|
||||
|
||||
# Since this is Python, we can attach data to our window, such
|
||||
# as its internal width (excluding the decorations).
|
||||
w.int_width = 300
|
||||
w.int_height = 300
|
||||
|
||||
# We can set window shaping...
|
||||
#w.update_shape(WindowShape.THRESHOLD_HALF)
|
||||
|
||||
# Move the window...
|
||||
w.move(100, 100)
|
||||
|
||||
def draw_decors():
|
||||
"""Render decorations for the window."""
|
||||
d.render(w)
|
||||
|
||||
def draw_window():
|
||||
"""Draw the window."""
|
||||
w.fill(0xFFFF00FF)
|
||||
draw_decors()
|
||||
|
||||
def finish_resize(msg):
|
||||
"""Accept a resize."""
|
||||
|
||||
# Tell the server we accept.
|
||||
w.resize_accept(msg.width, msg.height)
|
||||
|
||||
# Reinitialize internal graphics context.
|
||||
w.reinit()
|
||||
|
||||
# Calculate new internal dimensions.
|
||||
w.int_width = msg.width - d.width()
|
||||
w.int_height = msg.height - d.height()
|
||||
|
||||
# Redraw the window buffer.
|
||||
draw_window()
|
||||
|
||||
# Inform the server we are done.
|
||||
w.resize_done()
|
||||
|
||||
# And flip.
|
||||
w.flip()
|
||||
|
||||
# Do an initial draw.
|
||||
draw_window()
|
||||
|
||||
# Don't forget to flip. Our single-buffered window only needs
|
||||
# the Yutani flip call, but the API will perform both if needed.
|
||||
w.flip()
|
||||
|
||||
while 1:
|
||||
# Poll for events.
|
||||
msg = yutani_ctx.poll()
|
||||
if msg.type == Message.MSG_SESSION_END:
|
||||
# All applications should attempt to exit on SESSION_END.
|
||||
w.close()
|
||||
break
|
||||
elif msg.type == Message.MSG_KEY_EVENT:
|
||||
# Print key events for debugging.
|
||||
print(f'W({msg.wid}) key {msg.event.key} {msg.event.action}')
|
||||
if msg.event.key == b'q':
|
||||
# Convention says to close windows when 'q' is pressed,
|
||||
# unless we're using keyboard input "normally".
|
||||
w.close()
|
||||
break
|
||||
elif msg.type == Message.MSG_WINDOW_FOCUS_CHANGE:
|
||||
# If the focus of our window changes, redraw the borders.
|
||||
if msg.wid == w.wid:
|
||||
# This attribute is stored in the underlying struct
|
||||
# and used by the decoration library to pick which
|
||||
# version of the decorations to draw for the window.
|
||||
w.focused = msg.focused
|
||||
draw_decors()
|
||||
w.flip()
|
||||
elif msg.type == Message.MSG_RESIZE_OFFER:
|
||||
# Resize the window.
|
||||
finish_resize(msg)
|
||||
elif msg.type == Message.MSG_WINDOW_MOUSE_EVENT:
|
||||
# Handle mouse events, first by passing them
|
||||
# to the decorator library for processing.
|
||||
if d.handle_event(msg) == Decor.EVENT_CLOSE:
|
||||
# Close the window when the 'X' button is clicked.
|
||||
w.close()
|
||||
break
|
||||
else:
|
||||
# For events that didn't get handled by the decorations,
|
||||
# print a debug message with details.
|
||||
print(f'W({msg.wid}) mouse {msg.new_x},{msg.new_y}')
|
@ -1,63 +0,0 @@
|
||||
import yutani
|
||||
import menu_bar
|
||||
|
||||
def handle_event(msg):
|
||||
if msg.type == yutani.Message.MSG_SESSION_END:
|
||||
msg.free()
|
||||
return False
|
||||
elif msg.type == yutani.Message.MSG_WINDOW_CLOSE:
|
||||
# TODO should actually send a close signal to the window
|
||||
msg.free()
|
||||
return False
|
||||
elif yutani.yutani_ctx.process_menus(msg):
|
||||
return True
|
||||
elif msg.type == yutani.Message.MSG_KEY_EVENT:
|
||||
if msg.wid in yutani.yutani_windows:
|
||||
yutani.yutani_windows[msg.wid].keyboard_event(msg)
|
||||
elif msg.type == yutani.Message.MSG_WINDOW_FOCUS_CHANGE:
|
||||
if msg.wid in yutani.yutani_windows:
|
||||
window = yutani.yutani_windows[msg.wid]
|
||||
if msg.wid in menu_bar.menu_windows:
|
||||
if msg.focused == 0:
|
||||
window.leave_menu()
|
||||
if window.root and not window.root.menus and window.root.focused:
|
||||
window.root.focused = 0
|
||||
window.root.draw()
|
||||
elif msg.focused == 0 and 'menus' in dir(window) and window.menus:
|
||||
window.focused = 1
|
||||
window.draw()
|
||||
else:
|
||||
if 'focus_changed' in dir(window):
|
||||
window.focus_changed(msg)
|
||||
window.focused = msg.focused
|
||||
window.draw()
|
||||
elif msg.type == yutani.Message.MSG_RESIZE_OFFER:
|
||||
if msg.wid in yutani.yutani_windows:
|
||||
yutani.yutani_windows[msg.wid].finish_resize(msg)
|
||||
elif msg.type == yutani.Message.MSG_WINDOW_MOVE:
|
||||
if msg.wid in yutani.yutani_windows:
|
||||
window = yutani.yutani_windows[msg.wid]
|
||||
if 'window_moved' in dir(window):
|
||||
window.window_moved(msg)
|
||||
elif msg.type == yutani.Message.MSG_WINDOW_MOUSE_EVENT:
|
||||
if msg.wid in yutani.yutani_windows:
|
||||
window = yutani.yutani_windows[msg.wid]
|
||||
if msg.wid in menu_bar.menu_windows:
|
||||
if window.root:
|
||||
if msg.new_x >= 0 and msg.new_x < window.width and msg.new_y >= 0 and msg.new_y < window.height:
|
||||
window.root.hovered_menu = window
|
||||
else:
|
||||
window.root.hovered_menu = None
|
||||
window.mouse_action(msg)
|
||||
elif 'mouse_event' in dir(window):
|
||||
window.mouse_event(msg)
|
||||
msg.free()
|
||||
return True
|
||||
|
||||
|
||||
def mainloop():
|
||||
status = True
|
||||
while status:
|
||||
# Poll for events.
|
||||
msg = yutani.yutani_ctx.poll()
|
||||
status = handle_event(msg)
|
Loading…
Reference in New Issue
Block a user