Compare commits

..

15 Commits

Author SHA1 Message Date
somas95 d48115efd0
Merge pull request #106 from fitojb/patch-1
Fix a couple of typos
2019-03-23 01:46:18 +01:00
Adolfo Jayme-Barrientos f9a60c6acf
Fix a couple of typos
• Remove apostrophe from possessive (it isn’t a contraction)
• “Last” implies finality
2019-01-13 02:49:42 -06:00
somas95 e9430c975e fix footer height bug 2018-06-08 19:35:18 +02:00
somas95 c93e9114f7 add focus mode slide 2018-06-08 19:35:06 +02:00
somas95 994968ffa8 remove unnecesary files 2018-06-08 19:34:31 +02:00
somas95 d3140965ad finish last section and footer 2018-06-05 22:51:18 +02:00
somas95 ac64dc7e0b fix footer 2018-06-01 19:00:02 +02:00
somas95 ef8d486ecf fix images not showing 2018-06-01 17:19:54 +02:00
somas95 8185f3cf46 wip of the footer 2018-06-01 01:22:49 +02:00
somas95 8096c6ee45 Footer 2018-05-31 02:49:11 +02:00
somas95 b560d24e8a optimize svg (10%) 2018-05-31 01:14:08 +02:00
somas95 f1e6ecacd4 remove download btn on small screens 2018-05-31 01:13:49 +02:00
somas95 0a178fc575 remove download btn on small screens 2018-05-31 01:13:27 +02:00
somas95 b0ec3c683a Improve navbar 2018-05-30 21:52:26 +02:00
somas95 131fa6e0bb webpage 2018-05-30 18:41:16 +02:00
198 changed files with 7727 additions and 52072 deletions

13
.gitignore vendored
View File

@ -1,11 +1,2 @@
*.pyc
__pycache__/
_build/*
build/
*.*~
.vscode/
.idea/
builddir/*
build-aux/flatpak/_build/*
build-aux/flatpak/.flatpak-builder/*
flatpak/*
.sass-cache/*
assets/sass/styles.css.map

View File

@ -1,27 +0,0 @@
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment(please complete the following information):**
- Linux distribution:
- Desktop Enviroment:
- DE version:
- GTK version:
**Additional context**
Add any other context about the problem here.
/label ~bug ~triage
/assign @somas

View File

@ -1,14 +0,0 @@
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
/label ~"feature request"
/assign @somas

View File

@ -1,5 +0,0 @@
Wolf Vollprecht <w.vollprecht@gmail.com>
Vova Kolobok <vovkkk@ya.ru>
Manuel Genovés <manuel.genoves@gmail.com>
Gonçalo Silva <goncalossilva@gmail.com>
Thomas Lavend <lavendthomas@outlook.be>

View File

@ -1,76 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at manuel.genoves@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

674
LICENSE
View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,40 +0,0 @@
pkgname=apostrophe
_pkgname=apostrophe
pkgver=2.1.3
pkgrel=1
pkgdesc='A distraction free Markdown editor for GNU/Linux made with GTK+'
arch=('any')
url='http://apostrophe.github.io/apostrophe/'
license=('GPL3')
depends=('gtk3' 'pandoc' 'gspell')
makedepends=('python-setuptools')
optdepends=('texlive-core' 'otf-fira-mono: Recommended font')
provides=("$_pkgname")
conflicts=("$_pkgname")
source=('git+https://github.com/Apostrophe/apostrophe.git#branch=refactoring')
sha256sums=('SKIP')
pkgver() {
cd $_pkgname
git describe --long --tags | sed 's/^v//;s/\([^-]*-g\)/r\1/;s/-/./g'
}
build() {
cd $_pkgname
python setup.py build
}
package() {
cd $_pkgname
python setup.py install --skip-build --root="$pkgdir" --optimize=1
}
post_install() {
/usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas/
}
post_upgrade() {
/usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas/
}
post_remove() {
/usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas/
}

View File

@ -1,55 +0,0 @@
[![Please do not theme this app](https://stopthemingmy.app/badge.svg)](https://stopthemingmy.app)
# Apostrophe
![](screenshots/main.png)
## About
Apostrophe is a GTK+ based distraction free Markdown editor, mainly developed by Wolf Vollprecht and Manuel Genovés. It uses pandoc as backend for markdown parsing and offers a very clean and sleek user interface.
## Install
You can get Apostrophe on Flathub!
[Get it now](https://flathub.org/apps/details/de.wolfvollprecht.UberWriter)
## Contributions and localization
If you want to help to localize the project, just join us at [Poeditor](https://poeditor.com/join/project/gxVzFyXb2x)
Any help is appreciated!
## Building from Git
```bash
$ git clone https://github.com/Apostrophe/apostrophe.git
$ cd apostrophe
$ meson builddir --prefix=/usr
# sudo ninja -C builddir install
```
To use apostrophe, please make sure you have some dependencies installed:
- Pandoc, the program used to convert Markdown to basically anything else (the package name should be pandoc in most distributions)
- Of course, gtk3 etc. needs to be installed as well since this is a gtk application
- webkit2gtk is also needed for the preview panel
- Please find these packages on your distribution: `python3 python3-regex python3-setuptools python3-levenshtein python3-enchant python3-gi python3-cairo`
- Optional dependencies are `texlive` for the pdftex module.
### Running it without installing it
You can run Apostrophe with `./apostrophe.in` without installing it in the system,
but you'll need to install and compile the schemas before:
```bash
# sudo cp data/de.wolfvollprecht.UberWriter.gschema.xml /usr/share/glib-2.0/schemas/de.wolfvollprecht.UberWriter.gschema.xml
# sudo glib-compile-schemas /usr/share/glib-2.0/schemas
```
### Building a flatpak package
It's also possible to build, run and debug a flatpak package. You'll need flatpak-builder for this:
```bash
$ cd build-aux/flatpak
$ flatpak-builder --force-clean --install --user _build de.wolfvollprecht.UberWriter.json
```

View File

@ -1,63 +0,0 @@
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
### DO NOT EDIT THIS FILE ###
import sys
import os
import pkg_resources
import gettext
import locale
from gi.repository import Gio
# Add project root directory (enable symlink and trunk execution)
PROJECT_ROOT_DIRECTORY = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))
# Set the path if needed. This allows apostrophe to run without installing it :)
python_path = []
if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'apostrophe'))
and PROJECT_ROOT_DIRECTORY not in sys.path):
python_path.insert(0, PROJECT_ROOT_DIRECTORY)
sys.path.insert(0, PROJECT_ROOT_DIRECTORY)
if python_path:
os.putenv('PYTHONPATH', "%s:%s" % (os.getenv('PYTHONPATH', ''), ':'.join(python_path))) # for subprocesses
import apostrophe
localedir = '@LOCALE_DIR@'
pkgdatadir = '@DATA_DIR@'
#locale_dir = os.path.abspath(os.path.join(os.path.dirname(apostrophe.__file__),'../po/'))
# L10n
locale.textdomain('apostrophe')
locale.bindtextdomain('apostrophe', localedir)
gettext.textdomain('apostrophe')
gettext.bindtextdomain('apostrophe', localedir)
resource = Gio.resource_load(os.path.join(pkgdatadir, 'apostrophe/apostrophe.gresource'))
Gio.Resource._register(resource)
apostrophe.main()

View File

@ -1,568 +0,0 @@
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Specify a configuration file.
#rcfile=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
locally-enabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating,
deprecated-operator-function,
deprecated-urllib-function,
xreadlines-attribute,
deprecated-sys-function,
exception-escape,
comprehension-escape
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=msvs
# Tells whether to display a full report or only the messages.
reports=yes
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: he (hspell), en_IE
# (hunspell), es_BO (hunspell), en_NZ (hunspell), es_DO (hunspell), es_MX
# (hunspell), en_ZA (hunspell), en_IN (hunspell), en_TT (hunspell), ca
# (aspell), ca_FR (hunspell), es_HN (hunspell), ca_AD (hunspell), es_SV
# (hunspell), es_PA (hunspell), en_DK (hunspell), es_NI (hunspell), es_PE
# (hunspell), en_SG (hunspell), es_UY (hunspell), en_BS (hunspell), en_BW
# (hunspell), es_CL (hunspell), es_AR (hunspell), en_BZ (hunspell), es_CO
# (hunspell), en_ZW (hunspell), en_HK (hunspell), es_CR (hunspell), en_NA
# (hunspell), es_PR (hunspell), en_JM (hunspell), es_VE (hunspell), en_AG
# (hunspell), es_CU (hunspell), en_NG (hunspell), ca_ES (hunspell), es_ES
# (hunspell), es_ANY (hunspell), es_EC (hunspell), es_GT (hunspell), en_PH
# (hunspell), en_GB (hunspell), en_US (hunspell), ca_IT (hunspell), es_PY
# (hunspell), en_GH (hunspell)..
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=yes
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement.
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception".
overgeneral-exceptions=Exception

View File

@ -1,35 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import sys
import gi
gi.require_version('Gtk', '3.0')
from apostrophe import main_window
from apostrophe import application
from apostrophe.helpers import set_up_logging
from apostrophe.config import get_version
def main():
'constructor for your class instances'
# (options, args) = parse_options()
# Run the application.
app = application.Application()
app.run(sys.argv)

View File

@ -1,289 +0,0 @@
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see &lt;http://www.gnu.org/licenses/&gt;.
import argparse
from gettext import gettext as _
import gi
from apostrophe.main_window import MainWindow
gi.require_version('Gtk', '3.0') # pylint: disable=wrong-import-position
from gi.repository import GLib, Gio, Gtk, GdkPixbuf
from apostrophe import main_window
from apostrophe.settings import Settings
from apostrophe.helpers import set_up_logging
from apostrophe.preferences_dialog import PreferencesDialog
from apostrophe.helpers import get_media_path
class Application(Gtk.Application):
def __init__(self, *args, **kwargs):
super().__init__(*args, application_id="de.wolfvollprecht.UberWriter",
flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
**kwargs)
self.window = None
self.settings = Settings.new()
def do_startup(self, *args, **kwargs):
Gtk.Application.do_startup(self)
self.settings.connect("changed", self.on_settings_changed)
self._set_dark_mode ()
# Header bar
action = Gio.SimpleAction.new("new", None)
action.connect("activate", self.on_new)
self.add_action(action)
action = Gio.SimpleAction.new("open", None)
action.connect("activate", self.on_open)
self.add_action(action)
action = Gio.SimpleAction.new("open_recent", None)
action.connect("activate", self.on_open_recent)
self.add_action(action)
action = Gio.SimpleAction.new("save", None)
action.connect("activate", self.on_save)
self.add_action(action)
action = Gio.SimpleAction.new("search", None)
action.connect("activate", self.on_search)
self.add_action(action)
# App Menu
action = Gio.SimpleAction.new_stateful(
"focus_mode", None, GLib.Variant.new_boolean(False))
action.connect("change-state", self.on_focus_mode)
self.add_action(action)
action = Gio.SimpleAction.new_stateful(
"hemingway_mode", None, GLib.Variant.new_boolean(False))
action.connect("change-state", self.on_hemingway_mode)
self.add_action(action)
action = Gio.SimpleAction.new_stateful(
"preview", None, GLib.Variant.new_boolean(False))
action.connect("change-state", self.on_preview)
self.add_action(action)
action = Gio.SimpleAction.new_stateful(
"fullscreen", None, GLib.Variant.new_boolean(False))
action.connect("change-state", self.on_fullscreen)
self.add_action(action)
action = Gio.SimpleAction.new("save_as", None)
action.connect("activate", self.on_save_as)
self.add_action(action)
action = Gio.SimpleAction.new("export", GLib.VariantType("s"))
action.connect("activate", self.on_export)
self.add_action(action)
action = Gio.SimpleAction.new("copy_html", None)
action.connect("activate", self.on_copy_html)
self.add_action(action)
action = Gio.SimpleAction.new("search_replace", None)
action.connect("activate", self.on_search_replace)
self.add_action(action)
action = Gio.SimpleAction.new("preferences", None)
action.connect("activate", self.on_preferences)
self.add_action(action)
action = Gio.SimpleAction.new("shortcuts", None)
action.connect("activate", self.on_shortcuts)
self.add_action(action)
action = Gio.SimpleAction.new("open_tutorial", None)
action.connect("activate", self.on_open_tutorial)
self.add_action(action)
action = Gio.SimpleAction.new("about", None)
action.connect("activate", self.on_about)
self.add_action(action)
action = Gio.SimpleAction.new("quit", None)
action.connect("activate", self.on_quit)
self.add_action(action)
# Stats Menu
stat_default = self.settings.get_string("stat-default")
action = Gio.SimpleAction.new_stateful(
"stat_default", GLib.VariantType.new("s"), GLib.Variant.new_string(stat_default))
action.connect("activate", self.on_stat_default)
self.add_action(action)
# Preview Menu
preview_mode = self.settings.get_string("preview-mode")
action = Gio.SimpleAction.new_stateful(
"preview_mode", GLib.VariantType.new("s"), GLib.Variant.new_string(preview_mode))
action.connect("activate", self.on_preview_mode)
self.add_action(action)
# Shortcuts
# TODO: be aware that a couple of shortcuts are defined in base.css
self.set_accels_for_action("app.focus_mode", ["<Ctl>d"])
self.set_accels_for_action("app.hemingway_mode", ["<Ctl>t"])
self.set_accels_for_action("app.fullscreen", ["F11"])
self.set_accels_for_action("app.preview", ["<Ctl>p"])
self.set_accels_for_action("app.search", ["<Ctl>f"])
self.set_accels_for_action("app.search_replace", ["<Ctl>h"])
self.set_accels_for_action("app.spellcheck", ["F7"])
self.set_accels_for_action("app.new", ["<Ctl>n"])
self.set_accels_for_action("app.open", ["<Ctl>o"])
self.set_accels_for_action("app.save", ["<Ctl>s"])
self.set_accels_for_action("app.save_as", ["<Ctl><shift>s"])
self.set_accels_for_action("app.quit", ["<Ctl>w", "<Ctl>q"])
def do_activate(self, *args, **kwargs):
# We only allow a single window and raise any existing ones
if not self.window:
# Windows are associated with the application
# when the last one is closed the application shuts down
# self.window = Window(application=self, title="Apostrophe")
self.window = MainWindow(self)
if self.args:
self.window.load_file(self.args[0])
self.window.present()
def do_command_line(self, _command_line):
"""Support for command line options"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-v", "--verbose", action="count", dest="verbose",
help=_("Show debug messages (-vv debugs apostrophe also)"))
parser.add_argument(
"-e", "--experimental-features", help=_("Use experimental features"),
action='store_true')
(self.options, self.args) = parser.parse_known_args()
set_up_logging(self.options)
self.activate()
return 0
def _set_dark_mode (self):
dark = self.settings.get_value("dark-mode")
settings = Gtk.Settings.get_default()
settings.props.gtk_application_prefer_dark_theme = dark
if settings.props.gtk_theme_name == "HighContrast" and dark:
settings.props.gtk_theme_name = "HighContrastInverse"
elif settings.props.gtk_theme_name == "HighContrastInverse" and not dark:
settings.props.gtk_theme_name = "HighContrast"
def on_settings_changed(self, settings, key):
if key == "dark-mode":
self._set_dark_mode ()
elif key == "spellcheck":
self.window.toggle_spellcheck(settings.get_value(key))
elif key == "input-format":
self.window.reload_preview()
elif key == "sync-scroll":
self.window.reload_preview(reshow=True)
elif key == "stat-default":
self.window.update_default_stat()
elif key == "preview-mode":
self.window.update_preview_mode()
def on_new(self, _action, _value):
self.window.new_document()
def on_open(self, _action, _value):
self.window.open_document()
def on_open_recent(self, file):
self.window.load_file(file.get_current_uri())
def on_save(self, _action, _value):
self.window.save_document()
def on_search(self, _action, _value):
self.window.open_search()
def on_search_replace(self, _action, _value):
self.window.open_search(replace=True)
def on_focus_mode(self, action, value):
action.set_state(value)
self.window.set_focus_mode(value)
def on_hemingway_mode(self, action, value):
action.set_state(value)
self.window.set_hemingway_mode(value)
def on_preview(self, action, value):
action.set_state(value)
self.window.toggle_preview(value)
def on_fullscreen(self, action, value):
action.set_state(value)
self.window.set_fullscreen(value)
def on_save_as(self, _action, _value):
self.window.save_document_as()
def on_export(self, _action, value):
self.window.open_advanced_export(value.get_string())
def on_copy_html(self, _action, _value):
self.window.copy_html_to_clipboard()
def on_preferences(self, _action, _value):
PreferencesDialog(self.settings).show(self.window)
def on_shortcuts(self, _action, _param):
builder = Gtk.Builder()
builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Shortcuts.ui")
builder.get_object("shortcuts").set_transient_for(self.window)
builder.get_object("shortcuts").show()
def on_open_tutorial(self, _action, _value):
self.window.open_apostrophe_markdown()
def on_about(self, _action, _param):
builder = Gtk.Builder()
builder.add_from_resource("/de/wolfvollprecht/UberWriter/About.ui")
about_dialog = builder.get_object("AboutDialog")
about_dialog.set_transient_for(self.window)
about_dialog.present()
def on_quit(self, _action, _param):
self.quit()
def on_stat_default(self, action, value):
action.set_state(value)
self.settings.set_string("stat-default", value.get_string())
def on_preview_mode(self, action, value):
action.set_state(value)
self.settings.set_string("preview-mode", value.get_string())
# ~ if __name__ == "__main__":
# ~ app = Application()
# ~ app.run(sys.argv)

View File

@ -1,222 +0,0 @@
# ApostropheAutoCorrect
# The Apostrophe Auto Correct is a auto correction
# mechanism to prevent stupid typos
# CURRENTLY DISABLED
import os
import pickle
import configparser
import xml.etree.ElementTree as ET
from gi.repository import Gtk, Gdk
import enchant
from apostrophe import pressagio
# import apostrophe.pressagio.predictor
# import apostrophe.pressagio.tokenizer
# import apostrophe.pressagio.dbconnector
# import apostrophe.pressagio.context_tracker
# import apostrophe.pressagio.callback
# from Levenshtein import distance
from apostrophe.helpers import get_media_path
# Define and create PresageCallback object
class PressagioCallback(pressagio.callback.Callback):
def __init__(self, buffer):
super().__init__()
self.buffer = buffer
def past_stream(self):
return self.buffer
def future_stream(self):
return ''
class AutoCorrect:
def show_bubble(self, iterator, suggestion):
self.suggestion = suggestion
if self.bubble:
self.bubble_label.set_text(suggestion)
else:
pos = self.text_view.get_iter_location(iterator)
pos_adjusted = self.text_view.buffer_to_window_coords(
Gtk.TextWindowType.TEXT, pos.x, pos.y + pos.height)
self.bubble_eventbox = Gtk.EventBox.new()
self.bubble = Gtk.Grid.new()
self.bubble.set_name("AutoCorrect")
self.bubble_eventbox.add(self.bubble)
self.bubble_eventbox.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.bubble_eventbox.connect("button_press_event", self.clicked_bubble)
self.text_view.add_child_in_window(self.bubble_eventbox,
Gtk.TextWindowType.TEXT,
pos_adjusted[0], pos_adjusted[1])
self.bubble_label = Gtk.Label.new(suggestion)
self.bubble.attach(self.bubble_label, 0, 0, 1, 1)
self.bubble_close_eventbox = Gtk.EventBox.new()
self.bubble_close_eventbox.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.bubble_close_eventbox.connect("button_press_event", self.clicked_close)
close = Gtk.Image.new_from_icon_name('dialog-close', Gtk.IconSize.SMALL_TOOLBAR)
self.bubble_close_eventbox.add(close)
self.bubble.attach(self.bubble_close_eventbox, 1, 0, 1, 1)
self.bubble_eventbox.show_all()
def clicked_bubble(self, _widget, _data=None):
self.accept_suggestion()
def clicked_close(self, _widget, _data=None):
self.destroy_bubble()
def suggest(self, stump, context):
if self.enchant_dict.check(stump):
self.destroy_bubble()
return
self.callback.buffer = ' '.join(context) + ' ' + stump
self.callback.buffer = self.callback.buffer.lstrip().rstrip()
predictions = []
if self.use_pressagio:
predictions = self.prsgio.predict(6, None)
prediction = None
if not predictions:
if self.enchant_dict.check(stump):
self.destroy_bubble()
return
predictions = self.enchant_dict.suggest(stump)
suggestions_map = []
for suggestion in predictions:
if suggestion in self.frequency_dict:
suggestions_map.append({'suggestion': suggestion,
'freq': self.frequency_dict[suggestion]})
else:
suggestions_map.append({'suggestion': suggestion, 'freq': 0})
suggestions_map.sort(key=lambda x: x['freq'])
suggestions_map.reverse()
prediction = suggestions_map[0]
print(predictions)
prediction = predictions[0]
else:
prediction = predictions[0].word
anchor_iter = self.buffer.get_iter_at_mark(self.buffer.get_insert())
anchor_iter.backward_visible_word_start()
if len(stump) >= 1:
self.show_bubble(anchor_iter, prediction)
def destroy_bubble(self, *_args):
if not self.bubble:
return
self.bubble.destroy()
self.bubble = None
self.suggestion = ''
def get_frequency_dict(self, _language):
self.frequency_dict = {}
pp_pickled = get_media_path("frequency_dict_" + self.language + ".pickle")
if pp_pickled and os.path.isfile(pp_pickled):
frequency_file = open(pp_pickled, 'rb')
self.frequency_dict = pickle.load(frequency_file)
frequency_file.close()
else:
pp = get_media_path('wordlists/en_us_wordlist.xml')
frequencies = ET.parse(pp)
root = frequencies.getroot()
for child in root:
self.frequency_dict[child.text] = int(child.attrib['f'])
frequency_file = open('pickled_dict', 'wb+')
pickle.dump(self.frequency_dict, frequency_file)
frequency_file.close()
def accept_suggestion(self, append=""):
print("called")
curr_iter = self.buffer.get_iter_at_mark(self.buffer.get_insert())
start_iter = curr_iter.copy()
start_iter.backward_visible_word_start()
self.buffer.delete(start_iter, curr_iter)
self.buffer.insert_at_cursor(self.suggestion + append)
self.destroy_bubble()
def key_pressed(self, _widget, event):
if not self.bubble:
return False
if event.keyval in [Gdk.KEY_Escape, Gdk.KEY_BackSpace]:
self.destroy_bubble()
return False
def text_insert(self, buffer, location,
text, _length, _data=None):
# check if at end of a word
# if yes, check if suggestion available
# then display suggetion
if self.suggestion and text in [' ', '\t', '\n', '.', '?', '!',
',', ';', '\'', '"', ')', ':']:
self.accept_suggestion(append=text)
location.assign(self.buffer.get_iter_at_mark(self.buffer.get_insert()))
elif location.ends_word():
iter_start = location.copy()
iter_start.backward_visible_word_starts(3)
text = buffer.get_text(iter_start, location, False)
words = text.split()
self.suggest(words[-1], words[0:-1])
def disable(self):
self.disabled = True
def enable(self):
self.disabled = False
def set_language(self, language):
print("Language changed to: %s" % language)
# handle 2 char cases e.g. "en"
if len(language) == 2:
if "en":
language = "en_US"
if self.language == language:
return
self.language = language
print("Language changing")
config_file = get_media_path("pressagio_config.ini")
pres_config = configparser.ConfigParser()
pres_config.read(config_file)
pres_config.set("Database", "database",
get_media_path("corpora/" + self.language + ".sqlite"))
self.context_tracker = pressagio.context_tracker.ContextTracker(
pres_config, self.predictor_registry, self.callback)
self.prsgio = self.predictor_registry[0]
self.enchant_dict = enchant.Dict(self.language)
def __init__(self, textview, textbuffer):
self.text_view = textview
self.buffer = textbuffer
self.suggestion = ""
self.bubble = self.bubble_label = None
self.buffer.connect_after('insert-text', self.text_insert)
self.text_view.connect('key-press-event', self.key_pressed)
self.language = "en_US"
self.frequency_dict = {}
self.get_frequency_dict(self.language)
self.enchant_dict = enchant.Dict(self.language)
self.use_pressagio = False
config_file = get_media_path("pressagio_config.ini")
pres_config = configparser.ConfigParser()
pres_config.read(config_file)
pres_config.set("Database", "database",
get_media_path("corpora/" + self.language + ".sqlite"))
self.callback = PressagioCallback("")
self.predictor_registry = pressagio.predictor.PredictorRegistry(pres_config)
self.context_tracker = pressagio.context_tracker.ContextTracker(
pres_config, self.predictor_registry, self.callback)
self.prsgio = self.predictor_registry[0]

View File

@ -1,329 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# END LICENSE
### DO NOT EDIT THIS FILE ###
'''Enhances builder connections, provides object to access glade objects'''
import inspect
import functools
import logging
from xml.etree.cElementTree import ElementTree
import gi
gi.require_version('Gtk', '3.0') # pylint: disable=wrong-import-position
from gi.repository import GObject, Gtk # pylint: disable=E0611
LOGGER = logging.getLogger('apostrophe')
# this module is big so uses some conventional prefixes and postfixes
# *s list, except self.widgets is a dictionary
# *_dict dictionary
# *name string
# ele_* element in a ElementTree
# pylint: disable=R0904
# the many public methods is a feature of Gtk.Builder
class Builder(Gtk.Builder):
''' extra features
connects glade defined handler to default_handler if necessary
auto connects widget to handler with matching name or alias
auto connects several widgets to a handler via multiple aliases
allow handlers to lookup widget name
logs every connection made, and any on_* not made
'''
def __init__(self):
Gtk.Builder.__init__(self)
self.widgets = {}
self.glade_handler_dict = {}
self.connections = []
self._reverse_widget_dict = {}
# pylint: disable=R0201
# this is a method so that a subclass of Builder can redefine it
def default_handler(self,
handler_name, filename, *args, **kwargs):
'''helps the apprentice guru
glade defined handlers that do not exist come here instead.
An apprentice guru might wonder which signal does what he wants,
now he can define any likely candidates in glade and notice which
ones get triggered when he plays with the project.
this method does not appear in Gtk.Builder'''
LOGGER.debug('''tried to call non-existent function:%s()
expected in %s
args:%s
kwargs:%s''', handler_name, filename, args, kwargs)
# pylint: enable=R0201
def get_name(self, widget):
''' allows a handler to get the name (id) of a widget
this method does not appear in Gtk.Builder'''
return self._reverse_widget_dict.get(widget)
def add_from_file(self, filename):
'''parses xml file and stores wanted details'''
Gtk.Builder.add_from_file(self, filename)
# extract data for the extra interfaces
tree = ElementTree()
tree.parse(filename)
ele_widgets = tree.getiterator("object")
for ele_widget in ele_widgets:
name = ele_widget.attrib['id']
widget = self.get_object(name)
# populate indexes - a dictionary of widgets
self.widgets[name] = widget
# populate a reversed dictionary
self._reverse_widget_dict[widget] = name
# populate connections list
ele_signals = ele_widget.findall("signal")
connections = [
(name,
ele_signal.attrib['name'],
ele_signal.attrib['handler']) for ele_signal in ele_signals]
if connections:
self.connections.extend(connections)
ele_signals = tree.getiterator("signal")
for ele_signal in ele_signals:
self.glade_handler_dict.update(
{ele_signal.attrib["handler"]: None})
def connect_signals(self, callback_obj):
'''connect the handlers defined in glade
reports successful and failed connections
and logs call to missing handlers'''
filename = inspect.getfile(callback_obj.__class__)
callback_handler_dict = dict_from_callback_obj(callback_obj)
connection_dict = {}
connection_dict.update(self.glade_handler_dict)
connection_dict.update(callback_handler_dict)
for item in connection_dict.items():
if item[1] is None:
# the handler is missing so reroute to default_handler
handler = functools.partial(
self.default_handler, item[0], filename)
connection_dict[item[0]] = handler
# replace the run time warning
LOGGER.warning("expected handler '%s' in %s",
item[0], filename)
# connect glade define handlers
Gtk.Builder.connect_signals(self, connection_dict)
# let's tell the user how we applied the glade design
for connection in self.connections:
widget_name, signal_name, handler_name = connection
LOGGER.debug("connect builder by design '%s', '%s', '%s'",
widget_name, signal_name, handler_name)
def get_ui(self, callback_obj=None, by_name=True):
'''Creates the ui object with widgets as attributes
connects signals by 2 methods
this method does not appear in Gtk.Builder'''
result = UiFactory(self.widgets)
# Hook up any signals the user defined in glade
if callback_obj is not None:
# connect glade define handlers
self.connect_signals(callback_obj)
if by_name:
auto_connect_by_name(callback_obj, self)
return result
# pylint: disable=R0903
# this class deliberately does not provide any public interfaces
# apart from the glade widgets
class UiFactory():
''' provides an object with attributes as glade widgets'''
def __init__(self, widget_dict):
self._widget_dict = widget_dict
for (widget_name, widget) in widget_dict.items():
setattr(self, widget_name, widget)
# Mangle any non-usable names (like with spaces or dashes)
# into pythonic ones
cannot_message = """cannot bind ui.%s, name already exists
consider using a pythonic name instead of design name '%s'"""
consider_message = """consider using a pythonic name instead of design name '%s'"""
for (widget_name, widget) in widget_dict.items():
pyname = make_pyname(widget_name)
if pyname != widget_name:
if hasattr(self, pyname):
LOGGER.debug(cannot_message, pyname, widget_name)
else:
LOGGER.debug(consider_message, widget_name)
setattr(self, pyname, widget)
def iterator():
'''Support 'for o in self' '''
return iter(widget_dict.values())
setattr(self, '__iter__', iterator)
def __getitem__(self, name):
'access as dictionary where name might be non-pythonic'
return self._widget_dict[name]
# pylint: enable=R0903
def make_pyname(name):
''' mangles non-pythonic names into pythonic ones'''
pyname = ''
for character in name:
if (character.isalpha() or character == '_' or
(pyname and character.isdigit())):
pyname += character
else:
pyname += '_'
return pyname
# Until bug https://bugzilla.gnome.org/show_bug.cgi?id=652127 is fixed, we
# need to reimplement inspect.getmembers. GObject introspection doesn't
# play nice with it.
def getmembers(obj, check):
members = []
for k in dir(obj):
try:
attr = getattr(obj, k)
except:
continue
if check(attr):
members.append((k, attr))
members.sort()
return members
def dict_from_callback_obj(callback_obj):
'''a dictionary interface to callback_obj'''
methods = getmembers(callback_obj, inspect.ismethod)
aliased_methods = [x[1] for x in methods if hasattr(x[1], 'aliases')]
# a method may have several aliases
# ~ @alias('on_btn_foo_clicked')
# ~ @alias('on_tool_foo_activate')
# ~ on_menu_foo_activate():
# ~ pass
alias_groups = [(x.aliases, x) for x in aliased_methods]
aliases = []
for item in alias_groups:
for alias in item[0]:
aliases.append((alias, item[1]))
dict_methods = dict(methods)
dict_aliases = dict(aliases)
results = {}
results.update(dict_methods)
results.update(dict_aliases)
return results
def auto_connect_by_name(callback_obj, builder):
'''finds handlers like on_<widget_name>_<signal> and connects them
i.e. find widget,signal pair in builder and call
widget.connect(signal, on_<widget_name>_<signal>)'''
callback_handler_dict = dict_from_callback_obj(callback_obj)
for item in builder.widgets.items():
(widget_name, widget) = item
signal_ids = []
try:
widget_type = type(widget)
while widget_type:
signal_ids.extend(GObject.signal_list_ids(widget_type))
widget_type = GObject.type_parent(widget_type)
except RuntimeError: # pylint wants a specific error
pass
signal_names = [GObject.signal_name(sid) for sid in signal_ids]
# Now, automatically find any the user didn't specify in glade
for sig in signal_names:
# using convention suggested by glade
sig = sig.replace("-", "_")
handler_names = ["on_%s_%s" % (widget_name, sig)]
# Using the convention that the top level window is not
# specified in the handler name. That is use
# on_destroy() instead of on_windowname_destroy()
if widget is callback_obj:
handler_names.append("on_%s" % sig)
do_connect(item, sig, handler_names,
callback_handler_dict, builder.connections)
log_unconnected_functions(callback_handler_dict, builder.connections)
def do_connect(item, signal_name, handler_names,
callback_handler_dict, connections):
'''connect this signal to an unused handler'''
widget_name, widget = item
for handler_name in handler_names:
target = handler_name in callback_handler_dict.keys()
connection = (widget_name, signal_name, handler_name)
duplicate = connection in connections
if target and not duplicate:
widget.connect(signal_name, callback_handler_dict[handler_name])
connections.append(connection)
LOGGER.debug("connect builder by name '%s','%s', '%s'",
widget_name, signal_name, handler_name)
def log_unconnected_functions(callback_handler_dict, connections):
'''log functions like on_* that we could not connect'''
connected_functions = [x[2] for x in connections]
handler_names = callback_handler_dict.keys()
unconnected = [x for x in handler_names if x.startswith('on_')]
for handler_name in connected_functions:
try:
unconnected.remove(handler_name)
except ValueError:
pass
for handler_name in unconnected:
LOGGER.debug("Not connected to builder '%s'", handler_name)

View File

@ -1,74 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
### DO NOT EDIT THIS FILE ###
__all__ = [
'project_path_not_found',
'get_data_file',
'get_data_path',
]
# Where your project will look for your data (for instance, images and ui
# files). By default, this is ../data, relative your trunk layout
__apostrophe_data_directory__ = '../data/'
__license__ = 'GPL-3'
__version__ = 'VERSION'
import os
class ProjectPathNotFound(Exception):
"""Raised when we can't find the project directory."""
def get_data_file(*path_segments):
"""Get the full path to a data file.
Returns the path to a file underneath the data directory (as defined by
`get_data_path`). Equivalent to os.path.join(get_data_path(),
*path_segments).
"""
return os.path.join(get_data_path(), *path_segments)
def get_data_path():
"""Retrieve apostrophe data path
This path is by default <apostrophe_path>/../data/ in trunk
and /opt/apostrophe/data in an installed version but this path
is specified at installation time.
"""
# Get pathname absolute or relative.
if os.path.isfile("/.flatpak-info"):
return '/app/share/apostrophe/'
path = os.path.join(
os.path.dirname(__file__), __apostrophe_data_directory__)
# We try first if the data exists in the local folder and then
# in the system installation path
abs_data_path = os.path.abspath(path)
if not os.path.exists(abs_data_path):
abs_data_path = '/usr/share/apostrophe/'
elif not os.path.exists(abs_data_path):
raise ProjectPathNotFound
return abs_data_path
def get_version():
return __version__

View File

@ -1,432 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
"""Manages all the export operations and dialogs
"""
import logging
import os
from gettext import gettext as _
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
from apostrophe import helpers
from apostrophe.theme import Theme
LOGGER = logging.getLogger('apostrophe')
class Export:
"""
Manages all the export operations and dialogs
"""
__gtype_name__ = "export_dialog"
formats = [
{
"name": "LaTeX (pdf)",
"ext": "pdf",
"to": "pdf"
},
{
"name": "LaTeX Beamer Slideshow (pdf)",
"ext": "pdf",
"to": "beamer"
},
{
"name": "LaTeX (tex)",
"ext": "tex",
"to": "latex"
},
{
"name": "LaTeX Beamer Slideshow (tex)",
"ext": "tex",
"to": "beamer"
},
{
"name": "ConTeXt",
"ext": "tex",
"to": "context"
},
{
"name": "HTML",
"ext": "html",
"to": "html"
},
{
"name": "HTML and JavaScript Slideshow (Slidy)",
"ext": "html",
"to": "slidy"
},
{
"name": "HTML and JavaScript Slideshow (Slideous)",
"ext": "html",
"to": "slideous"
},
{
"name": "HTML5 and JavaScript Slideshow (DZSlides)",
"ext": "html",
"to": "dzslides"
},
{
"name": "HTML5 and JavaScript Slideshow (reveal.js)",
"ext": "html",
"to": "revealjs"
},
{
"name": "HTML and JavaScript Slideshow (S5)",
"ext": "html",
"to": "s5"
},
{
"name": "Textile",
"ext": "txt",
"to": "textile"
},
{
"name": "reStructuredText",
"ext": "txt",
"to": "rst"
},
{
"name": "MediaWiki Markup",
"ext": "txt",
"to": "mediawiki"
},
{
"name": "OpenDocument (xml)",
"ext": "xml",
"to": "opendocument"
},
{
"name": "OpenDocument (texi)",
"ext": "texi",
"to": "texinfo"
},
{
"name": "LibreOffice Text Document",
"ext": "odt",
"to": "odt"
},
{
"name": "Microsoft Word (docx)",
"ext": "docx",
"to": "docx"
},
{
"name": "Rich Text Format",
"ext": "rtf",
"to": "rtf"
},
{
"name": "Groff Man",
"ext": "man",
"to": "man"
},
{
"name": "EPUB v3",
"ext": "epub",
"to": "epub"
}
]
def __init__(self, filename, export_format, text):
"""Set up the export dialog"""
self.export_menu = {
"pdf":
{
"extension": "pdf",
"name": "PDF",
"mimetype": "application/pdf",
"dialog": self.regular_export_dialog
},
"html":
{
"extension": "html",
"name": "HTML",
"mimetype": "text/html",
"dialog": self.regular_export_dialog
},
"odt":
{
"extension": "odt",
"name": "ODT",
"mimetype": "application/vnd.oasis.opendocument.text",
"dialog": self.regular_export_dialog
},
"advanced":
{
"extension": "",
"name": "",
"mimetype": "",
"dialog": self.advanced_export_dialog
}
}
self.filename = filename or _("Untitled document.md")
self.export_format = export_format
self.dialog = self.export_menu[export_format]["dialog"]()
response = self.dialog.run()
if response == Gtk.ResponseType.ACCEPT:
try:
self.export(export_format, text)
except (NotADirectoryError, RuntimeError) as e:
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.CLOSE,
_("An error happened while trying to export:\n\n{err_msg}")
.format(err_msg= str(e).encode().decode("unicode-escape"))
)
dialog.run()
dialog.destroy()
self.dialog.destroy()
def regular_export_dialog(self):
texlive_installed = helpers.exist_executable("pdftex")
if (self.export_menu[self.export_format]["extension"] == "pdf" and
not texlive_installed):
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.INFO,
Gtk.ButtonsType.CLOSE,
_("Oh, no!")
)
dialog.props.secondary_text = _("Seems that you don't have TexLive installed.\n" +
disabled_text())
else:
dialog = Gtk.FileChooserNative.new(_("Export"),
None,
Gtk.FileChooserAction.SAVE,
_("Export to %s") %
self.export_menu[self.export_format]["extension"],
_("Cancel"))
dialog_filter = Gtk.FileFilter.new()
dialog_filter.set_name(self.export_menu[self.export_format]["name"])
dialog_filter.add_mime_type(self.export_menu[self.export_format]["mimetype"])
dialog.add_filter(dialog_filter)
dialog.set_do_overwrite_confirmation(True)
dialog.set_current_folder(os.path.dirname(self.filename))
dialog.set_current_name(os.path.basename(self.filename)[:-2] +
self.export_menu[self.export_format]["extension"])
return dialog
def advanced_export_dialog(self):
self.builder = Gtk.Builder()
self.builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Export.ui")
self.builder.get_object("highlight_style").set_active(0)
self.builder.get_object("css_filechooser").set_uri(
helpers.path_to_file(Theme.get_current().web_css_path))
format_store = Gtk.ListStore(int, str)
for i, fmt in enumerate(self.formats):
format_store.append([i, fmt["name"]])
self.format_field = self.builder.get_object('choose_format')
self.format_field.set_model(format_store)
format_renderer = Gtk.CellRendererText()
self.format_field.pack_start(format_renderer, True)
self.format_field.add_attribute(format_renderer, "text", 1)
self.format_field.set_active(0)
self.adv_export_folder = self.builder.get_object("advanced")
self.adv_export_name = self.builder.get_object("advanced_export_name")
self.adv_export_name.set_text(os.path.basename(self.filename)[:-3])
self.paper_size = self.builder.get_object("combobox_paper_size")
return self.builder.get_object("Export")
def export(self, export_type, text=""):
"""Export the given text using the specified format.
For advanced export, this includes special flags for the enabled options.
Keyword Arguments:
text {str} -- Text to export (default: {""})
"""
args = []
if export_type == "advanced":
filename = self.adv_export_name.get_text()
# TODO: use walrust operator
output_uri = self.adv_export_folder.get_uri()
if output_uri:
output_dir = GLib.filename_from_uri(output_uri)[0]
else:
raise NotADirectoryError(_("A folder must be selected before proceeding"))
basename = os.path.basename(filename)
fmt = self.formats[self.format_field.get_active()]
to = fmt["to"]
ext = fmt["ext"]
if self.builder.get_object("html5").get_active() and to == "html":
to = "html5"
if self.builder.get_object("smart").get_active():
to += "+smart"
args.extend(self.get_advanced_arguments(to, ext))
else:
args = [
"--variable=papersize:a4"
]
filename = self.dialog.get_filename()
if filename.endswith("." + export_type):
filename = filename[:-len(export_type)-1]
output_dir = os.path.abspath(os.path.join(filename, os.path.pardir))
basename = os.path.basename(filename)
to = export_type
ext = export_type
if export_type == "html":
to = "html5"
args.append("--self-contained")
args.append("--css=%s" % Theme.get_current().web_css_path)
args.append("--mathjax")
args.append("--lua-filter=%s" % helpers.get_script_path('relative_to_absolute.lua'))
args.append("--lua-filter=%s" % helpers.get_script_path('task-list.lua'))
helpers.pandoc_convert(
text, to=to, args=args,
outputfile="%s/%s.%s" % (output_dir, basename, ext))
def get_advanced_arguments(self, to_fmt, ext_fmt):
"""Retrieve a list of the selected advanced arguments
For most of the advanced option checkboxes, returns a list
of the related pandoc flags
Arguments:
basename {str} -- the name of the file
to_fmt {str} -- the format of the export
ext_fmt {str} -- the extension of the export
Returns:
list of {str} -- related pandoc flags
"""
highlight_style = self.builder.get_object("highlight_style").get_active_text()
conditions = [
{
"condition": to_fmt == "pdf",
"yes": "--variable=papersize:" + self.get_paper_size(),
"no": None
},
{
"condition": (self.get_paper_size() == "a4" and (to_fmt in ("odt", "docx"))),
"yes": "--reference-doc=" + helpers.get_reference_files_path('reference-a4.' + to_fmt),
"no": None
},
{
"condition": self.builder.get_object("toc").get_active(),
"yes": "--toc",
"no": None
},
{
"condition": self.builder.get_object("highlight").get_active(),
"yes": "--highlight-style=%s" % highlight_style,
"no": "--no-highlight"
},
{
"condition": self.builder.get_object("standalone").get_active(),
"yes": "--standalone",
"no": None
},
{
"condition": self.builder.get_object("number_sections").get_active(),
"yes": "--number-sections",
"no": None
},
{
"condition": self.builder.get_object("strict").get_active(),
"yes": "--strict",
"no": None
},
{
"condition": self.builder.get_object("incremental").get_active(),
"yes": "--incremental",
"no": None
},
{
"condition": self.builder.get_object("self_contained").get_active(),
"yes": "--self-contained",
"no": None
}
]
args = []
args.extend([c["yes"] if c["condition"] else c["no"] for c in conditions])
args = list(filter(lambda arg: arg is not None, args))
css_uri = self.builder.get_object("css_filechooser").get_uri()
if css_uri:
if css_uri.startswith("file://"):
css_uri = css_uri[7:]
args.append("--css=%s" % css_uri)
bib_uri = self.builder.get_object("bib_filechooser").get_uri()
if bib_uri:
if bib_uri.startswith("file://"):
bib_uri = bib_uri[7:]
args.append("--bibliography=%s" % bib_uri)
return args
def get_paper_size(self):
paper_size = self.paper_size.get_active_text()
paper_formats = {
"A4": "a4",
"US Letter": "letter"
}
return paper_formats[paper_size]
def disabled_text():
"""Return the TexLive installation instructions
Returns:
{str} -- [TexLive installation instructions]
"""
if os.path.isfile("/.flatpak-info"):
text = _("Please, install the TexLive extension from Gnome Software or running\n")\
+ ("flatpak install flathub de.wolfvollprecht.UberWriter.Plugin.TexLive")
else:
text = _("Please, install TexLive from your distribuiton repositories")
return text

View File

@ -1,210 +0,0 @@
import re
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import logging
logger = logging.getLogger('apostrophe')
class FixTable():
def __init__(self, TextBuffer):
self.TextBuffer = TextBuffer
@staticmethod
def create_seperator(widths, char):
"""
Generate a line of + and - as sepeartor
Example:
>>> create_separarator([2, 4], '-')
'+----+------+'
"""
line = []
for w in widths:
line.append("+" + char * (w + 2))
line.append("+")
return ''.join(line)
@staticmethod
def create_line(columns, widths):
"""
Crea una fila de la tabla separando los campos con un '|'.
El argumento `columns` es una lista con las celdas que se
quieren imprimir y el argumento `widths` tiene el ancho
de cada columna. Si la columna es mas ancha que el texto
a imprimir se agregan espacios vacíos.
Example
>>> create_line(['nombre', 'apellido'], [7, 10])
'| nombre | apellido |'
"""
line = zip(columns, widths)
result = []
for text, width in line:
spaces = " " * (width - len(text))
text = "| " + text + spaces + " "
result.append(text)
result.append("|")
return ''.join(result)
@staticmethod
def create_table(content):
"""Imprime una tabla en formato restructuredText.
El argumento `content` tiene que ser una lista
de celdas.
Example:
>>> print create_table([['software', 'vesion'], ['python', '3.2'],
['vim', '7.3']])
+----------+--------+
| software | vesion |
+==========+========+
| python | 3.2 |
+----------+--------+
| vim | 7.3 |
+----------+--------+
"""
# obtiene las columnas de toda la tabla.
columns = zip(*content)
# calcula el tamano maximo que debe tener cada columna.
# replace with len()
widths = [max([len(x) for x in i]) for i in columns]
result = []
result.append(FixTable.create_seperator(widths, '-'))
print(content, widths)
result.append(FixTable.create_line(content[0], widths))
result.append(FixTable.create_seperator(widths, '='))
for line in content[1:]:
result.append(FixTable.create_line(line, widths))
result.append(FixTable.create_seperator(widths, '-'))
return '\n'.join(result)
@staticmethod
def are_in_a_table(current_line):
"Line in a table?"
return "|" in current_line or "+" in current_line
@staticmethod
def are_in_a_paragraph(current_line):
"Line in a paragraph?"
return len(current_line.strip()) >= 1
def get_table_bounds(self, are_in_callback):
"""
Gets the row number where the table begins and ends.
are_in_callback argument must be a function
        indicating whether a particular line belongs or not
        to the table to be measured (or create).
        Returns two values as a tuple
"""
top = 0
buf = self.TextBuffer
start_iter = buf.get_start_iter()
end_iter = buf.get_end_iter()
text = self.TextBuffer.get_text(start_iter, end_iter, False).split('\n')
logger.debug(text)
length = len(text)
bottom = length - 1
insert_mark = self.TextBuffer.get_insert()
insert_iter = self.TextBuffer.get_iter_at_mark(insert_mark)
current_row_index = insert_iter.get_line()
for a in range(current_row_index, top, -1):
if not are_in_callback(text[a]):
top = a + 1
break
for b in range(current_row_index, length):
if not are_in_callback(text[b]):
bottom = b - 1
break
return top, bottom
@staticmethod
def remove_spaces(string):
"""Remove unnecessary spaces"""
return re.sub("\s\s+", " ", string)
@staticmethod
def create_separators_removing_spaces(string):
return re.sub("\s\s+", "|", string)
@staticmethod
def extract_cells_as_list(string):
"Extrae el texto de una fila de tabla y lo retorna como una lista."
string = FixTable.remove_spaces(string)
return [item.strip() for item in string.split('|') if item]
@staticmethod
def extract_table(text, top, bottom):
full_table_text = text[top:bottom]
# selecciona solamente las lineas que tienen celdas con texto.
only_text_lines = [x for x in full_table_text if '|' in x]
# extrae las celdas y descarta los separadores innecesarios.
return [FixTable.extract_cells_as_list(x) for x in only_text_lines]
@staticmethod
def extract_words_as_lists(text, top, bottom):
"Genera una lista de palabras para crear una lista."
lines = text[top:bottom + 1]
return [FixTable.create_separators_removing_spaces(line).split('|') for line in lines]
def fix_table(self):
"""
Fix Table, so all columns have the same width (again)
`initial_row` is a int idicationg the current row index
"""
cursor_mark = self.TextBuffer.get_insert()
cursor_iter = self.TextBuffer.get_iter_at_mark(cursor_mark)
cursor_iter.set_line(cursor_iter.get_line())
end_line = cursor_iter.copy()
end_line.forward_to_line_end()
line_text = self.TextBuffer.get_text(cursor_iter, end_line, False)
if FixTable.are_in_a_table(line_text):
# obtiene el indice donde comienza y termina la tabla.
r1, r2 = self.get_table_bounds(FixTable.are_in_a_table)
logger.debug('asdasd ')
# extrae de la tabla solo las celdas de texto
buf = self.TextBuffer
start_iter = buf.get_start_iter()
end_iter = buf.get_end_iter()
text = self.TextBuffer.get_text(start_iter, end_iter, False).split('\n')
table_as_list = FixTable.extract_table(text, r1, r2)
logger.debug(table_as_list)
# genera una nueva tabla tipo restructured text y la dibuja en el buffer.
table_content = FixTable.create_table(table_as_list)
logger.debug(table_content)
# Insert table back into Buffer ...
self.TextBuffer.insert(start_iter, table_content, -1)
else:
logger.debug("Not in a table")
print("Not in table")

View File

@ -1,306 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# END LICENSE
"""Manage all the headerbars related stuff
"""
import gi
from gettext import gettext as _
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
from apostrophe.helpers import get_descendant
from apostrophe.settings import Settings
class BaseHeaderbar:
"""Base class for all headerbars
"""
# preview modes
FULL_WIDTH = 0
HALF_WIDTH = 1
HALF_HEIGHT = 2
WINDOWED = 3
def __init__(self, app):
self.settings = Settings.new()
self.builder = Gtk.Builder()
self.builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Headerbar.ui")
self.builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/ExportPopover.ui")
self.hb = self.builder.get_object(
"Headerbar")
self.hb_revealer = self.builder.get_object(
"titlebar_revealer")
self.preview_toggle_revealer = self.builder.get_object(
"preview_switch_revealer")
self.preview_switcher_icon = self.builder.get_object(
"preview_switch_toggle_icon")
self.__populate_layout_switcher_menu()
self.update_preview_layout_icon()
self.sync_scroll_switch = self.builder.get_object("sync_scroll_switch")
self.sync_scroll_switch.set_active(self.settings.get_value("sync-scroll"))
self.sync_scroll_switch.connect("state-set", self.__on_sync_scroll)
self.menu_button = self.builder.get_object("menu_button")
self.recents_button = self.builder.get_object("recents_button")
self.export_button = self.builder.get_object("export_button")
export_popover = self.builder.get_object("export_menu")
self.preview_switch_button = self.builder.get_object("preview_switch_button")
self.export_button.set_popover(export_popover)
add_menus(self, app)
settings = Gtk.Settings.get_default()
# TODO: use walrust operator whenever Python3.8 lands on SDK
# if global_dark:= settings.props.gtk_theme_name.endswith("-dark"):
global_dark = settings.props.gtk_theme_name.endswith("-dark")
if global_dark:
self.light_button.set_sensitive(False)
self.light_button.set_tooltip_text(_(
"Light mode isn't available while using a dark global theme"))
self.dark_button.set_active(self.settings.get_boolean("dark-mode") or global_dark)
self.light_button.connect("toggled", self.__on_dark_mode)
self.select_preview_layout_row()
def update_preview_layout_icon(self):
mode = self.settings.get_enum("preview-mode")
self.preview_switcher_icon.set_from_icon_name(
self.__get_icon_for_preview_mode(mode), 4)
def select_preview_layout_row(self):
mode = self.settings.get_enum("preview-mode")
row = self.preview_menu.get_row_at_index(mode)
self.preview_menu.select_row(row)
def __populate_layout_switcher_menu(self):
self.preview_menu = self.builder.get_object("preview_switch_options")
modes = self.settings.props.settings_schema.get_key("preview-mode").get_range()[1]
for i, mode in enumerate(modes):
item_builder = Gtk.Builder()
item_builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/PreviewLayoutSwitcherItem.ui")
menu_item = item_builder.get_object("switcherItem")
menu_item.label = item_builder.get_object("label")
menu_item.label.set_text(self.__get_text_for_preview_mode(i))
menu_item.icon = item_builder.get_object("icon")
menu_item.icon.set_from_icon_name(self.__get_icon_for_preview_mode(i), 16)
menu_item.set_action_name("app.preview_mode")
menu_item.set_action_target_value(GLib.Variant.new_string(mode))
menu_item.show_all()
self.preview_menu.insert(menu_item, -1)
def __get_text_for_preview_mode(self, mode):
if mode == self.FULL_WIDTH:
return _("Full-Width")
elif mode == self.HALF_WIDTH:
return _("Half-Width")
elif mode == self.HALF_HEIGHT:
return _("Half-Height")
elif mode == self.WINDOWED:
return _("Windowed")
else:
raise ValueError("Unknown preview mode {}".format(mode))
def __get_icon_for_preview_mode(self, mode):
if mode == self.FULL_WIDTH:
return "preview-layout-full-width-symbolic"
elif mode == self.HALF_WIDTH:
return "preview-layout-half-width-symbolic"
elif mode == self.HALF_HEIGHT:
return "preview-layout-half-height-symbolic"
elif mode == self.WINDOWED:
return "preview-layout-windowed-symbolic"
else:
raise ValueError("Unknown preview mode {}".format(mode))
def __on_sync_scroll(self, _, state):
self.settings.set_boolean("sync-scroll", state)
return False
def __on_dark_mode(self, _):
self.settings.set_boolean("dark-mode", self.dark_button.get_active())
class MainHeaderbar(BaseHeaderbar): # pylint: disable=too-few-public-methods
"""Sets up the main application headerbar
"""
def __init__(self, app):
BaseHeaderbar.__init__(self, app)
self.hb.set_show_close_button(True)
self.hb_revealer.props.transition_duration = 0
class FullscreenHeaderbar(BaseHeaderbar):
"""Sets up and manages the fullscreen headerbar and his events
"""
def __init__(self, fs_builder, app):
BaseHeaderbar.__init__(self, app)
self.hb.set_show_close_button(False)
self.exit_fs_button = self.builder.get_object("exit_fs_button")
self.exit_fs_button.set_visible(True)
self.events = fs_builder.get_object("FullscreenEventbox")
self.events.add(self.hb_revealer)
# this is a little tricky
# we show hb when the cursor enters an area of 1px at the top
# as the hb is shown the height of the eventbox grows to accomodate it
self.events.connect('enter_notify_event', self.show_fs_hb)
self.events.connect('leave_notify_event', self.hide_fs_hb)
self.menu_button.get_popover().connect('closed', self.hide_fs_hb)
self.recents_button.get_popover().connect('closed', self.hide_fs_hb)
self.export_button.get_popover().connect('closed', self.hide_fs_hb)
self.preview_switch_button.get_popover().connect('closed', self.hide_fs_hb)
def show_fs_hb(self, _widget=None, _data=None):
"""show headerbar of the fullscreen mode
"""
self.hb_revealer.set_reveal_child(True)
def hide_fs_hb(self, _widget=None, _data=None):
"""hide headerbar of the fullscreen mode
"""
if (self.menu_button.get_active() or
self.recents_button.get_active() or
self.export_button.get_active() or
self.preview_switch_button.get_active()):
pass
else:
self.hb_revealer.set_reveal_child(False)
class DummyHeaderbar(BaseHeaderbar):
"""Sets up and manages the dummy headerbar wich fades away when entering
the free-distracting mode
"""
def __init__(self, app):
BaseHeaderbar.__init__(self, app)
self.hb.set_show_close_button(True)
self.hb_revealer.set_transition_type(
Gtk.RevealerTransitionType.CROSSFADE)
self.hb_revealer.set_reveal_child(False)
self.hb_revealer.hide()
self.menu_button.set_sensitive(True)
self.recents_button.set_sensitive(True)
def show_dm_hb(self):
"""show dummy headerbar:
It appears instantly to inmediatly fade away
"""
self.hb_revealer.show()
self.hb_revealer.set_transition_duration(0)
self.hb_revealer.set_reveal_child(True)
self.hb_revealer.set_transition_duration(600)
self.hb_revealer.set_reveal_child(False)
def hide_dm_hb(self):
"""hide dummy headerbar
It appears slowly to inmediatly dissapear
"""
self.hb_revealer.set_transition_duration(400)
self.hb_revealer.set_reveal_child(True)
GLib.timeout_add(400, self.hide_dm_hb_with_wait)
def hide_dm_hb_with_wait(self):
self.hb_revealer.set_transition_duration(0)
self.hb_revealer.set_reveal_child(False)
self.hb_revealer.hide()
return False
class PreviewHeaderbar:
"""Sets up the preview headerbar
"""
def __init__(self):
self.hb = Gtk.HeaderBar().new()
self.hb.props.show_close_button = True
self.hb.get_style_context().add_class("titlebar")
self.hb_revealer = Gtk.Revealer(name="titlebar-revealer-pv")
self.hb_revealer.add(self.hb)
self.hb_revealer.props.transition_duration = 750
self.hb_revealer.set_transition_type(
Gtk.RevealerTransitionType.CROSSFADE)
self.hb_revealer.show()
self.hb_revealer.set_reveal_child(True)
self.hb_container = Gtk.Frame(name="titlebar-container")
self.hb_container.set_shadow_type(Gtk.ShadowType.NONE)
self.hb_container.add(self.hb_revealer)
self.hb_container.show()
self.hb.show_all()
def add_menus(headerbar, app):
""" Add menu models to hb buttons
"""
# Add menu model to the menu button
builder_window_menu = Gtk.Builder()
builder_window_menu.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Menu.ui")
model = builder_window_menu.get_object("Menu")
headerbar.light_button = builder_window_menu.get_object("light_mode_button")
headerbar.dark_button = builder_window_menu.get_object("dark_mode_button")
headerbar.menu_button.set_popover(model)
# Add recents menu to the open recents button
recents_builder = Gtk.Builder()
recents_builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Recents.ui")
recents = recents_builder.get_object("recent_md_popover")
recents_treeview = get_descendant(recents, "recent_view", level=0)
recents_treeview.set_activate_on_single_click(True)
recents_wd = recents_builder.get_object("recent_md_widget")
recents_wd.connect('item-activated', app.on_open_recent)
headerbar.recents_button.set_popover(recents)
headerbar.recents_button.set_sensitive(True)

View File

@ -1,214 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# END LICENSE
### DO NOT EDIT THIS FILE ###
"""Helpers for the application."""
import logging
import os
import shutil
from contextlib import contextmanager
import gi
import pypandoc
from gi.overrides.Pango import Pango
from apostrophe.settings import Settings
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk # pylint: disable=E0611
from apostrophe.config import get_data_file
from apostrophe.builder import Builder
@contextmanager
def user_action(text_buffer):
text_buffer.begin_user_action()
yield text_buffer
text_buffer.end_user_action()
def path_to_file(path):
"""Return a file path (file:///) for the given path"""
return "file://" + path
def get_media_file(media_file_path):
"""Return the full path of a given filename under the media dir
(starts with file:///)
"""
return path_to_file(get_media_path(media_file_path))
def get_media_path(media_file_name):
"""Return the full path of a given filename under the media dir
(doesn't start with file:///)
"""
media_path = get_data_file('media', '%s' % (media_file_name,))
if not os.path.exists(media_path):
media_path = None
return media_path
def get_css_path(css_file_name):
"""Return the full path of a given filename under the css dir
(doesn't start with file:///)
"""
return get_media_path("css/{}".format(css_file_name))
def get_script_path(script_file_name):
"""Return the full path of a given filename under the script dir
"""
script_path = get_data_file('lua', '%s' % (script_file_name,))
if not os.path.exists(script_path):
script_path = None
return script_path
def get_reference_files_path(reference_file_name):
"""Return the full path of a given filename under the reference_files dir
"""
refs_path = get_data_file('reference_files', '%s' % (reference_file_name,))
if not os.path.exists(refs_path):
refs_path = ""
return refs_path
class NullHandler(logging.Handler):
def emit(self, record):
pass
def set_up_logging(opts):
# add a handler to prevent basicConfig
root = logging.getLogger()
null_handler = NullHandler()
root.addHandler(null_handler)
formatter = logging.Formatter(
"%(levelname)s:%(name)s: %(funcName)s() '%(message)s'")
logger = logging.getLogger('apostrophe')
logger_sh = logging.StreamHandler()
logger_sh.setFormatter(formatter)
logger.addHandler(logger_sh)
lib_logger = logging.getLogger('apostrophe')
lib_logger_sh = logging.StreamHandler()
lib_logger_sh.setFormatter(formatter)
lib_logger.addHandler(lib_logger_sh)
# Set the logging level to show debug messages.
if opts.verbose:
logger.setLevel(logging.DEBUG)
logger.debug('logging enabled')
if opts.verbose and opts.verbose > 1:
lib_logger.setLevel(logging.DEBUG)
def get_help_uri(page=None):
# help_uri from source tree - default language
here = os.path.dirname(__file__)
help_uri = os.path.abspath(os.path.join(here, '..', 'help', 'C'))
if not os.path.exists(help_uri):
# installed so use gnome help tree - user's language
help_uri = 'apostrophe'
# unspecified page is the index.page
if page is not None:
help_uri = '%s#%s' % (help_uri, page)
return help_uri
def show_uri(parent, link):
screen = parent.get_screen()
Gtk.show_uri(screen, link, Gtk.get_current_event_time())
def alias(alternative_function_name):
'''see http://www.drdobbs.com/web-development/184406073#l9'''
def decorator(function):
'''attach alternative_function_name(s) to function'''
if not hasattr(function, 'aliases'):
function.aliases = []
function.aliases.append(alternative_function_name)
return function
return decorator
def exist_executable(command):
"""return if a command can be executed in the SO
Arguments:
command {str} -- a command
Returns:
{bool} -- if the given command exists in the system
"""
return shutil.which(command) is not None
def get_descendant(widget, child_name, level, doPrint=False):
if widget is not None:
if doPrint: print("-" * level + str(Gtk.Buildable.get_name(widget)) +
" :: " + widget.get_name())
else:
if doPrint: print("-" * level + "None")
return None
# /*** If it is what we are looking for ***/
if Gtk.Buildable.get_name(widget) == child_name: # not widget.get_name() !
return widget
# /*** If this widget has one child only search its child ***/
if (hasattr(widget, 'get_child') and
callable(getattr(widget, 'get_child')) and
child_name != ""):
child = widget.get_child()
if child is not None:
return get_descendant(child, child_name, level + 1, doPrint)
# /*** Ity might have many children, so search them ***/
elif (hasattr(widget, 'get_children') and
callable(getattr(widget, 'get_children')) and
child_name != ""):
children = widget.get_children()
# /*** For each child ***/
found = None
for child in children:
if child is not None:
found = get_descendant(child, child_name, level + 1, doPrint) # //search the child
if found: return found
def get_char_width(widget):
return Pango.units_to_double(
widget.get_pango_context().get_metrics().get_approximate_char_width())
def pandoc_convert(text, to="html5", args=[], outputfile=None):
fr = Settings.new().get_value('input-format').get_string() or "markdown"
args.extend(["--quiet"])
return pypandoc.convert_text(text, to, fr, extra_args=args, outputfile=outputfile)

View File

@ -1,307 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# END LICENSE
import re
import os
import telnetlib
from gettext import gettext as _
from urllib.parse import unquote
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("WebKit2", "4.0")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib
from gi.repository import WebKit2
from apostrophe import latex_to_PNG, markup_regex
from apostrophe.settings import Settings
class DictAccessor:
reEndResponse = re.compile(br"^[2-5][0-58][0-9] .*\r\n$", re.DOTALL + re.MULTILINE)
reDefinition = re.compile(br"^151(.*?)^\.", re.DOTALL + re.MULTILINE)
def __init__(self, host="pan.alephnull.com", port=2628, timeout=60):
self.telnet = telnetlib.Telnet(host, port)
self.timeout = timeout
self.login_response = self.telnet.expect([self.reEndResponse], self.timeout)[2]
def run_command(self, cmd):
self.telnet.write(cmd.encode("utf-8") + b"\r\n")
return self.telnet.expect([self.reEndResponse], self.timeout)[2]
def get_matches(self, database, strategy, word):
if database in ["", "all"]:
d = "*"
else:
d = database
if strategy in ["", "default"]:
s = "."
else:
s = strategy
w = word.replace("\"", r"\\\"")
tsplit = self.run_command("MATCH {} {} \"{}\"".format(d, s, w)).splitlines()
mlist = list()
if tsplit[-1].startswith(b"250 ok") and tsplit[0].startswith(b"1"):
mlines = tsplit[1:-2]
for line in mlines:
lsplit = line.strip().split()
db = lsplit[0]
word = unquote(" ".join(lsplit[1:]))
mlist.append((db, word))
return mlist
def get_definition(self, database, word):
if database in ["", "all"]:
d = "*"
else:
d = database
w = word.replace("\"", r"\\\"")
dsplit = self.run_command("DEFINE {} \"{}\"".format(d, w)).splitlines(True)
dlist = list()
if dsplit[-1].startswith(b"250 ok") and dsplit[0].startswith(b"1"):
dlines = dsplit[1:-1]
dtext = b"".join(dlines)
dlist = [dtext]
return dlist
def close(self):
t = self.run_command("QUIT")
self.telnet.close()
return t
def parse_wordnet(self, response):
# consisting of group (n,v,adj,adv)
# number, description, examples, synonyms, antonyms
lines = response.splitlines()
lines = lines[2:]
lines = " ".join(lines)
lines = re.sub(r"\s+", " ", lines).strip()
lines = re.split(r"( adv | adj | n | v |^adv |^adj |^n |^v )", lines)
res = []
act_res = {"defs": [], "class": "none", "num": "None"}
for l in lines:
l = l.strip()
if not l:
continue
if l in ["adv", "adj", "n", "v"]:
if act_res:
res.append(act_res.copy())
act_res = {"defs": [], "class": l}
else:
ll = re.split(r"(?: |^)(\d): ", l)
act_def = {}
for lll in ll:
if lll.strip().isdigit() or not lll.strip():
if "description" in act_def and act_def["description"]:
act_res["defs"].append(act_def.copy())
act_def = {"num": lll}
continue
a = re.findall(r"(\[(syn|ant): (.+?)\] ??)+", lll)
for n in a:
if n[1] == "syn":
act_def["syn"] = re.findall(r"{(.*?)}.*?", n[2])
else:
act_def["ant"] = re.findall(r"{(.*?)}.*?", n[2])
tbr = re.search(r"\[.+\]", lll)
if tbr:
lll = lll[:tbr.start()]
lll = lll.split(";")
act_def["examples"] = []
act_def["description"] = []
for llll in lll:
llll = llll.strip()
if llll.strip().startswith("\""):
act_def["examples"].append(llll)
else:
act_def["description"].append(llll)
if act_def and "description" in act_def:
act_res["defs"].append(act_def.copy())
res.append(act_res.copy())
return res
def get_dictionary(term):
da = DictAccessor()
output = da.get_definition("wn", term)
if output:
output = output[0]
else:
return None
return da.parse_wordnet(output.decode(encoding="UTF-8"))
class InlinePreview:
WIDTH = 400
HEIGHT = 300
def __init__(self, text_view):
self.settings = Settings.new()
self.text_view = text_view
self.text_view.connect("button-press-event", self.on_button_press_event)
self.text_buffer = text_view.get_buffer()
self.cursor_mark = self.text_buffer.create_mark(
"click", self.text_buffer.get_iter_at_mark(self.text_buffer.get_insert()))
self.latex_converter = latex_to_PNG.LatexToPNG()
self.characters_per_line = self.settings.get_int("characters-per-line")
self.popover = Gtk.Popover.new(self.text_view)
self.popover.get_style_context().add_class("quick-preview-popup")
self.popover.set_modal(True)
self.preview_fns = {
markup_regex.MATH: self.get_view_for_math,
markup_regex.IMAGE: self.get_view_for_image,
markup_regex.LINK: self.get_view_for_link,
markup_regex.LINK_ALT: self.get_view_for_link,
markup_regex.FOOTNOTE_ID: self.get_view_for_footnote,
re.compile(r"(?P<text>\w+)"): self.get_view_for_lexikon
}
def on_button_press_event(self, _text_view, event):
if event.button == 1 and event.state & Gdk.ModifierType.CONTROL_MASK:
x, y = self.text_view.window_to_buffer_coords(2, int(event.x), int(event.y))
self.text_buffer.move_mark(
self.cursor_mark, self.text_view.get_iter_at_location(x, y).iter)
self.open_popover(self.text_view)
def get_view_for_math(self, match):
success, result = self.latex_converter.generatepng(match.group("text"))
if success:
return Gtk.Image.new_from_file(result)
else:
error = _("Formula looks incorrect:")
error += "\n\n{}".format(result)
return Gtk.Label(label=error)
def get_view_for_image(self, match):
path = match.group("url")
if path.startswith(("https://", "http://", "www.")):
return self.get_view_for_link(match)
if path.startswith(("file://")):
path = path[7:]
if not path.startswith(("/", "file://")):
path = os.path.join(self.settings.get_string("open-file-path"), path)
path = unquote(path)
return Gtk.Image.new_from_pixbuf(
GdkPixbuf.Pixbuf.new_from_file_at_size(path, self.WIDTH, self.HEIGHT))
def get_view_for_link(self, match):
url = match.group("url")
web_view = WebKit2.WebView(zoom_level=0.3125) # ~1280x960
web_view.set_size_request(self.WIDTH, self.HEIGHT)
if GLib.uri_parse_scheme(url) is None:
url = "http://{}".format(url)
web_view.load_uri(url)
return web_view
def get_view_for_footnote(self, match):
footnote_id = match.group("id")
fn_matches = re.finditer(markup_regex.FOOTNOTE, self.text_buffer.props.text)
for fn_match in fn_matches:
if fn_match.group("id") == footnote_id:
if fn_match:
footnote = re.sub("\n[\t ]+", "\n", fn_match.group("text"))
else:
footnote = _("No matching footnote found")
label = Gtk.Label(label=footnote)
label.set_max_width_chars(self.characters_per_line)
label.set_line_wrap(True)
return label
return None
def get_view_for_lexikon(self, match):
term = match.group("text")
lexikon_dict = get_dictionary(term)
if lexikon_dict:
grid = Gtk.Grid.new()
grid.get_style_context().add_class("lexikon")
grid.set_row_spacing(2)
grid.set_column_spacing(4)
i = 0
for entry in lexikon_dict:
if not entry["defs"]:
continue
elif entry["class"].startswith("n"):
word_type = _("noun")
elif entry["class"].startswith("v"):
word_type = _("verb")
elif entry["class"].startswith("adj"):
word_type = _("adjective")
elif entry["class"].startswith("adv"):
word_type = _("adverb")
else:
continue
vocab_label = Gtk.Label.new(term + " ~ " + word_type)
vocab_label.get_style_context().add_class("header")
if i == 0:
vocab_label.get_style_context().add_class("first")
vocab_label.set_halign(Gtk.Align.START)
vocab_label.set_justify(Gtk.Justification.LEFT)
grid.attach(vocab_label, 0, i, 3, 1)
for definition in entry["defs"]:
i = i + 1
num_label = Gtk.Label.new(definition["num"] + ".")
num_label.get_style_context().add_class("number")
num_label.set_valign(Gtk.Align.START)
grid.attach(num_label, 0, i, 1, 1)
def_label = Gtk.Label(label=" ".join(definition["description"]))
def_label.get_style_context().add_class("description")
def_label.set_halign(Gtk.Align.START)
def_label.set_max_width_chars(self.characters_per_line)
def_label.set_line_wrap(True)
def_label.set_justify(Gtk.Justification.FILL)
grid.attach(def_label, 1, i, 1, 1)
i = i + 1
if i > 0:
return grid
return None
def open_popover(self, _editor, _data=None):
start_iter = self.text_buffer.get_iter_at_mark(self.cursor_mark)
line_offset = start_iter.get_line_offset()
end_iter = start_iter.copy()
start_iter.set_line_offset(0)
end_iter.forward_to_line_end()
text = self.text_buffer.get_text(start_iter, end_iter, False)
for regex, get_view_fn in self.preview_fns.items():
matches = re.finditer(regex, text)
for match in matches:
if match.start() <= line_offset <= match.end():
prev_view = self.popover.get_child()
if prev_view:
prev_view.destroy()
view = get_view_fn(match)
view.show_all()
self.popover.add(view)
rect = self.text_view.get_iter_location(
self.text_buffer.get_iter_at_mark(self.cursor_mark))
rect.x, rect.y = self.text_view.buffer_to_window_coords(
Gtk.TextWindowType.TEXT, rect.x, rect.y)
self.popover.set_pointing_to(rect)
GLib.idle_add(self.popover.popup) # TODO: It doesn't popup without idle_add.
return

View File

@ -1,128 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
"""
Based on latex2png.py from Stuart Rackham
AUTHOR
Written by Stuart Rackham, <srackham@gmail.com>
The code was inspired by Kjell Magne Fauske"s code:
http://fauskes.net/nb/htmleqII/
See also:
http://www.amk.ca/python/code/mt-math
http://code.google.com/p/latexmath2png/
COPYING
Copyright (C) 2010 Stuart Rackham. Free use of this software is
granted under the terms of the MIT License.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in 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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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
AUTHORS 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
IN THE SOFTWARE.
"""
import os
import subprocess
import tempfile
class LatexToPNG:
TEX_HEADER = r"""\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{bm}
\newcommand{\mx}[1]{\mathbf{\bm{#1}}} % Matrix command
\newcommand{\vc}[1]{\mathbf{\bm{#1}}} % Vector command
\newcommand{\T}{\text{T}} % Transpose
\pagestyle{empty}
\begin{document}"""
TEX_FOOTER = r"""\end{document}"""
def __init__(self):
self.temp_result = tempfile.NamedTemporaryFile(suffix=".png")
def latex2png(self, tex, outfile, dpi, modified):
"""Convert LaTeX input file infile to PNG file named outfile."""
outfile = os.path.abspath(outfile)
outdir = os.path.dirname(outfile)
texfile = tempfile.mktemp(suffix=".tex", dir=os.path.dirname(outfile))
basefile = os.path.splitext(texfile)[0]
dvifile = basefile + ".dvi"
temps = [basefile + ext for ext in (".tex", ".dvi", ".aux", ".log")]
skip = False
tex = "{}\n{}\n{}\n".format(self.TEX_HEADER, tex.strip(), self.TEX_FOOTER)
open(texfile, "w").write(tex)
saved_pwd = os.getcwd()
os.chdir(outdir)
args = ["latex", "-halt-on-error", texfile]
p = subprocess.Popen(args,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE)
output = p.stdout
output_lines = output.readlines()
if os.path.isfile(dvifile): # DVI File exists
# Convert DVI file to PNG.
args = ["dvipng",
"-D", str(dpi),
"-T", "tight",
"-x", "1000",
"-z", "9",
"-bg", "Transparent",
"-o", outfile,
dvifile]
p = subprocess.Popen(args)
p.communicate()
else:
self.clean_up(temps)
"""
Errors in Latex output start with "! "
Stripping exclamation marks and superflous newlines
and telling the user what he"s done wrong.
"""
i = []
error = ""
for line in output_lines:
line = line.decode("utf-8")
if line.startswith("!"):
error += line[2:] # removing "! "
if error.endswith("\n"):
error = error[:-1]
raise Exception(error)
def generatepng(self, formula):
try:
self.temp_result = tempfile.NamedTemporaryFile(suffix=".png")
formula = "$" + formula + "$"
self.latex2png(formula, self.temp_result.name, 300, False)
return True, self.temp_result.name
except Exception as e:
self.temp_result.close()
return False, e.args[0]
def clean_up(self, files):
for f in files:
if os.path.isfile(f):
os.remove(f)

View File

@ -1,652 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# END LICENSE
import io
import locale
import logging
import os
import urllib
from gettext import gettext as _
import gi
from apostrophe.export_dialog import Export
from apostrophe.preview_handler import PreviewHandler
from apostrophe.stats_handler import StatsHandler
from apostrophe.styled_window import StyledWindow
from apostrophe.text_view import TextView
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject, GLib, Gio
import cairo
from apostrophe import helpers
from apostrophe.sidebar import Sidebar
from apostrophe.search_and_replace import SearchAndReplace
from apostrophe.settings import Settings
from . import headerbars
# Some Globals
# TODO move them somewhere for better
# accesibility from other files
LOGGER = logging.getLogger('apostrophe')
CONFIG_PATH = os.path.expanduser("~/.config/apostrophe/")
class MainWindow(StyledWindow):
__gsignals__ = {
'save-file': (GObject.SIGNAL_ACTION, None, ()),
'open-file': (GObject.SIGNAL_ACTION, None, ()),
'save-file-as': (GObject.SIGNAL_ACTION, None, ()),
'new-file': (GObject.SIGNAL_ACTION, None, ()),
'toggle-bibtex': (GObject.SIGNAL_ACTION, None, ()),
'toggle-preview': (GObject.SIGNAL_ACTION, None, ()),
'close-window': (GObject.SIGNAL_ACTION, None, ())
}
def __init__(self, app):
"""Set up the main window"""
super().__init__(application=Gio.Application.get_default(), title="Apostrophe")
self.get_style_context().add_class('apostrophe-window')
# Set UI
builder = Gtk.Builder()
builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Window.ui")
root = builder.get_object("AppOverlay")
self.connect("delete-event", self.on_delete_called)
self.add(root)
self.set_default_size(1000, 600)
# Preferences
self.settings = Settings.new()
# Headerbars
self.last_height = 0
self.headerbar = headerbars.MainHeaderbar(app)
self.headerbar.hb_revealer.connect(
"size_allocate", self.header_size_allocate)
self.set_titlebar(self.headerbar.hb_revealer)
self.fs_headerbar = headerbars.FullscreenHeaderbar(builder, app)
# Bind properties between normal and fs headerbar
self.headerbar.light_button.bind_property(
"active", self.fs_headerbar.light_button, "active",
GObject.BindingFlags.BIDIRECTIONAL
| GObject.BindingFlags.SYNC_CREATE)
self.headerbar.dark_button.bind_property(
"active", self.fs_headerbar.dark_button, "active",
GObject.BindingFlags.BIDIRECTIONAL
| GObject.BindingFlags.SYNC_CREATE)
# The dummy headerbar is a cosmetic hack to be able to
# crossfade the hb on top of the window
self.dm_headerbar = headerbars.DummyHeaderbar(app)
root.add_overlay(self.dm_headerbar.hb_revealer)
root.reorder_overlay(self.dm_headerbar.hb_revealer, 0)
root.set_overlay_pass_through(self.dm_headerbar.hb_revealer, True)
self.title_end = " Apostrophe"
self.set_headerbar_title("New File" + self.title_end)
self.accel_group = Gtk.AccelGroup()
self.add_accel_group(self.accel_group)
self.scrolled_window = builder.get_object('editor_scrolledwindow')
# Setup text editor
self.text_view = TextView(self.settings.get_int("characters-per-line"))
self.text_view.set_top_margin(80)
self.text_view.connect('focus-out-event', self.focus_out)
self.text_view.get_buffer().connect('changed', self.on_text_changed)
self.text_view.show()
self.text_view.grab_focus()
self.scrolled_window.add(self.text_view)
# Setup stats counter
self.stats_revealer = builder.get_object('editor_stats_revealer')
self.stats_button = builder.get_object('editor_stats_button')
self.stats_handler = StatsHandler(self.stats_button, self.text_view)
# Setup preview
content = builder.get_object('content')
editor = builder.get_object('editor')
self.preview_handler = PreviewHandler(self, content, editor, self.text_view)
# Setup header/stats bar
self.headerbar_visible = True
self.bottombar_visible = True
self.buffer_modified_for_status_bar = False
# Init file name with None
self.set_filename()
# Setting up spellcheck
self.auto_correct = None
self.toggle_spellcheck(self.settings.get_value("spellcheck"))
self.did_change = False
###
# Sidebar initialization test
###
self.paned_window = builder.get_object("main_paned")
self.sidebar_box = builder.get_object("sidebar_box")
self.sidebar = Sidebar(self)
self.sidebar_box.hide()
###
# Search and replace initialization
# Same interface as Sidebar ;)
###
self.searchreplace = SearchAndReplace(self, self.text_view, builder)
# EventBoxes
self.headerbar_eventbox = builder.get_object("HeaderbarEventbox")
self.headerbar_eventbox.connect('enter_notify_event',
self.reveal_headerbar_bottombar)
self.stats_revealer.connect('enter_notify_event', self.reveal_bottombar)
def header_size_allocate(self, widget, allocation):
""" When the main hb starts to shrink its size, add that size
to the textview margin, so it stays in place
"""
# prevent 1px jumps
if allocation.height == 1 and not widget.get_child_revealed():
allocation.height = 0
height = self.headerbar.hb.get_allocated_height() - allocation.height
if height == self.last_height:
return
self.last_height = height
self.text_view.update_vertical_margin(height)
self.text_view.queue_draw()
def on_text_changed(self, *_args):
"""called when the text changes, sets the self.did_change to true and
updates the title and the counters to reflect that
"""
if self.did_change is False:
self.did_change = True
title = self.get_title()
self.set_headerbar_title("* " + title)
self.buffer_modified_for_status_bar = True
if self.settings.get_value("autohide-headerbar"):
self.hide_headerbar_bottombar()
def set_fullscreen(self, state):
"""Puts the application in fullscreen mode and show/hides
the poller for motion in the top border
Arguments:
state {almost bool} -- The desired fullscreen state of the window
"""
if state.get_boolean():
self.fullscreen()
self.fs_headerbar.events.show()
self.fs_headerbar.hide_fs_hb()
self.headerbar_eventbox.hide()
else:
self.unfullscreen()
self.fs_headerbar.events.hide()
self.headerbar_eventbox.show()
self.text_view.grab_focus()
def set_focus_mode(self, state):
"""toggle focusmode
"""
self.text_view.set_focus_mode(state.get_boolean(), self.headerbar.hb.get_allocated_height())
self.text_view.grab_focus()
def set_hemingway_mode(self, state):
"""toggle hemingwaymode
"""
self.text_view.set_hemingway_mode(state.get_boolean())
self.text_view.grab_focus()
def toggle_preview(self, state):
"""Toggle the preview mode
Arguments:
state {gtk bool} -- Desired state of the preview mode (enabled/disabled)
"""
if state.get_boolean():
self.text_view.grab_focus()
self.preview_handler.show()
self.headerbar.preview_toggle_revealer.set_reveal_child(True)
self.fs_headerbar.preview_toggle_revealer.set_reveal_child(True)
self.dm_headerbar.preview_toggle_revealer.set_reveal_child(True)
else:
self.preview_handler.hide()
self.text_view.grab_focus()
self.headerbar.preview_toggle_revealer.set_reveal_child(False)
self.fs_headerbar.preview_toggle_revealer.set_reveal_child(False)
self.dm_headerbar.preview_toggle_revealer.set_reveal_child(False)
return True
# TODO: refactorizable
def save_document(self, _widget=None, _data=None):
"""provide to the user a filechooser and save the document
where he wants. Call set_headbar_title after that
"""
if self.filename:
LOGGER.info("saving")
filename = self.filename
file_to_save = io.open(filename, encoding="utf-8", mode='w')
file_to_save.write(self.text_view.get_text())
file_to_save.close()
if self.did_change:
self.did_change = False
title = self.get_title()
self.set_headerbar_title(title[2:])
return Gtk.ResponseType.OK
filefilter = Gtk.FileFilter.new()
filefilter.add_mime_type('text/x-markdown')
filefilter.add_mime_type('text/plain')
filefilter.set_name('Markdown (.md)')
filechooser = Gtk.FileChooserDialog(
_("Save your File"),
self,
Gtk.FileChooserAction.SAVE,
("_Cancel", Gtk.ResponseType.CANCEL,
"_Save", Gtk.ResponseType.OK)
)
filechooser.set_do_overwrite_confirmation(True)
filechooser.add_filter(filefilter)
response = filechooser.run()
if response == Gtk.ResponseType.OK:
filename = filechooser.get_filename()
if filename[-3:] != ".md":
filename = filename + ".md"
try:
self.recent_manager.add_item("file:/ " + filename)
except:
pass
file_to_save = io.open(filename, encoding="utf-8", mode='w')
file_to_save.write(self.text_view.get_text())
file_to_save.close()
self.set_filename(filename)
self.set_headerbar_title(
os.path.basename(filename) + self.title_end, filename)
self.did_change = False
filechooser.destroy()
return response
filechooser.destroy()
return Gtk.ResponseType.CANCEL
def save_document_as(self, _widget=None, _data=None):
"""provide to the user a filechooser and save the document
where he wants. Call set_headbar_title after that
"""
filechooser = Gtk.FileChooserDialog(
"Save your File",
self,
Gtk.FileChooserAction.SAVE,
("_Cancel", Gtk.ResponseType.CANCEL,
"_Save", Gtk.ResponseType.OK)
)
filechooser.set_do_overwrite_confirmation(True)
if self.filename:
filechooser.set_filename(self.filename)
response = filechooser.run()
if response == Gtk.ResponseType.OK:
filename = filechooser.get_filename()
if filename[-3:] != ".md":
filename = filename + ".md"
try:
self.recent_manager.remove_item("file:/" + filename)
self.recent_manager.add_item("file:/ " + filename)
except:
pass
file_to_save = io.open(filename, encoding="utf-8", mode='w')
file_to_save.write(self.text_view.get_text())
file_to_save.close()
self.set_filename(filename)
self.set_headerbar_title(
os.path.basename(filename) + self.title_end, filename)
try:
self.recent_manager.add_item(filename)
except:
pass
filechooser.destroy()
self.did_change = False
else:
filechooser.destroy()
return Gtk.ResponseType.CANCEL
def copy_html_to_clipboard(self, _widget=None, _date=None):
"""Copies only html without headers etc. to Clipboard
"""
output = helpers.pandoc_convert(self.text_view.get_text())
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(output, -1)
clipboard.store()
def open_document(self, _widget=None):
"""open the desired file
"""
if self.check_change() == Gtk.ResponseType.CANCEL:
return
markdown_filter = Gtk.FileFilter.new()
markdown_filter.add_mime_type('text/markdown')
markdown_filter.add_mime_type('text/x-markdown')
markdown_filter.set_name(_('Markdown Files'))
plaintext_filter = Gtk.FileFilter.new()
plaintext_filter.add_mime_type('text/plain')
plaintext_filter.set_name(_('Plain Text Files'))
filechooser = Gtk.FileChooserDialog(
_("Open a .md file"),
self,
Gtk.FileChooserAction.OPEN,
("_Cancel", Gtk.ResponseType.CANCEL,
"_Open", Gtk.ResponseType.OK)
)
filechooser.add_filter(markdown_filter)
filechooser.add_filter(plaintext_filter)
response = filechooser.run()
if response == Gtk.ResponseType.OK:
filename = filechooser.get_filename()
self.load_file(filename)
filechooser.destroy()
elif response == Gtk.ResponseType.CANCEL:
filechooser.destroy()
def check_change(self):
"""Show dialog to prevent loss of unsaved changes
"""
if self.filename:
title = os.path.basename(self.filename)
else:
title = _("New File")
if self.did_change and self.text_view.get_text():
dialog = Gtk.MessageDialog(self,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.NONE,
_("Save changes to document “%s” before closing?") %
title
)
dialog.props.secondary_text = _("If you dont save, " +
"all your changes will be permanently lost.")
close_button = dialog.add_button(_("Close without saving"), Gtk.ResponseType.NO)
dialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL)
dialog.add_button(_("Save now"), Gtk.ResponseType.YES)
close_button.get_style_context().add_class("destructive-action")
# dialog.set_default_size(200, 60)
dialog.set_default_response(Gtk.ResponseType.YES)
response = dialog.run()
if response == Gtk.ResponseType.YES:
if self.save_document() == Gtk.ResponseType.CANCEL:
dialog.destroy()
return self.check_change()
dialog.destroy()
return response
if response == Gtk.ResponseType.NO:
dialog.destroy()
return response
dialog.destroy()
return Gtk.ResponseType.CANCEL
def new_document(self, _widget=None):
"""create new document
"""
if self.check_change() == Gtk.ResponseType.CANCEL:
return
self.text_view.clear()
self.did_change = False
self.set_filename()
self.set_headerbar_title(_("New File") + self.title_end)
def update_default_stat(self):
self.stats_handler.update_default_stat()
def update_preview_mode(self):
self.preview_handler.update_preview_mode()
self.headerbar.update_preview_layout_icon()
self.headerbar.select_preview_layout_row()
self.fs_headerbar.update_preview_layout_icon()
self.fs_headerbar.select_preview_layout_row()
def menu_toggle_sidebar(self, _widget=None):
"""WIP
"""
self.sidebar.toggle_sidebar()
def toggle_spellcheck(self, state):
"""Enable/disable the autospellchecking
Arguments:
status {gtk bool} -- Desired status of the spellchecking
"""
self.text_view.set_spellcheck(state.get_boolean())
def reload_preview(self, reshow=False):
self.preview_handler.reload(reshow=reshow)
def load_file(self, filename=None):
"""Open File from command line or open / open recent etc."""
LOGGER.info("trying to open " + filename)
if self.check_change() == Gtk.ResponseType.CANCEL:
return
if filename:
if filename.startswith('file://'):
filename = filename[7:]
filename = urllib.parse.unquote_plus(filename)
self.text_view.clear()
try:
if os.path.exists(filename):
with io.open(filename, encoding="utf-8", mode='r') as current_file:
self.text_view.set_text(current_file.read())
else:
dialog = Gtk.MessageDialog(self,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.CLOSE,
_("The file you tried to open doesn't exist.\
\nA new file will be created in its place when you save the current one.")
)
dialog.run()
dialog.destroy()
self.set_headerbar_title(os.path.basename(filename) + self.title_end, filename)
self.set_filename(filename)
except Exception as e:
LOGGER.warning(_("Error Reading File: %r") % e)
dialog = Gtk.MessageDialog(self,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.CLOSE,
_("Error reading file:\
\n%r" %e)
)
dialog.run()
dialog.destroy()
self.did_change = False
else:
LOGGER.warning("No File arg")
def open_apostrophe_markdown(self, _widget=None, _data=None):
"""open a markdown mini tutorial
"""
if self.check_change() == Gtk.ResponseType.CANCEL:
return
self.load_file(helpers.get_media_file('apostrophe_markdown.md'))
def open_search(self, replace=False):
"""toggle the search box
"""
self.searchreplace.toggle_search(replace=replace)
def open_advanced_export(self, export_format):
"""open the export and advanced export dialog
"""
text = bytes(self.text_view.get_text(), "utf-8")
self.export = Export(self.filename, export_format, text)
def open_recent(self, _widget, data=None):
"""open the given recent document
"""
if data:
if self.check_change() == Gtk.ResponseType.CANCEL:
return
self.load_file(data)
def focus_out(self, _widget, _data=None):
"""events called when the window losses focus
"""
self.reveal_headerbar_bottombar()
def reveal_headerbar_bottombar(self, _widget=None, _data=None):
def __reveal_hb():
self.headerbar_eventbox.hide()
self.headerbar.hb_revealer.set_reveal_child(True)
self.get_style_context().remove_class("focus")
return False
self.reveal_bottombar()
if not self.headerbar_visible:
self.dm_headerbar.hide_dm_hb()
GLib.timeout_add(400, __reveal_hb)
self.headerbar_visible = True
def reveal_bottombar(self, _widget=None, _data=None):
if not self.bottombar_visible:
self.stats_revealer.set_reveal_child(True)
self.bottombar_visible = True
self.buffer_modified_for_status_bar = True
def hide_headerbar_bottombar(self):
if self.headerbar_visible:
self.headerbar.hb_revealer.set_reveal_child(False)
self.dm_headerbar.show_dm_hb()
self.get_style_context().add_class("focus")
self.headerbar_visible = False
if self.bottombar_visible:
self.stats_revealer.set_reveal_child(False)
self.bottombar_visible = False
self.headerbar_eventbox.show()
self.buffer_modified_for_status_bar = False
def on_delete_called(self, _widget, _data=None):
"""Called when the TexteditorWindow is closed.
"""
LOGGER.info('delete called')
if self.check_change() == Gtk.ResponseType.CANCEL:
return True
return False
def on_mnu_close_activate(self, _widget, _data=None):
"""Signal handler for closing the Window.
Overriden from parent Window Class
"""
if self.on_delete_called(self): # Really destroy?
return
self.destroy()
return
def set_headerbar_title(self, title, subtitle=None):
"""set the desired headerbar title
"""
self.headerbar.hb.props.title = title
self.dm_headerbar.hb.props.title = title
self.fs_headerbar.hb.props.title = title
if subtitle:
self.headerbar.hb.props.subtitle = subtitle
self.dm_headerbar.hb.props.subtitle = subtitle
self.fs_headerbar.hb.props.subtitle = subtitle
self.headerbar.hb.set_tooltip_text(subtitle)
self.fs_headerbar.hb.set_tooltip_text(subtitle)
self.set_title(title)
def set_filename(self, filename=None):
"""set filename
"""
if filename:
self.filename = filename
base_path = os.path.dirname(self.filename)
os.chdir(base_path)
else:
self.filename = None
base_path = "/"
self.settings.set_string("open-file-path", base_path)

View File

@ -1,42 +0,0 @@
import re
ITALIC_ASTERISK = re.compile(
r"(?<!\\)\*[^\s\*](?P<text>.*?\S?.*?)(?<!\\)\*")
ITALIC_UNDERSCORE = re.compile(
r"(?<!(\\|\S))_[^\s_](?P<text>.*?\S?.*?)(?<!\\)_(?=\s)")
BOLD = re.compile(
r"(\*\*|__)[^\s*](?P<text>.*?\S.*?)\1")
BOLD_ITALIC = re.compile(
r"((\*\*|__)([*_])|([*_])(\*\*|__))[^\s*](?P<text>.*?\S.*?)(?:\5\4|\3\2)")
STRIKETHROUGH = re.compile(
r"~~(?P<text>.*?\S.*?)~~")
CODE = re.compile(
r"`(?P<text>[^`].+?)`")
LINK = re.compile(
r"\[(?P<text>.*)\]\((?P<url>.+?)(?: \"(?P<title>.+)\")?\)")
LINK_ALT = re.compile(
r"<(?P<text>(?P<url>[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*|(?:[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)))>")
IMAGE = re.compile(
r"!\[(?P<text>.*)\]\((?P<url>.+?)(?: \"(?P<title>.+)\")?\)")
HORIZONTAL_RULE = re.compile(
r"(?:^|\n{2,})(?P<symbols> {0,3}[*\-_]{3,} *)(?:\n{2,}|$)")
LIST = re.compile(
r"(?:^|\n)(?P<content>(?P<indent>(?:\t| {4})*)[\-*+]( +)(?P<text>.+(?:\n+ \2.+)*))")
ORDERED_LIST = re.compile(
r"(?:^|\n)(?P<content>(?P<indent>(?:\t| {4})*)(?P<prefix>(?:\d|[a-z])+[.)]) (?P<text>.+(?:\n+ {2}\2.+)*))")
BLOCK_QUOTE = re.compile(
r"^ {0,3}(?:> ?)+(?P<text>.+)", re.M)
HEADER = re.compile(
r"^ {0,3}(?P<level>#{1,6}) (?P<text>[^\n]+)", re.M)
HEADER_UNDER = re.compile(
r"(?:^\n*|\n\n)(?P<text>[^\s].+)\n {0,3}[=\-]+(?: +?\n|$)")
CODE_BLOCK = re.compile(
r"(?:^|\n) {0,3}(?P<block>([`~]{3})(?P<text>.+?) {0,3}\2)(?:\s+?\n|$)", re.S)
TABLE = re.compile(
r"^[\-+]{5,}\n(?P<text>.+?)\n[\-+]{5,}\n", re.S)
MATH = re.compile(
r"([$]{1,2})(?P<text>[^` ].+?[^`\\ ])\1")
FOOTNOTE_ID = re.compile(
r"[^\s]+\[\^(?P<id>(?P<text>[^\s]+))\]")
FOOTNOTE = re.compile(
r"(?:^\n*|\n\n)\[\^(?P<id>[^\s]+)\]: (?P<text>(?:[^\n]+|\n+(?=(?:\t| {4})))+)(?:\n+|$)", re.M)

View File

@ -1,503 +0,0 @@
### 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.
### 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 an 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!

View File

@ -1 +0,0 @@
#from .bibtex import BibTex

View File

@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.19.0 -->
<interface>
<requires lib="gtk+" version="3.16"/>
<object class="GtkWindow" id="bibtex_window">
<property name="can_focus">False</property>
<property name="modal">True</property>
<property name="window_position">center-on-parent</property>
<property name="gravity">center</property>
<child>
<object class="GtkBox" id="box1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkSearchEntry" id="searchentry1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="primary_icon_name">edit-find-symbolic</property>
<property name="primary_icon_activatable">False</property>
<property name="primary_icon_sensitive">False</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkScrolledWindow" id="scrolledwindow1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="shadow_type">in</property>
<child>
<object class="GtkViewport" id="viewport1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkListBox" id="listbox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="activate_on_single_click">False</property>
</object>
</child>
</object>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
</interface>

View File

@ -1,75 +0,0 @@
from gi.repository import Gtk, Gio
from . import bibtexparser
from . import fuzzywuzzy
from .gi_composites import GtkTemplate
@GtkTemplate(ui='/home/wolfv/Programs/apostrophe/apostrophe/plugins/bibtex/bibtex_item.glade')
class BibTexItem(Gtk.Box):
__gtype_name__ = 'BibTexItem'
title_label = GtkTemplate.Child()
author_label = GtkTemplate.Child()
other_label = GtkTemplate.Child()
def __init__(self, data):
super(Gtk.Box, self).__init__()
# This must occur *after* you initialize your base
self.init_template()
self.title_label.set_text(data['title'])
self.author_label.set_text(data.get('author'))
self.other_label.set_text(data.get('year') if data.get('year') else 'N/A')
class BibTex(object):
"""docstring for Handler"""
def open_bibtex(self, event, *args):
self.match()
self.window.show_all()
# self.window.set_transient(True)
# self.window.set_modal(True)
def get_widget_for_box(self, word):
return Gtk.Label(word)
def real_row_activated(self, row, data=None):
print("A row was activated!!")
self.app.TextBuffer.insert_at_cursor('[@' + data + ']')
self.close()
print(data)
def row_activated(self, widget, row, data=None):
# row.activate()
return
def match(self, word=None):
self.rows = []
for i in self.bib_db.entries:
row = Gtk.ListBoxRow()
item = BibTexItem(i)
row.add(item)
row.set_activatable(True)
row.connect('activate', self.real_row_activated, i['ID'])
self.rows.append(row)
self.listview.add(row)
# self.listview.add(Gtk.Label('test'))
# self.listview.bind_model(a, self.get_widget_for_box)
self.listview.show_all()
def __init__(self, app):
self.app = app
self.app.connect('toggle_bibtex', self.open_bibtex)
with open('/home/wolfv/ownCloud/Studium/Semester Project/Report/listb.bib') as f:
self.bib_db = bibtexparser.load(f)
builder = Gtk.Builder()
builder.add_from_file('/home/wolfv/Programs/apostrophe/apostrophe/plugins/bibtex/bibtex.glade')
self.window = builder.get_object('bibtex_window')
self.window.set_transient_for(self.app)
self.window.set_modal(True)
self.listview = builder.get_object('listbox')

View File

@ -1,55 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.19.0 -->
<interface>
<requires lib="gtk+" version="3.16"/>
<template class="BibTexItem" parent="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">3</property>
<property name="margin_right">4</property>
<property name="margin_top">3</property>
<property name="margin_bottom">3</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkLabel" id="title_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="hexpand">True</property>
<property name="label" translatable="yes">label</property>
<property name="xalign">0</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="author_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="vexpand">False</property>
<property name="label" translatable="yes">label</property>
<property name="xalign">0</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="other_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">label</property>
<property name="xalign">0</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</template>
</interface>

View File

@ -1,91 +0,0 @@
"""
BibTeX <http://en.wikipedia.org/wiki/BibTeX> is a bibliographic data file format.
The :mod:`bibtexparser` module provides parsing and writing of BibTeX files functionality. The API is similar to the
:mod:`json` module. The parsed data is returned as a simple :class:`BibDatabase` object with the main attribute being
:attr:`entries` representing bibliographic sources such as books and journal articles.
Parsing is a simple as::
>>>> import bibtexparser
>>>> with open('bibtex.bib') as bibtex_file:
>>>> bibtex_database = bibtexparser.load(bibtex_file)
And writing::
>>>> import bibtexparser
>>>> with open('bibtex.bib', 'w') as bibtex_file:
>>>> bibtexparser.dump(bibtex_database, bibtex_file)
"""
__all__ = [
'loads', 'load', 'dumps', 'dump', 'bibdatabase',
'bparser', 'bwriter', 'latexenc', 'customization',
]
__version__ = '0.6.2'
from . import bibdatabase, bparser, bwriter, latexenc, customization
def loads(bibtex_str, parser=None):
"""
Load :class:`BibDatabase` object from a string
:param bibtex_str: input BibTeX string to be parsed
:type bibtex_str: str or unicode
:param parser: custom parser to use (optional)
:type parser: BibTexParser
:return: bibliographic database object
:rtype: BibDatabase
"""
if parser is None:
parser = bparser.BibTexParser()
return parser.parse(bibtex_str)
def load(bibtex_file, parser=None):
"""
Load :class:`BibDatabase` object from a file
:param bibtex_file: input file to be parsed
:type bibtex_file: file
:param parser: custom parser to use (optional)
:type parser: BibTexParser
:return: bibliographic database object
:rtype: BibDatabase
"""
if parser is None:
parser = bparser.BibTexParser()
return parser.parse_file(bibtex_file)
def dumps(bib_database, writer=None):
"""
Dump :class:`BibDatabase` object to a BibTeX string
:param bib_database: bibliographic database object
:type bib_database: BibDatabase
:param writer: custom writer to use (optional) (not yet implemented)
:type writer: BibTexWriter
:return: BibTeX string
:rtype: unicode
"""
if writer is None:
writer = bwriter.BibTexWriter()
return writer.write(bib_database)
def dump(bib_database, bibtex_file, writer=None):
"""
Save :class:`BibDatabase` object as a BibTeX text file
:param bib_database: bibliographic database object
:type bib_database: BibDatabase
:param bibtex_file: file to write to
:type bibtex_file: file
:param writer: custom writer to use (optional) (not yet implemented)
:type writer: BibTexWriter
"""
if writer is None:
writer = bwriter.BibTexWriter()
bibtex_file.write(writer.write(bib_database))

View File

@ -1,57 +0,0 @@
from collections import OrderedDict
import sys
if sys.version_info.major == 2:
TEXT_TYPE = unicode
else:
TEXT_TYPE = str
class BibDatabase(object):
"""
A bibliographic database object following the data structure of a BibTeX file.
"""
def __init__(self):
#: List of BibTeX entries, for example `@book{...}`, `@article{...}`, etc. Each entry is a simple dict with
#: BibTeX field-value pairs, for example `'author': 'Bird, R.B. and Armstrong, R.C. and Hassager, O.'` Each
#: entry will always have the following dict keys (in addition to other BibTeX fields):
#: - `ID` (BibTeX key)
#: - `ENTRYTYPE` (entry type in lowercase, e.g. `book`, `article` etc.)
self.entries = []
self._entries_dict = {}
#: List of BibTeX comment (`@comment{...}`) blocks.
self.comments = []
#: OrderedDict of BibTeX string definitions (`@string{...}`). In order of definition.
self.strings = OrderedDict() # Not sure if order is import, keep order just in case
#: List of BibTeX preamble (`@preamble{...}`) blocks.
self.preambles = []
def get_entry_list(self):
"""Get a list of bibtex entries.
:returns: BibTeX entries
:rtype: list
.. deprecated:: 0.5.6
Use :attr:`entries` instead.
"""
return self.entries
@staticmethod
def entry_sort_key(entry, fields):
result = []
for field in fields:
result.append(TEXT_TYPE(entry.get(field, '')).lower()) # Sorting always as string
return tuple(result)
def get_entry_dict(self):
"""Return a dictionary of BibTeX entries.
The dict key is the BibTeX entry key
"""
# If the hash has never been made, make it
if not self._entries_dict:
for entry in self.entries:
self._entries_dict[entry['ID']] = entry
return self._entries_dict
entries_dict = property(get_entry_dict)

View File

@ -1,422 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Original source: github.com/okfn/bibserver
# Authors:
# markmacgillivray
# Etienne Posthumus (epoz)
# Francois Boulogne <fboulogne at april dot org>
import sys
import logging
import io
import re
from .bibdatabase import BibDatabase
logger = logging.getLogger(__name__)
__all__ = ['BibTexParser']
if sys.version_info >= (3, 0):
from io import StringIO
ustr = str
else:
from StringIO import StringIO
ustr = unicode
class BibTexParser(object):
"""
A parser for reading BibTeX bibliographic data files.
Example::
from bibtexparser.bparser import BibTexParser
bibtex_str = ...
parser = BibTexParser()
parser.ignore_nonstandard_types = False
parser.homogenise_fields = False
bib_database = bibtexparser.loads(bibtex_str, parser)
"""
def __new__(cls, data=None,
customization=None,
ignore_nonstandard_types=True,
homogenise_fields=True):
"""
To catch the old API structure in which creating the parser would immediately parse and return data.
"""
if data is None:
return super(BibTexParser, cls).__new__(cls)
else:
# For backwards compatibility: if data is given, parse and return the `BibDatabase` object instead of the
# parser.
parser = BibTexParser()
parser.customization = customization
parser.ignore_nonstandard_types = ignore_nonstandard_types
parser.homogenise_fields = homogenise_fields
return parser.parse(data)
def __init__(self):
"""
Creates a parser for rading BibTeX files
:return: parser
:rtype: `BibTexParser`
"""
self.bib_database = BibDatabase()
#: Callback function to process BibTeX entries after parsing, for example to create a list from a string with
#: multiple values. By default all BibTeX values are treated as simple strings. Default: `None`.
self.customization = None
#: Ignore non-standard BibTeX types (`book`, `article`, etc). Default: `True`.
self.ignore_nonstandard_types = True
#: Sanitise BibTeX field names, for example change `url` to `link` etc. Field names are always converted to
#: lowercase names. Default: `True`.
self.homogenise_fields = True
# On some sample data files, the character encoding detection simply
# hangs We are going to default to utf8, and mandate it.
self.encoding = 'utf8'
# pre-defined set of key changes
self.alt_dict = {
'keyw': 'keyword',
'keywords': 'keyword',
'authors': 'author',
'editors': 'editor',
'url': 'link',
'urls': 'link',
'links': 'link',
'subjects': 'subject'
}
self.replace_all_re = re.compile(r'((?P<pre>"?)\s*(#|^)\s*(?P<id>[^\d\W]\w*)\s*(#|$)\s*(?P<post>"?))', re.UNICODE)
def _bibtex_file_obj(self, bibtex_str):
# Some files have Byte-order marks inserted at the start
byte = '\xef\xbb\xbf'
if not isinstance(byte, ustr):
byte = ustr('\xef\xbb\xbf', self.encoding, 'ignore')
if bibtex_str[:3] == byte:
bibtex_str = bibtex_str[3:]
return StringIO(bibtex_str)
def parse(self, bibtex_str):
"""Parse a BibTeX string into an object
:param bibtex_str: BibTeX string
:type: str or unicode
:return: bibliographic database
:rtype: BibDatabase
"""
self.bibtex_file_obj = self._bibtex_file_obj(bibtex_str)
self._parse_records(customization=self.customization)
return self.bib_database
def parse_file(self, file):
"""Parse a BibTeX file into an object
:param file: BibTeX file or file-like object
:type: file
:return: bibliographic database
:rtype: BibDatabase
"""
return self.parse(file.read())
def _parse_records(self, customization=None):
"""Parse the bibtex into a list of records.
:param customization: a function
"""
def _add_parsed_record(record, records):
"""
Atomic function to parse a record
and append the result in records
"""
if record != "":
logger.debug('The record is not empty. Let\'s parse it.')
parsed = self._parse_record(record, customization=customization)
if parsed:
logger.debug('Store the result of the parsed record')
records.append(parsed)
else:
logger.debug('Nothing returned from the parsed record!')
else:
logger.debug('The record is empty')
records = []
record = ""
# read each line, bundle them up until they form an object, then send for parsing
for linenumber, line in enumerate(self.bibtex_file_obj):
logger.debug('Inspect line %s', linenumber)
if line.strip().startswith('@'):
# Remove leading whitespaces
line = line.lstrip()
logger.debug('Line starts with @')
# Parse previous record
_add_parsed_record(record, records)
# Start new record
logger.debug('The record is set to empty')
record = ""
# Keep adding lines to the record
record += line
# catch any remaining record and send it for parsing
_add_parsed_record(record, records)
logger.debug('Set the list of entries')
self.bib_database.entries = records
def _parse_record(self, record, customization=None):
"""Parse a record.
* tidy whitespace and other rubbish
* parse out the bibtype and citekey
* find all the key-value pairs it contains
:param record: a record
:param customization: a function
:returns: dict --
"""
d = {}
if not record.startswith('@'):
logger.debug('The record does not start with @. Return empty dict.')
return {}
# if a comment record, add to bib_database.comments
if record.lower().startswith('@comment'):
logger.debug('The record startswith @comment')
logger.debug('Store comment in list of comments')
self.bib_database.comments.append(re.search('\{(.*)\}', record, re.DOTALL).group(1))
logger.debug('Return an empty dict')
return {}
# if a preamble record, add to bib_database.preambles
if record.lower().startswith('@preamble'):
logger.debug('The record startswith @preamble')
logger.debug('Store preamble in list of preambles')
self.bib_database.preambles.append(re.search('\{(.*)\}', record, re.DOTALL).group(1))
logger.debug('Return an empty dict')
return {}
# prepare record
record = '\n'.join([i.strip() for i in record.split('\n')])
if '}\n' in record:
logger.debug('}\\n detected in the record. Clean up.')
record = record.replace('\r\n', '\n').replace('\r', '\n').rstrip('\n')
# treat the case for which the last line of the record
# does not have a coma
if record.endswith('}\n}') or record.endswith('}}'):
logger.debug('Missing coma in the last line of the record. Fix it.')
record = re.sub('}(\n|)}$', '},\n}', record)
# if a string record, put it in the replace_dict
if record.lower().startswith('@string'):
logger.debug('The record startswith @string')
key, val = [i.strip().strip('{').strip('}').replace('\n', ' ') for i in record.split('{', 1)[1].strip('}').strip('\n').strip(',').split('=')]
key = key.lower() # key is case insensitive
val = self._string_subst_partial(val)
if val.startswith('"') or val.lower() not in self.bib_database.strings:
self.bib_database.strings[key] = val.strip('"')
else:
self.bib_database.strings[key] = self.bib_database.strings[val.lower()]
logger.debug('Return a dict')
return d
# for each line in record
logger.debug('Split the record of its lines and treat them')
kvs = [i.strip() for i in re.split(',\s*\n|\n\s*,', record)]
inkey = ""
inval = ""
for kv in kvs:
logger.debug('Inspect: %s', kv)
# TODO: We may check that the keyword belongs to a known type
if kv.startswith('@') and not inkey:
# it is the start of the record - set the bibtype and citekey (id)
logger.debug('Line starts with @ and the key is not stored yet.')
bibtype, id = kv.split('{', 1)
bibtype = self._add_key(bibtype)
id = id.lstrip().strip('}').strip(',')
logger.debug('bibtype = %s', bibtype)
logger.debug('id = %s', id)
if self.ignore_nonstandard_types and bibtype not in ('article',
'book',
'booklet',
'conference',
'inbook',
'incollection',
'inproceedings',
'manual',
'mastersthesis',
'misc',
'phdthesis',
'proceedings',
'techreport',
'unpublished'):
logger.warning('Entry type %s not standard. Not considered.', bibtype)
break
elif '=' in kv and not inkey:
# it is a line with a key value pair on it
logger.debug('Line contains a key-pair value and the key is not stored yet.')
key, val = [i.strip() for i in kv.split('=', 1)]
key = self._add_key(key)
val = self._string_subst_partial(val)
# if it looks like the value spans lines, store details for next loop
if (val.count('{') != val.count('}')) or (val.startswith('"') and not val.replace('}', '').endswith('"')):
logger.debug('The line is not ending the record.')
inkey = key
inval = val
else:
logger.debug('The line is the end of the record.')
d[key] = self._add_val(val)
elif inkey:
logger.debug('Continues the previous line to complete the key pair value...')
# if this line continues the value from a previous line, append
inval += ', ' + kv
# if it looks like this line finishes the value, store it and clear for next loop
if (inval.startswith('{') and inval.endswith('}')) or (inval.startswith('"') and inval.endswith('"')):
logger.debug('This line represents the end of the current key-pair value')
d[inkey] = self._add_val(inval)
inkey = ""
inval = ""
else:
logger.debug('This line does NOT represent the end of the current key-pair value')
logger.debug('All lines have been treated')
if not d:
logger.debug('The dict is empty, return it.')
return d
d['ENTRYTYPE'] = bibtype
d['ID'] = id
if customization is None:
logger.debug('No customization to apply, return dict')
return d
else:
# apply any customizations to the record object then return it
logger.debug('Apply customizations and return dict')
return customization(d)
def _strip_quotes(self, val):
"""Strip double quotes enclosing string
:param val: a value
:type val: string
:returns: string -- value
"""
logger.debug('Strip quotes')
val = val.strip()
if val.startswith('"') and val.endswith('"'):
return val[1:-1]
return val
def _strip_braces(self, val):
"""Strip braces enclosing string
:param val: a value
:type val: string
:returns: string -- value
"""
logger.debug('Strip braces')
val = val.strip()
if val.startswith('{') and val.endswith('}') and self._full_span(val):
return val[1:-1]
return val
def _full_span(self, val):
cnt = 0
for i in range(0, len(val)):
if val[i] == '{':
cnt += 1
elif val[i] == '}':
cnt -= 1
if cnt == 0:
break
if i == len(val) - 1:
return True
else:
return False
def _string_subst(self, val):
""" Substitute string definitions
:param val: a value
:type val: string
:returns: string -- value
"""
logger.debug('Substitute string definitions')
if not val:
return ''
for k in list(self.bib_database.strings.keys()):
if val.lower() == k:
val = self.bib_database.strings[k]
if not isinstance(val, ustr):
val = ustr(val, self.encoding, 'ignore')
return val
def _string_subst_partial(self, val):
""" Substitute string definitions inside larger expressions
:param val: a value
:type val: string
:returns: string -- value
"""
def repl(m):
k = m.group('id')
replacement = self.bib_database.strings[k.lower()] if k.lower() in self.bib_database.strings else k
pre = '"' if m.group('pre') != '"' else ''
post = '"' if m.group('post') != '"' else ''
return pre + replacement + post
logger.debug('Substitute string definitions inside larger expressions')
if '#' not in val:
return val
# TODO?: Does not match two subsequent variables or strings, such as "start" # foo # bar # "end" or "start" # "end".
# TODO: Does not support braces instead of quotes, e.g.: {start} # foo # {bar}
# TODO: Does not support strings like: "te#s#t"
return self.replace_all_re.sub(repl, val)
def _add_val(self, val):
""" Clean instring before adding to dictionary
:param val: a value
:type val: string
:returns: string -- value
"""
if not val or val == "{}":
return ''
val = self._strip_braces(val)
val = self._strip_quotes(val)
val = self._strip_braces(val)
val = self._string_subst(val)
return val
def _add_key(self, key):
""" Add a key and homogeneize alternative forms.
:param key: a key
:type key: string
:returns: string -- value
"""
key = key.strip().strip('@').lower()
if self.homogenise_fields:
if key in list(self.alt_dict.keys()):
key = self.alt_dict[key]
if not isinstance(key, ustr):
return ustr(key, 'utf-8')
else:
return key

View File

@ -1,136 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Francois Boulogne
# License:
import logging
from .bibdatabase import BibDatabase
logger = logging.getLogger(__name__)
__all__ = ['BibTexWriter']
def to_bibtex(parsed):
"""
Convenience function for backwards compatibility.
"""
return BibTexWriter().write(parsed)
class BibTexWriter(object):
"""
Writer to convert a :class:`BibDatabase` object to a string or file formatted as a BibTeX file.
Example::
from bibtexparser.bwriter import BibTexWriter
bib_database = ...
writer = BibTexWriter()
writer.contents = ['comments', 'entries']
writer.indent = ' '
writer.order_entries_by = ('ENTRYTYPE', 'author', 'year')
bibtex_str = bibtexparser.dumps(bib_database, writer)
"""
_valid_contents = ['entries', 'comments', 'preambles', 'strings']
def __init__(self):
#: List of BibTeX elements to write, valid values are `entries`, `comments`, `preambles`, `strings`.
self.contents = ['comments', 'preambles', 'strings', 'entries']
#: Character(s) for indenting BibTeX field-value pairs. Default: single space.
self.indent = ' '
#: Align values. Determines the maximal number of characters used in any fieldname and aligns all values
# according to that by filling up with single spaces. Default: False
self.align_values = False
#: Characters(s) for separating BibTeX entries. Default: new line.
self.entry_separator = '\n'
#: Tuple of fields for ordering BibTeX entries. Set to `None` to disable sorting. Default: BibTeX key `('ID', )`.
self.order_entries_by = ('ID', )
#: Tuple of fields for display order in a single BibTeX entry. Fields not listed here will be displayed
#: alphabetically at the end. Set to '[]' for alphabetical order. Default: '[]'
self.display_order = []
#: BibTeX syntax allows comma first syntax
#: (common in functional languages), use this to enable
#: comma first syntax as the bwritter output
self.comma_first = False
#: internal variable used if self.align_values = True
self._max_field_width = 0
def write(self, bib_database):
"""
Converts a bibliographic database to a BibTeX-formatted string.
:param bib_database: bibliographic database to be converted to a BibTeX string
:type bib_database: BibDatabase
:return: BibTeX-formatted string
:rtype: str or unicode
"""
bibtex = ''
for content in self.contents:
try:
# Add each element set (entries, comments)
bibtex += getattr(self, '_' + content + '_to_bibtex')(bib_database)
except AttributeError:
logger.warning("BibTeX item '{}' does not exist and will not be written. Valid items are {}."
.format(content, self._valid_contents))
return bibtex
def _entries_to_bibtex(self, bib_database):
bibtex = ''
if self.order_entries_by:
# TODO: allow sort field does not exist for entry
entries = sorted(bib_database.entries, key=lambda x: BibDatabase.entry_sort_key(x, self.order_entries_by))
else:
entries = bib_database.entries
if self.align_values:
# determine maximum field width to be used
widths = [max(map(len, entry.keys())) for entry in entries]
self._max_field_width = max(widths)
for entry in entries:
bibtex += self._entry_to_bibtex(entry)
return bibtex
def _entry_to_bibtex(self, entry):
bibtex = ''
# Write BibTeX key
bibtex += '@' + entry['ENTRYTYPE'] + '{' + entry['ID']
# create display_order of fields for this entry
# first those keys which are both in self.display_order and in entry.keys
display_order = [i for i in self.display_order if i in entry]
# then all the other fields sorted alphabetically
more_fields = [i for i in sorted(entry) if i not in self.display_order]
display_order += [i for i in sorted(entry) if i not in self.display_order]
# Write field = value lines
for field in [i for i in display_order if i not in ['ENTRYTYPE', 'ID']]:
try:
if self.comma_first:
bibtex += "\n" + self.indent + ", " + "{0:<{1}}".format(field, self._max_field_width) + " = {" + entry[field] + "}"
else:
bibtex += ",\n" + self.indent + "{0:<{1}}".format(field, self._max_field_width) + " = {" + entry[field] + "}"
except TypeError:
raise TypeError(u"The field %s in entry %s must be a string"
% (field, entry['ID']))
bibtex += "\n}\n" + self.entry_separator
return bibtex
def _comments_to_bibtex(self, bib_database):
return ''.join(['@comment{{{0}}}\n{1}'.format(comment, self.entry_separator)
for comment in bib_database.comments])
def _preambles_to_bibtex(self, bib_database):
return ''.join(['@preamble{{{0}}}\n{1}'.format(preamble, self.entry_separator)
for preamble in bib_database.preambles])
def _strings_to_bibtex(self, bib_database):
return ''.join(['@string{{{0} = "{1}"}}\n{2}'.format(name, value, self.entry_separator)
for name, value in bib_database.strings.items()])

View File

@ -1,255 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A set of functions useful for customizing bibtex fields.
You can find inspiration from these functions to design yours.
Each of them takes a record and return the modified record.
"""
import itertools
import re
import logging
from .latexenc import unicode_to_latex, unicode_to_crappy_latex1, unicode_to_crappy_latex2, string_to_latex, protect_uppercase
logger = logging.getLogger(__name__)
__all__ = ['getnames', 'author', 'editor', 'journal', 'keyword', 'link',
'page_double_hyphen', 'doi', 'type', 'convert_to_unicode',
'homogeneize_latex_encoding']
def getnames(names):
"""Make people names as surname, firstnames
or surname, initials. Should eventually combine up the two.
:param names: a list of names
:type names: list
:returns: list -- Correctly formated names
"""
tidynames = []
for namestring in names:
namestring = namestring.strip()
if len(namestring) < 1:
continue
if ',' in namestring:
namesplit = namestring.split(',', 1)
last = namesplit[0].strip()
firsts = [i.strip() for i in namesplit[1].split()]
else:
namesplit = namestring.split()
last = namesplit.pop()
firsts = [i.replace('.', '. ').strip() for i in namesplit]
if last in ['jnr', 'jr', 'junior']:
last = firsts.pop()
for item in firsts:
if item in ['ben', 'van', 'der', 'de', 'la', 'le']:
last = firsts.pop() + ' ' + last
tidynames.append(last + ", " + ' '.join(firsts))
return tidynames
def author(record):
"""
Split author field into a list of "Name, Surname".
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "author" in record:
if record["author"]:
record["author"] = getnames([i.strip() for i in record["author"].replace('\n', ' ').split(" and ")])
else:
del record["author"]
return record
def editor(record):
"""
Turn the editor field into a dict composed of the original editor name
and a editor id (without coma or blank).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "editor" in record:
if record["editor"]:
record["editor"] = getnames([i.strip() for i in record["editor"].replace('\n', ' ').split(" and ")])
# convert editor to object
record["editor"] = [{"name": i, "ID": i.replace(',', '').replace(' ', '').replace('.', '')} for i in record["editor"]]
else:
del record["editor"]
return record
def page_double_hyphen(record):
"""
Separate pages by a double hyphen (--).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "pages" in record:
# hyphen, non-breaking hyphen, en dash, em dash, hyphen-minus, minus sign
separators = [u'', u'', u'', u'', u'-', u'']
for separator in separators:
if separator in record["pages"]:
p = [i.strip().strip(separator) for i in record["pages"].split(separator)]
record["pages"] = p[0] + '--' + p[-1]
return record
def type(record):
"""
Put the type into lower case.
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "type" in record:
record["type"] = record["type"].lower()
return record
def journal(record):
"""
Turn the journal field into a dict composed of the original journal name
and a journal id (without coma or blank).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "journal" in record:
# switch journal to object
if record["journal"]:
record["journal"] = {"name": record["journal"], "ID": record["journal"].replace(',', '').replace(' ', '').replace('.', '')}
return record
def keyword(record, sep=',|;'):
"""
Split keyword field into a list.
:param record: the record.
:type record: dict
:param sep: pattern used for the splitting regexp.
:type record: string, optional
:returns: dict -- the modified record.
"""
if "keyword" in record:
record["keyword"] = [i.strip() for i in re.split(sep, record["keyword"].replace('\n', ''))]
return record
def link(record):
"""
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "link" in record:
links = [i.strip().replace(" ", " ") for i in record["link"].split('\n')]
record['link'] = []
for link in links:
parts = link.split(" ")
linkobj = {"url": parts[0]}
if len(parts) > 1:
linkobj["anchor"] = parts[1]
if len(parts) > 2:
linkobj["format"] = parts[2]
if len(linkobj["url"]) > 0:
record["link"].append(linkobj)
return record
def doi(record):
"""
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if 'doi' in record:
if 'link' not in record:
record['link'] = []
nodoi = True
for item in record['link']:
if 'doi' in item:
nodoi = False
if nodoi:
link = record['doi']
if link.startswith('10'):
link = 'http://dx.doi.org/' + link
record['link'].append({"url": link, "anchor": "doi"})
return record
def convert_to_unicode(record):
"""
Convert accent from latex to unicode style.
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
for val in record:
if '\\' in record[val] or '{' in record[val]:
for k, v in itertools.chain(unicode_to_crappy_latex1, unicode_to_latex):
if v in record[val]:
record[val] = record[val].replace(v, k)
# If there is still very crappy items
if '\\' in record[val]:
for k, v in unicode_to_crappy_latex2:
if v in record[val]:
parts = record[val].split(str(v))
for key, record[val] in enumerate(parts):
if key+1 < len(parts) and len(parts[key+1]) > 0:
# Change order to display accents
parts[key] = parts[key] + parts[key+1][0]
parts[key+1] = parts[key+1][1:]
record[val] = k.join(parts)
return record
def homogeneize_latex_encoding(record):
"""
Homogeneize the latex enconding style for bibtex
This function is experimental.
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
# First, we convert everything to unicode
record = convert_to_unicode(record)
# And then, we fall back
for val in record:
if val not in ('ID',):
logger.debug('Apply string_to_latex to: %s', val)
record[val] = string_to_latex(record[val])
if val == 'title':
logger.debug('Protect uppercase in title')
logger.debug('Before: %s', record[val])
record[val] = protect_uppercase(record[val])
logger.debug('After: %s', record[val])
return record

File diff suppressed because it is too large Load Diff

View File

@ -1,79 +0,0 @@
#!/usr/bin/env python
# encoding: utf-8
"""
StringMatcher.py
ported from python-Levenshtein
[https://github.com/miohtama/python-Levenshtein]
"""
from Levenshtein import *
from warnings import warn
class StringMatcher:
"""A SequenceMatcher-like class built on the top of Levenshtein"""
def _reset_cache(self):
self._ratio = self._distance = None
self._opcodes = self._editops = self._matching_blocks = None
def __init__(self, isjunk=None, seq1='', seq2=''):
if isjunk:
warn("isjunk not NOT implemented, it will be ignored")
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seqs(self, seq1, seq2):
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seq1(self, seq1):
self._str1 = seq1
self._reset_cache()
def set_seq2(self, seq2):
self._str2 = seq2
self._reset_cache()
def get_opcodes(self):
if not self._opcodes:
if self._editops:
self._opcodes = opcodes(self._editops, self._str1, self._str2)
else:
self._opcodes = opcodes(self._str1, self._str2)
return self._opcodes
def get_editops(self):
if not self._editops:
if self._opcodes:
self._editops = editops(self._opcodes, self._str1, self._str2)
else:
self._editops = editops(self._str1, self._str2)
return self._editops
def get_matching_blocks(self):
if not self._matching_blocks:
self._matching_blocks = matching_blocks(self.get_opcodes(),
self._str1, self._str2)
return self._matching_blocks
def ratio(self):
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def quick_ratio(self):
# This is usually quick enough :o)
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def real_quick_ratio(self):
len1, len2 = len(self._str1), len(self._str2)
return 2.0 * min(len1, len2) / (len1 + len2)
def distance(self):
if not self._distance:
self._distance = distance(self._str1, self._str2)
return self._distance

View File

@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
__version__ = '0.8.1'

View File

@ -1,263 +0,0 @@
#!/usr/bin/env python
# encoding: utf-8
"""
fuzz.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in 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:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
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 AUTHORS 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 IN THE SOFTWARE.
"""
from __future__ import unicode_literals
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')
from difflib import SequenceMatcher
from . import utils
###########################
# Basic Scoring Functions #
###########################
@utils.check_for_none
@utils.check_empty_string
def ratio(s1, s2):
s1, s2 = utils.make_type_consistent(s1, s2)
m = SequenceMatcher(None, s1, s2)
return utils.intr(100 * m.ratio())
@utils.check_for_none
@utils.check_empty_string
def partial_ratio(s1, s2):
""""Return the ratio of the most similar substring
as a number between 0 and 100."""
s1, s2 = utils.make_type_consistent(s1, s2)
if len(s1) <= len(s2):
shorter = s1
longer = s2
else:
shorter = s2
longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blocks()
# each block represents a sequence of matching characters in a string
# of the form (idx_1, idx_2, len)
# the best partial match will block align with at least one of those blocks
# e.g. shorter = "abcd", longer = XXXbcdeEEE
# block = (1,3,3)
# best score === ratio("abcd", "Xbcd")
scores = []
for block in blocks:
long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0
long_end = long_start + len(shorter)
long_substr = longer[long_start:long_end]
m2 = SequenceMatcher(None, shorter, long_substr)
r = m2.ratio()
if r > .995:
return 100
else:
scores.append(r)
return utils.intr(100 * max(scores))
##############################
# Advanced Scoring Functions #
##############################
def _process_and_sort(s, force_ascii):
"""Return a cleaned string with token sorted."""
# pull tokens
tokens = utils.full_process(s, force_ascii=force_ascii).split()
# sort tokens and join
sorted_string = u" ".join(sorted(tokens))
return sorted_string.strip()
# Sorted Token
# find all alphanumeric tokens in the string
# sort those tokens and take ratio of resulting joined strings
# controls for unordered string elements
@utils.check_for_none
def _token_sort(s1, s2, partial=True, force_ascii=True):
sorted1 = _process_and_sort(s1, force_ascii)
sorted2 = _process_and_sort(s2, force_ascii)
if partial:
return partial_ratio(sorted1, sorted2)
else:
return ratio(sorted1, sorted2)
def token_sort_ratio(s1, s2, force_ascii=True):
"""Return a measure of the sequences' similarity between 0 and 100
but sorting the token before comparing.
"""
return _token_sort(s1, s2, partial=False, force_ascii=force_ascii)
def partial_token_sort_ratio(s1, s2, force_ascii=True):
"""Return the ratio of the most similar substring as a number between
0 and 100 but sorting the token before comparing.
"""
return _token_sort(s1, s2, partial=True, force_ascii=force_ascii)
@utils.check_for_none
def _token_set(s1, s2, partial=True, force_ascii=True):
"""Find all alphanumeric tokens in each string...
- treat them as a set
- construct two strings of the form:
<sorted_intersection><sorted_remainder>
- take ratios of those two strings
- controls for unordered partial matches"""
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
# pull tokens
tokens1 = set(utils.full_process(p1).split())
tokens2 = set(utils.full_process(p2).split())
intersection = tokens1.intersection(tokens2)
diff1to2 = tokens1.difference(tokens2)
diff2to1 = tokens2.difference(tokens1)
sorted_sect = " ".join(sorted(intersection))
sorted_1to2 = " ".join(sorted(diff1to2))
sorted_2to1 = " ".join(sorted(diff2to1))
combined_1to2 = sorted_sect + " " + sorted_1to2
combined_2to1 = sorted_sect + " " + sorted_2to1
# strip
sorted_sect = sorted_sect.strip()
combined_1to2 = combined_1to2.strip()
combined_2to1 = combined_2to1.strip()
if partial:
ratio_func = partial_ratio
else:
ratio_func = ratio
pairwise = [
ratio_func(sorted_sect, combined_1to2),
ratio_func(sorted_sect, combined_2to1),
ratio_func(combined_1to2, combined_2to1)
]
return max(pairwise)
def token_set_ratio(s1, s2, force_ascii=True):
return _token_set(s1, s2, partial=False, force_ascii=force_ascii)
def partial_token_set_ratio(s1, s2, force_ascii=True):
return _token_set(s1, s2, partial=True, force_ascii=force_ascii)
###################
# Combination API #
###################
# q is for quick
def QRatio(s1, s2, force_ascii=True):
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
return ratio(p1, p2)
def UQRatio(s1, s2):
return QRatio(s1, s2, force_ascii=False)
# w is for weighted
def WRatio(s1, s2, force_ascii=True):
"""Return a measure of the sequences' similarity between 0 and 100,
using different algorithms.
"""
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
# should we look at partials?
try_partial = True
unbase_scale = .95
partial_scale = .90
base = ratio(p1, p2)
len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2))
# if strings are similar length, don't use partials
if len_ratio < 1.5:
try_partial = False
# if one string is much much shorter than the other
if len_ratio > 8:
partial_scale = .6
if try_partial:
partial = partial_ratio(p1, p2) * partial_scale
ptsor = partial_token_sort_ratio(p1, p2, force_ascii=force_ascii) \
* unbase_scale * partial_scale
ptser = partial_token_set_ratio(p1, p2, force_ascii=force_ascii) \
* unbase_scale * partial_scale
return utils.intr(max(base, partial, ptsor, ptser))
else:
tsor = token_sort_ratio(p1, p2, force_ascii=force_ascii) * unbase_scale
tser = token_set_ratio(p1, p2, force_ascii=force_ascii) * unbase_scale
return utils.intr(max(base, tsor, tser))
def UWRatio(s1, s2):
"""Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode.
"""
return WRatio(s1, s2, force_ascii=False)

View File

@ -1,227 +0,0 @@
#!/usr/bin/env python
# encoding: utf-8
"""
process.py
Copyright (c) 2011 Adam Cohen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in 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:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
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 AUTHORS 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 IN THE SOFTWARE.
"""
import itertools
from . import fuzz
from . import utils
def extract(query, choices, processor=None, scorer=None, limit=5):
"""Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
list of tuples containing the match and it's score. If a dictionary
is used, also returns the key for each match.
Arguments:
query: An object representing the thing we want to find.
choices: An iterable or dictionary-like object containing choices
to be matched against the query. Dictionary arguments of
{key: value} pairs will attempt to match the query against
each value.
processor: Optional function of the form f(a) -> b, where a is an
individual choice and b is the choice to be used in matching.
This can be used to match against, say, the first element of
a list:
lambda x: x[0]
Defaults to fuzzywuzzy.utils.full_process().
scorer: Optional function for scoring matches between the query and
an individual processed choice. This should be a function
of the form f(query, choice) -> int.
By default, fuzz.WRatio() is used and expects both query and
choice to be strings.
limit: Optional maximum for the number of elements returned. Defaults
to 5.
Returns:
List of tuples containing the match and its score.
If a list is used for choices, then the result will be 2-tuples.
If a dictionary is used, then the result will be 3-tuples containing
he key for each match.
For example, searching for 'bird' in the dictionary
{'bard': 'train', 'dog': 'man'}
may return
[('train', 22, 'bard'), ('man', 0, 'dog')]
"""
if choices is None:
return []
# Catch generators without lengths
try:
if len(choices) == 0:
return []
except TypeError:
pass
# default, turn whatever the choice is into a workable string
if not processor:
processor = utils.full_process
# default: wratio
if not scorer:
scorer = fuzz.WRatio
sl = []
try:
# See if choices is a dictionary-like object.
for key, choice in choices.items():
processed = processor(choice)
score = scorer(query, processed)
sl.append((choice, score, key))
except AttributeError:
# It's a list; just iterate over it.
for choice in choices:
processed = processor(choice)
score = scorer(query, processed)
sl.append((choice, score))
sl.sort(key=lambda i: i[1], reverse=True)
return sl[:limit]
def extractBests(query, choices, processor=None, scorer=None, score_cutoff=0, limit=5):
"""Get a list of the best matches to a collection of choices.
Convenience function for getting the choices with best scores.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
extract().
processor: Optional function for transforming choices before matching.
See extract().
scorer: Scoring function for extract().
score_cutoff: Optional argument for score threshold. No matches with
a score less than this number will be returned. Defaults to 0.
limit: Optional maximum for the number of elements returned. Defaults
to 5.
Returns: A a list of (match, score) tuples.
"""
best_list = extract(query, choices, processor, scorer, limit)
return list(itertools.takewhile(lambda x: x[1] >= score_cutoff, best_list))
def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0):
"""Find the single best match above a score in a list of choices.
This is a convenience method which returns the single best choice.
See extract() for the full arguments list.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
extract().
processor: Optional function for transforming choices before matching.
See extract().
scorer: Scoring function for extract().
score_cutoff: Optional argument for score threshold. If the best
match is found, but it is not greater than this number, then
return None anyway ("not a good enough match"). Defaults to 0.
Returns:
A tuple containing a single match and its score, if a match
was found that was above score_cutoff. Otherwise, returns None.
"""
best_list = extract(query, choices, processor, scorer, limit=1)
if len(best_list) > 0 and best_list[0][1] >= score_cutoff:
return best_list[0]
return None
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio):
"""This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify
and remove duplicates. Specifically, it uses the process.extract to identify duplicates that
score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list
since we assume this item contains the most entity information and returns that. It breaks string
length ties on an alphabetical sort.
Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the
returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less
sensitive.
Args:
contains_dupes: A list of strings that we would like to dedupe.
threshold: the numerical value (0,100) point at which we expect to find duplicates.
Defaults to 70 out of 100
scorer: Optional function for scoring matches between the query and
an individual processed choice. This should be a function
of the form f(query, choice) -> int.
By default, fuzz.token_set_ratio() is used and expects both query and
choice to be strings.
Returns:
A deduplicated list. For example:
In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins']
In: fuzzy_dedupe(contains_dupes)
Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf']
"""
extractor = []
# iterate over items in *contains_dupes*
for item in contains_dupes:
# return all duplicate matches found
matches = extract(item, contains_dupes, limit=None, scorer=scorer)
# filter matches based on the threshold
filtered = [x for x in matches if x[1] > threshold]
# if there is only 1 item in *filtered*, no duplicates were found so append to *extracted*
if len(filtered) == 1:
extractor.append(filtered[0][0])
else:
# alpha sort
filtered = sorted(filtered, key=lambda x: x[0])
# length sort
filter_sort = sorted(filtered, key=lambda x: len(x[0]), reverse=True)
# take first item as our 'canonical example'
extractor.append(filter_sort[0][0])
# uniquify *extractor* list
keys = {}
for e in extractor:
keys[e] = 1
extractor = keys.keys()
# check that extractor differs from contain_dupes (e.g. duplicates were found)
# if not, then return the original list
if len(extractor) == len(contains_dupes):
return contains_dupes
else:
return extractor

View File

@ -1,34 +0,0 @@
from __future__ import unicode_literals
import re
import string
import sys
PY3 = sys.version_info[0] == 3
class StringProcessor(object):
"""
This class defines method to process strings in the most
efficient way. Ideally all the methods below use unicode strings
for both input and output.
"""
regex = re.compile(r"(?ui)\W")
@classmethod
def replace_non_letters_non_numbers_with_whitespace(cls, a_string):
"""
This function replaces any sequence of non letters and non
numbers with a single white space.
"""
return cls.regex.sub(u" ", a_string)
if PY3:
strip = staticmethod(str.strip)
to_lower_case = staticmethod(str.lower)
to_upper_case = staticmethod(str.upper)
else:
strip = staticmethod(string.strip)
to_lower_case = staticmethod(string.lower)
to_upper_case = staticmethod(string.upper)

View File

@ -1,94 +0,0 @@
from __future__ import unicode_literals
import sys
import functools
from fuzzywuzzy.string_processing import StringProcessor
PY3 = sys.version_info[0] == 3
def validate_string(s):
try:
return len(s) > 0
except TypeError:
return False
def check_for_none(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
if args[0] is None:
raise TypeError("s1 is None")
if args[1] is None:
raise TypeError("s2 is None")
return func(*args, **kwargs)
return decorator
def check_empty_string(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
if len(args[0]) == 0 or len(args[1]) == 0:
return 0
return func(*args, **kwargs)
return decorator
bad_chars = str("").join([chr(i) for i in range(128, 256)]) # ascii dammit!
if PY3:
translation_table = dict((ord(c), None) for c in bad_chars)
unicode = str
def asciionly(s):
if PY3:
return s.translate(translation_table)
else:
return s.translate(None, bad_chars)
def asciidammit(s):
if type(s) is str:
return asciionly(s)
elif type(s) is unicode:
return asciionly(s.encode('ascii', 'ignore'))
else:
return asciidammit(unicode(s))
def make_type_consistent(s1, s2):
"""If both objects aren't either both string or unicode instances force them to unicode"""
if isinstance(s1, str) and isinstance(s2, str):
return s1, s2
elif isinstance(s1, unicode) and isinstance(s2, unicode):
return s1, s2
else:
return unicode(s1), unicode(s2)
def full_process(s, force_ascii=False):
"""Process string by
-- removing all but letters and numbers
-- trim whitespace
-- force to lower case
if force_ascii == True, force convert to ascii"""
if s is None:
return ""
if force_ascii:
s = asciidammit(s)
# Keep only Letters and Numbers (see Unicode docs).
string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s)
# Force into lowercase.
string_out = StringProcessor.to_lower_case(string_out)
# Remove leading and trailing whitespaces.
string_out = StringProcessor.strip(string_out)
return string_out
def intr(n):
'''Returns a correctly rounded integer'''
return int(round(n))

View File

@ -1,276 +0,0 @@
#
# Copyright (C) 2015 Dustin Spicuzza <dustin@virtualroadside.com>
#
# 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 St, Fifth Floor, Boston, MA 02110-1301
# USA
from os.path import abspath, join
import inspect
import warnings
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
__all__ = ['GtkTemplate']
class GtkTemplateWarning(UserWarning):
pass
def _connect_func(builder, obj, signal_name, handler_name,
connect_object, flags, cls):
'''Handles GtkBuilder signal connect events'''
if connect_object is None:
extra = ()
else:
extra = (connect_object,)
# The handler name refers to an attribute on the template instance,
# so ask GtkBuilder for the template instance
template_inst = builder.get_object(cls.__gtype_name__)
if template_inst is None: # This should never happen
errmsg = "Internal error: cannot find template instance! obj: %s; " \
"signal: %s; handler: %s; connect_obj: %s; class: %s" % \
(obj, signal_name, handler_name, connect_object, cls)
warnings.warn(errmsg, GtkTemplateWarning)
return
handler = getattr(template_inst, handler_name)
if flags == GObject.ConnectFlags.AFTER:
obj.connect_after(signal_name, handler, *extra)
else:
obj.connect(signal_name, handler, *extra)
template_inst.__connected_template_signals__.add(handler_name)
def _register_template(cls, template_bytes):
'''Registers the template for the widget and hooks init_template'''
# This implementation won't work if there are nested templates, but
# we can't do that anyways due to PyGObject limitations so it's ok
if not hasattr(cls, 'set_template'):
raise TypeError("Requires PyGObject 3.13.2 or greater")
cls.set_template(template_bytes)
bound_methods = set()
bound_widgets = set()
# Walk the class, find marked callbacks and child attributes
for name in dir(cls):
o = getattr(cls, name, None)
if inspect.ismethod(o):
if hasattr(o, '_gtk_callback'):
bound_methods.add(name)
# Don't need to call this, as connect_func always gets called
#cls.bind_template_callback_full(name, o)
elif isinstance(o, _Child):
cls.bind_template_child_full(name, True, 0)
bound_widgets.add(name)
# Have to setup a special connect function to connect at template init
# because the methods are not bound yet
cls.set_connect_func(_connect_func, cls)
cls.__gtemplate_methods__ = bound_methods
cls.__gtemplate_widgets__ = bound_widgets
base_init_template = cls.init_template
cls.init_template = lambda s: _init_template(s, cls, base_init_template)
def _init_template(self, cls, base_init_template):
'''This would be better as an override for Gtk.Widget'''
# TODO: could disallow using a metaclass.. but this is good enough
# .. if you disagree, feel free to fix it and issue a PR :)
if self.__class__ is not cls:
raise TypeError("Inheritance from classes with @GtkTemplate decorators "
"is not allowed at this time")
connected_signals = set()
self.__connected_template_signals__ = connected_signals
base_init_template(self)
print('initing template')
print(self.__gtemplate_widgets__)
for name in self.__gtemplate_widgets__:
widget = self.get_template_child(cls, name)
self.__dict__[name] = widget
print(name)
if widget is None:
# Bug: if you bind a template child, and one of them was
# not present, then the whole template is broken (and
# it's not currently possible for us to know which
# one is broken either -- but the stderr should show
# something useful with a Gtk-CRITICAL message)
raise AttributeError("A missing child widget was set using "
"GtkTemplate.Child and the entire "
"template is now broken (widgets: %s)" %
', '.join(self.__gtemplate_widgets__))
for name in self.__gtemplate_methods__.difference(connected_signals):
errmsg = ("Signal '%s' was declared with @GtkTemplate.Callback " +
"but was not present in template") % name
warnings.warn(errmsg, GtkTemplateWarning)
# TODO: Make it easier for IDE to introspect this
class _Child(object):
'''
Assign this to an attribute in your class definition and it will
be replaced with a widget defined in the UI file when init_template
is called
'''
__slots__ = []
@staticmethod
def widgets(count):
'''
Allows declaring multiple widgets with less typing::
button \
label1 \
label2 = GtkTemplate.Child.widgets(3)
'''
return [_Child() for _ in range(count)]
class _GtkTemplate(object):
'''
Use this class decorator to signify that a class is a composite
widget which will receive widgets and connect to signals as
defined in a UI template. You must call init_template to
cause the widgets/signals to be initialized from the template::
@GtkTemplate(ui='foo.ui')
class Foo(Gtk.Box):
def __init__(self):
super(Foo, self).__init__()
self.init_template()
The 'ui' parameter can either be a file path or a GResource resource
path::
@GtkTemplate(ui='/org/example/foo.ui')
class Foo(Gtk.Box):
pass
To connect a signal to a method on your instance, do::
@GtkTemplate.Callback
def on_thing_happened(self, widget):
pass
To create a child attribute that is retrieved from your template,
add this to your class definition::
@GtkTemplate(ui='foo.ui')
class Foo(Gtk.Box):
widget = GtkTemplate.Child()
Note: This is implemented as a class decorator, but if it were
included with PyGI I suspect it might be better to do this
in the GObject metaclass (or similar) so that init_template
can be called automatically instead of forcing the user to do it.
.. note:: Due to limitations in PyGObject, you may not inherit from
python objects that use the GtkTemplate decorator.
'''
__ui_path__ = None
@staticmethod
def Callback(f):
'''
Decorator that designates a method to be attached to a signal from
the template
'''
f._gtk_callback = True
return f
Child = _Child
@staticmethod
def set_ui_path(*path):
'''
If using file paths instead of resources, call this *before*
loading anything that uses GtkTemplate, or it will fail to load
your template file
:param path: one or more path elements, will be joined together
to create the final path
TODO: Alternatively, could wait until first class instantiation
before registering templates? Would need a metaclass...
'''
_GtkTemplate.__ui_path__ = abspath(join(*path))
def __init__(self, ui):
self.ui = ui
def __call__(self, cls):
if not issubclass(cls, Gtk.Widget):
raise TypeError("Can only use @GtkTemplate on Widgets")
# Nested templates don't work
if hasattr(cls, '__gtemplate_methods__'):
raise TypeError("Cannot nest template classes")
# Load the template either from a resource path or a file
# - Prefer the resource path first
try:
template_bytes = Gio.resources_lookup_data(self.ui, Gio.ResourceLookupFlags.NONE)
except GLib.GError:
ui = self.ui
if isinstance(ui, (list, tuple)):
ui = join(ui)
if _GtkTemplate.__ui_path__ is not None:
ui = join(_GtkTemplate.__ui_path__, ui)
with open(ui, 'rb') as fp:
template_bytes = GLib.Bytes.new(fp.read())
_register_template(cls, template_bytes)
return cls
# Future shim support if this makes it into PyGI?
#if hasattr(Gtk, 'GtkTemplate'):
# GtkTemplate = lambda c: c
#else:
GtkTemplate = _GtkTemplate

View File

@ -1,110 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
<requires lib="gtk+" version="3.12"/>
<object class="GtkMenu" id="menu1">
<property name="visible">True</property>
<property name="can_focus">False</property>
</object>
<object class="GtkTextBuffer" id="textbuffer1">
<signal name="changed" handler="recompile_image" swapped="no"/>
</object>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="delete-event" handler="onDeleteWindow" swapped="no"/>
<child>
<object class="GtkGrid" id="grid1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">5</property>
<property name="margin_right">5</property>
<property name="margin_top">5</property>
<property name="margin_bottom">5</property>
<child>
<object class="GtkImage" id="image1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<property name="stock">gtk-justify-center</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
<property name="width">3</property>
</packing>
</child>
<child>
<object class="GtkTextView" id="textview1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="buffer">textbuffer1</property>
<signal name="key-press-event" handler="textview_after_key_pressed" after="yes" swapped="no"/>
<signal name="key-press-event" handler="textview_key_pressed" swapped="no"/>
<signal name="key-release-event" handler="textview_after_key_pressed" swapped="no"/>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">2</property>
<property name="width">3</property>
</packing>
</child>
<child>
<object class="GtkBox" id="box1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkSearchEntry" id="searchentry1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="margin_bottom">5</property>
<property name="primary_icon_name">edit-find-symbolic</property>
<property name="primary_icon_activatable">False</property>
<property name="primary_icon_sensitive">False</property>
<signal name="search-changed" handler="searchentry_changed" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkScrolledWindow" id="scrolledwindow1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="shadow_type">in</property>
<child>
<object class="GtkViewport" id="viewport1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkListBox" id="listbox">
<property name="name">listbox</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="vexpand">True</property>
<property name="activate_on_single_click">False</property>
</object>
</child>
</object>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
<property name="width">3</property>
</packing>
</child>
</object>
</child>
</object>
</interface>

View File

@ -1,10 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='4.64012pt' version='1.1' viewBox='-144 -143.973 19.8509 4.64012' width='19.8509pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M7.23288 -3.25778C7.65131 -2.89913 8.1594 -2.6401 8.48817 -2.49066C8.12951 -2.33126 7.64134 -2.07223 7.23288 -1.72354H0.9066C0.737235 -1.72354 0.547945 -1.72354 0.547945 -1.52428S0.727273 -1.32503 0.896638 -1.32503H6.78456C6.30635 -0.86675 5.78829 0.00996264 5.78829 0.139477C5.78829 0.249066 5.91781 0.249066 5.97758 0.249066C6.05729 0.249066 6.12702 0.249066 6.16687 0.169365C6.37609 -0.209215 6.65504 -0.737235 7.30262 -1.31507C7.99004 -1.92279 8.65753 -2.19178 9.17559 -2.34122C9.34496 -2.401 9.35492 -2.41096 9.37484 -2.43088C9.39477 -2.44085 9.39477 -2.47073 9.39477 -2.49066S9.39477 -2.53051 9.38481 -2.55044L9.35492 -2.57036C9.33499 -2.58032 9.32503 -2.59029 9.13574 -2.65006C7.79078 -3.04857 6.79452 -3.95517 6.23661 -5.02117C6.12702 -5.22042 6.11706 -5.23039 5.97758 -5.23039C5.91781 -5.23039 5.78829 -5.23039 5.78829 -5.1208C5.78829 -4.99128 6.29639 -4.12453 6.78456 -3.65629H0.896638C0.727273 -3.65629 0.547945 -3.65629 0.547945 -3.45704S0.737235 -3.25778 0.9066 -3.25778H7.23288Z' id='g0-41'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g0-41' y='-68.345'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1,12 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='13.2135pt' version='1.1' viewBox='-144 -143.978 19.9559 13.2135' width='19.9559pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M3.32752 -3.00872C3.3873 -3.26775 3.61644 -4.18431 4.31382 -4.18431C4.36364 -4.18431 4.60274 -4.18431 4.81196 -4.05479C4.533 -4.00498 4.33375 -3.75592 4.33375 -3.51681C4.33375 -3.35741 4.44334 -3.16812 4.71233 -3.16812C4.93151 -3.16812 5.25031 -3.34745 5.25031 -3.74595C5.25031 -4.26401 4.66252 -4.40349 4.32379 -4.40349C3.74595 -4.40349 3.39726 -3.87547 3.27771 -3.64633C3.02864 -4.30386 2.49066 -4.40349 2.20174 -4.40349C1.16563 -4.40349 0.597758 -3.11831 0.597758 -2.86924C0.597758 -2.76961 0.697385 -2.76961 0.71731 -2.76961C0.797011 -2.76961 0.826899 -2.78954 0.846824 -2.8792C1.18555 -3.93524 1.84309 -4.18431 2.18182 -4.18431C2.37111 -4.18431 2.7198 -4.09465 2.7198 -3.51681C2.7198 -3.20797 2.55044 -2.54047 2.18182 -1.1457C2.02242 -0.52802 1.67372 -0.109589 1.23537 -0.109589C1.17559 -0.109589 0.946451 -0.109589 0.737235 -0.239103C0.986301 -0.288917 1.20548 -0.498132 1.20548 -0.777086C1.20548 -1.04608 0.986301 -1.12578 0.836862 -1.12578C0.537983 -1.12578 0.288917 -0.86675 0.288917 -0.547945C0.288917 -0.0896638 0.787049 0.109589 1.2254 0.109589C1.88294 0.109589 2.24159 -0.587796 2.27148 -0.647572C2.39103 -0.278954 2.74969 0.109589 3.34745 0.109589C4.3736 0.109589 4.94147 -1.17559 4.94147 -1.42466C4.94147 -1.52428 4.85181 -1.52428 4.82192 -1.52428C4.73225 -1.52428 4.71233 -1.48443 4.6924 -1.41469C4.36364 -0.348692 3.68618 -0.109589 3.36737 -0.109589C2.97883 -0.109589 2.81943 -0.428394 2.81943 -0.767123C2.81943 -0.986301 2.8792 -1.20548 2.98879 -1.64384L3.32752 -3.00872Z' id='g0-120'/>
<path d='M2.94296 -2.66401C2.79651 -2.89415 2.5594 -3.07547 2.22466 -3.07547C1.332 -3.07547 0.425405 -2.09215 0.425405 -1.08792C0.425405 -0.411457 0.878705 0.0697385 1.47846 0.0697385C1.85504 0.0697385 2.18979 -0.146451 2.46874 -0.418431C2.60125 0 3.00573 0.0697385 3.18705 0.0697385C3.43811 0.0697385 3.61245 -0.0836862 3.73798 -0.299875C3.89141 -0.571856 3.98207 -0.969365 3.98207 -0.99726C3.98207 -1.08792 3.89141 -1.08792 3.87049 -1.08792C3.77285 -1.08792 3.76588 -1.06002 3.71706 -0.871731C3.63337 -0.536986 3.50087 -0.125529 3.20797 -0.125529C3.02665 -0.125529 2.97783 -0.278954 2.97783 -0.467248C2.97783 -0.585803 3.03362 -0.836862 3.08244 -1.01818C3.13126 -1.20648 3.201 -1.4924 3.23587 -1.64583L3.37534 -2.17584C3.41719 -2.35716 3.50087 -2.68493 3.50087 -2.7198C3.50087 -2.87323 3.37534 -2.94296 3.26376 -2.94296C3.14521 -2.94296 2.98481 -2.85928 2.94296 -2.66401ZM2.49664 -0.871731C2.44782 -0.676463 2.2944 -0.536986 2.14097 -0.404483C2.07821 -0.348692 1.79925 -0.125529 1.49938 -0.125529C1.24134 -0.125529 0.990286 -0.306849 0.990286 -0.801993C0.990286 -1.17161 1.19253 -1.93873 1.35293 -2.21768C1.67372 -2.77559 2.02939 -2.8802 2.22466 -2.8802C2.71283 -2.8802 2.84533 -2.35019 2.84533 -2.27347C2.84533 -2.24558 2.83138 -2.19676 2.82441 -2.17584L2.49664 -0.871731Z' id='g1-97'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g0-120' y='-65.382'/>
<use x='-66.3273' xlink:href='#g1-97' y='-68.9974'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,12 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='11.5356pt' version='1.1' viewBox='-144 -143.968 19.9559 11.5356' width='19.9559pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M3.32752 -3.00872C3.3873 -3.26775 3.61644 -4.18431 4.31382 -4.18431C4.36364 -4.18431 4.60274 -4.18431 4.81196 -4.05479C4.533 -4.00498 4.33375 -3.75592 4.33375 -3.51681C4.33375 -3.35741 4.44334 -3.16812 4.71233 -3.16812C4.93151 -3.16812 5.25031 -3.34745 5.25031 -3.74595C5.25031 -4.26401 4.66252 -4.40349 4.32379 -4.40349C3.74595 -4.40349 3.39726 -3.87547 3.27771 -3.64633C3.02864 -4.30386 2.49066 -4.40349 2.20174 -4.40349C1.16563 -4.40349 0.597758 -3.11831 0.597758 -2.86924C0.597758 -2.76961 0.697385 -2.76961 0.71731 -2.76961C0.797011 -2.76961 0.826899 -2.78954 0.846824 -2.8792C1.18555 -3.93524 1.84309 -4.18431 2.18182 -4.18431C2.37111 -4.18431 2.7198 -4.09465 2.7198 -3.51681C2.7198 -3.20797 2.55044 -2.54047 2.18182 -1.1457C2.02242 -0.52802 1.67372 -0.109589 1.23537 -0.109589C1.17559 -0.109589 0.946451 -0.109589 0.737235 -0.239103C0.986301 -0.288917 1.20548 -0.498132 1.20548 -0.777086C1.20548 -1.04608 0.986301 -1.12578 0.836862 -1.12578C0.537983 -1.12578 0.288917 -0.86675 0.288917 -0.547945C0.288917 -0.0896638 0.787049 0.109589 1.2254 0.109589C1.88294 0.109589 2.24159 -0.587796 2.27148 -0.647572C2.39103 -0.278954 2.74969 0.109589 3.34745 0.109589C4.3736 0.109589 4.94147 -1.17559 4.94147 -1.42466C4.94147 -1.52428 4.85181 -1.52428 4.82192 -1.52428C4.73225 -1.52428 4.71233 -1.48443 4.6924 -1.41469C4.36364 -0.348692 3.68618 -0.109589 3.36737 -0.109589C2.97883 -0.109589 2.81943 -0.428394 2.81943 -0.767123C2.81943 -0.986301 2.8792 -1.20548 2.98879 -1.64384L3.32752 -3.00872Z' id='g0-120'/>
<path d='M2.94296 -2.66401C2.79651 -2.89415 2.5594 -3.07547 2.22466 -3.07547C1.332 -3.07547 0.425405 -2.09215 0.425405 -1.08792C0.425405 -0.411457 0.878705 0.0697385 1.47846 0.0697385C1.85504 0.0697385 2.18979 -0.146451 2.46874 -0.418431C2.60125 0 3.00573 0.0697385 3.18705 0.0697385C3.43811 0.0697385 3.61245 -0.0836862 3.73798 -0.299875C3.89141 -0.571856 3.98207 -0.969365 3.98207 -0.99726C3.98207 -1.08792 3.89141 -1.08792 3.87049 -1.08792C3.77285 -1.08792 3.76588 -1.06002 3.71706 -0.871731C3.63337 -0.536986 3.50087 -0.125529 3.20797 -0.125529C3.02665 -0.125529 2.97783 -0.278954 2.97783 -0.467248C2.97783 -0.585803 3.03362 -0.836862 3.08244 -1.01818C3.13126 -1.20648 3.201 -1.4924 3.23587 -1.64583L3.37534 -2.17584C3.41719 -2.35716 3.50087 -2.68493 3.50087 -2.7198C3.50087 -2.87323 3.37534 -2.94296 3.26376 -2.94296C3.14521 -2.94296 2.98481 -2.85928 2.94296 -2.66401ZM2.49664 -0.871731C2.44782 -0.676463 2.2944 -0.536986 2.14097 -0.404483C2.07821 -0.348692 1.79925 -0.125529 1.49938 -0.125529C1.24134 -0.125529 0.990286 -0.306849 0.990286 -0.801993C0.990286 -1.17161 1.19253 -1.93873 1.35293 -2.21768C1.67372 -2.77559 2.02939 -2.8802 2.22466 -2.8802C2.71283 -2.8802 2.84533 -2.35019 2.84533 -2.27347C2.84533 -2.24558 2.83138 -2.19676 2.82441 -2.17584L2.49664 -0.871731Z' id='g1-97'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g0-120' y='-67.7105'/>
<use x='-66.3273' xlink:href='#g1-97' y='-66.2162'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,10 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='8.54689pt' version='1.1' viewBox='-144 -143.968 12.7721 8.54689' width='12.7721pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M4.75218 -2.35118C4.75218 -3.91532 3.82565 -4.40349 3.08842 -4.40349C1.72354 -4.40349 0.408468 -2.97883 0.408468 -1.5741C0.408468 -0.647572 1.00623 0.109589 2.02242 0.109589C2.65006 0.109589 3.36737 -0.119552 4.12453 -0.727273C4.25405 -0.199253 4.58281 0.109589 5.03113 0.109589C5.55915 0.109589 5.868 -0.438356 5.868 -0.597758C5.868 -0.667497 5.80822 -0.697385 5.74844 -0.697385C5.6787 -0.697385 5.64882 -0.667497 5.61893 -0.597758C5.4396 -0.109589 5.08095 -0.109589 5.06102 -0.109589C4.75218 -0.109589 4.75218 -0.886675 4.75218 -1.12578C4.75218 -1.33499 4.75218 -1.35492 4.85181 -1.47447C5.78829 -2.65006 5.99751 -3.80573 5.99751 -3.81569C5.99751 -3.83562 5.98755 -3.91532 5.87796 -3.91532C5.77833 -3.91532 5.77833 -3.88543 5.72852 -3.7061C5.54919 -3.07846 5.22042 -2.3213 4.75218 -1.7335V-2.35118ZM4.08468 -0.986301C3.20797 -0.219178 2.44085 -0.109589 2.04234 -0.109589C1.44458 -0.109589 1.1457 -0.557908 1.1457 -1.19552C1.1457 -1.68369 1.40473 -2.75965 1.72354 -3.26775C2.19178 -3.99502 2.72976 -4.18431 3.07846 -4.18431C4.06476 -4.18431 4.06476 -2.8792 4.06476 -2.10212C4.06476 -1.7335 4.06476 -1.15567 4.08468 -0.986301Z' id='g0-11'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g0-11' y='-67.7105'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -1,10 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='17.6452pt' version='1.1' viewBox='-144 -143.948 12.2758 17.6452' width='12.2758pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M5.72852 -5.66874C5.72852 -6.41594 5.18057 -7.03362 4.3736 -7.03362C3.79577 -7.03362 3.51681 -6.87422 3.16812 -6.61519C2.62017 -6.21669 2.07223 -5.25031 1.88294 -4.49315L0.298879 1.83313C0.288917 1.87298 0.33873 1.93275 0.418431 1.93275S0.52802 1.91283 0.537983 1.88294L1.23537 -0.86675C1.42466 -0.268991 1.86301 0.0996264 2.59029 0.0996264S4.06476 -0.249066 4.51308 -0.687422C4.99128 -1.1457 5.31009 -1.78331 5.31009 -2.52055C5.31009 -3.23786 4.94147 -3.75592 4.58281 -4.00498C5.16065 -4.33375 5.72852 -4.95143 5.72852 -5.66874ZM3.93524 -4.01494C3.80573 -3.96513 3.69614 -3.94521 3.45704 -3.94521C3.31756 -3.94521 3.11831 -3.93524 3.01868 -3.98506C3.03861 -4.08468 3.39726 -4.06476 3.50685 -4.06476C3.71606 -4.06476 3.80573 -4.06476 3.93524 -4.01494ZM5.17061 -5.89788C5.17061 -5.2005 4.79203 -4.48319 4.27397 -4.17435C4.00498 -4.27397 3.80573 -4.2939 3.50685 -4.2939C3.29763 -4.2939 2.73973 -4.30386 2.73973 -3.97509C2.72976 -3.69614 3.24782 -3.72603 3.42715 -3.72603C3.79577 -3.72603 3.94521 -3.73599 4.24408 -3.85554C4.62267 -3.49689 4.67248 -3.18804 4.68244 -2.72976C4.70237 -2.15193 4.46326 -1.40473 4.18431 -1.01619C3.79577 -0.478207 3.12827 -0.119552 2.5604 -0.119552C1.80324 -0.119552 1.42466 -0.697385 1.42466 -1.40473C1.42466 -1.50436 1.42466 -1.6538 1.47447 -1.84309L2.11208 -4.36364C2.33126 -5.22042 3.04857 -6.80448 4.24408 -6.80448C4.82192 -6.80448 5.17061 -6.49564 5.17061 -5.89788Z' id='g0-12'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g0-12' y='-65.0815'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -1,16 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg height='27.8594pt' version='1.1' viewBox='-144 -143.964 33.1982 27.8594' width='33.1982pt' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<defs>
<path d='M3.94521 -3.7858C3.7858 -3.7858 3.64633 -3.7858 3.50685 -3.64633C3.34745 -3.49689 3.32752 -3.32752 3.32752 -3.25778C3.32752 -3.01868 3.50685 -2.90909 3.69614 -2.90909C3.98506 -2.90909 4.25405 -3.14819 4.25405 -3.5467C4.25405 -4.03487 3.7858 -4.40349 3.07846 -4.40349C1.7335 -4.40349 0.408468 -2.97883 0.408468 -1.5741C0.408468 -0.67746 0.986301 0.109589 2.02242 0.109589C3.44707 0.109589 4.28394 -0.946451 4.28394 -1.066C4.28394 -1.12578 4.22416 -1.19552 4.16438 -1.19552C4.11457 -1.19552 4.09465 -1.17559 4.03487 -1.09589C3.24782 -0.109589 2.16189 -0.109589 2.04234 -0.109589C1.41469 -0.109589 1.1457 -0.597758 1.1457 -1.19552C1.1457 -1.60399 1.34496 -2.57036 1.68369 -3.18804C1.99253 -3.75592 2.54047 -4.18431 3.08842 -4.18431C3.42715 -4.18431 3.80573 -4.05479 3.94521 -3.7858Z' id='g0-99'/>
<path d='M2.94296 -2.66401C2.79651 -2.89415 2.5594 -3.07547 2.22466 -3.07547C1.332 -3.07547 0.425405 -2.09215 0.425405 -1.08792C0.425405 -0.411457 0.878705 0.0697385 1.47846 0.0697385C1.85504 0.0697385 2.18979 -0.146451 2.46874 -0.418431C2.60125 0 3.00573 0.0697385 3.18705 0.0697385C3.43811 0.0697385 3.61245 -0.0836862 3.73798 -0.299875C3.89141 -0.571856 3.98207 -0.969365 3.98207 -0.99726C3.98207 -1.08792 3.89141 -1.08792 3.87049 -1.08792C3.77285 -1.08792 3.76588 -1.06002 3.71706 -0.871731C3.63337 -0.536986 3.50087 -0.125529 3.20797 -0.125529C3.02665 -0.125529 2.97783 -0.278954 2.97783 -0.467248C2.97783 -0.585803 3.03362 -0.836862 3.08244 -1.01818C3.13126 -1.20648 3.201 -1.4924 3.23587 -1.64583L3.37534 -2.17584C3.41719 -2.35716 3.50087 -2.68493 3.50087 -2.7198C3.50087 -2.87323 3.37534 -2.94296 3.26376 -2.94296C3.14521 -2.94296 2.98481 -2.85928 2.94296 -2.66401ZM2.49664 -0.871731C2.44782 -0.676463 2.2944 -0.536986 2.14097 -0.404483C2.07821 -0.348692 1.79925 -0.125529 1.49938 -0.125529C1.24134 -0.125529 0.990286 -0.306849 0.990286 -0.801993C0.990286 -1.17161 1.19253 -1.93873 1.35293 -2.21768C1.67372 -2.77559 2.02939 -2.8802 2.22466 -2.8802C2.71283 -2.8802 2.84533 -2.35019 2.84533 -2.27347C2.84533 -2.24558 2.83138 -2.19676 2.82441 -2.17584L2.49664 -0.871731Z' id='g1-97'/>
<path d='M1.8411 -4.63064C1.84807 -4.64458 1.86899 -4.73524 1.86899 -4.74222C1.86899 -4.77709 1.8411 -4.83985 1.75741 -4.83985C1.61793 -4.83985 1.0391 -4.78406 0.864757 -4.77011C0.808966 -4.76314 0.711333 -4.75616 0.711333 -4.60971C0.711333 -4.51208 0.808966 -4.51208 0.892653 -4.51208C1.2274 -4.51208 1.2274 -4.46326 1.2274 -4.40747C1.2274 -4.35866 1.15766 -4.0797 1.11582 -3.9193L0.955417 -3.27771C0.892653 -3.0406 0.509091 -1.51333 0.495143 -1.42267C0.460274 -1.25529 0.460274 -1.16463 0.460274 -1.08095C0.460274 -0.376588 0.9066 0.0697385 1.48543 0.0697385C2.35716 0.0697385 3.28468 -0.878705 3.28468 -1.91083C3.28468 -2.72677 2.7198 -3.07547 2.23861 -3.07547C1.87597 -3.07547 1.56912 -2.87323 1.3599 -2.69191L1.8411 -4.63064ZM1.4924 -0.125529C1.15068 -0.125529 0.955417 -0.425405 0.955417 -0.836862C0.955417 -1.09489 1.01818 -1.332 1.21345 -2.12005C1.25529 -2.25255 1.25529 -2.2665 1.3878 -2.41993C1.6528 -2.72677 1.96663 -2.8802 2.21768 -2.8802C2.48966 -2.8802 2.72677 -2.67796 2.72677 -2.20374C2.72677 -1.91781 2.57335 -1.20648 2.36413 -0.801993C2.19676 -0.460274 1.84807 -0.125529 1.4924 -0.125529Z' id='g1-98'/>
<path d='M2.70984 8.76712C2.58032 10.401 2.22167 10.8493 1.6538 10.8493C1.52428 10.8493 1.2254 10.8194 1.01619 10.6401C1.30511 10.6002 1.38481 10.3711 1.38481 10.2316C1.38481 9.94271 1.16563 9.8132 0.976339 9.8132C0.777086 9.8132 0.557908 9.94271 0.557908 10.2416C0.557908 10.7198 1.05604 11.0685 1.6538 11.0685C2.60025 11.0685 3.07846 10.2017 3.29763 9.30511C3.42715 8.78705 3.7858 5.88792 3.8655 4.78207L4.05479 2.30137C4.19427 0.468244 4.533 0.219178 4.98132 0.219178C5.08095 0.219178 5.38979 0.239103 5.60897 0.428394C5.32005 0.468244 5.24035 0.697385 5.24035 0.836862C5.24035 1.12578 5.45953 1.25529 5.64882 1.25529C5.84807 1.25529 6.06725 1.12578 6.06725 0.826899C6.06725 0.348692 5.56912 0 4.97136 0C4.02491 0 3.63636 0.966376 3.467 1.72354C3.34745 2.27148 2.98879 5.08095 2.89913 6.28643L2.70984 8.76712Z' id='g2-82'/>
</defs>
<g id='page1' transform='matrix(2 0 0 2 0 0)'>
<use x='-72' xlink:href='#g2-82' y='-69.62'/>
<use x='-65.3582' xlink:href='#g1-98' y='-67.1571'/>
<use x='-67.2954' xlink:href='#g1-97' y='-58.0522'/>
<use x='-59.6962' xlink:href='#g0-99' y='-61.5945'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 4.5 KiB

View File

@ -1,5 +0,0 @@
<?xml version='1.0'?>
<!-- This file was generated by dvisvgm 1.6 -->
<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<g id='page1' transform='matrix(2 0 0 2 0 0)'/>
</svg>

Before

Width:  |  Height:  |  Size: 223 B

View File

@ -1,218 +0,0 @@
from gi.repository import Gtk, Gdk
import subprocess
import threading
import time
import uuid
import os
from fuzzywuzzy import fuzz, process
FNULL = open(os.devnull, 'w')
objs = {
"Decorations": [
{
"name": "Superscript",
"tex": "$^{0}"
},
{
"name": "Subscript",
"tex": "$_{0}"
}
],
"Greek": [
{
"name": "Alpha",
"tex": "\\alpha"
},
{
"name": "Beta",
"tex": "\\beta"
}
],
"Math": [
{
"name": "Integral",
"tex": "\\int_{0}^{1}{2}"
}
],
"Arrows": [
{
"name": "Rightarrow",
"tex": "\\Rightarrow"
}
]
}
def get_svg(text):
fn = uuid.uuid4()
f = open("/tmp/{0}.tex".format(fn), "w+")
f.write("""%&latex
\\documentclass{standalone}
\\pagestyle{empty}
\\begin{document}
$""")
f.write(text)
f.write("""$
\\end{document}
""")
f.close()
subprocess.call(['pdftex', '-output-directory=/tmp',
'-interaction=nonstopmode', '/tmp/{0}.tex'.format(fn)],stdout=FNULL)
subprocess.call(['dvisvgm', '--no-fonts', '--scale=2', '/tmp/{0}.dvi'.format(fn),
'-o', '/tmp/{0}.svg'.format(fn)],stdout=FNULL)
return "/tmp/{0}.svg".format(fn)
class Handler:
def __init__(self, b):
self.b = b
self.current_search = ""
def onDeleteWindow(self, *args):
Gtk.main_quit(*args)
def recompile_image(self, buffer):
def recomp():
text = buffer.get_text(buffer.get_start_iter(),
buffer.get_end_iter(), False)
svgfn = get_svg(text)
im = self.b.get_object("image1")
im.set_from_file(svgfn)
self.thread = threading.Thread(target=recomp)
self.thread.daemon = False
self.thread.start()
def alpha_clicked(self, button):
bf = self.b.get_object("textbuffer1")
bf.insert_at_cursor("\\alpha")
def searchentry_changed(self, widget, data=None):
self.current_search = widget.get_text().lower()
self.b.get_object("listbox").invalidate_filter()
def sort_func(self, row_a, row_b, data=None):
if self.b.get_object("searchentry1").get_text():
if fuzz.partial_ratio(self.current_search, row_a.entry_name.lower()) > \
fuzz.partial_ratio(self.current_search, row_b.entry_name.lower()):
return False
else:
return True
return False
def filter_func(self, row, data=None):
if fuzz.partial_ratio(self.current_search, row.entry_name.lower()) < 80:
return False
# if not row.entry_name.startswith(self.b.get_object("searchentry1").get_text()):
# return False
return True
def textview_key_pressed(self, widget, key, data=None):
if key.keyval == Gdk.KEY_Tab:
print("\n\nTAB PRESSED\n\n")
# Tab Key:
# Move forward to next open curly bracket and
# highlight all text up to the next closing curly bracket
buf = widget.get_buffer()
cursor_iter = buf.get_iter_at_mark(buf.get_insert())
cursor_iter.forward_find_char(lambda x, data: x == "{", None, None)
bound = cursor_iter.copy()
bound.forward_chars(3)
buf.move_mark_by_name("insert", cursor_iter)
buf.move_mark_by_name("selection_bound", bound)
return True
def textview_after_key_pressed(self, widget, key, data=None):
print("\n\ntestign for context")
buf = widget.get_buffer()
cursor_iter = buf.get_iter_at_mark(buf.get_insert())
start_iter = cursor_iter.copy()
start_iter.backward_word_start()
start_iter.backward_cursor_position()
current_context = buf.get_text(start_iter, cursor_iter, False)
print("Current Context: ", current_context)
if current_context.startswith("\\"):
print("in context!!")
# we are in some latex specific context so we should try to complete
# whatever is going on :)
self.current_search = current_context.lower()[1:]
self.b.get_object("listbox").invalidate_filter()
def create_icons(builder):
import shutil
import re
tb = builder.get_object("textbuffer1")
menu = Gtk.Menu.new()
try:
os.makedirs("./icons")
except:
pass
def insert_tex_snippet(widget, row, data=None):
tb.insert_at_cursor(row.tex_data)
lb = builder.get_object("listbox")
from gi.repository import GObject
for obj in objs:
for val in objs[obj]:
tex_code = val["tex"]
tex_code = tex_code.format(*"abcdefghijklmn")
tex_code = re.sub("\$", "x", tex_code)
icon_fn = "./icons/" + re.sub(r"[\\\$]", "", val["tex"])
im_exists = os.path.exists(icon_fn)
if not im_exists:
svg_filename = get_svg(tex_code)
shutil.copy(svg_filename, icon_fn)
bx = Gtk.ListBoxRow.new()
bx.tex_data = val["tex"]
bx.entry_name = val["name"]
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
hbox.pack_start(Gtk.Image.new_from_file(icon_fn), True, True, 0)
hbox.pack_start(Gtk.Label(val["tex"]), True, True, 0)
hbox.show_all()
bx.add(hbox)
lb.add(bx)
lb.connect("row-activated", insert_tex_snippet)
return menu
pass
def run():
builder = Gtk.Builder()
builder.add_from_file("equation_widget.glade")
menu = create_icons(builder)
#menu.show_all()
l = builder.get_object("listbox")
window = builder.get_object("window1")
window.show_all()
handlers = Handler(builder)
builder.connect_signals(handlers)
l.set_filter_func(handlers.filter_func)
l.set_sort_func(handlers.sort_func)
Gtk.main()
if __name__ == "__main__":
run()

View File

@ -1,117 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
### DO NOT EDIT THIS FILE ###
"""this dialog adjusts values in gsettings
"""
import webbrowser
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Pango, GLib # pylint: disable=E0611
import logging
logger = logging.getLogger('apostrophe')
class PreferencesDialog:
__gtype_name__ = "PreferencesDialog"
formats = [
{
"name": "Pandoc's Markdown",
"format": "markdown",
"help": "https://pandoc.org/MANUAL.html#pandocs-markdown"
},
{
"name": "CommonMark",
"format": "commonmark",
"help": "https://commonmark.org"
},
{
"name": "GitHub Flavored Markdown",
"format": "gfm",
"help": "https://help.github.com/en/categories/writing-on-github"
},
{
"name": "MultiMarkdown",
"format": "markdown_mmd",
"help": "https://fletcherpenney.net/multimarkdown"
},
{
"name": "Plain Markdown",
"format": "markdown_strict",
"help": "https://daringfireball.net/projects/markdown"
}
]
def __init__(self, settings):
self.settings = settings
self.builder = Gtk.Builder()
self.builder.add_from_resource(
"/de/wolfvollprecht/UberWriter/ui/Preferences.ui")
self.autohide_headerbar_switch = self.builder.get_object("autohide_headerbar_switch")
self.autohide_headerbar_switch.set_active(self.settings.get_value("autohide-headerbar"))
self.autohide_headerbar_switch.connect("state-set", self.on_autohide_headerbar)
self.spellcheck_switch = self.builder.get_object("spellcheck_switch")
self.spellcheck_switch.set_active(self.settings.get_value("spellcheck"))
self.spellcheck_switch.connect("state-set", self.on_spellcheck)
input_format_store = Gtk.ListStore(int, str)
input_format = self.settings.get_string("input-format")
input_format_active = 0
for i, fmt in enumerate(self.formats):
input_format_store.append([i, fmt["name"]])
if fmt["format"] == input_format:
input_format_active = i
self.input_format_combobox = self.builder.get_object("input_format_combobox")
self.input_format_combobox.set_model(input_format_store)
input_format_renderer = Gtk.CellRendererText()
self.input_format_combobox.pack_start(input_format_renderer, True)
self.input_format_combobox.add_attribute(input_format_renderer, "text", 1)
self.input_format_combobox.set_active(input_format_active)
self.input_format_combobox.connect("changed", self.on_input_format)
self.input_format_help_button = self.builder.get_object("input_format_help_button")
self.input_format_help_button.connect('clicked', self.on_input_format_help)
def show(self, window):
preferences_window = self.builder.get_object("PreferencesWindow")
preferences_window.set_application(window.get_application())
preferences_window.set_transient_for(window)
preferences_window.show()
def on_autohide_headerbar(self, _, state):
self.settings.set_boolean("autohide-headerbar", state)
return False
def on_spellcheck(self, _, state):
self.settings.set_boolean("spellcheck", state)
return False
def on_input_format(self, combobox):
fmt = self.formats[combobox.get_active()]
self.settings.set_string("input-format", fmt["format"])
def on_input_format_help(self, _):
fmt = self.formats[self.input_format_combobox.get_active()]
webbrowser.open(fmt["help"])

View File

@ -1,50 +0,0 @@
from queue import Queue
from threading import Thread
import os
from gi.repository import GLib
from apostrophe import helpers
from apostrophe.theme import Theme
class PreviewConverter:
"""Converts markdown to html using a background thread."""
def __init__(self):
super().__init__()
self.queue = Queue()
worker = Thread(target=self.__do_convert, name="preview-converter")
worker.daemon = True
worker.start()
def convert(self, text, callback, *user_data):
"""Converts text to html, calling callback when done.
The callback argument contains the result."""
self.queue.put((text, callback, user_data))
def stop(self):
"""Stops the background worker. PreviewConverter shouldn't be used after this."""
self.queue.put((None, None))
def __do_convert(self):
while True:
while True:
(text, callback, user_data) = self.queue.get()
if text is None and callback is None:
return
if self.queue.empty():
break
args = ['--standalone',
'--mathjax',
'--css=' + Theme.get_current().web_css_path,
'--lua-filter=' + helpers.get_script_path('relative_to_absolute.lua'),
'--lua-filter=' + helpers.get_script_path('task-list.lua')]
text = helpers.pandoc_convert(text, to="html5", args=args)
GLib.idle_add(callback, text, *user_data)

View File

@ -1,154 +0,0 @@
import math
import webbrowser
from enum import auto, IntEnum
import gi
from apostrophe.preview_renderer import PreviewRenderer
from apostrophe.settings import Settings
gi.require_version('WebKit2', '4.0')
from gi.repository import WebKit2, GLib, Gtk
from apostrophe.preview_converter import PreviewConverter
from apostrophe.preview_web_view import PreviewWebView
class Step(IntEnum):
CONVERT_HTML = auto()
LOAD_WEBVIEW = auto()
RENDER = auto()
class PreviewHandler:
"""Handles showing/hiding the preview, and allows the user to toggle between modes.
The rendering itself is handled by `PreviewRendered`. This class handles conversion/loading and
connects it all together (including synchronization, ie. text changes, scroll)."""
def __init__(self, window, content, editor, text_view):
self.text_view = text_view
self.web_view = None
self.web_view_pending_html = None
self.preview_converter = PreviewConverter()
self.preview_renderer = PreviewRenderer(
window, content, editor, text_view)
window.connect("style-updated", self.reload)
self.text_changed_handler_id = None
self.settings = Settings.new()
self.web_scroll_handler_id = None
self.text_scroll_handler_id = None
self.loading = False
self.shown = False
def show(self):
self.__show()
def __show(self, html=None, step=Step.CONVERT_HTML):
if step == Step.CONVERT_HTML:
# First step: convert text to HTML.
buf = self.text_view.get_buffer()
self.preview_converter.convert(
buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False),
self.__show, Step.LOAD_WEBVIEW)
elif step == Step.LOAD_WEBVIEW:
# Second step: load HTML.
self.loading = True
if not self.web_view:
self.web_view = PreviewWebView()
self.web_view.get_settings().set_allow_universal_access_from_file_urls(True)
# Show preview once the load is finished
self.web_view.connect("load-changed", self.on_load_changed)
# All links will be opened in default browser, but local files are opened in apps.
self.web_view.connect("decide-policy", self.on_click_link)
if self.web_view.is_loading():
self.web_view_pending_html = html
else:
self.web_view.load_html(html, "file://localhost/")
elif step == Step.RENDER:
# Last step: show the preview. This is a one-time step.
if self.shown:
return
self.shown = True
self.text_changed_handler_id = \
self.text_view.get_buffer().connect("changed", self.__show)
GLib.idle_add(self.web_view.set_scroll_scale, self.text_view.get_scroll_scale())
self.preview_renderer.show(self.web_view)
if self.settings.get_boolean("sync-scroll"):
self.web_scroll_handler_id = \
self.web_view.connect("scroll-scale-changed", self.on_web_view_scrolled)
self.text_scroll_handler_id = \
self.text_view.connect("scroll-scale-changed", self.on_text_view_scrolled)
def reload(self, *_widget, reshow=False):
if self.shown:
if reshow:
self.hide()
self.show()
def hide(self):
if self.shown:
self.shown = False
self.text_view.get_buffer().disconnect(self.text_changed_handler_id)
GLib.idle_add(self.text_view.set_scroll_scale, self.web_view.get_scroll_scale())
self.preview_renderer.hide(self.web_view)
if self.text_scroll_handler_id:
self.text_view.disconnect(self.text_scroll_handler_id)
self.text_scroll_handler_id = None
if self.web_scroll_handler_id:
self.web_view.disconnect(self.web_scroll_handler_id)
self.web_scroll_handler_id = None
if self.loading:
self.loading = False
self.web_view.destroy()
self.web_view = None
def update_preview_mode(self):
self.preview_renderer.update_mode(self.web_view)
def on_load_changed(self, _web_view, event):
if event == WebKit2.LoadEvent.FINISHED:
self.loading = False
if self.web_view_pending_html:
self.__show(html=self.web_view_pending_html, step=Step.LOAD_WEBVIEW)
self.web_view_pending_html = None
else:
self.__show(step=Step.RENDER)
def on_text_view_scrolled(self, _text_view, scale):
if self.shown and not math.isclose(scale, self.web_view.get_scroll_scale(), rel_tol=1e-4):
self.web_view.set_scroll_scale(scale)
def on_web_view_scrolled(self, _web_view, scale):
if self.shown and self.text_view.get_mapped() and \
not math.isclose(scale, self.text_view.get_scroll_scale(), rel_tol=1e-4):
self.text_view.set_scroll_scale(scale)
@staticmethod
def on_click_link(web_view, decision, _decision_type):
if web_view.get_uri().startswith(("http://", "https://", "www.")):
webbrowser.open(web_view.get_uri())
decision.ignore()
return True

View File

@ -1,136 +0,0 @@
from gettext import gettext as _
from gi.repository import Gtk, Gio, GLib
from apostrophe import headerbars
from apostrophe.settings import Settings
from apostrophe.styled_window import StyledWindow
class PreviewRenderer:
"""Renders the preview according to the user selected mode."""
# Must match the order/index defined in gschema.xml
FULL_WIDTH = 0
HALF_WIDTH = 1
HALF_HEIGHT = 2
WINDOWED = 3
def __init__(
self, main_window, content, editor, text_view):
self.main_window = main_window
self.main_window.connect("delete-event", self.on_window_closed)
self.content = content
self.editor = editor
self.text_view = text_view
self.settings = Settings.new()
self.popover = None
self.window = None
self.headerbar = None
self.mode = self.settings.get_enum("preview-mode")
self.update_mode()
def show(self, web_view):
"""Show the preview, depending on the currently selected mode."""
# Windowed preview: create a window and show the preview in it.
if self.mode == self.WINDOWED:
# Create transient window of the main window.
self.window = StyledWindow(application=self.main_window.get_application())
self.window.connect("delete-event", self.on_window_closed)
# Create a custom header bar and move the mode button there.
headerbar = headerbars.PreviewHeaderbar()
self.headerbar = headerbar.hb
self.headerbar.set_title(_("Preview"))
self.window.set_titlebar(headerbar.hb_container)
# Position it next to the main window.
width, height = self.main_window.get_size()
self.window.resize(width, height)
x, y = self.main_window.get_position()
if x is not None and y is not None:
self.main_window.move(x, y)
self.window.move(x + width + 16, y)
# Add webview and show.
self.window.add(web_view)
self.window.show()
else:
self.content.pack_start(web_view, True, True, 0)
# Full-width preview: swap editor with preview.
if self.mode == self.FULL_WIDTH:
self.content.remove(self.editor)
# Half-width preview: set horizontal orientation and add the preview.
# Ask for a minimum width that respects the editor's minimum requirements.
elif self.mode == self.HALF_WIDTH:
self.content.set_orientation(Gtk.Orientation.HORIZONTAL)
self.content.set_size_request(self.text_view.get_min_width() * 2, -1)
# Half-height preview: set vertical orientation and add the preview.
# Ask for a minimum height that provides a comfortable experience.
elif self.mode == self.HALF_HEIGHT:
self.content.set_orientation(Gtk.Orientation.VERTICAL)
self.content.set_size_request(-1, 768)
else:
raise ValueError("Unknown preview mode {}".format(self.mode))
web_view.show()
def hide(self, web_view):
"""Hide the preview, depending on the currently selected mode."""
# Windowed preview: remove preview and destroy window.
if self.mode == self.WINDOWED:
self.main_window.present()
self.headerbar = None
self.window.remove(web_view)
self.window.destroy()
self.window = None
else:
self.content.remove(web_view)
# Full-width preview: swap preview with editor.
if self.mode == self.FULL_WIDTH:
self.content.add(self.editor)
# Half-width/height previews: remove preview and reset size requirements.
elif self.mode == self.HALF_WIDTH or self.mode == self.HALF_HEIGHT:
self.content.set_size_request(-1, -1)
else:
raise ValueError("Unknown preview mode {}".format(self.mode))
def update_mode(self, web_view=None):
"""Update preview mode, adjusting the mode button and the preview itself."""
mode = self.settings.get_enum("preview-mode")
if web_view and mode != self.mode:
self.hide(web_view)
self.mode = mode
self.show(web_view)
else:
self.mode = mode
def on_window_closed(self, window, _event):
preview_action = window.get_application().lookup_action("preview")
preview_action.change_state(GLib.Variant.new_boolean(False))
def get_text_for_preview_mode(self, mode):
if mode == self.FULL_WIDTH:
return _("Full-Width")
elif mode == self.HALF_WIDTH:
return _("Half-Width")
elif mode == self.HALF_HEIGHT:
return _("Half-Height")
elif mode == self.WINDOWED:
return _("Windowed")
else:
raise ValueError("Unknown preview mode {}".format(mode))

View File

@ -1,146 +0,0 @@
import webbrowser
import gi
gi.require_version('WebKit2', '4.0')
from gi.repository import WebKit2, GLib, GObject
class PreviewWebView(WebKit2.WebView):
"""A WebView that provides read/write access to scroll.
It does so using JavaScript, by continuously monitoring it while loaded.
The alternative is using a WebExtension and C-bindings (see reference), but that is more
complicated implementation-wise, as well as build-wise until we start building with Meson.
Reference: https://github.com/aperezdc/webkit2gtk-python-webextension-example
"""
SYNC_SCROLL_SCALE_JS = """
scale = {:.16f};
write = {};
// Configure MathJax.
if (typeof hasMathJax === "undefined") {{
hasMathJax = typeof MathJax !== "undefined";
if (hasMathJax) {{
MathJax.Hub.Config({{ messageStyle: "none" }});
}}
}}
// Figure out if scrollable and rendered.
e = document.documentElement;
canScroll = e.scrollHeight > e.clientHeight;
wasRendered = typeof isRendered !== "undefined" && isRendered;
isRendered = wasRendered ||
!hasMathJax ||
MathJax.Hub.queue.running == 0 && MathJax.Hub.queue.pending == 0;
// Write the current scroll if instructed or if it was just rendered.
if (canScroll && (write || isRendered && !wasRendered)) {{
e.scrollTop = (e.scrollHeight - e.clientHeight) * scale;
}}
// Return the current scroll if scrollable and rendered, or -1.
if (canScroll && isRendered) {{
e.scrollTop / (e.scrollHeight - e.clientHeight);
}} else {{
-1;
}}
""".strip()
__gsignals__ = {
"scroll-scale-changed": (GObject.SIGNAL_RUN_LAST, None, (float,)),
}
def __init__(self):
super().__init__()
self.connect("size-allocate", self.on_size_allocate)
self.connect("decide-policy", self.on_decide_policy)
self.connect("load-changed", self.on_load_changed)
self.connect("load-failed", self.on_load_failed)
self.connect("destroy", self.on_destroy)
self.props.expand = True
self.scroll_scale = -1
self.state_loaded = False
self.state_load_failed = False
self.state_discard_read = False
self.state_dirty = False
self.state_waiting = False
self.timeout_id = None
def can_scroll(self):
return self.scroll_scale != -1
def get_scroll_scale(self):
return self.scroll_scale
def set_scroll_scale(self, scale):
self.state_dirty = scale != self.scroll_scale
self.scroll_scale = scale
self.state_loop()
def on_size_allocate(self, *_):
self.set_scroll_scale(self.scroll_scale)
def on_decide_policy(self, _web_view, decision, decision_type):
if decision_type == WebKit2.PolicyDecisionType.NAVIGATION_ACTION and \
decision.get_navigation_action().is_user_gesture():
webbrowser.open(decision.get_request().get_uri())
decision.ignore() # Do not follow the link in the WebView
return True
return False
def on_load_changed(self, _web_view, event):
self.state_loaded = event >= WebKit2.LoadEvent.COMMITTED and not self.state_load_failed
self.state_load_failed = False
self.state_discard_read = event == WebKit2.LoadEvent.STARTED and self.state_waiting
self.state_dirty = True
self.state_loop()
def on_load_failed(self, _web_view, _event):
self.state_loaded = False
self.state_load_failed = True
self.state_loop()
def on_destroy(self, _widget):
self.state_loaded = False
self.state_loop()
def sync_scroll_scale(self, scroll_scale, write):
self.state_waiting = True
self.run_javascript(
self.SYNC_SCROLL_SCALE_JS.format(scroll_scale, "true" if write else "false"),
None, self.finish_sync_scroll_scale)
def finish_sync_scroll_scale(self, _web_view, result):
self.state_waiting = False
result = self.run_javascript_finish(result)
self.state_loop(result.get_js_value().to_double())
def state_loop(self, scroll_scale=None, delay=16): # 16ms ~ 60hz
# Remove any pending callbacks
if self.timeout_id:
GLib.source_remove(self.timeout_id)
self.timeout_id = None
# Set scroll scale if specified, and the state is not dirty
if not self.state_discard_read and scroll_scale not in (None, self.scroll_scale):
self.scroll_scale = scroll_scale
if self.scroll_scale != -1:
self.emit("scroll-scale-changed", self.scroll_scale)
self.state_discard_read = False
# Handle the current state
if not self.state_loaded or self.state_load_failed or self.state_waiting:
return
elif self.state_dirty or delay == 0:
self.sync_scroll_scale(self.scroll_scale, self.state_dirty)
self.state_dirty = False
else:
self.timeout_id = GLib.timeout_add(delay, self.state_loop, None, 0)

View File

@ -1,49 +0,0 @@
# -*- coding:utf-8 -*-
#
# Copyright (C) 2019, Maximilian Köhl <linuxmaxi@googlemail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
__version__ = '1.2'
__project__ = 'Python Locales'
__short_name__ = 'pylocales'
__authors__ = 'Maximilian Köhl'
__emails__ = 'linuxmaxi@googlemail.com'
__website__ = 'http://koehlma.github.com/projects/pygtkspellcheck.html'
__source__ = 'https://github.com/koehlma/pygtkspellcheck/'
__vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git'
__copyright__ = '2012, Maximilian Köhl'
__desc_short__ = 'query the ISO 639/3166 database about a country or a language.'
__desc_long__ = ('Query the ISO 639/3166 database about a country or a'
'language. The locales database contains ISO 639 language'
'definitions and ISO 3166 country definitions. This package'
'provides translation for country and language names if'
'the iso-code messages are installed on your system.')
__metadata__ = {'__version__' : __version__,
'__project__' : __project__,
'__short_name__' : __short_name__,
'__authors__' : __authors__,
'__emails__' : __emails__,
'__website__' : __website__,
'__source__' : __source__,
'__vcs__' : __vcs__,
'__copyright__' : __copyright__,
'__desc_short__' : __desc_short__,
'__desc_long__' : __desc_long__}
from .locales import (Country, Language, LanguageNotFound,
CountryNotFound, code_to_name)

Binary file not shown.

View File

@ -1,156 +0,0 @@
# -*- coding:utf-8 -*-
#
# Copyright (C) 2019, Maximilian Köhl <linuxmaxi@googlemail.com>
# Copyright (C) 2019, Carlos Jenkins <carlos@jenkins.co.cr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Query the ISO 639/3166 database about a country or a language. The locales
database contains ISO 639 language definitions and ISO 3166 country definitions.
This package provides translation for country and language names if the
iso-code messages are installed on your system.
"""
import gettext
import logging
import os
import sqlite3
import sys
# public objects
__all__ = ['Country', 'Language', 'LanguageNotFound',
'CountryNotFound', 'code_to_name']
# translation
_translator_language = gettext.translation('iso_639', fallback=True).gettext
_translator_country = gettext.translation('iso_3166', fallback=True).gettext
# Decides where the database is located. If an application provides an
# os.path.get_module_path monkey patch to determine the path where the module
# is located it uses this. If not it searches in the directory of this source
# code file.
__path__ = None
if hasattr(os.path, 'get_module_path'):
__path__ = os.path.get_module_path(__file__)
if not os.path.isfile(os.path.join(__path__, 'locales.db')):
__path__ = None
if __path__ is None:
frozen = getattr(sys, 'frozen', None)
if frozen in ('dll', 'console_exe', 'windows_exe'):
__path__ = os.path.abspath(os.path.dirname(sys.executable))
elif frozen == 'macosx_app':
__path__ = os.path.abspath(os.environ['RESOURCEPATH'])
elif frozen is True:
# Handle executables produced by PyInstaller.
__path__ = sys._MEIPASS
else:
__path__ = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
# loading the database
_database = sqlite3.connect(os.path.join(__path__, 'locales.db'))
logger = logging.getLogger(__name__)
class LanguageNotFound(Exception):
"""
The specified language wasn't found in the database.
"""
class CountryNotFound(Exception):
"""
The specified country wasn't found in the database.
"""
class Country(object):
def __init__(self, rowid):
country = _database.execute('SELECT * FROM countries WHERE rowid == ?',
(rowid,)).fetchone()
self.name = country[0]
self.official_name = country[1]
self.alpha_2 = country[2]
self.alpha_3 = country[3]
self.numeric = country[4]
self.translation = _translator_country(self.name)
@classmethod
def get_country(cls, code, codec):
country = _database.execute(
'SELECT rowid FROM countries WHERE %s == ?' % (codec),
(code,)).fetchone()
if country:
return cls(country[0])
raise CountryNotFound('code: %s, codec: %s' % (code, codec))
@classmethod
def by_alpha_2(cls, code):
return Country.get_country(code, 'alpha_2')
@classmethod
def by_alpha_3(cls, code):
return Country.get_country(code, 'alpha_3')
@classmethod
def by_numeric(cls, code):
return Country.get_country(code, 'numeric')
class Language(object):
def __init__(self, rowid):
language = _database.execute('SELECT * FROM languages WHERE rowid == ?',
(rowid,)).fetchone()
self.name = language[0]
self.iso_639_2B = language[1]
self.iso_639_2T = language[2]
self.iso_639_1 = language[3]
self.translation = _translator_language(self.name)
@classmethod
def get_language(cls, code, codec):
language = _database.execute(
'SELECT rowid FROM languages WHERE %s == ?' % (codec),
(code,)).fetchone()
if language:
return cls(language[0])
raise LanguageNotFound('code: %s, codec: %s' % (code, codec))
@classmethod
def by_iso_639_2B(cls, code):
return Language.get_language(code, 'iso_639_2B')
@classmethod
def by_iso_639_2T(cls, code):
return Language.get_language(code, 'iso_639_2T')
@classmethod
def by_iso_639_1(cls, code):
return Language.get_language(code, 'iso_639_1')
def code_to_name(code, separator='_'):
"""
Get the human readable and translated name of a language based on it's code.
:param code: the code of the language (e.g. de_DE, en_US)
:param target: separator used to separate language from country
:rtype: human readable and translated language name
"""
logger.debug('requesting name for code "{}"'.format(code))
code = code.split(separator)
if len(code) > 1:
lang = Language.by_iso_639_1(code[0]).translation
country = Country.by_alpha_2(code[1]).translation
return '{} ({})'.format(lang, country)
else:
return Language.by_iso_639_1(code[0]).translation

View File

@ -1,195 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import logging
import re
import gi
from apostrophe.helpers import user_action
gi.require_version('Gtk', '3.0')
from gi.repository import Gdk
# from plugins import plugins
LOGGER = logging.getLogger('apostrophe')
class SearchAndReplace:
"""
Adds (regex) search and replace functionality to
apostrophe
"""
def __init__(self, parentwindow, textview, builder):
self.parentwindow = parentwindow
self.textview = textview
self.textbuffer = textview.get_buffer()
self.box = builder.get_object("searchbar_placeholder")
self.box.set_reveal_child(False)
self.searchbar = builder.get_object("searchbar")
self.searchentry = builder.get_object("searchentrybox")
self.searchentry.connect('changed', self.search)
self.searchentry.connect('activate', self.scrolltonext)
self.searchentry.connect('key-press-event', self.key_pressed)
self.open_replace_button = builder.get_object("replace")
self.open_replace_button.connect("toggled", self.toggle_replace)
self.nextbutton = builder.get_object("next_result")
self.prevbutton = builder.get_object("previous_result")
self.regexbutton = builder.get_object("regex")
self.casesensitivebutton = builder.get_object("case_sensitive")
self.replacebox = builder.get_object("replace_placeholder")
self.replacebox.set_reveal_child(False)
self.replace_one_button = builder.get_object("replace_one")
self.replace_all_button = builder.get_object("replace_all")
self.replaceentry = builder.get_object("replaceentrybox")
self.replace_all_button.connect('clicked', self.replace_all)
self.replace_one_button.connect('clicked', self.replace_clicked)
self.replaceentry.connect('activate', self.replace_clicked)
self.nextbutton.connect('clicked', self.scrolltonext)
self.prevbutton.connect('clicked', self.scrolltoprev)
self.regexbutton.connect('toggled', self.search)
self.casesensitivebutton.connect('toggled', self.search)
self.highlight = self.textbuffer.create_tag('search_highlight', background="yellow")
self.textview.connect("focus-in-event", self.focused_texteditor)
self.matches = []
self.active = 0
def toggle_replace(self, widget, _data=None):
"""toggle the replace box
"""
self.replacebox.set_reveal_child(widget.get_active())
def key_pressed(self, _widget, event, _data=None):
"""hide the search and replace content box when ESC is pressed
"""
if event.keyval == Gdk.KEY_Escape:
self.hide()
def focused_texteditor(self, _widget, _data=None):
"""hide the search and replace content box
"""
self.hide()
def toggle_search(self, replace=False):
"""
toggle search box
"""
search_hidden = self.textview.get_mapped() and (
self.box.get_reveal_child() is False or self.searchbar.get_search_mode() is False)
replace_hidden = not self.open_replace_button.get_active()
if search_hidden or (replace and replace_hidden):
self.searchbar.set_search_mode(True)
self.box.set_reveal_child(True)
self.searchentry.grab_focus()
if replace:
self.open_replace_button.set_active(True)
else:
self.hide()
self.open_replace_button.set_active(False)
def search(self, _widget=None, _data=None, scroll=True):
searchtext = self.searchentry.get_text()
context_start = self.textbuffer.get_start_iter()
context_end = self.textbuffer.get_end_iter()
text = self.textbuffer.get_slice(context_start, context_end, False)
self.textbuffer.remove_tag(self.highlight, context_start, context_end)
# case sensitive?
flags = False
if not self.casesensitivebutton.get_active():
flags = flags | re.I
# regex?
if not self.regexbutton.get_active():
searchtext = re.escape(searchtext)
matches = re.finditer(searchtext, text, flags)
self.matches = []
self.active = 0
for match in matches:
self.matches.append((match.start(), match.end()))
start_iter = self.textbuffer.get_iter_at_offset(match.start())
end_iter = self.textbuffer.get_iter_at_offset(match.end())
self.textbuffer.apply_tag(self.highlight, start_iter, end_iter)
if scroll:
self.scrollto(self.active)
LOGGER.debug(searchtext)
def scrolltonext(self, _widget, _data=None):
self.scrollto(self.active + 1)
def scrolltoprev(self, _widget, _data=None):
self.scrollto(self.active - 1)
def scrollto(self, index):
if not self.matches:
return
self.active = index % len(self.matches)
match = self.matches[self.active]
start_iter = self.textbuffer.get_iter_at_offset(match[0])
end_iter = self.textbuffer.get_iter_at_offset(match[1])
# create a mark at the start of the coincidence to scroll to it
mark = self.textbuffer.create_mark(None, start_iter, False)
self.textview.scroller.scroll_to_mark(mark, center=True)
# select coincidence
self.textbuffer.select_range(start_iter, end_iter)
def hide(self):
self.box.set_reveal_child(False)
self.textbuffer.remove_tag(self.highlight,
self.textbuffer.get_start_iter(),
self.textbuffer.get_end_iter())
self.textview.grab_focus()
def replace_clicked(self, _widget, _data=None):
self.replace(self.active)
def replace_all(self, _widget=None, _data=None):
with user_action(self.textbuffer):
for match in reversed(self.matches):
self.__do_replace(match)
self.search(scroll=False)
def replace(self, searchindex, _inloop=False):
with user_action(self.textbuffer):
self.__do_replace(self.matches[searchindex])
active = self.active
self.search(scroll=False)
self.active = active
self.scrollto(self.active)
def __do_replace(self, match):
start_iter = self.textbuffer.get_iter_at_offset(match[0])
end_iter = self.textbuffer.get_iter_at_offset(match[1])
self.textbuffer.delete(start_iter, end_iter)
start_iter = self.textbuffer.get_iter_at_offset(match[0])
self.textbuffer.insert(start_iter, self.replaceentry.get_text())

View File

@ -1,37 +0,0 @@
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
from gi.repository import Gio
class Settings(Gio.Settings):
"""
Apostrophe Settings
"""
def __init__(self):
"""
Init Settings
"""
Gio.Settings.__init__(self)
@classmethod
def new(cls):
"""
Return a new Settings object
"""
settings = Gio.Settings.new("de.wolfvollprecht.UberWriter")
settings.__class__ = Settings
return settings

View File

@ -1,194 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import os
import subprocess
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
# from plugins import plugins
import logging
logger = logging.getLogger('apostrophe')
class Shelve():
"""
Shelve holds a collection of folders
folders:
List of folders
name:
descriptive name of shelve e.g. blog, notes etc.
"""
name = ""
folders = []
def __init__(self, name, folders):
self.name = name
self.folders = folders
def get_tree(self, store):
node = {}
for folder in self.folders:
node[folder] = store.append(None, [os.path.basename(folder), folder])
for root, dirs, files in os.walk(folder):
logger.debug(root)
for directory in dirs:
node[root + "/" + directory] = store.append(node[root], [directory, root + "/" + directory])
for filename in files:
store.append(node[root], [filename, root + "/" + filename])
class Sidebar():
"""
Presentational class for shelves and files managed by the "sidebar"
parentwindow:
Reference to Window
"""
def __init__(self, parentwindow):
"""
Initialize Treeview and Treestore
"""
self.parentwindow = parentwindow
self.paned_window = parentwindow.paned_window
self.sidebar_box = parentwindow.sidebar_box
self.sidebar_open = True
# (GtkBox *box,
# GtkWidget *child,
# gboolean expand,
# gboolean fill,
# guint padding);
self.shelve_store = Gtk.ListStore(str)
self.shelve_store.append(["testshelve"])
self.shelves_dropdown = Gtk.ComboBox.new_with_model_and_entry(self.shelve_store)
self.sidebar_box.pack_start(self.shelves_dropdown, False, False, 5)
self.sidebar_scrolledwindow = Gtk.ScrolledWindow()
self.sidebar_scrolledwindow.set_hexpand(True)
self.sidebar_scrolledwindow.set_vexpand(True)
self.store = Gtk.TreeStore(str, str)
self.active_shelf = Shelve("testshelve", ["/home/wolf/Documents/asd/"])
self.active_shelf.get_tree(self.store)
self.treeview = Gtk.TreeView(self.store)
self.treeview.set_headers_visible(False)
# expand first folder (root folder, but not children)
self.treeview.expand_row(Gtk.TreePath.new_from_string("0"), False)
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Title", renderer, text=0)
self.treeview.append_column(column)
# new selection
self.treeview.connect('cursor_changed', self.get_selected_file)
# right click handler
self.treeview.connect('button-press-event', self.handle_button_press)
self.treeview.show()
self.sidebar_scrolledwindow.add(self.treeview)
self.sidebar_box.pack_start(self.sidebar_scrolledwindow, True, True, 5)
self.menu_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.menu_button = Gtk.MenuButton.new()
# TODO refactor
mb_menu = Gtk.Menu.new()
mitem = Gtk.MenuItem.new_with_label('etstasd asd as d')
mitem.show()
mb_menu.append(mitem)
mb_menu.show()
self.menu_button.set_popup(mb_menu)
self.menu_box.pack_start(self.menu_button, False, False, 5)
self.sidebar_box.pack_end(self.menu_box, False, False, 5)
self.sidebar_box.show_all()
self.paned_window.pack1(self.sidebar_box, True, True);
self.paned_window.show_all()
def get_selected_file(self, widget, data=None):
"""
Handle left click on file
"""
selection = self.treeview.get_selection()
if not selection:
return
selection.set_mode(Gtk.SelectionMode.SINGLE)
treemodel, treeiter = selection.get_selected()
selected_file = treemodel.get_value(treeiter, 1)
self.parentwindow.load_file(selected_file)
logger.debug(selected_file)
def handle_button_press(self, widget, event):
"""
Handle right click (context menu)
"""
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
# reference to self to not have it garbage collected
self.popup = Gtk.Menu.new()
pathinfo = self.treeview.get_path_at_pos(event.x, event.y)
if pathinfo:
path, col, cellx, celly = pathinfo
treeiter = self.store.get_iter(path)
filename = self.store.get_value(treeiter, 1)
item = Gtk.MenuItem.new()
item.set_label("Open ...")
# item.connect("activate", self.context_menu_open_file)
# item.filename = filename
item.show()
# self.popup.append(item)
self.popup.show()
self.popup.popup(None, None, None, None, event.button, event.time)
return True
def get_treeview(self):
"""
Return Treeview to append to scrolled window
"""
return self.treeview
def context_menu_open_file(self, widget, data=None):
"""
Open selected file with xdg-open
"""
selected_file = widget.filename
subprocess.call(["xdg-open", selected_file])
def toggle_sidebar(self):
if self.sidebar_open:
self.close_sidebar()
else:
self.open_sidebar()
def open_sidebar(self):
# self.paned_window.set_property('min-position', 0)
self.paned_window.set_position(200)
self.sidebar_open = True
def close_sidebar(self):
# self.paned_window.set_property('min-position', 0)
self.paned_window.set_position(0)
self.sidebar_open = False

View File

@ -1,115 +0,0 @@
import re
from multiprocessing import Process, Pipe
from gi.repository import GLib
from apostrophe.markup_regex import ITALIC_ASTERISK, ITALIC_UNDERSCORE, BOLD_ITALIC, BOLD, STRIKETHROUGH, IMAGE, LINK, LINK_ALT,\
HORIZONTAL_RULE, LIST, MATH, TABLE, CODE_BLOCK, HEADER_UNDER, HEADER, BLOCK_QUOTE, ORDERED_LIST, \
FOOTNOTE_ID, FOOTNOTE
class StatsCounter:
"""Counts characters, words, sentences and read time using a worker process."""
# Regexp that matches any character, except for newlines and subsequent spaces.
CHARACTERS = re.compile(r"[^\s]|(?:[^\S\n](?!\s))")
# Regexp that matches Asian letters, general symbols and hieroglyphs,
# as well as sequences of word characters optionally containing non-word characters in-between.
WORDS = re.compile(r"[\u3040-\uffff]|(?:\w+\S?\w*)+", re.UNICODE)
# Regexp that matches sentence-ending punctuation characters, ie. full stop, question mark,
# exclamation mark, paragraph, and variants.
SENTENCES = re.compile(r"[^\n][.。।෴۔።?՞;⸮؟?፧꘏⳺⳻⁇﹖⁈⁉‽!﹗!՜߹႟᥄\n]+")
# Regexp that matches paragraphs, ie. anything separated by at least 2 newlines.
PARAGRAPHS = re.compile(r"[^\n]+(\n{2,}|$)")
# List of regexp whose matches should be replaced by their "text" group. Order is important.
MARKUP_REGEXP_REPLACE = (
BOLD_ITALIC, ITALIC_ASTERISK, ITALIC_UNDERSCORE, BOLD, STRIKETHROUGH, IMAGE, LINK, LINK_ALT, LIST, ORDERED_LIST,
BLOCK_QUOTE, HEADER, HEADER_UNDER, CODE_BLOCK, TABLE, MATH, FOOTNOTE_ID, FOOTNOTE
)
# List of regexp whose matches should be removed. Order is important.
MARKUP_REGEXP_REMOVE = (
HORIZONTAL_RULE,
)
def __init__(self, callback):
super().__init__()
# Worker process to handle counting.
self.counting = False
self.count_pending_text = None
self.parent_conn, child_conn = Pipe()
Process(target=self.do_count, args=(child_conn,), daemon=True).start()
GLib.io_add_watch(
self.parent_conn.fileno(), GLib.PRIORITY_LOW, GLib.IO_IN, self.on_counted, callback)
def count(self, text):
"""Count stats for text.
In case counting is already running, it will re-count once it finishes. This ensure that
the pipe doesn't fill (and block) if multiple requests are made in quick succession."""
if not self.counting:
self.counting = True
self.count_pending_text = None
self.parent_conn.send(text)
else:
self.count_pending_text = text
def do_count(self, child_conn):
"""Counts stats in a worker process.
The result is in the format: (characters, words, sentences, (hours, minutes, seconds))"""
while True:
while True:
try:
text = child_conn.recv()
if not child_conn.poll():
break
except EOFError:
child_conn.close()
return
for regexp in self.MARKUP_REGEXP_REPLACE:
text = re.sub(regexp, r"\g<text>", text)
for regexp in self.MARKUP_REGEXP_REMOVE:
text = re.sub(regexp, "", text)
character_count = len(re.findall(self.CHARACTERS, text))
word_count = len(re.findall(self.WORDS, text))
sentence_count = len(re.findall(self.SENTENCES, text))
paragraph_count = len(re.findall(self.PARAGRAPHS, text))
read_m, read_s = divmod(word_count / 200 * 60, 60)
read_h, read_m = divmod(read_m, 60)
read_time = (int(read_h), int(read_m), int(read_s))
child_conn.send(
(character_count, word_count, sentence_count, paragraph_count, read_time))
def on_counted(self, _source, _condition, callback):
"""Reads the counting result from the pipe and triggers any pending count."""
self.counting = False
if self.count_pending_text is not None:
self.count(self.count_pending_text) # self.count clears the pending text.
try:
if self.parent_conn.poll():
callback(self.parent_conn.recv())
return True
except EOFError:
return False
def stop(self):
"""Stops the worker process. StatsCounter shouldn't be used after this."""
self.parent_conn.close()

View File

@ -1,96 +0,0 @@
from gettext import gettext as _
from gi.repository import GLib, Gio, Gtk
from apostrophe.settings import Settings
from apostrophe.stats_counter import StatsCounter
class StatsHandler:
"""Shows a default statistic on the stats button, and allows the user to toggle which one."""
# Must match the order/index defined in gschema.xml
CHARACTERS = 0
WORDS = 1
SENTENCES = 2
PARAGRAPHS = 3
READ_TIME = 4
def __init__(self, stats_button, text_view):
super().__init__()
self.stats_button = stats_button
self.stats_button.connect("clicked", self.on_stats_button_clicked)
self.stats_button.connect("destroy", self.on_destroy)
self.text_view = text_view
self.text_view.get_buffer().connect("changed", self.on_text_changed)
self.popover = None
self.characters = 0
self.words = 0
self.sentences = 0
self.paragraphs = 0
self.read_time = (0, 0, 0)
self.settings = Settings.new()
self.stats_counter = StatsCounter(self.update_stats)
self.update_default_stat()
def on_stats_button_clicked(self, _button):
self.stats_button.set_state_flags(Gtk.StateFlags.CHECKED, False)
menu = Gio.Menu()
stats = self.settings.props.settings_schema.get_key("stat-default").get_range()[1]
for i, stat in enumerate(stats):
menu_item = Gio.MenuItem.new(self.get_text_for_stat(i), None)
menu_item.set_action_and_target_value("app.stat_default", GLib.Variant.new_string(stat))
menu.append_item(menu_item)
self.popover = Gtk.Popover.new_from_model(self.stats_button, menu)
self.popover.connect('closed', self.on_popover_closed)
self.popover.popup()
def on_popover_closed(self, _popover):
self.stats_button.unset_state_flags(Gtk.StateFlags.CHECKED)
self.popover = None
self.text_view.grab_focus()
def on_text_changed(self, buf):
self.stats_counter.count(buf.get_text(buf.get_start_iter(), buf.get_end_iter(), False))
def get_text_for_stat(self, stat):
if stat == self.CHARACTERS:
return _("{:n} Characters").format(self.characters)
elif stat == self.WORDS:
return _("{:n} Words").format(self.words)
elif stat == self.SENTENCES:
return _("{:n} Sentences").format(self.sentences)
elif stat == self.PARAGRAPHS:
return _("{:n} Paragraphs").format(self.paragraphs)
elif stat == self.READ_TIME:
return _("{:d}:{:02d}:{:02d} Read Time").format(*self.read_time)
else:
raise ValueError("Unknown stat {}".format(stat))
def update_stats(self, stats):
(characters, words, sentences, paragraphs, read_time) = stats
self.characters = characters
self.words = words
self.sentences = sentences
self.paragraphs = paragraphs
self.read_time = read_time
self.update_default_stat(False)
def update_default_stat(self, close_popover=True):
stat = self.settings.get_enum("stat-default")
text = self.get_text_for_stat(stat)
self.stats_button.set_label(text)
if close_popover and self.popover:
self.popover.popdown()
def on_destroy(self, _widget):
self.stats_counter.stop()

View File

@ -1,22 +0,0 @@
import gi
from apostrophe import helpers
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, Gio
class StyledWindow(Gtk.ApplicationWindow):
"""A window that will redraw itself upon theme changes."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Set theme css
css_provider_file = Gio.File.new_for_uri(
"resource:///de/wolfvollprecht/UberWriter/media/css/gtk/base.css")
style_provider = Gtk.CssProvider()
style_provider.load_from_file(css_provider_file)
Gtk.StyleContext.add_provider_for_screen(
self.get_screen(), style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

View File

@ -1,209 +0,0 @@
# -*- encoding: utf-8 -*-
import re
import vim
def cjk_width(text):
import sys
if sys.version_info[0] < 3:
if not isinstance(text, unicode):
text = text.decode("utf-8")
from unicodedata import east_asian_width
return sum(1+(east_asian_width(c) in "WF") for c in text)
def create_separarator(widths, char):
"""Genera una linea para separar filas de una tabla.
El parametro `widths` es un lista indicando el ancho de cada
columna. En cambio el argumento `char` es el caracter que se
tiene que utilizar para imprimir.
El valor retornado es un string.
Por ejemplo::
>>> create_separarator([2, 4], '-')
'+----+------+'
"""
line = []
for w in widths:
line.append("+" + char * (w + 2))
line.append("+")
return ''.join(line)
def create_line(columns, widths):
"""Crea una fila de la tabla separando los campos con un '|'.
El argumento `columns` es una lista con las celdas que se
quieren imprimir y el argumento `widths` tiene el ancho
de cada columna. Si la columna es mas ancha que el texto
a imprimir se agregan espacios vacíos.
Por ejemplo::
>>> create_line(['nombre', 'apellido'], [7, 10])
'| nombre | apellido |'
"""
line = zip(columns, widths)
result = []
for text, width in line:
spaces = " " * (width - cjk_width(text))
text = "| " + text + spaces + " "
result.append(text)
result.append("|")
return ''.join(result)
def create_table(content):
"""Imprime una tabla en formato restructuredText.
El argumento `content` tiene que ser una lista
de celdas.
Por ejemplo::
>>> print create_table([['software', 'vesion'], ['python', '3.2'], ['vim', '7.3']])
+----------+--------+
| software | vesion |
+==========+========+
| python | 3.2 |
+----------+--------+
| vim | 7.3 |
+----------+--------+
"""
# obtiene las columnas de toda la tabla.
columns = zip(*content)
# calcula el tamano maximo que debe tener cada columna.
widths = [max([cjk_width(x) for x in i]) for i in columns]
result = []
result.append(create_separarator(widths, '-'))
result.append(create_line(content[0], widths))
result.append(create_separarator(widths, '='))
for line in content[1:]:
result.append(create_line(line, widths))
result.append(create_separarator(widths, '-'))
return '\n'.join(result)
def are_in_a_table(current_line):
"Indica si el cursor se encuentra dentro de una tabla."
return "|" in current_line or "+" in current_line
def are_in_a_paragraph(current_line):
"Indica si la linea actual es parte de algun parrafo"
return len(current_line.strip()) >= 1
def get_table_bounds(current_row_index, are_in_callback):
"""Obtiene el numero de fila donde comienza y termina la tabla.
el argumento `are_in_callback` tiene que ser una función
que indique si una determinada linea pertenece o no
a la tabla que se quiere medir (o crear).
Retorna ambos valores como una tupla.
"""
top = 0
buffer = vim.current.buffer
max = len(buffer)
bottom = max - 1
for a in range(current_row_index, top, -1):
if not are_in_callback(buffer[a]):
top = a + 1
break
for b in range(current_row_index, max):
if not are_in_callback(buffer[b]):
bottom = b - 1
break
return top, bottom
def remove_spaces(string):
"Elimina los espacios innecesarios de una fila de tabla."
return re.sub("\s\s+", " ", string)
def create_separators_removing_spaces(string):
return re.sub("\s\s+", "|", string)
def extract_cells_as_list(string):
"Extrae el texto de una fila de tabla y lo retorna como una lista."
string = remove_spaces(string)
return [item.strip() for item in string.split('|') if item]
def extract_table(buffer, top, bottom):
full_table_text = buffer[top:bottom]
# selecciona solamente las lineas que tienen celdas con texto.
only_text_lines = [x for x in full_table_text if '|' in x]
# extrae las celdas y descarta los separadores innecesarios.
return [extract_cells_as_list(x) for x in only_text_lines]
def extract_words_as_lists(buffer, top, bottom):
"Genera una lista de palabras para crear una lista."
lines = buffer[top:bottom + 1]
return [create_separators_removing_spaces(line).split('|') for line in lines]
def copy_to_buffer(buffer, string, index):
lines = string.split('\n')
for line in lines:
buffer[index] = line
index += 1
def fix_table(current_row_index):
"""Arregla una tabla para que todas las columnas tengan el mismo ancho.
`initial_row` es un numero entero que indica en que
linea se encuenta el cursor."""
# obtiene el indice donde comienza y termina la tabla.
r1, r2 = get_table_bounds(current_row_index, are_in_a_table)
# extrae de la tabla solo las celdas de texto
table_as_list = extract_table(vim.current.buffer, r1, r2)
# genera una nueva tabla tipo restructured text y la dibuja en el buffer.
table_content = create_table(table_as_list)
copy_to_buffer(vim.current.buffer, table_content, r1)
def FixTable():
(row, col) = vim.current.window.cursor
line = vim.current.buffer[row - 1]
if are_in_a_table(line):
fix_table(row - 1)
else:
print("No estoy en una tabla. Terminando...")
def CreateTable():
(row, col) = vim.current.window.cursor
top, bottom = get_table_bounds(row - 1, are_in_a_paragraph)
lines = extract_words_as_lists(vim.current.buffer, top, bottom)
table_content = create_table(lines)
vim.current.buffer[top:bottom + 1] = table_content.split('\n')

View File

@ -1,304 +0,0 @@
import gi
from apostrophe.helpers import user_action
from apostrophe.inline_preview import InlinePreview
from apostrophe.text_view_drag_drop_handler import DragDropHandler, TARGET_URI, TARGET_TEXT
from apostrophe.text_view_format_inserter import FormatInserter
from apostrophe.text_view_markup_handler import MarkupHandler
from apostrophe.text_view_scroller import TextViewScroller
from apostrophe.text_view_undo_redo_handler import UndoRedoHandler
gi.require_version('Gtk', '3.0')
gi.require_version('Gspell', '1')
from gi.repository import Gtk, Gdk, GObject, GLib, Gspell
import logging
LOGGER = logging.getLogger('apostrophe')
class TextView(Gtk.TextView):
"""ApostropheTextView encapsulates all the features around the editor.
It combines the following:
- Undo / redo (via TextBufferUndoRedoHandler)
- Format shortcuts (via TextBufferShortcutInserter)
- Markup (via TextBufferMarkupHandler)
- Preview popover (via TextBufferMarkupHandler)
- Drag and drop (via TextViewDragDropHandler)
- Scrolling (via TextViewScroller)
- The various modes supported by Apostrophe (eg. Focus Mode, Hemingway Mode)
"""
__gsignals__ = {
'insert-italic': (GObject.SignalFlags.ACTION, None, ()),
'insert-bold': (GObject.SignalFlags.ACTION, None, ()),
'insert-hrule': (GObject.SignalFlags.ACTION, None, ()),
'insert-listitem': (GObject.SignalFlags.ACTION, None, ()),
'insert-header': (GObject.SignalFlags.ACTION, None, ()),
'insert-strikethrough': (GObject.SignalFlags.ACTION, None, ()),
'undo': (GObject.SignalFlags.ACTION, None, ()),
'redo': (GObject.SignalFlags.ACTION, None, ()),
'scroll-scale-changed': (GObject.SIGNAL_RUN_LAST, None, (float,)),
}
font_sizes = [18, 17, 16, 15, 14] # Must match CSS selectors in gtk/base.css
def __init__(self, line_chars):
super().__init__()
# Appearance
self.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
self.set_pixels_above_lines(4)
self.set_pixels_below_lines(4)
self.set_pixels_inside_wrap(8)
self.get_style_context().add_class('apostrophe-editor')
self.set_margin_left(8)
self.set_margin_right(8)
# Text sizing
self.props.halign = Gtk.Align.FILL
self.line_chars = line_chars
self.font_size = 16
self.get_style_context().add_class('size16')
# General behavior
self.connect('size-allocate', self.on_size_allocate)
self.get_buffer().connect('changed', self.on_text_changed)
self.get_buffer().connect('paste-done', self.on_paste_done)
# Spell checking
self.spellcheck = True
self.gspell_view = Gspell.TextView.get_from_gtk_text_view(self)
self.gspell_view.basic_setup()
# Undo / redo
self.undo_redo = UndoRedoHandler()
self.get_buffer().connect('begin-user-action', self.undo_redo.on_begin_user_action)
self.get_buffer().connect('end-user-action', self.undo_redo.on_end_user_action)
self.get_buffer().connect('insert-text', self.undo_redo.on_insert_text)
self.get_buffer().connect('delete-range', self.undo_redo.on_delete_range)
self.connect('undo', self.undo_redo.undo)
self.connect('redo', self.undo_redo.redo)
# Format shortcuts
self.shortcut = FormatInserter()
self.connect('insert-italic', self.shortcut.insert_italic)
self.connect('insert-bold', self.shortcut.insert_bold)
self.connect('insert-strikethrough', self.shortcut.insert_strikethrough)
self.connect('insert-hrule', self.shortcut.insert_horizontal_rule)
self.connect('insert-listitem', self.shortcut.insert_list_item)
self.connect('insert-header', self.shortcut.insert_header)
# Markup
self.markup = MarkupHandler(self)
self.connect('style-updated', self.markup.on_style_updated)
self.connect('destroy', self.markup.stop)
# Preview popover
self.preview_popover = InlinePreview(self)
# Drag and drop
self.drag_drop = DragDropHandler(self, TARGET_URI, TARGET_TEXT)
# Scrolling
self.scroller = None
self.connect('parent-set', self.on_parent_set)
self.get_buffer().connect('mark-set', self.on_mark_set)
# Focus mode
self.focus_mode = False
self.connect('button-release-event', self.on_button_release_event)
# Hemingway mode
self.hemingway_mode = False
self.connect('key-press-event', self._on_key_press_event)
# While resizing the TextView, there is unwanted scroll upwards if a top margin is present.
# When a size allocation is detected, this variable will hold the scroll to re-set until the
# UI is idle again.
# TODO: Find a better way to handle unwanted scroll.
self.frozen_scroll_scale = None
def get_text(self):
text_buffer = self.get_buffer()
start_iter = text_buffer.get_start_iter()
end_iter = text_buffer.get_end_iter()
return text_buffer.get_text(start_iter, end_iter, False)
def set_text(self, text):
"""Set text and clear undo history"""
text_buffer = self.get_buffer()
with user_action(text_buffer):
text_buffer.set_text(text)
self.undo_redo.clear()
def can_scroll(self):
return self.scroller.can_scroll()
def get_scroll_scale(self):
return self.scroller.get_scroll_scale() if self.scroller else 0
def set_scroll_scale(self, scale):
if self.scroller:
self.scroller.set_scroll_scale(scale)
def on_size_allocate(self, *_):
self.update_horizontal_margin()
self.markup.update_margins_indents()
self.queue_draw()
# TODO: Find a better way to handle unwanted scroll on resize.
self.frozen_scroll_scale = self.get_scroll_scale()
GLib.idle_add(self.unfreeze_scroll_scale)
def on_text_changed(self, *_):
self.markup.apply()
def on_paste_done(self, *_):
self.smooth_scroll_to()
def on_parent_set(self, *_):
parent = self.get_parent()
if parent:
parent.set_size_request(self.get_min_width(), 500)
self.scroller = TextViewScroller(self, parent)
parent.get_vadjustment().connect("changed", self.on_vadjustment_changed)
parent.get_vadjustment().connect("value-changed", self.on_vadjustment_changed)
else:
self.scroller = None
def on_mark_set(self, _text_buffer, _location, mark, _data=None):
if mark.get_name() == 'selection_bound':
self.markup.apply()
if not self.get_buffer().get_has_selection():
self.smooth_scroll_to(mark)
elif mark.get_name() == 'gtk_drag_target':
self.smooth_scroll_to(mark)
return True
def on_button_release_event(self, _widget, _event):
if self.focus_mode:
self.markup.apply()
return False
def on_vadjustment_changed(self, *_):
if self.frozen_scroll_scale is not None:
self.set_scroll_scale(self.frozen_scroll_scale)
elif self.can_scroll():
self.emit("scroll-scale-changed", self.get_scroll_scale())
def unfreeze_scroll_scale(self):
self.frozen_scroll_scale = None
self.queue_draw()
def set_focus_mode(self, focus_mode, hb_height):
"""Toggle focus mode.
When in focus mode, the cursor sits in the middle of the text view,
and the surrounding text is greyed out."""
self.focus_mode = focus_mode
self.update_vertical_margin(hb_size=hb_height)
self.markup.apply()
self.smooth_scroll_to()
self.set_spellcheck(self.spellcheck)
def set_spellcheck(self, spellcheck):
self.spellcheck = spellcheck
self.gspell_view.set_inline_spell_checking(self.spellcheck and not self.focus_mode)
def update_horizontal_margin(self):
width = self.get_allocation().width
# Ensure the appropriate font size is being used
for font_size in self.font_sizes:
if width >= self.get_min_width(font_size) or font_size == self.font_sizes[-1]:
if font_size != self.font_size:
self.font_size = font_size
for fs in self.font_sizes:
self.get_style_context().remove_class("size{}".format(fs))
self.get_style_context().add_class("size{}".format(font_size))
break
# Apply margin with the remaining space to allow for markup
line_width = (self.line_chars + 1) * int(self.get_char_width(self.font_size)) - 1
horizontal_margin = (width - line_width) / 2
self.props.left_margin = horizontal_margin
self.props.right_margin = horizontal_margin
def update_vertical_margin(self, top_margin=0, hb_size=0):
if self.focus_mode:
height = self.get_allocation().height + top_margin + hb_size
self.props.top_margin = height / 2 + top_margin
self.props.bottom_margin = height / 2 - top_margin
else:
self.props.top_margin = 80 + top_margin
self.props.bottom_margin = 64
def set_hemingway_mode(self, hemingway_mode):
"""Toggle hemingway mode.
When in hemingway mode, the backspace and delete keys are ignored."""
self.hemingway_mode = hemingway_mode
def clear(self):
"""Clear text and undo history"""
self.set_text('')
def smooth_scroll_to(self, mark=None):
"""Scrolls if needed to ensure mark is visible.
If mark is unspecified, the cursor is used."""
if self.scroller is None:
return
if mark is None:
mark = self.get_buffer().get_insert()
GLib.idle_add(self.scroller.smooth_scroll_to_mark, mark, self.focus_mode)
def get_min_width(self, font_size=None):
"""Returns the minimum width of this text view."""
if font_size is None:
font_size = self.font_sizes[-1]
return (self.line_chars + self.get_pad_chars(font_size) + 1) \
* self.get_char_width(font_size) - 1
def get_pad_chars(self, font_size):
"""Returns the amount of character padding for font_size.
Markup can use up to 7 in normal conditions."""
return 8 * (1 + font_size - self.font_sizes[-1])
@staticmethod
def get_char_width(font_size):
"""Returns the font width for a given size. Note: specific to Fira Mono!"""
return font_size * 1 / 1.6
def _on_key_press_event(self, _widget, event):
if self.hemingway_mode:
return event.keyval == Gdk.KEY_BackSpace or event.keyval == Gdk.KEY_Delete
if event.state & Gdk.ModifierType.SHIFT_MASK == Gdk.ModifierType.SHIFT_MASK \
and event.keyval == Gdk.KEY_ISO_Left_Tab: # Capure Shift-Tab
self._on_shift_tab()
return True
def _on_shift_tab(self):
"""Delete last character if it is a tab"""
text_buffer = self.get_buffer()
pen_iter = text_buffer.get_end_iter()
pen_iter.backward_char()
end_iter = text_buffer.get_end_iter()
if pen_iter.get_char() == "\t":
with user_action(text_buffer):
text_buffer.delete(pen_iter, end_iter)

View File

@ -1,92 +0,0 @@
import mimetypes
import urllib
from gettext import gettext as _
from os.path import basename
from apostrophe.settings import Settings
from gi.repository import Gtk
(TARGET_URI, TARGET_TEXT) = range(2)
class DragDropHandler:
TARGET_URI = None
def __init__(self, text_view, *targets):
super().__init__()
self.settings = Settings.new()
self.target_list = Gtk.TargetList.new([])
if TARGET_URI in targets:
self.target_list.add_uri_targets(TARGET_URI)
if TARGET_TEXT in targets:
self.target_list.add_text_targets(TARGET_TEXT)
text_view.drag_dest_set_target_list(self.target_list)
text_view.connect_after('drag-data-received', self.on_drag_data_received)
def on_drag_data_received(self, text_view, drag_context, _x, _y, data, info, time):
"""Handle drag and drop events"""
text_buffer = text_view.get_buffer()
if info == TARGET_URI:
uris = data.get_uris()
for uri in uris:
name = basename(urllib.parse.unquote_plus(uri))
mime = mimetypes.guess_type(uri)
if mime[0] is not None and mime[0].startswith('image/'):
basepath = self.settings.get_string("open-file-path")
basepath = urllib.parse.quote(basepath)
if uri.startswith("file://"):
uri = uri[7:]
# for handling local URIs we need to substract the basepath
# except when it is "/" (document not saved)
if uri.startswith(basepath) and basepath != "/":
uri = uri[len(basepath)+1:]
text = "![{}]({})".format(name, uri)
limit_left = 2
limit_right = len(name)
else:
text = "[{}]({})".format(name, uri)
limit_left = 1
limit_right = len(name)
elif info == TARGET_TEXT:
text = data.get_text()
# delete automatically added DnD text
insert_mark = text_buffer.get_insert()
cursor_iter_r = text_buffer.get_iter_at_mark(insert_mark)
cursor_iter_l = cursor_iter_r.copy()
cursor_iter_l.backward_chars(len(data.get_text()))
text_buffer.delete(cursor_iter_l, cursor_iter_r)
if text.startswith(("http://", "https://", "www.")):
text = "[{}]({})".format(_("web page"), text)
limit_left = 1
limit_right = len(_("web page"))
else:
limit_left = 0
limit_right = 0
text_buffer.place_cursor(text_buffer.get_iter_at_mark(
text_buffer.get_mark('gtk_drag_target')))
text_buffer.insert_at_cursor(text)
insert_mark = text_buffer.get_insert()
selection_bound = text_buffer.get_selection_bound()
cursor_iter = text_buffer.get_iter_at_mark(insert_mark)
cursor_iter.backward_chars(len(text) - limit_left)
text_buffer.move_mark(insert_mark, cursor_iter)
cursor_iter.forward_chars(limit_right)
text_buffer.move_mark(selection_bound, cursor_iter)
Gtk.drag_finish(drag_context, True, True, time)
text_view.get_toplevel().present_with_time(time)
return False

View File

@ -1,162 +0,0 @@
from gettext import gettext as _
from apostrophe.helpers import user_action
class FormatInserter:
"""Manages insertion of formatting.
Methods can be called directly, as well as be used as signal callbacks."""
def insert_italic(self, text_view, _data=None):
"""Insert italic or mark a selection as bold"""
self.__wrap(text_view, "_", _("italic text"))
def insert_bold(self, text_view, _data=None):
"""Insert bold or mark a selection as bold"""
self.__wrap(text_view, "**", _("bold text"))
def insert_strikethrough(self, text_view, _data=None):
"""Insert strikethrough or mark a selection as strikethrough"""
self.__wrap(text_view, "~~", _("strikethrough text"))
def insert_horizontal_rule(self, text_view, _data=None):
"""Insert horizontal rule"""
text_buffer = text_view.get_buffer()
with user_action(text_buffer):
text_buffer.insert_at_cursor("\n\n---\n")
text_view.scroll_mark_onscreen(text_buffer.get_insert())
def insert_list_item(self, text_view, _data=None):
"""Insert list item or mark a selection as list item"""
text_buffer = text_view.get_buffer()
if text_buffer.get_has_selection():
(start, end) = text_buffer.get_selection_bounds()
if start.starts_line():
with user_action(text_buffer):
text = text_buffer.get_text(start, end, False)
if text.startswith(("- ", "* ", "+ ")):
delete_end = start.copy()
delete_end.forward_chars(2)
text_buffer.delete(start, delete_end)
else:
text_buffer.insert(start, "- ")
else:
helptext = _("Item")
text_length = len(helptext)
cursor_mark = text_buffer.get_insert()
cursor_iter = text_buffer.get_iter_at_mark(cursor_mark)
start_ext = cursor_iter.copy()
start_ext.backward_lines(3)
text = text_buffer.get_text(cursor_iter, start_ext, False)
lines = text.splitlines()
with user_action(text_buffer):
for line in reversed(lines):
if line and line.startswith(("- ", "* ", "+ ")):
if cursor_iter.starts_line():
text_buffer.insert_at_cursor(line[:2] + helptext)
else:
text_buffer.insert_at_cursor("\n" + line[:2] + helptext)
break
else:
if not lines[-1] and not lines[-2]:
text_buffer.insert_at_cursor("- " + helptext)
elif not lines[-1]:
if cursor_iter.starts_line():
text_buffer.insert_at_cursor("- " + helptext)
else:
text_buffer.insert_at_cursor("\n- " + helptext)
else:
text_buffer.insert_at_cursor("\n\n- " + helptext)
break
self.__select_text(text_view, 0, text_length)
def insert_ordered_list_item(self, _text_view, _data=None):
# TODO: implement ordered lists
pass
def insert_header(self, text_view, _data=None):
"""Insert header or mark a selection as a list header"""
text_buffer = text_view.get_buffer()
with user_action(text_buffer):
if text_buffer.get_has_selection():
(start, end) = text_buffer.get_selection_bounds()
text = text_buffer.get_text(start, end, False)
text_buffer.delete(start, end)
else:
text = _("Header")
text_buffer.insert_at_cursor("#" + " " + text)
self.__select_text(text_view, 0, len(text))
@staticmethod
def __wrap(text_view, wrap, helptext=""):
"""Inserts wrap format to the selected text (helper text when nothing selected)"""
text_buffer = text_view.get_buffer()
with user_action(text_buffer):
if text_buffer.get_has_selection():
# Find current highlighting
(start, end) = text_buffer.get_selection_bounds()
moved = False
if (start.get_offset() >= len(wrap) and
end.get_offset() <= text_buffer.get_char_count() - len(wrap)):
moved = True
ext_start = start.copy()
ext_start.backward_chars(len(wrap))
ext_end = end.copy()
ext_end.forward_chars(len(wrap))
text = text_buffer.get_text(ext_start, ext_end, True)
else:
text = text_buffer.get_text(start, end, True)
if moved and text.startswith(wrap) and text.endswith(wrap):
text = text[len(wrap):-len(wrap)]
new_text = text
text_buffer.delete(ext_start, ext_end)
move_back = 0
else:
if moved:
text = text[len(wrap):-len(wrap)]
new_text = text.lstrip().rstrip()
text = text.replace(new_text, wrap + new_text + wrap)
text_buffer.delete(start, end)
move_back = len(wrap)
text_buffer.insert_at_cursor(text)
text_length = len(new_text)
else:
text_buffer.insert_at_cursor(wrap + helptext + wrap)
text_length = len(helptext)
move_back = len(wrap)
cursor_mark = text_buffer.get_insert()
cursor_iter = text_buffer.get_iter_at_mark(cursor_mark)
cursor_iter.backward_chars(move_back)
text_buffer.move_mark_by_name('selection_bound', cursor_iter)
cursor_iter.backward_chars(text_length)
text_buffer.move_mark_by_name('insert', cursor_iter)
@staticmethod
def __select_text(text_view, offset, length):
"""Selects text starting at the current cursor minus offset, length characters."""
text_buffer = text_view.get_buffer()
cursor_mark = text_buffer.get_insert()
cursor_iter = text_buffer.get_iter_at_mark(cursor_mark)
cursor_iter.backward_chars(offset)
text_buffer.move_mark_by_name('selection_bound', cursor_iter)
cursor_iter.backward_chars(length)
text_buffer.move_mark_by_name('insert', cursor_iter)

View File

@ -1,386 +0,0 @@
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2019, Wolf Vollprecht <w.vollprecht@gmail.com>
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE
import re
from multiprocessing import Pipe, Process
import gi
from apostrophe import helpers, markup_regex
from apostrophe.markup_regex import STRIKETHROUGH, BOLD_ITALIC, BOLD, ITALIC_ASTERISK, ITALIC_UNDERSCORE, IMAGE, LINK,\
LINK_ALT, HORIZONTAL_RULE, LIST, ORDERED_LIST, BLOCK_QUOTE, HEADER, HEADER_UNDER, TABLE, MATH, \
CODE
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
from gi.repository import Pango
class MarkupHandler:
TAG_NAME_ITALIC = 'italic'
TAG_NAME_BOLD = 'bold'
TAG_NAME_BOLD_ITALIC = 'bold_italic'
TAG_NAME_STRIKETHROUGH = 'strikethrough'
TAG_NAME_CENTER = 'center'
TAG_NAME_WRAP_NONE = 'wrap_none'
TAG_NAME_PLAIN_TEXT = 'plain_text'
TAG_NAME_GRAY_TEXT = 'gray_text'
TAG_NAME_CODE_TEXT = 'code_text'
TAG_NAME_CODE_BLOCK = 'code_block'
TAG_NAME_UNFOCUSED_TEXT = 'unfocused_text'
TAG_NAME_MARGIN_INDENT = 'margin_indent'
def __init__(self, text_view):
self.text_view = text_view
self.text_buffer = text_view.get_buffer()
self.marked_up_text = None
# Tags.
buffer = self.text_buffer
self.tag_italic = buffer.create_tag(self.TAG_NAME_ITALIC,
weight=Pango.Weight.NORMAL,
style=Pango.Style.ITALIC)
self.tag_bold = buffer.create_tag(self.TAG_NAME_BOLD,
weight=Pango.Weight.BOLD,
style=Pango.Style.NORMAL)
self.tag_bold_italic = buffer.create_tag(self.TAG_NAME_BOLD_ITALIC,
weight=Pango.Weight.BOLD,
style=Pango.Style.ITALIC)
self.tag_strikethrough = buffer.create_tag(self.TAG_NAME_STRIKETHROUGH,
strikethrough=True)
self.tag_center = buffer.create_tag(self.TAG_NAME_CENTER,
justification=Gtk.Justification.CENTER)
self.tag_wrap_none = buffer.create_tag(self.TAG_NAME_WRAP_NONE,
wrap_mode=Gtk.WrapMode.NONE,
pixels_above_lines=0,
pixels_below_lines=0)
self.tag_plain_text = buffer.create_tag(self.TAG_NAME_PLAIN_TEXT,
weight=Pango.Weight.NORMAL,
style=Pango.Style.NORMAL,
strikethrough=False,
justification=Gtk.Justification.LEFT)
self.tag_gray_text = buffer.create_tag(self.TAG_NAME_GRAY_TEXT,
foreground='gray',
weight=Pango.Weight.NORMAL,
style=Pango.Style.NORMAL)
self.tag_code_text = buffer.create_tag(self.TAG_NAME_CODE_TEXT,
weight=Pango.Weight.NORMAL,
style=Pango.Style.NORMAL,
strikethrough=False)
self.tag_code_block = buffer.create_tag(self.TAG_NAME_CODE_BLOCK,
weight=Pango.Weight.NORMAL,
style=Pango.Style.NORMAL,
strikethrough=False,
indent=self.get_margin_indent(0, 1)[1])
self.tags_markup = {
self.TAG_NAME_ITALIC: lambda args: self.tag_italic,
self.TAG_NAME_BOLD: lambda args: self.tag_bold,
self.TAG_NAME_BOLD_ITALIC: lambda args: self.tag_bold_italic,
self.TAG_NAME_STRIKETHROUGH: lambda args: self.tag_strikethrough,
self.TAG_NAME_CENTER: lambda args: self.tag_center,
self.TAG_NAME_WRAP_NONE: lambda args: self.tag_wrap_none,
self.TAG_NAME_PLAIN_TEXT: lambda args: self.tag_plain_text,
self.TAG_NAME_GRAY_TEXT: lambda args: self.tag_gray_text,
self.TAG_NAME_CODE_TEXT: lambda args: self.tag_code_text,
self.TAG_NAME_CODE_BLOCK: lambda args: self.tag_code_block,
self.TAG_NAME_MARGIN_INDENT: lambda args: self.get_margin_indent_tag(*args)
}
# Focus mode.
self.tag_unfocused_text = buffer.create_tag(self.TAG_NAME_UNFOCUSED_TEXT,
foreground='gray',
weight=Pango.Weight.NORMAL,
style=Pango.Style.NORMAL)
# Margin and indents.
# A baseline margin is set to allow negative offsets for formatting headers, lists, etc.
self.tags_margins_indents = {}
self.baseline_margin = 0
self.char_width = 0
self.update_margins_indents()
# Style.
self.on_style_updated()
# Worker process to handle parsing.
self.parsing = False
self.apply_pending = False
self.parent_conn, child_conn = Pipe()
Process(target=self.parse, args=(child_conn,), daemon=True).start()
GLib.io_add_watch(
self.parent_conn.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, self.on_parsed)
def on_style_updated(self, *_):
style_context = self.text_view.get_style_context()
(found, color) = style_context.lookup_color('code_bg_color')
if not found:
(_, color) = style_context.lookup_color('background_color')
self.tag_code_text.set_property("background", color.to_string())
self.tag_code_block.set_property("paragraph-background", color.to_string())
def apply(self):
"""Applies markup, parsing it in a worker process if the text has changed.
In case parsing is already running, it will re-apply once it finishes. This ensure that
the pipe doesn't fill (and block) if multiple requests are made in quick succession."""
if not self.parsing:
self.parsing = True
self.apply_pending = False
text = self.text_buffer.get_slice(
self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False)
if text != self.marked_up_text:
self.parent_conn.send(text)
else:
self.do_apply(text)
else:
self.apply_pending = True
def parse(self, child_conn):
"""Parses markup in a worker process."""
while True:
while True:
try:
text = child_conn.recv()
if not child_conn.poll():
break
except EOFError:
child_conn.close()
return
# List of tuples in the form (tag_name, tag_args, tag_start, tag_end).
result = []
# Find:
# - "_italic_" (italic)
# - "**bold**" (bold)
# - "***bolditalic***" (bold/italic)
# - "~~strikethrough~~" (strikethrough)
# - "`code`" (colorize)
# - "$math$" (colorize)
# - "---" table (wrap/pixels)
regexps = (
(ITALIC_ASTERISK, self.TAG_NAME_ITALIC),
(ITALIC_UNDERSCORE, self.TAG_NAME_ITALIC),
(BOLD, self.TAG_NAME_BOLD),
(BOLD_ITALIC, self.TAG_NAME_BOLD_ITALIC),
(STRIKETHROUGH, self.TAG_NAME_STRIKETHROUGH),
(CODE, self.TAG_NAME_CODE_TEXT),
(MATH, self.TAG_NAME_CODE_TEXT),
(TABLE, self.TAG_NAME_WRAP_NONE)
)
for regexp, tag_name in regexps:
matches = re.finditer(regexp, text)
for match in matches:
result.append((tag_name, (), match.start(), match.end()))
# Find:
# - "[description](url)" (gray out)
# - "![description](image_url)" (gray out)
regexps = (
(LINK, self.TAG_NAME_GRAY_TEXT),
(IMAGE, self.TAG_NAME_GRAY_TEXT)
)
for regexp, tag_name in regexps:
matches = re.finditer(regexp, text)
for match in matches:
result.append((tag_name, (), match.start(), match.start("text")))
result.append((tag_name, (), match.end("text"), match.end()))
# Find "<url>" links (gray out).
matches = re.finditer(LINK_ALT, text)
for match in matches:
result.append((
self.TAG_NAME_GRAY_TEXT, (), match.start("text"), match.end("text")))
# Find "---" horizontal rule (center).
matches = re.finditer(HORIZONTAL_RULE, text)
for match in matches:
result.append((
self.TAG_NAME_CENTER, (), match.start("symbols"), match.end("symbols")))
# Find "* list" (offset).
matches = re.finditer(LIST, text)
for match in matches:
# Lists use character+space (eg. "* ").
length = 2
nest = len(match.group("indent").replace(" ", "\t"))
margin = -length - 2 * nest
indent = -length - 2 * length * nest
result.append((
self.TAG_NAME_MARGIN_INDENT,
(margin, indent),
match.start("content"),
match.end("content")
))
# Find "1. ordered list" (offset).
matches = re.finditer(ORDERED_LIST, text)
for match in matches:
# Ordered lists use numbers/letters+dot/parens+space (eg. "123. ").
length = len(match.group("prefix")) + 1
nest = len(match.group("indent").replace(" ", "\t"))
margin = -length - 2 * nest
indent = -length - 2 * length * nest
result.append((
self.TAG_NAME_MARGIN_INDENT,
(margin, indent),
match.start("content"),
match.end("content")
))
# Find "> blockquote" (offset).
matches = re.finditer(BLOCK_QUOTE, text)
for match in matches:
result.append((self.TAG_NAME_MARGIN_INDENT, (2, -2), match.start(), match.end()))
# Find "# Header" (offset+bold).
matches = re.finditer(HEADER, text)
for match in matches:
margin = -len(match.group("level")) - 1
result.append((
self.TAG_NAME_MARGIN_INDENT, (margin, 0), match.start(), match.end()))
result.append((self.TAG_NAME_BOLD, (), match.start(), match.end()))
# Find "=======" header underline (bold).
matches = re.finditer(HEADER_UNDER, text)
for match in matches:
result.append((self.TAG_NAME_BOLD, (), match.start(), match.end()))
# Find "```" code block tag (offset + colorize paragraph).
matches = re.finditer(markup_regex.CODE_BLOCK, text)
for match in matches:
result.append((
self.TAG_NAME_CODE_BLOCK, (), match.start("block"), match.end("block")))
# Send parsed data back.
child_conn.send((text, result))
def on_parsed(self, _source, _condition):
"""Reads the parsing result from the pipe and triggers any pending apply."""
self.parsing = False
if self.apply_pending:
self.apply() # self.apply clears the apply pending flag.
try:
if self.parent_conn.poll():
self.do_apply(*self.parent_conn.recv())
return True
except EOFError:
return False
def do_apply(self, original_text, result=[]):
"""Applies the result of parsing if the current text matches the original text."""
buffer = self.text_buffer
start = buffer.get_start_iter()
end = buffer.get_end_iter()
text = self.text_buffer.get_slice(start, end, False)
# Apply markup tags.
if text == original_text and text != self.marked_up_text:
buffer.remove_tag(self.tag_italic, start, end)
buffer.remove_tag(self.tag_bold, start, end)
buffer.remove_tag(self.tag_bold_italic, start, end)
buffer.remove_tag(self.tag_strikethrough, start, end)
buffer.remove_tag(self.tag_center, start, end)
buffer.remove_tag(self.tag_plain_text, start, end)
buffer.remove_tag(self.tag_gray_text, start, end)
buffer.remove_tag(self.tag_code_text, start, end)
buffer.remove_tag(self.tag_code_block, start, end)
buffer.remove_tag(self.tag_wrap_none, start, end)
for tag in self.tags_margins_indents.values():
buffer.remove_tag(tag, start, end)
for tag_name, tag_args, tag_start, tag_end in result:
buffer.apply_tag(
self.tags_markup[tag_name](tag_args),
buffer.get_iter_at_offset(tag_start),
buffer.get_iter_at_offset(tag_end))
# Apply focus mode tag (grey out before/after current sentence).
buffer.remove_tag(self.tag_unfocused_text, start, end)
if self.text_view.focus_mode:
cursor_iter = buffer.get_iter_at_mark(buffer.get_insert())
start_sentence = cursor_iter.copy()
start_sentence.backward_sentence_start()
end_sentence = cursor_iter.copy()
end_sentence.forward_sentence_end()
buffer.apply_tag(self.tag_unfocused_text, start, start_sentence)
buffer.apply_tag(self.tag_unfocused_text, end_sentence, end)
# Margin and indent are cumulative. They differ in two ways:
# * Margin is always in the beginning, which means it effectively only affects the first line
# of multi-line text. Indent is applied to every line.
# * Margin level can be negative, as a baseline margin exists from which it can be subtracted.
# Indent is always positive, or 0.
def get_margin_indent_tag(self, margin_level, indent_level):
level = (margin_level, indent_level)
if level not in self.tags_margins_indents:
margin, indent = self.get_margin_indent(margin_level, indent_level)
tag = self.text_buffer.create_tag(
"margin_indent_{}_{}".format(margin_level, indent_level),
left_margin=margin, indent=indent)
self.tags_margins_indents[level] = tag
return tag
else:
return self.tags_margins_indents[level]
def get_margin_indent(self, margin_level, indent_level, baseline_margin=None, char_width=None):
if baseline_margin is None:
baseline_margin = self.text_view.props.left_margin
if char_width is None:
char_width = helpers.get_char_width(self.text_view)
margin = max(baseline_margin + char_width * margin_level, 0)
indent = char_width * indent_level
return margin, indent
def update_margins_indents(self):
baseline_margin = self.text_view.props.left_margin
char_width = helpers.get_char_width(self.text_view)
# Bail out if neither the baseline margin nor character width change
if baseline_margin == self.baseline_margin and char_width == self.char_width:
return
self.baseline_margin = baseline_margin
self.char_width = char_width
# Adjust tab size
tab_array = Pango.TabArray.new(1, True)
tab_array.set_tab(0, Pango.TabAlign.LEFT, 4 * char_width)
self.text_view.set_tabs(tab_array)
# Adjust margins and indents
for level, tag in self.tags_margins_indents.items():
margin, indent = self.get_margin_indent(*level, baseline_margin, char_width)
tag.set_properties(left_margin=margin, indent=indent)
def stop(self, *_):
self.parent_conn.close()

View File

@ -1,110 +0,0 @@
class TextViewScroller:
def __init__(self, text_view, scrolled_window):
super().__init__()
self.text_view = text_view
self.scrolled_window = scrolled_window
self.smooth_scroller = None
def can_scroll(self):
vap = self.scrolled_window.get_vadjustment().props
return vap.upper > vap.page_size
def get_scroll_scale(self):
vap = self.scrolled_window.get_vadjustment().props
if vap.upper > vap.page_size:
return vap.value / (vap.upper - vap.page_size)
else:
return 0
def set_scroll_scale(self, scale):
vap = self.scrolled_window.get_vadjustment().props
vap.value = (vap.upper - vap.page_size) * scale
def scroll_to_mark(self, mark, center):
"""Scrolls until mark is visible, if needed."""
target_pos = self.get_target_pos_for_mark(mark, center)
if target_pos:
self.scrolled_window.get_vadjustment().set_value(target_pos)
def smooth_scroll_to_mark(self, mark, center):
"""Smoothly scrolls until mark is visible, if needed."""
if self.smooth_scroller and self.smooth_scroller.is_started:
self.smooth_scroller.end()
target_pos = self.get_target_pos_for_mark(mark, center)
if target_pos:
source_pos = self.scrolled_window.get_vadjustment().props.value
self.smooth_scroller = SmoothScroller(self.scrolled_window, source_pos, target_pos)
self.smooth_scroller.start()
def get_target_pos_for_mark(self, mark, center):
margin = 32
mark_iter = self.text_view.get_buffer().get_iter_at_mark(mark)
mark_rect = self.text_view.get_iter_location(mark_iter)
vap = self.scrolled_window.get_vadjustment().props
pos_y = mark_rect.y + mark_rect.height + self.text_view.props.top_margin
pos_viewport_y = pos_y - vap.value
target_pos = None
if center:
if pos_viewport_y != vap.page_size / 2:
target_pos = pos_y - (vap.page_size / 2)
elif pos_viewport_y > vap.page_size - margin:
target_pos = pos_y - vap.page_size + margin
elif pos_viewport_y < margin:
target_pos = pos_y - margin - mark_rect.height
return target_pos
class SmoothScroller:
def __init__(self, scrolled_window, source_pos, target_pos):
super().__init__()
self.scrolled_window = scrolled_window
self.source_pos = source_pos
self.target_pos = target_pos
self.duration = max(100, (target_pos - source_pos) / 50) * 1000
self.is_started = False
self.is_setup = False
self.start_time = 0
self.end_time = 0
self.tick_callback_id = 0
def start(self):
self.is_started = True
self.tick_callback_id = self.scrolled_window.add_tick_callback(self.on_tick)
def end(self):
self.scrolled_window.remove_tick_callback(self.tick_callback_id)
self.is_started = False
def setup(self, time):
self.start_time = time
self.end_time = time + self.duration
self.is_setup = True
def on_tick(self, widget, frame_clock):
def ease_out_cubic(value):
return pow(value - 1, 3) + 1
now = frame_clock.get_frame_time()
if not self.is_setup:
self.setup(now)
if now < self.end_time:
time = float(now - self.start_time) / float(self.end_time - self.start_time)
else:
time = 1
self.end()
time = ease_out_cubic(time)
pos = self.source_pos + (time * (self.target_pos - self.source_pos))
widget.get_vadjustment().props.value = pos
return True

View File

@ -1,223 +0,0 @@
import logging
LOGGER = logging.getLogger('apostrophe')
class UndoableInsert:
"""Something has been inserted into text_buffer"""
def __init__(self, text_iter, text, length):
self.offset = text_iter.get_offset()
self.text = text
self.length = length
self.mergeable = not bool(self.length > 1 or self.text in ("\r", "\n", " "))
def undo(self, text_buffer):
offset = self.offset
start = text_buffer.get_iter_at_offset(offset)
stop = text_buffer.get_iter_at_offset(offset + self.length)
text_buffer.place_cursor(start)
text_buffer.delete(start, stop)
def redo(self, text_buffer):
start = text_buffer.get_iter_at_offset(self.offset)
text_buffer.insert(start, self.text)
new_cursor_pos = text_buffer.get_iter_at_offset(self.offset + self.length)
text_buffer.place_cursor(new_cursor_pos)
def merge(self, next_action):
"""Merge a following action into this insert, if possible
can't merge if prev is not another insert
can't merge if prev and cur are not mergeable in the first place
can't merge when user set the input bar somewhere else
can't merge across word boundaries"""
if not isinstance(next_action, UndoableInsert):
return False
if not self.mergeable or not next_action.mergeable:
return False
if self.offset + self.length != next_action.offset:
return False
whitespace = (' ', '\t')
if self.text in whitespace != next_action.text in whitespace:
return False
self.length += next_action.length
self.text += next_action.text
return True
class UndoableDelete:
"""Something has been deleted from text_buffer"""
def __init__(self, text_buffer, start_iter, end_iter):
self.text = text_buffer.get_text(start_iter, end_iter, False)
self.start = start_iter.get_offset()
self.end = end_iter.get_offset()
# Find out if backspace or delete were used to not mess up redo
insert_iter = text_buffer.get_iter_at_mark(text_buffer.get_insert())
self.delete_key_used = bool(insert_iter.get_offset() <= self.start)
self.mergeable = not bool(self.end - self.start > 1 or self.text in ("\r", "\n", " "))
def undo(self, text_buffer):
start = text_buffer.get_iter_at_offset(self.start)
text_buffer.insert(start, self.text)
if self.delete_key_used:
text_buffer.place_cursor(start)
else:
stop = text_buffer.get_iter_at_offset(self.end)
text_buffer.place_cursor(stop)
def redo(self, text_buffer):
start = text_buffer.get_iter_at_offset(self.start)
stop = text_buffer.get_iter_at_offset(self.end)
text_buffer.delete(start, stop)
text_buffer.place_cursor(start)
def merge(self, next_action):
"""Check if this delete can be merged with a previous action
can't merge if prev is not another delete
can't merge if prev and cur are not mergeable in the first place
can't merge if delete and backspace key were both used
can't merge across word boundaries"""
if not isinstance(next_action, UndoableDelete):
return False
if not self.mergeable or not next_action.mergeable:
return False
if self.delete_key_used != next_action.delete_key_used:
return False
if self.start != next_action.start and self.start != next_action.end:
return False
whitespace = (' ', '\t')
if self.text in whitespace != next_action.text in whitespace:
return False
if self.delete_key_used:
self.text += next_action.text
self.end += (next_action.end - next_action.start)
else:
self.text = "%s%s" % (next_action.text, next_action.text)
self.start = next_action.start
return True
class UndoableGroup(list):
"""A list of undoable actions, usually corresponding to a single user action"""
def undo(self, text_buffer):
for undoable in reversed(self):
undoable.undo(text_buffer)
def redo(self, text_buffer):
for undoable in self:
undoable.redo(text_buffer)
def merge(self, next_action):
if len(self) == 1:
return self[0].merge(next_action)
else:
return False
class UndoRedoHandler:
"""Manages undo/redo for a given text_buffer.
Methods can be called directly, as well as be used as signal callbacks."""
def __init__(self):
self.undo_stack = []
self.redo_stack = []
self.current_undo_group = None
self.undo_in_progress = False
def undo(self, text_view, _data=None):
"""Undo insertions or deletions. Undone actions are moved to redo stack.
This method can be registered to a custom undo signal, or used independently."""
if not self.undo_stack:
return
self.undo_in_progress = True
undo_action = self.undo_stack.pop()
self.redo_stack.append(undo_action)
undo_action.undo(text_view.get_buffer())
self.undo_in_progress = False
def redo(self, text_view, _data=None):
"""Redo insertions or deletions. Redone actions are moved to undo stack
This method can be registered to a custom redo signal, or used independently."""
if not self.redo_stack:
return
self.undo_in_progress = True
redo_action = self.redo_stack.pop()
self.undo_stack.append(redo_action)
redo_action.redo(text_view.get_buffer())
self.undo_in_progress = False
def clear(self):
self.undo_stack = []
self.redo_stack = []
def on_begin_user_action(self, _text_buffer):
"""Start of a user action. Refer to TextBuffer's "begin-user-action" signal.
This method must be registered to TextBuffer's "begin-user-action" signal, or called
manually followed by on_end_user_action."""
self.current_undo_group = UndoableGroup()
def on_end_user_action(self, _text_buffer):
"""End of a user action. Refer to TextBuffer's "end-user-action" signal.
This method must be registered to TextBuffer's "end-user-action" signal, or called
manually preceded by on_start_user_action."""
if self.current_undo_group:
self.undo_stack.append(self.current_undo_group)
self.current_undo_group = None
def on_insert_text(self, _text_buffer, text_iter, text, _length):
"""Records a text insert. Refer to TextBuffer's "insert-text" signal.
This method must be registered to TextBuffer's "insert-text" signal, or called manually
in between on_begin_user_action and on_end_user_action."""
self.__record_undoable(UndoableInsert(text_iter, text, len(text)))
def on_delete_range(self, text_buffer, start_iter, end_iter):
"""Records a range deletion. Refer to TextBuffer's "delete-range" signal.
This method must be registered to TextBuffer's "delete-range" signal, or called manually
in between on_begin_user_action and on_end_user_action."""
self.__record_undoable(UndoableDelete(text_buffer, start_iter, end_iter))
def __record_undoable(self, undoable):
"""Records a change, merging it to a previous one if possible."""
if not self.undo_in_progress:
self.redo_stack = []
else:
return
prev_group_undoable = self.current_undo_group[-1] if self.current_undo_group else None
prev_stack_undoable = self.undo_stack[-1] if self.undo_stack else None
if prev_group_undoable:
merged = prev_group_undoable.merge(undoable)
elif prev_stack_undoable:
merged = prev_stack_undoable.merge(undoable)
else:
merged = False
if not merged:
if self.current_undo_group is None:
LOGGER.warning("Recording a change without a user action.")
self.undo_stack.append(undoable)
else:
self.current_undo_group.append(undoable)

View File

@ -1,66 +0,0 @@
from gi.repository import Gtk
from apostrophe.settings import Settings
from apostrophe.helpers import get_css_path
class Theme:
"""
The Theme enum lists all supported themes using their "gtk-theme-name" value.
The light variant is listed first, followed by the dark variant, if any.
"""
previous = None
settings = Settings.new()
def __init__(self, name, web_css_path, is_dark, inverse_name):
self.name = name
self.web_css_path = web_css_path
self.is_dark = is_dark
self.inverse_name = inverse_name
@classmethod
def get_for_name(cls, name, default=None):
current_theme = default or defaultThemes[0]
for theme in defaultThemes:
if name == theme.name:
current_theme = theme
return current_theme
@classmethod
def get_current_changed(cls):
theme_name = Gtk.Settings.get_default().get_property('gtk-theme-name')
dark_mode = cls.settings.get_boolean('dark-mode')
current_theme = cls.get_for_name(theme_name)
if dark_mode != current_theme.is_dark and current_theme.inverse_name:
current_theme = cls.get_for_name(current_theme.inverse_name, current_theme.name)
changed = current_theme != cls.previous
cls.previous = current_theme
return current_theme, changed
@classmethod
def get_current(cls):
current_theme, _ = cls.get_current_changed()
return current_theme
def __eq__(self, other):
return isinstance(other, self.__class__) and \
self.name == other.name and \
self.web_css_path == other.web_css_path and \
self.is_dark == other.is_dark and \
self.inverse_name == other.inverse_name
defaultThemes = [
# https://gitlab.gnome.org/GNOME/gtk/tree/master/gtk/theme/Adwaita
Theme('Adwaita', get_css_path('web/adwaita.css'), False, 'Adwaita-dark'),
Theme('Adwaita-dark', get_css_path('web/adwaita.css'), True, 'Adwaita'),
# https://github.com/NicoHood/arc-theme/tree/master/common/gtk-3.0/3.20/sass
Theme('Arc', get_css_path('web/arc.css'), False, 'Arc-Dark'),
Theme('Arc-Darker', get_css_path('web/arc.css'), False, 'Arc-Dark'),
Theme('Arc-Dark', get_css_path('web/arc.css'), True, 'Arc'),
# https://gitlab.gnome.org/GNOME/gtk/tree/master/gtk/theme/HighContrast
Theme('HighContrast', get_css_path('web/highcontrast.css'), False, 'HighContrastInverse'),
Theme('HighContrastInverse', get_css_path('web/highcontrast_inverse.css'), True, 'HighContrast')
]

View File

@ -0,0 +1,847 @@
/*!
* jQuery Scrollify
* Version 1.0.19
*
* Requires:
* - jQuery 1.7 or higher
*
* https://github.com/lukehaas/Scrollify
*
* Copyright 2016, Luke Haas
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* 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:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* 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 AUTHORS 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 IN THE SOFTWARE.
if touchScroll is false - update index
*/
(function (global,factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'), global, global.document);
} else {
// Browser globals
factory(jQuery, global, global.document);
}
}(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) {
"use strict";
var heights = [],
names = [],
elements = [],
overflow = [],
index = 0,
currentIndex = 0,
interstitialIndex = 1,
hasLocation = false,
timeoutId,
timeoutId2,
$window = $(window),
portHeight,
top = $window.scrollTop(),
scrollable = false,
locked = false,
scrolled = false,
manualScroll,
swipeScroll,
util,
disabled = false,
scrollSamples = [],
scrollTime = new Date().getTime(),
firstLoad = true,
initialised = false,
destination = 0,
wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll',
settings = {
//section should be an identifier that is the same for each section
section: ".section",
sectionName: "section-name",
interstitialSection: "",
easing: "easeOutExpo",
scrollSpeed: 1100,
offset: 0,
scrollbars: true,
target:"html,body",
standardScrollElements: false,
setHeights: true,
overflowScroll:true,
updateHash: true,
touchScroll:true,
before:function() {},
after:function() {},
afterResize:function() {},
afterRender:function() {}
};
function getportHeight() {
return ($window.height() + settings.offset);
}
function animateScroll(index,instant,callbacks,toTop) {
if(currentIndex===index) {
callbacks = false;
}
if(disabled===true) {
return true;
}
if(names[index]) {
scrollable = false;
if(firstLoad===true) {
settings.afterRender();
firstLoad = false;
}
if(callbacks) {
if( typeof settings.before == 'function' && settings.before(index,elements) === false ){
return true;
}
}
interstitialIndex = 1;
destination = heights[index];
if(firstLoad===false && currentIndex>index && toTop===false) {
//We're going backwards
if(overflow[index]) {
portHeight = getportHeight();
interstitialIndex = parseInt(elements[index].outerHeight()/portHeight);
destination = parseInt(heights[index])+(elements[index].outerHeight()-portHeight);
}
}
if(settings.updateHash && settings.sectionName && !(firstLoad===true && index===0)) {
if(history.pushState) {
try {
history.replaceState(null, null, names[index]);
} catch (e) {
if(window.console) {
console.warn("Scrollify warning: Page must be hosted to manipulate the hash value.");
}
}
} else {
window.location.hash = names[index];
}
}
currentIndex = index;
if(instant) {
$(settings.target).stop().scrollTop(destination);
if(callbacks) {
settings.after(index,elements);
}
} else {
locked = true;
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: destination,
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: destination
}, settings.scrollSpeed,settings.easing);
}
if(window.location.hash.length && settings.sectionName && window.console) {
try {
if($(window.location.hash).length) {
console.warn("Scrollify warning: ID matches hash value - this will cause the page to anchor.");
}
} catch (e) {}
}
$(settings.target).promise().done(function(){
locked = false;
firstLoad = false;
if(callbacks) {
settings.after(index,elements);
}
});
}
}
}
function isAccelerating(samples) {
function average(num) {
var sum = 0;
var lastElements = samples.slice(Math.max(samples.length - num, 1));
for(var i = 0; i < lastElements.length; i++){
sum += lastElements[i];
}
return Math.ceil(sum/num);
}
var avEnd = average(10);
var avMiddle = average(70);
if(avEnd >= avMiddle) {
return true;
} else {
return false;
}
}
var scrollify = function(options) {
initialised = true;
$.easing['easeOutExpo'] = function(x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};
manualScroll = {
handleMousedown:function() {
if(disabled===true) {
return true;
}
scrollable = false;
scrolled = false;
},
handleMouseup:function() {
if(disabled===true) {
return true;
}
scrollable = true;
if(scrolled) {
//instant,callbacks
manualScroll.calculateNearest(false,true);
}
},
handleScroll:function() {
if(disabled===true) {
return true;
}
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function(){
scrolled = true;
if(scrollable===false) {
return false;
}
scrollable = false;
//instant,callbacks
manualScroll.calculateNearest(false,true);
}, 200);
},
calculateNearest:function(instant,callbacks) {
top = $window.scrollTop();
var i =1,
max = heights.length,
closest = 0,
prev = Math.abs(heights[0] - top),
diff;
for(;i<max;i++) {
diff = Math.abs(heights[i] - top);
if(diff < prev) {
prev = diff;
closest = i;
}
}
if((atBottom() && closest>index) || atTop()) {
index = closest;
//index, instant, callbacks, toTop
animateScroll(closest,instant,callbacks,false);
}
},
wheelHandler:function(e) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
return true;
}
}
if(!overflow[index]) {
e.preventDefault();
}
var currentScrollTime = new Date().getTime();
e = e || window.event;
var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail;
var delta = Math.max(-1, Math.min(1, value));
//delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;
if(scrollSamples.length > 149){
scrollSamples.shift();
}
//scrollSamples.push(Math.abs(delta*10));
scrollSamples.push(Math.abs(value));
if((currentScrollTime-scrollTime) > 200){
scrollSamples = [];
}
scrollTime = currentScrollTime;
if(locked) {
return false;
}
if(delta<0) {
if(index<heights.length-1) {
if(atBottom()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index++;
locked = true;
//index, instant, callbacks, toTop
animateScroll(index,false,true, false);
} else {
return false;
}
}
}
} else if(delta>0) {
if(index>0) {
if(atTop()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index--;
locked = true;
//index, instant, callbacks, toTop
animateScroll(index,false,true, false);
} else {
return false
}
}
}
}
},
keyHandler:function(e) {
if(disabled===true || document.activeElement.readOnly===false) {
return true;
} else if(settings.standardScrollElements) {
if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
return true;
}
}
if(locked===true) {
return false;
}
if(e.keyCode==38 || e.keyCode==33) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks, toTop
animateScroll(index,false,true,false);
}
}
} else if(e.keyCode==40 || e.keyCode==34) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks, toTop
animateScroll(index,false,true,false);
}
}
}
},
init:function() {
if(settings.scrollbars) {
$window.on('mousedown', manualScroll.handleMousedown);
$window.on('mouseup', manualScroll.handleMouseup);
$window.on('scroll', manualScroll.handleScroll);
} else {
$("body").css({"overflow":"hidden"});
}
$window.on(wheelEvent,manualScroll.wheelHandler);
//$(document).bind(wheelEvent,manualScroll.wheelHandler);
$window.on('keydown', manualScroll.keyHandler);
}
};
swipeScroll = {
touches : {
"touchstart": {"y":-1,"x":-1},
"touchmove" : {"y":-1,"x":-1},
"touchend" : false,
"direction" : "undetermined"
},
options:{
"distance" : 30,
"timeGap" : 800,
"timeStamp" : new Date().getTime()
},
touchHandler: function(event) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) {
return true;
}
}
var touch;
if (typeof event !== 'undefined'){
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
swipeScroll.touches.touchstart.y = touch.pageY;
swipeScroll.touches.touchmove.y = -1;
swipeScroll.touches.touchstart.x = touch.pageX;
swipeScroll.touches.touchmove.x = -1;
swipeScroll.options.timeStamp = new Date().getTime();
swipeScroll.touches.touchend = false;
case 'touchmove':
swipeScroll.touches.touchmove.y = touch.pageY;
swipeScroll.touches.touchmove.x = touch.pageX;
if(swipeScroll.touches.touchstart.y!==swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y-swipeScroll.touches.touchmove.y)>Math.abs(swipeScroll.touches.touchstart.x-swipeScroll.touches.touchmove.x))) {
//if(!overflow[index]) {
event.preventDefault();
//}
swipeScroll.touches.direction = "y";
if((swipeScroll.options.timeStamp+swipeScroll.options.timeGap)<(new Date().getTime()) && swipeScroll.touches.touchend == false) {
swipeScroll.touches.touchend = true;
if (swipeScroll.touches.touchstart.y > -1) {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
}
}
}
break;
case 'touchend':
if(swipeScroll.touches[event.type]===false) {
swipeScroll.touches[event.type] = true;
if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction==="y") {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
swipeScroll.touches.touchstart.y = -1;
swipeScroll.touches.touchstart.x = -1;
swipeScroll.touches.direction = "undetermined";
}
}
default:
break;
}
}
}
},
down: function() {
if(index<heights.length) {
if(atBottom() && index<heights.length-1) {
index++;
//index, instant, callbacks, toTop
animateScroll(index,false,true,false);
} else {
portHeight = getportHeight();
if(Math.floor(elements[index].height()/portHeight)>interstitialIndex) {
interstitialScroll(parseInt(heights[index])+(portHeight*interstitialIndex));
interstitialIndex += 1;
} else {
interstitialScroll(parseInt(heights[index])+(elements[index].outerHeight()-portHeight));
}
}
}
},
up: function() {
if(index>=0) {
if(atTop() && index>0) {
index--;
//index, instant, callbacks, toTop
animateScroll(index,false,true,false);
} else {
if(interstitialIndex>2) {
portHeight = getportHeight();
interstitialIndex -= 1;
interstitialScroll(parseInt(heights[index])+(portHeight*interstitialIndex));
} else {
interstitialIndex = 1;
interstitialScroll(parseInt(heights[index]));
}
}
}
},
init: function() {
if (document.addEventListener && settings.touchScroll) {
var eventListenerOptions = {
passive: false
};
document.addEventListener('touchstart', swipeScroll.touchHandler, eventListenerOptions);
document.addEventListener('touchmove', swipeScroll.touchHandler, eventListenerOptions);
document.addEventListener('touchend', swipeScroll.touchHandler, eventListenerOptions);
}
}
};
util = {
refresh:function(withCallback,scroll) {
clearTimeout(timeoutId2);
timeoutId2 = setTimeout(function() {
//retain position
sizePanels(true);
//scroll, firstLoad
calculatePositions(scroll,false);
if(withCallback) {
settings.afterResize();
}
},400);
},
handleUpdate:function() {
//callbacks, scroll
//changed from false,true to false,false
util.refresh(false,false);
},
handleResize:function() {
//callbacks, scroll
util.refresh(true,false);
},
handleOrientation:function() {
//callbacks, scroll
util.refresh(true,true);
}
};
settings = $.extend(settings, options);
//retain position
sizePanels(false);
calculatePositions(false,true);
if(true===hasLocation) {
//index, instant, callbacks, toTop
animateScroll(index,false,true,true);
} else {
setTimeout(function() {
//instant,callbacks
manualScroll.calculateNearest(true,false);
},200);
}
if(heights.length) {
manualScroll.init();
swipeScroll.init();
$window.on("resize",util.handleResize);
if (document.addEventListener) {
window.addEventListener("orientationchange", util.handleOrientation, false);
}
}
function interstitialScroll(pos) {
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: pos,
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: pos
}, settings.scrollSpeed,settings.easing);
}
}
function sizePanels(keepPosition) {
if(keepPosition) {
top = $window.scrollTop();
}
var selector = settings.section;
overflow = [];
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
if(settings.scrollbars===false) {
settings.overflowScroll = false;
}
portHeight = getportHeight();
$(selector).each(function(i) {
var $this = $(this);
if(settings.setHeights) {
if($this.is(settings.interstitialSection)) {
overflow[i] = false;
} else {
if(($this.css("height","auto").outerHeight()<portHeight) || $this.css("overflow")==="hidden") {
$this.css({"height":portHeight});
overflow[i] = false;
} else {
$this.css({"height":$this.height()});
if(settings.overflowScroll) {
overflow[i] = true;
} else {
overflow[i] = false;
}
}
}
} else {
if(($this.outerHeight()<portHeight) || (settings.overflowScroll===false)) {
overflow[i] = false;
} else {
overflow[i] = true;
}
}
});
if(keepPosition) {
$window.scrollTop(top);
}
}
function calculatePositions(scroll,firstLoad) {
var selector = settings.section;
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
heights = [];
names = [];
elements = [];
$(selector).each(function(i){
var $this = $(this);
if(i>0) {
heights[i] = parseInt($this.offset().top) + settings.offset;
} else {
heights[i] = parseInt($this.offset().top);
}
if(settings.sectionName && $this.data(settings.sectionName)) {
names[i] = "#" + $this.data(settings.sectionName).toString().replace(/ /g,"-");
} else {
if($this.is(settings.interstitialSection)===false) {
names[i] = "#" + (i + 1);
} else {
names[i] = "#";
if(i===$(selector).length-1 && i>1) {
heights[i] = heights[i-1] + (parseInt($($(selector)[i-1]).outerHeight()) - parseInt($(window).height())) + parseInt($this.outerHeight());
}
}
}
elements[i] = $this;
try {
if($(names[i]).length && window.console) {
console.warn("Scrollify warning: Section names can't match IDs - this will cause the browser to anchor.");
}
} catch (e) {}
if(window.location.hash===names[i]) {
index = i;
hasLocation = true;
}
});
if(true===scroll) {
//index, instant, callbacks, toTop
animateScroll(index,false,false,false);
}
}
function atTop() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top>parseInt(heights[index])) {
return false;
} else {
return true;
}
}
function atBottom() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
portHeight = getportHeight();
if(top<parseInt(heights[index])+(elements[index].outerHeight()-portHeight)-28) {
return false;
} else {
return true;
}
}
}
function move(panel,instant) {
var z = names.length;
for(;z>=0;z--) {
if(typeof panel === 'string') {
if (names[z]===panel) {
index = z;
//index, instant, callbacks, toTop
animateScroll(z,instant,true,true);
}
} else {
if(z===panel) {
index = z;
//index, instant, callbacks, toTop
animateScroll(z,instant,true,true);
}
}
}
}
scrollify.move = function(panel) {
if(panel===undefined) {
return false;
}
if(panel.originalEvent) {
panel = $(this).attr("href");
}
move(panel,false);
};
scrollify.instantMove = function(panel) {
if(panel===undefined) {
return false;
}
move(panel,true);
};
scrollify.next = function() {
if(index<names.length) {
index += 1;
//index, instant, callbacks, toTop
animateScroll(index,false,true,true);
}
};
scrollify.previous = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks, toTop
animateScroll(index,false,true,true);
}
};
scrollify.instantNext = function() {
if(index<names.length) {
index += 1;
//index, instant, callbacks, toTop
animateScroll(index,true,true,true);
}
};
scrollify.instantPrevious = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks, toTop
animateScroll(index,true,true,true);
}
};
scrollify.destroy = function() {
if(!initialised) {
return false;
}
if(settings.setHeights) {
$(settings.section).each(function() {
$(this).css("height","auto");
});
}
$window.off("resize",util.handleResize);
if(settings.scrollbars) {
$window.off('mousedown', manualScroll.handleMousedown);
$window.off('mouseup', manualScroll.handleMouseup);
$window.off('scroll', manualScroll.handleScroll);
}
$window.off(wheelEvent,manualScroll.wheelHandler);
$window.off('keydown', manualScroll.keyHandler);
if (document.addEventListener && settings.touchScroll) {
document.removeEventListener('touchstart', swipeScroll.touchHandler, false);
document.removeEventListener('touchmove', swipeScroll.touchHandler, false);
document.removeEventListener('touchend', swipeScroll.touchHandler, false);
}
heights = [];
names = [];
elements = [];
overflow = [];
};
scrollify.update = function() {
if(!initialised) {
return false;
}
util.handleUpdate();
};
scrollify.current = function() {
return elements[index];
};
scrollify.currentIndex = function() {
return index;
};
scrollify.disable = function() {
disabled = true;
};
scrollify.enable = function() {
disabled = false;
if (initialised) {
//instant,callbacks
manualScroll.calculateNearest(false,false);
}
};
scrollify.isDisabled = function() {
return disabled;
};
scrollify.setOptions = function(updatedOptions) {
if(!initialised) {
return false;
}
if(typeof updatedOptions === "object") {
settings = $.extend(settings, updatedOptions);
util.handleUpdate();
} else if(window.console) {
console.warn("Scrollify warning: setOptions expects an object.");
}
};
$.scrollify = scrollify;
return scrollify;
}));

View File

@ -0,0 +1,589 @@
/*! sanitize.css v5.0.0 | CC0 License | github.com/jonathantneal/sanitize.css */
/* Document (https://html.spec.whatwg.org/multipage/semantics.html#semantics)
========================================================================== */
/**
* 1. Remove repeating backgrounds in all browsers (opinionated).
* 2. Add box sizing inheritence in all browsers (opinionated).
*/
*,
::before,
::after {
background-repeat: no-repeat; /* 1 */
box-sizing: inherit; /* 2 */
}
/**
* 1. Add text decoration inheritance in all browsers (opinionated).
* 2. Add vertical alignment inheritence in all browsers (opinionated).
*/
::before,
::after {
text-decoration: inherit; /* 1 */
vertical-align: inherit; /* 2 */
}
/**
* 1. Add border box sizing in all browsers (opinionated).
* 2. Add the default cursor in all browsers (opinionated).
* 3. Prevent font size adjustments after orientation changes in IE and iOS.
*/
html {
box-sizing: border-box; /* 1 */
cursor: default; /* 2 */
-ms-text-size-adjust: 100%; /* 3 */
-webkit-text-size-adjust: 100%; /* 3 */
}
/* Sections (https://html.spec.whatwg.org/multipage/semantics.html#sections)
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
article,
aside,
footer,
header,
nav,
section {
display: block;
}
/**
* Remove the margin in all browsers (opinionated).
*/
body {
margin: 0;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: .67em 0;
}
/* Grouping content (https://html.spec.whatwg.org/multipage/semantics.html#grouping-content)
========================================================================== */
/**
* Add the correct display in IE 9-.
* 1. Add the correct display in IE.
*/
figcaption,
figure,
main { /* 1 */
display: block;
}
/**
* Add the correct margin in IE 8.
*/
figure {
margin: 1em 40px;
}
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* Remove the list style on navigation lists in all browsers (opinionated).
*/
nav ol,
nav ul {
list-style: none;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics (https://html.spec.whatwg.org/multipage/semantics.html#text-level-semantics)
========================================================================== */
/**
* 1. Remove the gray background on active links in IE 10.
* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
*/
a {
background-color: transparent; /* 1 */
-webkit-text-decoration-skip: objects; /* 2 */
}
/**
* 1. Remove the bottom border in Firefox 39-.
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Prevent the duplicate application of `bolder` by the next rule in Safari 6.
*/
b,
strong {
font-weight: inherit;
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font style in Android 4.3-.
*/
dfn {
font-style: italic;
}
/**
* Add the correct background and color in IE 9-.
*/
mark {
background-color: #ffff00;
color: #000000;
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -.25em;
}
sup {
top: -.5em;
}
/*
* Remove the text shadow on text selections (opinionated).
* 1. Restore the coloring undone by defining the text shadow (opinionated).
*/
::-moz-selection {
background-color: #b3d4fc; /* 1 */
color: #000000; /* 1 */
text-shadow: none;
}
::selection {
background-color: #b3d4fc; /* 1 */
color: #000000; /* 1 */
text-shadow: none;
}
/* Embedded content (https://html.spec.whatwg.org/multipage/embedded-content.html#embedded-content)
========================================================================== */
/*
* Change the alignment on media elements in all browers (opinionated).
*/
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle;
}
/**
* Add the correct display in IE 9-.
*/
audio,
video {
display: inline-block;
}
/**
* Add the correct display in iOS 4-7.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Remove the border on images inside links in IE 10-.
*/
img {
border-style: none;
}
/**
* Change the fill color to match the text color in all browsers (opinionated).
*/
svg {
fill: currentColor;
}
/**
* Hide the overflow in IE.
*/
svg:not(:root) {
overflow: hidden;
}
/* Tabular data (https://html.spec.whatwg.org/multipage/tables.html#tables)
========================================================================== */
/**
* Collapse border spacing
*/
table {
border-collapse: collapse;
}
/* Forms (https://html.spec.whatwg.org/multipage/forms.html#forms)
========================================================================== */
/**
* Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
margin: 0;
}
/**
* Inherit styling in all browsers (opinionated).
*/
button,
input,
select,
textarea {
color: inherit;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
* controls in Android 4.
* 2. Correct the inability to style clickable types in iOS and Safari.
*/
button,
html [type="button"], /* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 2 */
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* 1. Add the correct display in IE 9-.
* 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* 1. Remove the default vertical scrollbar in IE.
* 2. Change the resize direction on textareas in all browsers (opinionated).
*/
textarea {
overflow: auto; /* 1 */
resize: vertical; /* 2 */
}
/**
* 1. Add the correct box sizing in IE 10-.
* 2. Remove the padding in IE 10-.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive elements (https://html.spec.whatwg.org/multipage/forms.html#interactive-elements)
========================================================================== */
/*
* Add the correct display in IE 9-.
* 1. Add the correct display in Edge, IE, and Firefox.
*/
details, /* 1 */
menu {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Scripting (https://html.spec.whatwg.org/multipage/scripting.html#scripting-3)
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
canvas {
display: inline-block;
}
/**
* Add the correct display in IE.
*/
template {
display: none;
}
/* User interaction (https://html.spec.whatwg.org/multipage/interaction.html#editing)
========================================================================== */
/*
* Remove the tapping delay on clickable elements (opinionated).
* 1. Remove the tapping delay in IE 10.
*/
a,
area,
button,
input,
label,
select,
summary,
textarea,
[tabindex] {
-ms-touch-action: manipulation; /* 1 */
touch-action: manipulation;
}
/**
* Add the correct display in IE 10-.
*/
[hidden] {
display: none;
}
/* ARIA (https://w3c.github.io/html-aria/)
========================================================================== */
/**
* Change the cursor on busy elements (opinionated).
*/
[aria-busy="true"] {
cursor: progress;
}
/*
* Change the cursor on control elements (opinionated).
*/
[aria-controls] {
cursor: pointer;
}
/*
* Change the display on visually hidden accessible elements (opinionated).
*/
[aria-hidden="false"][hidden]:not(:focus) {
clip: rect(0, 0, 0, 0);
display: inherit;
position: absolute;
}
/*
* Change the cursor on disabled, not-editable, or otherwise
* inoperable elements (opinionated).
*/
[aria-disabled] {
cursor: default;
}

View File

@ -0,0 +1,3 @@
body {
font-family: 'Fira Sans', sans-serif;
}

View File

@ -0,0 +1,14 @@
.background-1 {
background: rgb(105,155,200);
background: -moz-radial-gradient(top left, ellipse cover, rgba(105,155,200,1) 0%, rgba(181,197,216,1) 57%);
background: -webkit-gradient(radial, top left, 0px, top left, 100%, color-stop(0%,rgba(105,155,200,1)), color-stop(57%,rgba(181,197,216,1)));
background: -webkit-radial-gradient(top left, ellipse cover, rgba(105,155,200,1) 0%,rgba(181,197,216,1) 57%);
background: -o-radial-gradient(top left, ellipse cover, rgba(105,155,200,1) 0%,rgba(181,197,216,1) 57%);
background: -ms-radial-gradient(top left, ellipse cover, rgba(105,155,200,1) 0%,rgba(181,197,216,1) 57%);
background: radial-gradient(ellipse at top left, rgba(105,155,200,1) 0%,rgba(181,197,216,1) 57%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#699bc8', endColorstr='#b5c5d8',GradientType=1 );
}
.background-2 {
background: rgb(54, 54, 54);
}

View File

@ -0,0 +1,34 @@
button {
margin-left: 5px;
border:none;
color: black;
font-size: 20px;
background: #ec6410;
padding: 10px 20px 10px 20px;
text-decoration: none;
height: 100%;
}
button:hover {
background: rgb(150, 55, 0);
color: whitesmoke;
text-decoration: none;
}
.donate {
background-color: rgba(194, 194, 194, 0);
color: #6b6b6b;
}
.donate:hover {
background: #6b6b6b;
color: white;
}
/* Maximum width */
@media (max-width: 480px) {
#download {
display: none;
}
}

View File

@ -0,0 +1,37 @@
.programmer {
display: flex;
flex-flow: column;
align-items: center;
margin-left: auto;
margin-right: auto;
padding: 20px;
width: 50%;
}
.programmer p{
margin-top: 60px;
width: 60%;
}
.programmer img{
filter: none;
border-radius: 100%;
height: auto;
width: 40%;
}
/********MOBILE************/
@media (max-width: 480px) {
.programmer{
width: 100%;
}
.programmer p{
width: 100%;
}
}

View File

@ -0,0 +1,34 @@
footer {
height: 20vh;
width: 100%;
position: fixed;
bottom: 0px;
z-index: 0;
display: flex;
color: whitesmoke;
}
footer a {
color: whitesmoke;
}
#about, #links {
display: flex;
align-items: center;
}
#about {
margin-left: 30px;
}
#links {
margin-left: auto;
margin-right: 30px;
}
#links a{
margin-left:10px;
}

View File

View File

@ -0,0 +1,32 @@
header {
background-color: #f5f5f588;
width: 100%;
height: 10vh;
/* box-shadow: 0px -17px 20px 20px #29292978; */
position: fixed;
top: 0px;
z-index: 3;
display: flex;
align-items: center;
}
header h1{
color: #6b6b6b;
font-size: 2rem;
}
header a {
text-decoration: none;
}
.logo {
height: 80%;
padding-left: 15px;
}
.buttons {
margin-left: auto;
height: 100%;
}

View File

@ -0,0 +1,5 @@
main {
position: absolute;
z-index: 2;
width: 100%;
}

View File

@ -0,0 +1,57 @@
.section {
height: 100vh;
display: flex;
// align-items: center;
justify-content: center;
padding-top: 10vh;
flex-wrap: wrap;
background: whitesmoke;
}
.section img {
filter: drop-shadow( 0px 10px 40px #888888 );
width: 80%;
z-index: 3;
/* display: block;
margin-left: auto;
margin-right: auto;
justify-content: center; */
}
.section.dark {
background: rgba(0, 0, 0, 0);
height: 900px;
flex-wrap: wrap;
}
.section.programmers {
/* min-height: 80vh;
overflow: hidden; */
height: auto;
width: 100%;
position: absolute;
margin-bottom: 20vh;
display: flex;
flex-flow: wrap;
z-index: 2;
background: whitesmoke;
box-shadow: 0px 20px 40px 0px #1010104f;
}
/********MOBILE************/
@media (max-width: 480px) {
.section.programmers{
min-height: 80vh;
height: auto;
flex-flow: column;
}
}

View File

@ -0,0 +1,689 @@
/* BASE - Base Variable files
========================================================================== */
/*! sanitize.css v5.0.0 | CC0 License | github.com/jonathantneal/sanitize.css */
/* Document (https://html.spec.whatwg.org/multipage/semantics.html#semantics)
========================================================================== */
/**
* 1. Remove repeating backgrounds in all browsers (opinionated).
* 2. Add box sizing inheritence in all browsers (opinionated).
*/
*,
::before,
::after {
background-repeat: no-repeat;
/* 1 */
box-sizing: inherit;
/* 2 */ }
/**
* 1. Add text decoration inheritance in all browsers (opinionated).
* 2. Add vertical alignment inheritence in all browsers (opinionated).
*/
::before,
::after {
text-decoration: inherit;
/* 1 */
vertical-align: inherit;
/* 2 */ }
/**
* 1. Add border box sizing in all browsers (opinionated).
* 2. Add the default cursor in all browsers (opinionated).
* 3. Prevent font size adjustments after orientation changes in IE and iOS.
*/
html {
box-sizing: border-box;
/* 1 */
cursor: default;
/* 2 */
-ms-text-size-adjust: 100%;
/* 3 */
-webkit-text-size-adjust: 100%;
/* 3 */ }
/* Sections (https://html.spec.whatwg.org/multipage/semantics.html#sections)
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
article,
aside,
footer,
header,
nav,
section {
display: block; }
/**
* Remove the margin in all browsers (opinionated).
*/
body {
margin: 0; }
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: .67em 0; }
/* Grouping content (https://html.spec.whatwg.org/multipage/semantics.html#grouping-content)
========================================================================== */
/**
* Add the correct display in IE 9-.
* 1. Add the correct display in IE.
*/
figcaption,
figure,
main {
/* 1 */
display: block; }
/**
* Add the correct margin in IE 8.
*/
figure {
margin: 1em 40px; }
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box;
/* 1 */
height: 0;
/* 1 */
overflow: visible;
/* 2 */ }
/**
* Remove the list style on navigation lists in all browsers (opinionated).
*/
nav ol,
nav ul {
list-style: none; }
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */ }
/* Text-level semantics (https://html.spec.whatwg.org/multipage/semantics.html#text-level-semantics)
========================================================================== */
/**
* 1. Remove the gray background on active links in IE 10.
* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
*/
a {
background-color: transparent;
/* 1 */
-webkit-text-decoration-skip: objects;
/* 2 */ }
/**
* 1. Remove the bottom border in Firefox 39-.
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none;
/* 1 */
text-decoration: underline;
/* 2 */
text-decoration: underline dotted;
/* 2 */ }
/**
* Prevent the duplicate application of `bolder` by the next rule in Safari 6.
*/
b,
strong {
font-weight: inherit; }
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder; }
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */ }
/**
* Add the correct font style in Android 4.3-.
*/
dfn {
font-style: italic; }
/**
* Add the correct background and color in IE 9-.
*/
mark {
background-color: #ffff00;
color: #000000; }
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%; }
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline; }
sub {
bottom: -.25em; }
sup {
top: -.5em; }
/*
* Remove the text shadow on text selections (opinionated).
* 1. Restore the coloring undone by defining the text shadow (opinionated).
*/
::-moz-selection {
background-color: #b3d4fc;
/* 1 */
color: #000000;
/* 1 */
text-shadow: none; }
::selection {
background-color: #b3d4fc;
/* 1 */
color: #000000;
/* 1 */
text-shadow: none; }
/* Embedded content (https://html.spec.whatwg.org/multipage/embedded-content.html#embedded-content)
========================================================================== */
/*
* Change the alignment on media elements in all browers (opinionated).
*/
audio,
canvas,
iframe,
img,
svg,
video {
vertical-align: middle; }
/**
* Add the correct display in IE 9-.
*/
audio,
video {
display: inline-block; }
/**
* Add the correct display in iOS 4-7.
*/
audio:not([controls]) {
display: none;
height: 0; }
/**
* Remove the border on images inside links in IE 10-.
*/
img {
border-style: none; }
/**
* Change the fill color to match the text color in all browsers (opinionated).
*/
svg {
fill: currentColor; }
/**
* Hide the overflow in IE.
*/
svg:not(:root) {
overflow: hidden; }
/* Tabular data (https://html.spec.whatwg.org/multipage/tables.html#tables)
========================================================================== */
/**
* Collapse border spacing
*/
table {
border-collapse: collapse; }
/* Forms (https://html.spec.whatwg.org/multipage/forms.html#forms)
========================================================================== */
/**
* Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
margin: 0; }
/**
* Inherit styling in all browsers (opinionated).
*/
button,
input,
select,
textarea {
color: inherit;
font-family: inherit;
font-size: inherit;
line-height: inherit; }
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input {
/* 1 */
overflow: visible; }
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select {
/* 1 */
text-transform: none; }
/**
* 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
* controls in Android 4.
* 2. Correct the inability to style clickable types in iOS and Safari.
*/
button,
html [type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
/* 2 */ }
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0; }
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText; }
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box;
/* 1 */
color: inherit;
/* 2 */
display: table;
/* 1 */
max-width: 100%;
/* 1 */
padding: 0;
/* 3 */
white-space: normal;
/* 1 */ }
/**
* 1. Add the correct display in IE 9-.
* 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */ }
/**
* 1. Remove the default vertical scrollbar in IE.
* 2. Change the resize direction on textareas in all browsers (opinionated).
*/
textarea {
overflow: auto;
/* 1 */
resize: vertical;
/* 2 */ }
/**
* 1. Add the correct box sizing in IE 10-.
* 2. Remove the padding in IE 10-.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */ }
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto; }
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */ }
/**
* Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none; }
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */ }
/* Interactive elements (https://html.spec.whatwg.org/multipage/forms.html#interactive-elements)
========================================================================== */
/*
* Add the correct display in IE 9-.
* 1. Add the correct display in Edge, IE, and Firefox.
*/
details,
menu {
display: block; }
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item; }
/* Scripting (https://html.spec.whatwg.org/multipage/scripting.html#scripting-3)
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
canvas {
display: inline-block; }
/**
* Add the correct display in IE.
*/
template {
display: none; }
/* User interaction (https://html.spec.whatwg.org/multipage/interaction.html#editing)
========================================================================== */
/*
* Remove the tapping delay on clickable elements (opinionated).
* 1. Remove the tapping delay in IE 10.
*/
a,
area,
button,
input,
label,
select,
summary,
textarea,
[tabindex] {
-ms-touch-action: manipulation;
/* 1 */
touch-action: manipulation; }
/**
* Add the correct display in IE 10-.
*/
[hidden] {
display: none; }
/* ARIA (https://w3c.github.io/html-aria/)
========================================================================== */
/**
* Change the cursor on busy elements (opinionated).
*/
[aria-busy="true"] {
cursor: progress; }
/*
* Change the cursor on control elements (opinionated).
*/
[aria-controls] {
cursor: pointer; }
/*
* Change the display on visually hidden accessible elements (opinionated).
*/
[aria-hidden="false"][hidden]:not(:focus) {
clip: rect(0, 0, 0, 0);
display: inherit;
position: absolute; }
/*
* Change the cursor on disabled, not-editable, or otherwise
* inoperable elements (opinionated).
*/
[aria-disabled] {
cursor: default; }
body {
font-family: 'Fira Sans', sans-serif; }
/* LAYOUT - Structure and layout files.
========================================================================== */
main {
position: absolute;
z-index: 2;
width: 100%; }
header {
background-color: #f5f5f588;
width: 100%;
height: 10vh;
/* box-shadow: 0px -17px 20px 20px #29292978; */
position: fixed;
top: 0px;
z-index: 3;
display: flex;
align-items: center; }
header h1 {
color: #6b6b6b;
font-size: 2rem; }
header a {
text-decoration: none; }
.logo {
height: 80%;
padding-left: 15px; }
.buttons {
margin-left: auto;
height: 100%; }
footer {
height: 20vh;
width: 100%;
position: fixed;
bottom: 0px;
z-index: 0;
display: flex;
color: whitesmoke; }
footer a {
color: whitesmoke; }
#about, #links {
display: flex;
align-items: center; }
#about {
margin-left: 30px; }
#links {
margin-left: auto;
margin-right: 30px; }
#links a {
margin-left: 10px; }
.section {
height: 100vh;
display: flex;
justify-content: center;
padding-top: 10vh;
flex-wrap: wrap;
background: whitesmoke; }
.section img {
filter: drop-shadow(0px 10px 40px #888888);
width: 80%;
z-index: 3;
/* display: block;
margin-left: auto;
margin-right: auto;
justify-content: center; */ }
.section.dark {
background: rgba(0, 0, 0, 0);
height: 900px;
flex-wrap: wrap; }
.section.programmers {
/* min-height: 80vh;
overflow: hidden; */
height: auto;
width: 100%;
position: absolute;
margin-bottom: 20vh;
display: flex;
flex-flow: wrap;
z-index: 2;
background: whitesmoke;
box-shadow: 0px 20px 40px 0px #1010104f; }
/********MOBILE************/
@media (max-width: 480px) {
.section.programmers {
min-height: 80vh;
height: auto;
flex-flow: column; } }
/* MODULES - Re-usable site elements.
========================================================================== */
.background-1 {
background: #699bc8;
background: -moz-radial-gradient(top left, ellipse cover, #699bc8 0%, #b5c5d8 57%);
background: -webkit-gradient(radial, top left, 0px, top left, 100%, color-stop(0%, #699bc8), color-stop(57%, #b5c5d8));
background: -webkit-radial-gradient(top left, ellipse cover, #699bc8 0%, #b5c5d8 57%);
background: -o-radial-gradient(top left, ellipse cover, #699bc8 0%, #b5c5d8 57%);
background: -ms-radial-gradient(top left, ellipse cover, #699bc8 0%, #b5c5d8 57%);
background: radial-gradient(ellipse at top left, #699bc8 0%, #b5c5d8 57%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#699bc8', endColorstr='#b5c5d8',GradientType=1 ); }
.background-2 {
background: #363636; }
button {
margin-left: 5px;
border: none;
color: black;
font-size: 20px;
background: #ec6410;
padding: 10px 20px 10px 20px;
text-decoration: none;
height: 100%; }
button:hover {
background: #963700;
color: whitesmoke;
text-decoration: none; }
.donate {
background-color: rgba(194, 194, 194, 0);
color: #6b6b6b; }
.donate:hover {
background: #6b6b6b;
color: white; }
/* Maximum width */
@media (max-width: 480px) {
#download {
display: none; } }
.programmer {
display: flex;
flex-flow: column;
align-items: center;
margin-left: auto;
margin-right: auto;
padding: 20px;
width: 50%; }
.programmer p {
margin-top: 60px;
width: 60%; }
.programmer img {
filter: none;
border-radius: 100%;
height: auto;
width: 40%; }
/********MOBILE************/
@media (max-width: 480px) {
.programmer {
width: 100%; }
.programmer p {
width: 100%; } }
/*# sourceMappingURL=styles.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
/* BASE - Base Variable files
========================================================================== */
@import 'base/sanitize.scss';
@import 'base/typography.scss';
/* LAYOUT - Structure and layout files.
========================================================================== */
@import 'layout/_main.scss';
@import 'layout/_grid.scss';
@import 'layout/_header.scss';
@import 'layout/_footer.scss';
@import 'layout/_section.scss';
/* MODULES - Re-usable site elements.
========================================================================== */
@import 'components/_backgrounds.scss';
@import 'components/_buttons.scss';
@import 'components/_programmers.scss';
// @import 'modules/_buttons.scss';
// @import 'modules/_lists.scss';
// @import 'modules/_tabs.scss';

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="addon">
<id>de.wolfvollprecht.UberWriter.Plugin.TexLive</id>
<extends>de.wolfvollprecht.UberWriter</extends>
<name>TexLive Plugin</name>
<summary>Allows to export to pdf and to show formulas in the inline preview</summary>
<url type="homepage">https://www.tug.org/texlive//</url>
<project_license>LPPL</project_license>
<metadata_license>CC0-1.0</metadata_license>
<update_contact>w.vollprecht_AT_gmail.com</update_contact>
</component>

View File

@ -1,109 +0,0 @@
{
"app-id": "de.wolfvollprecht.UberWriter",
"runtime": "org.gnome.Platform",
"runtime-version": "3.36",
"sdk": "org.gnome.Sdk",
"command": "uberwriter",
"finish-args": [
"--socket=x11",
"--socket=wayland",
"--share=ipc",
"--share=network",
"--filesystem=host",
"--env=PATH=/app/bin:/usr/bin:/app/extensions/TexLive/2019/bin/x86_64-linux/",
"--metadata=X-DConf=migrate-path=/de/wolfvollprecht/UberWriter/"
],
"add-extensions": {
"de.wolfvollprecht.UberWriter.Plugin": {
"directory": "extensions",
"version": "stable",
"subdirectories": true,
"no-autodownload": true,
"autodelete": true
}
},
"modules": [{
"name":"gspell",
"sources":[{
"type":"archive",
"url":"https://download.gnome.org/sources/gspell/1.8/gspell-1.8.3.tar.xz",
"sha256":"5ae514dd0216be069176accf6d0049d6a01cfa6a50df4bc06be85f7080b62de8"
}]
},
{
"name": "pandoc",
"only-arches": [
"x86_64"
],
"buildsystem": "simple",
"build-commands": [
"cp bin/pandoc /app/bin/pandoc",
"cp bin/pandoc-citeproc /app/bin/pandoc-citeproc"
],
"sources": [{
"type": "archive",
"url": "https://github.com/jgm/pandoc/releases/download/2.9.2/pandoc-2.9.2-linux-amd64.tar.gz",
"sha256": "039f155b6166c1e268479bcb06af2dba99eb7795cbff7b3c13b4875388195d08"
}]
},
{
"name": "pipdeps",
"buildsystem": "simple",
"build-commands": [
"pip3 install --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} regex pypandoc"
],
"sources": [{
"type": "file",
"url": "https://files.pythonhosted.org/packages/75/28/521c6dc7fef23a68368efefdcd682f5b3d1d58c2b90b06dc1d0b805b51ae/wheel-0.34.2.tar.gz",
"sha256": "8788e9155fe14f54164c1b9eb0a319d98ef02c160725587ad60f14ddc57b6f96"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/8e/76/66066b7bc71817238924c7e4b448abdb17eb0c92d645769c223f9ace478f/pip-20.0.2.tar.gz",
"sha256": "7db0c8ea4c7ea51c8049640e8e6e7fde949de672bfa4949920675563a5a6967f"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/71/81/00184643e5a10a456b4118fc12c96780823adb8ed974eb2289f29703b29b/pypandoc-1.4.tar.gz",
"sha256": "e914e6d5f84a76764887e4d909b09d63308725f0cbb5293872c2c92f07c11a5b"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/e8/76/8ac7f467617b9cfbafcef3c76df6f22b15de654a62bea719792b00a83195/regex-2020.2.20.tar.gz",
"sha256": "9e9624440d754733eddbcd4614378c18713d2d9d0dc647cf9c72f64e39671be5"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/14/4b/6f7a3f2bb1e2fa4d3007126578cae0b9910ff46c4957bef5bd4b92733011/pyenchant-3.0.1.tar.gz",
"sha256": "1bd26a644abf80196a9de3f2d820ebafb7e7f78385e392ce77cb1552f164d559"
}]
},
{
"name": "fonts",
"buildsystem": "simple",
"build-commands": [
"mkdir -p /app/share/fonts/",
"cp ttf/* /app/share/fonts/"
],
"sources": [{
"type": "git",
"url": "https://github.com/mozilla/Fira",
"tag": "4.202"
}]
},
{
"name": "uberwriter",
"buildsystem": "meson",
"config-opts" : [
"-Dprofile=development"
],
"sources": [{
"type" : "dir",
"path" : "../../"
}],
"post-install": [
"install -d /app/extensions"
]
}
]
}

View File

@ -1,35 +0,0 @@
{
"name": "pipdeps",
"buildsystem": "simple",
"build-commands": [
"pip3 install --no-index --find-links=\"file://${PWD}\" --prefix=${FLATPAK_DEST} pyenchant regex pypandoc"
],
"sources": [
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/5d/c1/45947333669b31bc6b4933308dd07c2aa2fedcec0a95b14eedae993bd449/wheel-0.31.0.tar.gz",
"sha256": "1ae8153bed701cb062913b72429bcf854ba824f973735427681882a688cb55ce"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/ae/e8/2340d46ecadb1692a1e455f13f75e596d4eab3d11a57446f08259dee8f02/pip-10.0.1.tar.gz",
"sha256": "f2bd08e0cd1b06e10218feaf6fef299f473ba706582eb3bd9d52203fdbd7ee68"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/71/81/00184643e5a10a456b4118fc12c96780823adb8ed974eb2289f29703b29b/pypandoc-1.4.tar.gz",
"sha256": "e914e6d5f84a76764887e4d909b09d63308725f0cbb5293872c2c92f07c11a5b"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/a2/51/c39562cfed3272592c60cfd229e5464d715b78537e332eac2b695422dc49/regex-2018.02.21.tar.gz",
"sha256": "b44624a38d07d3c954c84ad302c29f7930f4bf01443beef5589e9157b14e2a29"
},
{
"type": "file",
"url": "https://files.pythonhosted.org/packages/9e/54/04d88a59efa33fefb88133ceb638cdf754319030c28aadc5a379d82140ed/pyenchant-2.0.0.tar.gz",
"sha256": "fc31cda72ace001da8fe5d42f11c26e514a91fa8c70468739216ddd8de64e2a0"
}
]
}

View File

@ -1,66 +0,0 @@
{
"id": "de.wolfvollprecht.UberWriter.Plugin.TexLive",
"runtime": "de.wolfvollprecht.UberWriter",
"branch": "stable",
"sdk": "org.gnome.Sdk//3.34",
"build-extension": true,
"separate-locales": false,
"appstream-compose": false,
"finish-args": [
],
"build-options" : {
"prefix": "/app/extensions/TexLive",
"cflags": "-O2 -g",
"cxxflags": "-O2 -g",
"env": {
"PATH": "/app/extensions/TexLive/bin:/app/extensions/TexLive/2019/bin/x86_64-linux:/app/bin:/usr/bin"
}
},
"cleanup": ["/bin/wget"],
"modules": [
{
"name": "wget",
"builddir": true,
"config-opts": ["--prefix=/app/extensions/TexLive"],
"sources": [
{
"type": "archive",
"url": "https://ftp.gnu.org/gnu/wget/wget-1.19.4.tar.gz",
"sha256": "93fb96b0f48a20ff5be0d9d9d3c4a986b469cb853131f9d5fe4cc9cecbc8b5b5"
}
]
},
{
"name": "texlive",
"builddir": false,
"build-options" : {
"build-args": ["--share=network"],
"config-opts": ["--prefix=/app/extensions/TexLive"]
},
"build-commands": [
],
"sources": [
{
"type": "file",
"path": "texlive_install.sh",
"dest-filename": "configure"
}
]
},
{
"name": "appdata",
"buildsystem": "simple",
"build-commands": [
"mkdir -p /app/extensions/TexLive/share/appdata",
"install -Dm644 de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml /app/extensions/TexLive/share/appdata/de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml",
"appstream-compose --basename=de.wolfvollprecht.UberWriter.Plugin.TexLive --prefix=/app/extensions/TexLive --origin=flatpak de.wolfvollprecht.UberWriter.Plugin.TexLive"
],
"sources": [
{
"type": "file",
"path": "de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml"
}
]
}
]
}

View File

@ -1,91 +0,0 @@
{
"id": "de.wolfvollprecht.UberWriter.Plugin.TexLive",
"runtime": "de.wolfvollprecht.UberWriter",
"branch": "stable",
"sdk": "org.gnome.Sdk//3.34",
"build-extension": true,
"separate-locales": false,
"appstream-compose": false,
"finish-args": [
],
"build-options" : {
"prefix": "/app/extensions/TexLive",
"cflags": "-O2 -g",
"cxxflags": "-O2 -g",
"env": {
"PATH": "/app/extensions/TexLive/bin:/app/extensions/TexLive/2019/bin/x86_64-linux:/app/bin:/usr/bin"
}
},
"cleanup": ["/bin/wget"],
"modules": [
{
"name": "wget",
"builddir": true,
"config-opts": ["--prefix=/app/extensions/TexLive"],
"sources": [
{
"type": "archive",
"url": "https://ftp.gnu.org/gnu/wget/wget-1.19.4.tar.gz",
"sha256": "93fb96b0f48a20ff5be0d9d9d3c4a986b469cb853131f9d5fe4cc9cecbc8b5b5"
}
]
},
{
"name": "p7zip",
"no-autogen": true,
"config-opts": ["--prefix=/app/extensions/TexLive"],
"make-args": ["7z"],
"cleanup": ["*"],
"sources": [
{
"type": "archive",
"url": "https://sourceforge.net/projects/p7zip/files/p7zip/16.02/p7zip_16.02_src_all.tar.bz2",
"sha256": "5eb20ac0e2944f6cb9c2d51dd6c4518941c185347d4089ea89087ffdd6e2341f"
},
{
"type": "shell",
"commands": ["sed -i 's|/usr/local|/app/extensions/TexLive|g' makefile.common"]
}
]
},
{
"name": "texlive",
"buildsystem": "simple",
"sources": [
{
"type":"file",
"url": "http://mirrors.ctan.org/systems/texlive/Images/texlive.iso",
"sha512": "a00a943ce4438fe2aecf8b1e05f9055135ef03c56b6782a49205bac9023d77c781f3cab50f2f9555ac116bb0d97d6570afffe7c60b8745325b9941f82af7ef83 "
},
{
"type": "file",
"path": "texlive.profile"
},
{
"type": "shell",
"commands": ["7z x texlive.iso"]
}
],
"build-commands": [
"chmod +x install-tl",
"echo \"In\" | TEXLIVE_INSTALL_PREFIX=/app/extensions/TexLive ./install-tl --profile texlive.profile",
"yes | rm -r /app/extensions/TexLive/texmf-dist/doc"
]
},
{
"name": "appdata",
"buildsystem": "simple",
"build-commands": [
"mkdir -p /app/extensions/TexLive/share/appdata",
"install -Dm644 de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml /app/extensions/TexLive/share/appdata/de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml",
"appstream-compose --basename=de.wolfvollprecht.UberWriter.Plugin.TexLive --prefix=/app/extensions/TexLive --origin=flatpak de.wolfvollprecht.UberWriter.Plugin.TexLive"
],
"sources": [
{
"type": "file",
"path": "de.wolfvollprecht.UberWriter.Plugin.TexLive.appdata.xml"
}
]
}
]
}

View File

@ -1,30 +0,0 @@
selected_scheme scheme-basic
TEXDIR /app/extensions/TexLive/2018
TEXMFCONFIG ~/.texlive2018/texmf-config
TEXMFHOME ~/texmf
TEXMFLOCAL /app/extensions/TexLive/texmf-local
TEXMFSYSCONFIG /app/extensions/TexLive/2018/texmf-config
TEXMFSYSVAR /app/extensions/TexLive/2018/texmf-var
TEXMFVAR ~/.texlive2018/texmf-var
binary_x86_64-linux 1
collection-latex 1
collection-binextra 1
collection-fontsrecommended 1
instopt_adjustpath 0
instopt_adjustrepo 1
instopt_letter 0
instopt_portable 1
instopt_write18_restricted 1
tlpdbopt_autobackup 1
tlpdbopt_backupdir tlpkg/backups
tlpdbopt_create_formats 1
tlpdbopt_desktop_integration 1
tlpdbopt_file_assocs 1
tlpdbopt_generate_updmap 0
tlpdbopt_install_docfiles 0
tlpdbopt_install_srcfiles 0
tlpdbopt_post_code 1
tlpdbopt_sys_bin /usr/local/bin
tlpdbopt_sys_info /usr/local/share/info
tlpdbopt_sys_man /usr/local/share/man
tlpdbopt_w32_multi_user 1

View File

@ -1,62 +0,0 @@
# Download the installer!
# Currently using 2017 edition, upgrade to 2018 tomorrow! (just released, needs)
# time to propagate everywhere
wget ftp://tug.org/historic/systems/texlive/2019/install-tl-unx.tar.gz
myhash=$(sha256sum install-tl-unx.tar.gz | cut -d' ' -f1)
if [ $myhash != "44aa41b5783e345b7021387f19ac9637ff1ce5406a59754230c666642dfe7750" ] ; then echo "CHECKSUM MISMATCH!"; exit 1 ; fi
tar xvf install-tl-unx.tar.gz
# The texlive profile sets some variables for the installation
# so the installer doesn't use the text user interface
# Most importantly (besides the paths') is "selected-scheme"
# Currently set to scheme-minimal which installs almost nothing
# (which is great for testing, but less for actual usage! :)
cat <<EOF > texlive.profile
# texlive.profile written on Sat Apr 28 18:37:30 2018 UTC
# It will NOT be updated and reflects only the
# installation profile at installation time.
selected_scheme scheme-basic
TEXDIR /app/extensions/TexLive/2019
TEXMFCONFIG ~/.texlive2019/texmf-config
TEXMFHOME ~/texmf
TEXMFLOCAL /app/extensions/TexLive/texmf-local
TEXMFSYSCONFIG /app/extensions/TexLive/2019/texmf-config
TEXMFSYSVAR /app/extensions/TexLive/2019/texmf-var
TEXMFVAR ~/.texlive2019/texmf-var
binary_x86_64-linux 1
collection-latex 1
collection-binextra 1
collection-fontsrecommended 1
instopt_adjustpath 0
instopt_adjustrepo 1
instopt_letter 0
instopt_portable 1
instopt_write18_restricted 1
tlpdbopt_autobackup 1
tlpdbopt_backupdir tlpkg/backups
tlpdbopt_create_formats 1
tlpdbopt_desktop_integration 1
tlpdbopt_file_assocs 1
tlpdbopt_generate_updmap 0
tlpdbopt_install_docfiles 0
tlpdbopt_install_srcfiles 0
tlpdbopt_post_code 1
tlpdbopt_sys_bin /usr/local/bin
tlpdbopt_sys_info /usr/local/share/info
tlpdbopt_sys_man /usr/local/share/man
tlpdbopt_w32_multi_user 1
EOF
# Makefile which is required by flatpak ... so this one is almost empty
# except for the install command which uses the texlive installer to download
# all the packages!
cat <<EOF > Makefile
all:
echo "I am a pretty empty Makefile."
install:
./install-tl-20190410/install-tl --profile texlive.profile
EOF

View File

@ -1,13 +0,0 @@
#!/usr/bin/env python3
from os import environ, path
from subprocess import call
if not environ.get('DESTDIR', ''):
PREFIX = environ.get('MESON_INSTALL_PREFIX', '/usr/local')
DATA_DIR = path.join(PREFIX, 'share')
print('Updating icon cache...')
call(['gtk-update-icon-cache', '-qtf', path.join(DATA_DIR, 'icons/hicolor')])
print("compiling new schemas")
call(["glib-compile-schemas", path.join(DATA_DIR, 'glib-2.0/schemas')])

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/de/wolfvollprecht/UberWriter/">
<file compressed="true" alias="icons/scalable/status/preview-layout-full-width-symbolic.svg">media/icons/preview-layout-full-width-symbolic.svg</file>
<file compressed="true" alias="icons/scalable/status/preview-layout-half-width-symbolic.svg">media/icons/preview-layout-half-width-symbolic.svg</file>
<file compressed="true" alias="icons/scalable/status/preview-layout-windowed-symbolic.svg">media/icons/preview-layout-windowed-symbolic.svg</file>
<file compressed="true" alias="icons/scalable/status/preview-layout-half-height-symbolic.svg">media/icons/preview-layout-half-height-symbolic.svg</file>
<file compressed="true">media/css/gtk/base.css</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Export.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/ExportPopover.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Menu.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Preferences.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Recents.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Shortcuts.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Window.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/Headerbar.ui</file>
<file compressed="true" preprocess="xml-stripblanks">ui/PreviewLayoutSwitcherItem.ui</file>
<file compressed="true" preprocess="xml-stripblanks">About.ui</file>
</gresource>
</gresources>

View File

@ -1,147 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>@app-id@</id>
<launchable type="desktop-id">@app-id@.desktop</launchable>
<name>Apostrophe</name>
<summary>An elegant, distraction-free GTK markdown editor</summary>
<description>
<p>Apostrophe is a GTK based distraction free Markdown editor, originally created by Wolf Vollprecht and maintained by Manuel Genovés. It uses pandoc as backend for markdown parsing and offers a very clean and sleek user interface.</p>
<p>You can install the recommended TexLive extension with the command:</p>
<p>flatpak install flathub de.wolfvollprecht.UberWriter.Plugin.TexLive</p>
<p>or from Gnome-Software</p>
</description>
<screenshots>
<screenshot type="default">
<image type="source">https://raw.githubusercontent.com/UberWriter/apostrophe/master/screenshots/main.png</image>
</screenshot>
<screenshot>
<image type="source">https://raw.githubusercontent.com/UberWriter/apostrophe/master/screenshots/main-dark.png</image>
</screenshot>
<screenshot>
<image type="source">https://raw.githubusercontent.com/UberWriter/apostrophe/master/screenshots/formula.png</image>
</screenshot>
<screenshot>
<image type="source">https://raw.githubusercontent.com/UberWriter/apostrophe/master/screenshots/preview.png</image>
</screenshot>
<screenshot>
<image type="source">https://raw.githubusercontent.com/UberWriter/apostrophe/master/screenshots/focus.png</image>
</screenshot>
</screenshots>
<releases>
<release date="2020-03-19" version="2.2.0">
<description>
<p>UI/UX/Functionality</p>
<ul>
<li>New headerbar design</li>
<li>New preview modes, with the option to sync them to the edit view</li>
<li>New preview mode selector</li>
<li>New theme selector</li>
<li>Rework the autohiding mechanism; now the headerbar fades away when typing, only to reappear when the cursor moves to the top portion of the window</li>
<li>Now the content of the texview goes visually bellow the headerbar</li>
<li>Overall better styling</li>
<li>Added Hemingway mode, which disables the backspace key</li>
<li>Added Github Flavoured Markdow, MultiMarkdown, Pandoc's Markdown and Commonmark support, being CommonMark the default from now on</li>
<li>New stats counter, with the option to show count of characters/words/sentences/paragrafs/reading time</li>
<li>Better handling of DnD events</li>
<li>Export to A4 by default</li>
</ul>
<p>Technical improvements</p>
<ul>
<li>Port of the buildsystem to Meson. Now you can hit the "build" button on Builder and everything works as expected</li>
<li>Port to gspell</li>
<li>Partial port to gresources</li>
<li>Overall refactorization of the codebase</li>
<li>General bugfixes and improvements</li>
</ul>
</description>
</release>
<release date="2019-03-10" version="2.1.5">
<description>
<ul>
<li>Added italian language</li>
<li>Initial themes support: now apostrophe adapts his colors to the current GTK theme</li>
<li>Disabled scroll gradient, can be enabled in the preferences dialog</li>
<li>Allow to disable headerbar autohidding in Dconf</li>
<li>Now a single click is enough to open files in the recent files popover</li>
<li>Spellchecking status is now saved between sessions</li>
<li>Minor UI fixes</li>
<li>Added -d flag to enable webdev tools</li>
</ul>
</description>
</release>
<release date="2018-12-06" version="2.1.4">
<description>
<p>Updated css styles.</p>
</description>
</release>
<release date="2018-11-28" version="2.1.3">
<description>
<p>This release features a new logo, polishes the Appmenu, fixes usability bugs and flatpak related bugs.</p>
</description>
</release>
<release date="2018-07-27" version="2.1.2">
<description>
<p>This release provides a fix to a bug that caused Apostrophe to not mark properly **bold**, *cursive*, and ***bold and cursive*** words.</p>
</description>
</release>
<release date="2018-07-26" version="2.1.1">
<description>
<p>This release solves two minor bugs:</p>
<ul>
<li>One on focus mode which caused the lines to be highlighted on edit rather than on click</li>
<li>Non symbolic icons on the searchbar</li>
</ul>
</description>
</release>
<release date="2018-07-18" version="2.1.0">
<description>
<p>This release features a ton of UX/UI improvements, like:</p>
<ul>
<li>Drop AppMenu support</li>
<li>HeaderBar and menus redesign, with a new unified menu and quick access buttons on the headerbar</li>
<li>Now the fullscreen view shows a headerbar when the cursor approaches the top of the screen</li>
<li>A new unified export dialog, with updated options, and quick access to pdf, odt and html export</li>
<li>Bugfixes.</li>
</ul>
</description>
</release>
<release date="2018-06-24" version="2.0.4">
<description>
<p>Now the menu is a Popover instead a regular menu.</p>
<p>The headerbar matches the theme selected for the application.</p>
<p>Updated translations.</p>
</description>
</release>
<release date="2018-06-14" version="2.0.3">
<description>
<p>Small bug fixes, updated links.</p>
</description>
</release>
<release date="2018-05-16" version="2.0.2">
<description>
<p>Fix a bug with the preview mode.</p>
</description>
</release>
<release date="2018-05-14" version="2.0.1">
<description>
<p>Don't use env variable to check if in flatpak.</p>
</description>
</release>
<release date="2018-05-12" version="2.0.0">
<description>
<p>First re-release</p>
</description>
</release>
</releases>
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0+</project_license>
<url type="homepage">http://apostrophe.github.io/apostrophe</url>
<content_rating type="oars-1.1"/>
<developer_name>Wolf V., Manuel G.</developer_name>
<url type="bugtracker">https://github.com/Apostrophe/apostrophe/issues</url>
<url type="donation">https://liberapay.com/Apostrophe/donate</url>
<url type="help">http://apostrophe.github.io/apostrophe</url>
<url type="translate">https://poeditor.com/join/project/gxVzFyXb2x</url>
<update_contact>manuel.genoves_at_gmail.com</update_contact>
<translation type="gettext">@gettext-package@</translation>
</component>

View File

@ -1,11 +0,0 @@
[Desktop Entry]
Name=Apostrophe
# Translators: Search terms to find this application. Do NOT translate or localize the semicolons! The list MUST also end with a semicolon!
Keywords=uberwriter;UberWriter;apostrophe;markdown;editor;
Comment=Apostrophe, a simple and distraction free Markdown Editor
Categories=GNOME;GTK;Office;
Exec=apostrophe %U
Icon=@icon@
Terminal=false
Type=Application
MimeType=text/x-markdown;text/plain;

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