2025-12-01

This commit is contained in:
2026-03-17 14:58:51 -06:00
parent 183e865f8b
commit 4b82b57113
6846 changed files with 954887 additions and 162606 deletions
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+3
View File
@@ -0,0 +1,3 @@
Blender Log is an add-on which provides an interface for managing warnings and errors for other add-ons. No add-on should strictly depend on this one, but they can be enhanced if they integrate with it.
You can find the documentation [here](https://studio.blender.org/tools/addons/blender_log).
+59
View File
@@ -0,0 +1,59 @@
# SPDX-FileCopyrightText: 2024 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
bl_info = {
"name": "Blender Log",
"author": "Demeter Dzadik",
"version": (0, 0, 1),
"blender": (4, 2, 0),
"location": "3D View -> Sidebar -> (You can choose which panel)",
"description": "A dedicated place for other add-ons to report, organize, and fix issues",
"category": "System",
"doc_url": "",
"tracker_url": "https://projects.blender.org/studio/blender-studio-tools/src/branch/main/scripts-blender/addons/blender_log",
}
import importlib
import bpy
from . import prefs, props, operators, ui, app_handlers, id_types, hotkeys
# Each module can have register() and unregister() functions and a list of classes to register called "registry".
modules = [prefs, props, operators, ui, app_handlers]
def register_unregister_modules(modules, register: bool):
"""Recursively register or unregister modules by looking for either
un/register() functions or lists named `registry` which should be a list of
registerable classes.
"""
register_func = bpy.utils.register_class if register else bpy.utils.unregister_class
for m in modules:
if register:
importlib.reload(m)
if hasattr(m, 'registry'):
for c in m.registry:
un = 'un' if not register else ''
try:
register_func(c)
except Exception as e:
print(f"Warning: Failed to {un}register class: {c.__name__}")
print(e)
if hasattr(m, 'modules'):
register_unregister_modules(m.modules, register)
if register and hasattr(m, 'register'):
m.register()
elif hasattr(m, 'unregister'):
m.unregister()
def register():
register_unregister_modules(modules, register=True)
def unregister():
register_unregister_modules(modules, register=False)
@@ -0,0 +1,3 @@
from . import purge_pre_save
modules = [purge_pre_save]
@@ -0,0 +1,18 @@
import bpy
from bpy.app.handlers import persistent
from ..util import get_addon_prefs
@persistent
def purge_before_save(scene):
prefs = get_addon_prefs()
if prefs.purge_on_save:
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=False, do_recursive=True)
def register():
bpy.app.handlers.save_pre.append(purge_before_save)
def unregister():
bpy.app.handlers.save_pre.remove(purge_before_save)
@@ -0,0 +1,19 @@
schema_version = "1.0.0"
id = "blender_log"
version = "0.0.1"
name = "Blender Log"
tagline = "A dedicated place for other add-ons to report, organize, and fix issues"
maintainer = "Demeter Dzadik <demeter@blender.org>"
type = "add-on"
website = "https://studio.blender.org/tools/addons/blender_log"
tags = ["System", "User Interface"]
blender_version_min = "4.2.0"
license = [
"SPDX:GPL-3.0-or-later",
]
copyright = [
"2019-2025 Demeter Dzadik & Blender Studio",
]
+609
View File
@@ -0,0 +1,609 @@
from typing import List, Dict, Tuple, Optional
import bpy
from bpy.types import KeyConfig, KeyMap, KeyMapItem, Operator
def addon_hotkey_register(
keymap_name='Window',
op_idname='',
key_id='A',
event_type='PRESS',
any=False,
ctrl=False,
alt=False,
shift=False,
oskey=False,
key_modifier='NONE',
direction='ANY',
repeat=False,
op_kwargs={},
add_on_conflict=True,
warn_on_conflict=True,
error_on_conflict=False,
):
"""Top-level function for registering a hotkey as conveniently as possible.
If you want to better manage the registered hotkey (for example, to be able
to un-register it), it's advised to instantiate PyKeyMapItems yourself instead.
:param str keymap_name: Name of the KeyMap that this hotkey will be created in. Used to define what contexts the hotkey is available in
:param str op_idname: bl_idname of the operator this hotkey should execute
:param str key_id: Name of the key that must be interacted with to trigger this hotkey
:param str event_type: Type of interaction to trigger this hotkey
:param bool any: If True, all modifier keys will be valid to trigger this hotkey
:param bool ctrl: Whether the Ctrl key needs to be pressed in addition to the primary key
:param bool alt: Whether the Alt key needs to be pressed in addition to the primary key
:param bool shift: Whether the Shift key needs to be pressed in addition to the primary key
:param bool oskey: Whether the OS key needs to be pressed in addition to the primary key
:param str key_modifier: Another non-modifier key that should be used as a modifier key
:param str direction: For interaction methods with a direction, this defines the direction
:param bool repeat: Whether the hotkey should repeat its action as long as the keys remain held
:param op_kwargs: A dictionary of parameters that should be passed as operator parameters
:return: The PyKeyMapItem that manages this hotkey
"""
py_kmi = PyKeyMapItem(
op_idname=op_idname,
key_id=key_id,
event_type=event_type,
any=any,
ctrl=ctrl,
alt=alt,
shift=shift,
oskey=oskey,
key_modifier=key_modifier,
direction=direction,
repeat=repeat,
op_kwargs=op_kwargs,
)
keymap, kmi = py_kmi.register(
keymap_name=keymap_name,
add_on_conflict=add_on_conflict,
warn_on_conflict=warn_on_conflict,
error_on_conflict=error_on_conflict,
)
return keymap, kmi
class PyKeyMapItem:
"""Class to help conveniently manage a single KeyMapItem, independently of
any particular KeyMap or any other container or built-in bpy_type."""
def __init__(
self,
op_idname='',
key_id='A',
event_type='PRESS',
any=False,
ctrl=False,
alt=False,
shift=False,
oskey=False,
key_modifier='NONE',
direction='ANY',
repeat=False,
op_kwargs={},
):
self.op_idname = op_idname
self.key_id = self.type = key_id
self.check_key_id()
self.event_type = self.value = event_type
self.check_event_type()
self.any = any
self.ctrl = ctrl
self.alt = alt
self.shift = shift
self.oskey = oskey
self.key_modifier = key_modifier
self.direction = direction
self.repeat = repeat
self.op_kwargs = op_kwargs
@staticmethod
def new_from_keymap_item(kmi: KeyMapItem, context=None) -> "PyKeyMapItem":
op_kwargs = {}
if kmi.properties:
op_kwargs = {key: value for key, value in kmi.properties.items()}
return PyKeyMapItem(
op_idname=kmi.idname,
key_id=kmi.type,
event_type=kmi.value,
any=kmi.any,
ctrl=kmi.ctrl,
alt=kmi.alt,
shift=kmi.shift,
oskey=kmi.oskey,
key_modifier=kmi.key_modifier,
direction=kmi.direction,
repeat=kmi.repeat,
op_kwargs=op_kwargs,
)
def check_key_id(self):
"""Raise a KeyMapException if the keymap_name isn't a valid KeyMap name that
actually exists in Blender's keymap system.
"""
return check_key_id(self.key_id)
def check_event_type(self):
"""Raise a KeyMapException if the event_type isn't one that actually exists
in Blender's keymap system."""
return check_event_type(self.event_type)
@property
def key_string(self) -> str:
return get_kmi_key_string(self)
def register(
self,
context=None,
keymap_name='Window',
*,
add_on_conflict=True,
warn_on_conflict=True,
error_on_conflict=False,
) -> Optional[Tuple[KeyMap, KeyMapItem]]:
"""Higher-level function for addon dev convenience.
The caller doesn't have to worry about the KeyConfig or the KeyMap.
The `addon` KeyConfig will be used.
"""
if not context:
context = bpy.context
wm = context.window_manager
kconf_addon = wm.keyconfigs.addon
if not kconf_addon:
# This happens when running Blender in background mode.
return
check_keymap_name(keymap_name)
# Find conflicts.
user_km = get_keymap_of_config(wm.keyconfigs.user, keymap_name)
if not user_km:
conflicts = []
else:
conflicts = self.find_in_keymap_conflicts(user_km)
kmi = None
keymap = None
if not conflicts or add_on_conflict:
# Add the keymap if there is no conflict, or if we are allowed
# to add it in spite of a conflict.
# If this KeyMap already exists, new() will return the existing one,
# which is confusing, but ideal.
space_type, region_type = get_ui_types_of_keymap(keymap_name)
keymap = kconf_addon.keymaps.new(
name=keymap_name, space_type=space_type, region_type=region_type
)
kmi = self.register_in_keymap(keymap)
# Warn or raise error about conflicts.
if conflicts and (warn_on_conflict or error_on_conflict):
conflict_info = "\n".join(["Conflict: " + kmi_to_str(kmi) for kmi in conflicts])
if error_on_conflict:
raise KeyMapException("Failed to register KeyMapItem due to conflicting items:" + conflict_info)
if warn_on_conflict:
print(
"Warning: Conflicting KeyMapItems: " + str(self) + "\n" + conflict_info
)
return keymap, kmi
def register_in_keymap(self, keymap: KeyMap) -> Optional[KeyMapItem]:
"""Lower-level function, for registering in a specific KeyMap."""
kmi = keymap.keymap_items.new(
self.op_idname,
type=self.key_id,
value=self.event_type,
any=self.any,
ctrl=self.ctrl,
alt=self.alt,
shift=self.shift,
oskey=self.oskey,
key_modifier=self.key_modifier,
direction=self.direction,
repeat=self.repeat,
)
for key in self.op_kwargs:
value = self.op_kwargs[key]
setattr(kmi.properties, key, value)
return kmi
def unregister(self, context=None) -> bool:
"""Higher-level function for addon dev convenience.
The caller doesn't have to worry about the KeyConfig or the KeyMap.
The hotkey will be removed from all KeyMaps of both `addon` and 'user' KeyConfigs.
"""
if not context:
context = bpy.context
wm = context.window_manager
kconfs = wm.keyconfigs
success = False
for kconf in (kconfs.user, kconfs.addon):
if not kconf:
# This happens when running Blender in background mode.
continue
for km in self.find_containing_keymaps(kconf):
self.unregister_from_keymap(km)
success = True
return success
def unregister_from_keymap(self, keymap: KeyMap):
"""Lower-level function, for unregistering from a specific KeyMap."""
kmi = self.find_in_keymap_exact(keymap)
if not kmi:
return False
keymap.keymap_items.remove(kmi)
return True
def find_containing_keymaps(self, key_config: KeyConfig) -> List[KeyMap]:
"""Return list of KeyMaps in a KeyConfig that contain a matching KeyMapItem."""
matches: List[KeyMap] = []
for km in key_config.keymaps:
match = self.find_in_keymap_exact(km)
if match:
matches.append(km)
return matches
def find_in_keymap_exact(self, keymap: KeyMap) -> Optional[KeyMapItem]:
"""Find zero or one KeyMapItem in the given KeyMap that is an exact match
with this in its operator, parameters, and key binding.
More than one will result in an error.
"""
matches = self.find_in_keymap_exact_multi(keymap)
if len(matches) > 1:
# This should happen only if an addon dev or a user creates two keymaps
# that are identical in everything except their ``repeat`` flag.
raise KeyMapException(
"More than one KeyMapItems match this PyKeyMapItem: \n"
+ str(self)
+ "\n".join([str(match) for match in matches])
)
if matches:
return matches[0]
def find_in_keymap_exact_multi(self, keymap: KeyMap) -> List[KeyMapItem]:
"""Return KeyMapItems in the given KeyMap that are an exact match with
this PyKeyMapItem in its operator, parameters, and key binding.
"""
return [kmi for kmi in keymap.keymap_items if self.compare_to_kmi_exact(kmi)]
def compare_to_kmi_exact(self, kmi: KeyMapItem) -> bool:
"""Return whether we have the same operator, params, and trigger
as the passed KeyMapItem.
"""
return self.compare_to_kmi_by_operator(
kmi, match_kwargs=True
) and self.compare_to_kmi_by_trigger(kmi)
def find_in_keymap_by_operator(
self, keymap: KeyMap, *, match_kwargs=True
) -> List[KeyMapItem]:
"""Return all KeyMapItems in the given KeyMap, which triggers the given
operator with the given parameters.
"""
return [
kmi
for kmi in keymap.keymap_items
if self.compare_to_kmi_by_operator(kmi, match_kwargs=match_kwargs)
]
def compare_to_kmi_by_operator(self, kmi: KeyMapItem, *, match_kwargs=True) -> bool:
"""Return whether we have the same operator
(and optionally operator params) as the passed KMI.
"""
if kmi.idname != self.op_idname:
return False
if not match_kwargs:
return True
# Check for mismatching default-ness of operator parameters.
if set(kmi.properties.keys()) != set(self.op_kwargs.keys()):
# This happens when the parameter overrides specified in the KMI
# aren't the same as what we're searching for.
return False
# Check for mismatching values of operator parameters.
for prop_name in kmi.properties.keys():
# It's important to use getattr() instead of dictionary syntax here,
# otherwise enum values will be integers instead of identifier strings.
value = getattr(kmi.properties, prop_name)
if value != self.op_kwargs[prop_name]:
return False
return True
def find_in_keymap_conflicts(self, keymap: KeyMap) -> List[KeyMapItem]:
"""Return any KeyMapItems in the given KeyMap which are bound to the
same key combination.
"""
return [
kmi for kmi in keymap.keymap_items if self.compare_to_kmi_by_trigger(kmi)
]
def compare_to_kmi_by_trigger(self, kmi: KeyMapItem) -> bool:
"""Return whether we have the same trigger settings as the passed KMI."""
return (
kmi.type == self.key_id
and kmi.value == self.event_type
and kmi.any == self.any
and kmi.ctrl == self.ctrl
and kmi.alt == self.alt
and kmi.shift == self.shift
and kmi.oskey == self.oskey
and kmi.key_modifier == self.key_modifier
and kmi.direction == self.direction
)
def get_user_kmis(self, context=None) -> List[KeyMapItem]:
"""Return all matching KeyMapItems in the user keyconfig."""
if not context:
context = bpy.context
user_kconf = context.window_manager.keyconfigs.user
matches = []
for km in user_kconf.keymaps:
for kmi in km.keymap_items:
if self.compare_to_kmi_exact(kmi):
matches.append(kmi)
return matches
def update(self, **kwargs):
"""Update all KeyMapItems with the passed keyword arguments."""
for key, value in kwargs.items():
for kmi in self.get_user_kmis():
setattr(kmi, key, value)
setattr(self, key, value)
def __str__(self) -> str:
"""Return an informative but compact string representation."""
ret = f"PyKeyMapItem: < {self.key_string}"
if self.op_idname:
op = find_operator_class_by_bl_idname(self.op_idname)
if not op:
ret += " | " + self.op_idname + " (Unregistered)"
else:
op_ui_name = op.name if hasattr(op, 'name') else op.bl_label
op_class_name = op.bl_rna.identifier
ret += " | " + op_ui_name + f" | {self.op_idname} | {op_class_name}"
if self.op_kwargs:
ret += " | " + str(self.op_kwargs)
else:
ret += " | (No operator assigned.)"
return ret + " >"
def __repr__(self):
"""Return a string representation that evaluates back to this object."""
pretty_kwargs = str(self.op_kwargs).replace(", ", ",\n")
return (
"PyKeyMapItem(\n"
f" op_idname='{self.op_idname}',\n"
f" key_id='{self.key_id}',\n"
f" event_type='{self.event_type}',\n"
"\n"
f" any={self.any},\n"
f" ctrl={self.ctrl},\n"
f" alt={self.alt},\n"
f" shift={self.shift},\n"
f" oskey={self.oskey},\n"
f" key_modifier='{self.key_modifier}',\n"
f" direction='{self.direction}',\n"
f" repeat='{self.repeat}',\n"
"\n"
f" op_kwargs={pretty_kwargs}\n"
")"
)
def kmi_to_str(kmi: KeyMapItem) -> str:
"""Similar to PyKeyMapItem.__str__: Return a compact string representation of this KeyMapItem."""
ret = f"KeyMapItem: < {get_kmi_key_string(kmi)}"
if kmi.idname:
op = find_operator_class_by_bl_idname(kmi.idname)
if not op:
ret += " | " + kmi.idname + " (Unregistered)"
else:
op_ui_name = op.name if hasattr(op, 'name') else op.bl_label
op_class_name = op.bl_rna.identifier
ret += " | " + op_ui_name + f" | {kmi.idname} | {op_class_name}"
# if kmi.properties: # TODO: This currently causes a crash: https://projects.blender.org/blender/blender/issues/111702
# ret += " | " + str({key:value for key, value in kmi.properties.items()})
else:
ret += " | (No operator assigned.)"
return ret + " >"
def get_kmi_key_string(kmi) -> str:
"""A user-friendly description string of the keys needed to activate this hotkey.
Should be identical to what's displayed in Blender's Keymap preferences.
"""
key_data = get_enum_values(bpy.types.KeyMapItem, 'type')
keys = []
if kmi.shift:
keys.append("Shift")
if kmi.ctrl:
keys.append("Ctrl")
if kmi.alt:
keys.append("Alt")
if kmi.oskey:
keys.append("OS")
if kmi.key_modifier != 'NONE':
keys.append(key_data[kmi.key_modifier][0])
keys.append(key_data[kmi.type][0])
final_string = " ".join(keys)
if not final_string:
return "Unassigned"
return final_string
def get_keymap_of_config(keyconfig: KeyConfig, keymap_name: str) -> Optional[KeyMap]:
space_type, region_type = get_ui_types_of_keymap(keymap_name)
keymap = keyconfig.keymaps.find(
keymap_name, space_type=space_type, region_type=region_type
)
return keymap
def ensure_keymap_in_config(keyconfig, keymap_name: str) -> KeyMap:
space_type, region_type = get_ui_types_of_keymap(keymap_name)
keymap = keyconfig.keymaps.new(
keymap_name, space_type=space_type, region_type=region_type
)
return keymap
def get_enum_values(bpy_type, enum_prop_name: str) -> Dict[str, Tuple[str, str]]:
"""Given a registered EnumProperty's owner and name, return the enum's
possible states as a dictionary, mapping the enum identifiers to a tuple
of its name and description.
:param bpy_type: The RNA type that owns the Enum property
:param str enum_prop_name: The name of the Enum property
:return: A dictionary mapping the enum's identifiers to its name and description
:rtype: dict{str: (str, str)}
"""
# If it's a Python Operator.
if isinstance(bpy_type, Operator):
try:
enum_items = bpy_type.__annotations__[enum_prop_name].keywords['items']
return {e[0]: (e[1], e[2]) for e in enum_items}
except:
return
# If it's a built-in operator.
enum_items = bpy_type.bl_rna.properties[enum_prop_name].enum_items
return {e.identifier: (e.name, e.description) for e in enum_items}
def get_all_keymap_names() -> List[str]:
"""Returns a list of all keymap names in Blender.
:return: A list of all valid keymap names
:rtype: list[str]
"""
return bpy.context.window_manager.keyconfigs.default.keymaps.keys()
def get_ui_types_of_keymap(keymap_name: str) -> Tuple[str, str]:
# The default KeyConfig contains all the possible valid KeyMap names,
# with the correct space_type and region_type already assigned.
kc_default = bpy.context.window_manager.keyconfigs.default
# This is useful to acquire the correct parameters for new KeyMapItems,
# since having the wrong params causes the KeyMapItem to fail silently.
check_keymap_name(keymap_name)
km = kc_default.keymaps.get(keymap_name)
assert km, f"Error: KeyMap not found: '{keymap_name}'"
return km.space_type, km.region_type
def find_operator_class_by_bl_idname(bl_idname: str):
"""
Returns the class of the operator registered with the given bl_idname.
:param str bl_idname: Identifier of the operator to find
:return: Class of the operator registered with the given bl_idname
:rtype: bpy.types.Operator (for Python ops) or bpy_struct (for built-ins)
"""
# Try Python operators first.
for cl in Operator.__subclasses__():
if not hasattr(cl, 'bl_idname'):
# This can happen with mix-in classes.
continue
if cl.bl_idname == bl_idname:
return cl
# Then built-ins.
module_name, op_name = bl_idname.split(".")
module = getattr(bpy.ops, module_name)
if not module:
return
op = getattr(module, op_name)
if not op:
return
return op.get_rna_type()
class KeyMapException(Exception):
"""Raised when a KeyMapItem cannot (un)register."""
pass
def check_keymap_name(keymap_name: str):
"""Raise a KeyMapException if the keymap_name isn't a valid KeyMap name that
actually exists in Blender's keymap system.
"""
all_km_names = get_all_keymap_names()
is_valid = keymap_name in all_km_names
if not is_valid:
print("All valid keymap names:")
print("\n".join(all_km_names))
raise KeyMapException(
f'"{keymap_name}" is not a valid keymap name. Must be one of the above.'
)
def check_key_id(key_id: str):
"""Raise a KeyMapException if the key_id isn't one that actually exists
in Blender's keymap system.
"""
all_valid_key_identifiers = get_enum_values(KeyMapItem, 'type')
is_valid = key_id in all_valid_key_identifiers
if not is_valid:
print("All valid key identifiers and names:")
print("\n".join(list(all_valid_key_identifiers.items())))
raise KeyMapException(
f'"{key_id}" is not a valid key identifier. Must be one of the above.'
)
def check_event_type(event_type: str):
"""Raise a KeyMapException if the event_type isn't one that actually exists
in Blender's keymap system.
"""
all_valid_event_types = get_enum_values(KeyMapItem, 'value')
is_valid = event_type in all_valid_event_types
if not is_valid:
print("All valid event names:")
print("\n".join(list(all_valid_event_types.keys())))
raise KeyMapException(
f'"{event_type}" is not a valid event type. Must be one of the above.'
)
return is_valid
def find_broken_items_of_keymap(keymap: bpy.types.KeyMap):
"""I encountered one case where kmi.properties.keys() resulted in an error.
If that happens again, use this func to troubleshoot.
"""
broken = []
for kmi in keymap.keymap_items:
try:
kmi.properties.keys()
except:
broken.append(kmi)
return broken
+77
View File
@@ -0,0 +1,77 @@
import bpy, os
from bpy import types
from typing import List, Tuple, Dict, Any
# List of datablock type information tuples:
# (type_class, type_enum_string, bpy.data.<collprop_name>)
def get_id_info() -> List[Tuple[type, str, str]]:
bpy_prop_collection = type(bpy.data.objects)
id_info = []
for prop_name in dir(bpy.data):
prop = getattr(bpy.data, prop_name)
if type(prop) == bpy_prop_collection:
if len(prop) == 0:
# We can't get full info about the ID type if there isn't at least one entry of it.
# But we shouldn't need it, since we don't have any entries of it!
continue
id_info.append((type(prop[0]), prop[0].id_type, prop_name))
return id_info
def get_id_storage_by_type_str(typ_name: str):
for typ, typ_str, container_str in get_id_info():
if typ_str == typ_name:
return getattr(bpy.data, container_str), container_str
def get_datablock_types_enum_items() -> List[Tuple[str, str, str, str, int]]:
"""Return the items needed to define an EnumProperty representing a datablock type selector."""
enum_items = types.DriverTarget.bl_rna.properties['id_type'].enum_items
ret = []
for i, typ in enumerate(enum_items):
ret.append((typ.identifier, typ.name, typ.name, typ.icon, i))
ret.append(('SCREEN', 'Screen', 'Screen', 'RESTRICT_VIEW_OFF', len(ret)))
ret.append(('METABALL', 'Metaball', 'Metaball', 'OUTLINER_OB_META', len(ret)))
ret.append(('CACHE_FILE', 'Cache File', 'Cache File', 'MOD_MESHDEFORM', len(ret)))
ret.append(('POINT_CLOUD', 'Point Cloud', 'Point Cloud', 'OUTLINER_OB_POINTCLOUD', len(ret)))
ret.append(('HAIR_CURVES', 'Hair Curves', 'Hair Curves', 'OUTLINER_OB_CURVES', len(ret)))
ret.append(('PAINT_CURVE', 'Paint Curve', 'Paint Curve', 'FORCE_CURVE', len(ret)))
ret.append(('MOVIE_CLIP', 'Movie Clip', 'Movie Clip', 'FILE_MOVIE', len(ret)))
return ret
# List of 5-tuples that can be used to define the items of an EnumProperty.
ID_TYPE_ENUM_ITEMS: List[Tuple[str, str, str, str, int]] = get_datablock_types_enum_items()
# Map datablock type enum strings to their name and icon strings.
ID_TYPE_INFO: Dict[str, Tuple[str, str]] = {tup[0] : (tup[1], tup[3]) for tup in ID_TYPE_ENUM_ITEMS}
def get_datablock_icon(id) -> str:
id_type = get_fundamental_id_type(id)[1]
return ID_TYPE_INFO[id_type][1]
def get_fundamental_id_type(datablock: bpy.types.ID) -> Tuple[Any, str]:
"""Certain datablocks have very specific types.
This function should return their fundamental type, ie. parent class."""
id_info = get_id_info()
for typ, typ_str, _container_str in id_info:
if isinstance(datablock, typ):
return typ, typ_str
def get_id(id_name: str, id_type: str, lib_path="") -> bpy.types.ID:
container = get_id_storage_by_type_str(id_type)[0]
if lib_path and lib_path != 'Local Data':
return container.get((id_name, lib_path))
return container.get((id_name, None))
### Library utilities
def get_library_icon(lib_path: str) -> str:
"""Return the library or the broken library icon, as appropriate."""
if lib_path == 'Local Data':
return 'FILE_BLEND'
filepath = os.path.abspath(bpy.path.abspath(lib_path))
if not os.path.exists(filepath):
return 'LIBRARY_DATA_BROKEN'
return 'LIBRARY_DATA_DIRECT'
@@ -0,0 +1,23 @@
from . import (
better_delete,
cleanup_shotfile,
drivers,
id_management_pie,
libraries,
names,
users,
overrides,
relink_overridden_asset,
)
modules = [
better_delete,
cleanup_shotfile,
drivers,
id_management_pie,
libraries,
names,
users,
overrides,
relink_overridden_asset,
]
@@ -0,0 +1,170 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from typing import List
from ..hotkeys import addon_hotkey_register
from ..util import get_addon_prefs
class OBJECT_OT_blenlog_unlink_from_scene(bpy.types.Operator):
bl_idname = "object.blenlog_unlink_from_scene"
bl_label = "Unlink Selected From Scene"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
if context.area.type == 'OUTLINER':
return bool(get_objects_to_unlink(context) or get_collections_to_unlink(context))
elif context.area.type == 'VIEW_3D':
return bool(get_objects_to_unlink(context))
def execute(self, context):
unlink_collections_from_scene(get_collections_to_unlink(context), context.scene)
unlink_objects_from_scene(get_objects_to_unlink(context), context.scene)
return {'FINISHED'}
class OUTLINER_OT_blenlog_better_delete(bpy.types.Operator):
bl_idname = "outliner.blenlog_better_delete"
bl_label = "Delete Datablocks From File"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return context.area.type == 'OUTLINER' and context.selected_ids
def execute(self, context):
if context.scene in context.selected_ids:
self.report({'ERROR'}, "Cannot delete active Scene.")
return {'CANCELLED'}
if context.workspace in context.selected_ids:
self.report({'ERROR'}, "Cannot delete active Workspace.")
return {'CANCELLED'}
for id in context.selected_ids:
if id.id_type in {'SCREEN', 'WINDOWMANAGER'}:
self.report({'ERROR'}, f"Cannot delete type: {id.id_type}")
return {'CANCELLED'}
count = len(context.selected_ids)
plural = "s" if count>1 else ""
bpy.data.batch_remove(context.selected_ids)
self.report({'INFO'}, f"Deleted {count} datablock{plural}.")
return {'FINISHED'}
def get_objects_to_unlink(context) -> List[bpy.types.Object]:
if context.area.type == 'OUTLINER':
selected_objs = [id for id in context.selected_ids if type(id) == bpy.types.Object]
elif context.area.type == 'VIEW_3D':
selected_objs = context.selected_objects
scene_objs = set(context.scene.objects)
return [ob for ob in selected_objs if ob in scene_objs]
def unlink_objects_from_scene(objects, scene):
for obj in objects:
for coll in [scene.collection] + scene.collection.children_recursive:
if obj.name in coll.objects:
coll.objects.unlink(obj)
def get_collections_to_unlink(context) -> List[bpy.types.Collection]:
if context.area.type == 'OUTLINER':
return [id for id in context.selected_ids if type(id) == bpy.types.Collection]
elif context.area.type == 'VIEW_3D':
return []
def unlink_collections_from_scene(collections_to_unlink, scene):
for coll_to_unlink in collections_to_unlink:
for coll in scene.collection.children_recursive:
if coll_to_unlink.name in coll.children:
coll.children.unlink(coll_to_unlink)
class OBJECT_MT_delete_pie(bpy.types.Menu):
# bl_label is displayed at the center of the pie menu
bl_label = 'Unlink / Delete'
bl_idname = 'OBJECT_MT_delete_pie'
@classmethod
def poll(cls, context):
return context.area.type in {'VIEW_3D', 'OUTLINER'}
def draw(self, context):
layout = self.layout
pie = layout.menu_pie()
# <
pie.operator(OBJECT_OT_blenlog_unlink_from_scene.bl_idname, icon='TRASH', text="Unlink From Scene")
if context.area.type == 'VIEW_3D':
# > 3D View
op = pie.operator('object.delete', icon='X', text="Delete From File")
op.use_global = True
op.confirm = False
return
# >
pie.operator('outliner.blenlog_better_delete', icon='X', text="Delete From File")
# V
pie.operator('outliner.id_operation', text="Unlink From Collection", icon="OUTLINER_COLLECTION").type='UNLINK'
# ^
pie.operator('outliner.delete', text="Delete Hierarchy", icon="OUTLINER").hierarchy=True
registry = [
OBJECT_OT_blenlog_unlink_from_scene,
OUTLINER_OT_blenlog_better_delete,
OBJECT_MT_delete_pie
]
addon_hotkeys = []
def register_hotkeys():
addon_hotkeys.append(
addon_hotkey_register(
op_idname='wm.call_menu_pie',
keymap_name='Outliner',
key_id='X',
op_kwargs={'name': OBJECT_MT_delete_pie.bl_idname},
add_on_conflict=True,
warn_on_conflict=False,
error_on_conflict=False,
)
)
addon_hotkeys.append(
addon_hotkey_register(
op_idname='wm.call_menu_pie',
keymap_name='Object Mode',
key_id='X',
op_kwargs={'name': OBJECT_MT_delete_pie.bl_idname},
add_on_conflict=True,
warn_on_conflict=False,
error_on_conflict=False,
)
)
def delayed_hotkey_register():
"""We want to register hotkeys when Blender opens, but
only is the user preference is enabled.
And we can't access the user preference during registration, so
we gotta use a timer to do it with a delay.
"""
if get_addon_prefs().use_deletion_pie and addon_hotkeys == []:
register_hotkeys()
def unregister_hotkeys():
global addon_hotkeys
for keymap, kmi in addon_hotkeys:
keymap.keymap_items.remove(kmi)
addon_hotkeys = []
def register():
bpy.app.timers.register(delayed_hotkey_register)
def unregister():
unregister_hotkeys()
@@ -0,0 +1,281 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""
This script is meant to be executed by Blender Crawl on every single shot file,
hopefully removing any useless data, fixing some names, reporting missing links,
resyncing overrides, all without breaking anything.
"""
import bpy
from typing import Set
from bpy.types import Library
from bpy.props import BoolProperty
import os
from .relink_overridden_asset import relink_all_override_hierarchies
def clean_file(
context, allow_remove_suffix=False, allow_replace_suffix=False, only_warn_local_issues=False
) -> int:
# Reset frame to start.
context.scene.frame_current = context.scene.frame_start
# Enable Simplify (only in .anim files)
if '.anim' in bpy.data.filepath:
context.scene.render.use_simplify = True
context.scene.render.simplify_subdivision = 0
nuke_addon_properties()
issue_counter = 0
issue_counter += warn_primitive_names(only_local=only_warn_local_issues)
issue_counter += warn_number_names(
only_local=only_warn_local_issues,
allow_remove_suffix=allow_remove_suffix,
allow_replace_suffix=allow_replace_suffix,
)
issue_counter += warn_bad_libs()
issue_counter += warn_broken_links()
fix_local_obdata_names()
return issue_counter
def nuke_override_hidden():
nukelist = [c for c in bpy.data.collections if 'OVERRIDE_HIDDEN' in c.name]
for coll in nukelist:
bpy.data.collections.remove(coll)
def resync_overrides(context):
ui_type = context.area.ui_type
context.area.ui_type = 'OUTLINER'
for coll in get_override_roots():
with context.temp_override(collection=coll):
bpy.ops.outliner.liboverride_troubleshoot_operation(
type='OVERRIDE_LIBRARY_RESYNC_HIERARCHY', selection_set='SELECTED'
)
context.area.ui_type = ui_type
def get_override_roots():
override_roots = set()
for coll in bpy.data.collections:
if coll.override_library:
override_roots.add(coll.override_library.hierarchy_root)
return override_roots
def warn_primitive_names(only_local=False) -> int:
issue_counter = 0
primitive_names = [
"Plane",
"Cube",
"Circle",
"Sphere",
"Icosphere",
"Cylinder",
"Cone",
"Torus",
"Suzanne",
"BezierCurve",
"BezierCircle",
"Empty",
"Key",
"Material",
]
for id in bpy.data.user_map().keys():
if (id.library or id.override_library) and only_local:
continue
if "WGT" in id.name:
# Widgets are allowed to be named after primitives.
continue
for prim_name in primitive_names:
if prim_name in id.name:
msg = f"WARNING: Primitive name: {id.name}, {type(id)}"
if id.override_library:
msg += " " + id.override_library.reference.library.filepath
print(msg)
issue_counter += 1
return issue_counter
def warn_number_names(
only_local=False, allow_remove_suffix=False, allow_replace_suffix=False
) -> int:
issue_counter = 0
all_ids = {id.name: id for id in bpy.data.user_map().keys()}
all_local_ids = {id.name: id for id in all_ids.values() if not id.library}
for name, id in all_ids.items():
if (id.library or id.override_library) and only_local:
continue
if len(id.name) < 4:
if type(id) == bpy.types.Brush:
continue
print("WARNING: Very short ID name: ", id.name, type(id))
issue_counter += 1
continue
if id.name[-4] == ".":
try:
int(id.name[-3:])
except:
# Suffix is not a number, so it's fine.
continue
msg = "WARNING: Number suffix in name: " + id.name
if id.override_library:
msg += " " + id.override_library.reference.library.filepath
if id.library:
msg += " " + id.library.filepath
if not id.override_library and not id.library:
if allow_remove_suffix:
name_without_suffix = id.name[:-4]
existing = all_local_ids.get(name_without_suffix)
if not existing:
id.name = name_without_suffix
elif allow_replace_suffix:
id.name = id.name[:-4] + "_" + id.name[-3:]
else:
print(msg)
issue_counter += 1
else:
print(msg)
issue_counter += 1
return issue_counter
def fix_local_obdata_names():
for o in bpy.data.objects:
if o.library or o.override_library:
continue
if o.data:
if (
o.data.name != o.name
): # This matters because for some reason, sometimes setting the name to what it already is, gives it a .001... lol.
o.data.name = o.name
if (
hasattr(o.data, 'shape_keys')
and o.data.shape_keys
and o.data.shape_keys.name != o.name
):
o.data.shape_keys.name = o.name
def warn_broken_links():
issue_counter = 0
for id in bpy.data.user_map().keys():
if id.is_missing:
msg = "MISSING ID: " + id.name
if id.library:
msg += " " + id.library.filepath
print(msg)
issue_counter += 1
return issue_counter
def warn_bad_libs() -> int:
issue_counter = 0
invalid_libs = get_invalid_libraries()
for invalid_lib in invalid_libs:
print("INVALID LIBRARY: ", invalid_lib.filepath)
issue_counter += 1
absolute_libs = get_absolute_libraries()
for absolute_lib in absolute_libs:
print("ABSOLUTE LIBRARY: ", absolute_lib.filepath)
issue_counter += 1
return issue_counter
def get_invalid_libraries() -> Set[Library]:
"""Return a set of library datablocks whose filepath does not exist."""
invalid_libs: Set[Library] = set()
for l in bpy.data.libraries:
if not os.path.exists(bpy.path.abspath(l.filepath)):
invalid_libs.add(l)
return invalid_libs
def get_absolute_libraries() -> Set[Library]:
"""Return a set of library datablocks whose filepaths are not relative."""
abs_libs: Set[Library] = set()
for lib in bpy.data.libraries:
if not lib.filepath.startswith("//"):
abs_libs.add(lib)
return abs_libs
def nuke_addon_properties():
property_blacklist = {"hops"}
for id in bpy.data.user_map().keys():
if id.library or id.override_library:
continue
for key in list(id.keys()):
if key in property_blacklist:
del id[key]
class OUTLINER_OT_cleanup_shotfile(bpy.types.Operator):
bl_idname = "outliner.cleanup_shotfile"
bl_label = "Cleanup Shotfile"
bl_options = {'REGISTER', 'UNDO'}
allow_remove_suffix: BoolProperty(
name="Allow Removing Number Suffix",
description="If a local ID has a .00x suffix, and it can be removed without conflicting with another existing ID, just do it",
default=True,
)
allow_replace_suffix: BoolProperty(
name="Allow Replacing Suffix Separator",
description="If a local ID has a .00x suffix, change it to _00x instead. It's best to manually look over these cases first",
default=False,
)
only_warn_local_issues: BoolProperty(
name="Only Warn Local Issues",
description="If an issue relates to a linked ID, don't warn about it",
default=False,
)
relink_overrides: BoolProperty(
name="Relink Overrides",
description="Relink all overridden hierarchy roots. Keyframe any overridden RNA Paths that were overridden but not keyed. Preserve the assigned action, constraints, pointers. Only armatures will be editable overrides, unless there was an actual override on a non-armature object",
default=False,
)
def execute(self, context):
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_recursive=True, do_linked_ids=True)
if self.relink_overrides:
# Relink ALL overridden assets from scratch, while (hopefully)
# preserving all intentionally created data on them.
relink_all_override_hierarchies(context)
issue_count = clean_file(
context,
allow_remove_suffix=self.allow_remove_suffix,
allow_replace_suffix=self.allow_replace_suffix,
only_warn_local_issues=self.only_warn_local_issues,
)
if issue_count > 0:
self.report(
{'WARNING'},
f"Cleanup complete. {issue_count} issues still need attention. See terminal for details.",
)
else:
self.report({'INFO'}, "Cleanup complete. No remaining issues detected.")
return {'FINISHED'}
registry = [OUTLINER_OT_cleanup_shotfile]
@@ -0,0 +1,123 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.props import StringProperty, IntProperty
from bpy.types import Object
from typing import List
def report_invalid_drivers(context, objects: List[Object]):
blenlog = context.scene.blender_log
cat_leftover = 'Leftover Driver'
blenlog.clear_category(cat_leftover)
cat_invalid = 'Invalid Driver'
blenlog.clear_category(cat_invalid)
counter = 0
for obj in objects:
if obj.library or obj.override_library:
continue
if not obj.animation_data:
continue
for fcurve in obj.animation_data.drivers:
kwargs = {
'icon': 'DRIVER_TRANSFORM',
'operator': BLENLOG_OT_delete_driver.bl_idname,
'op_kwargs': {
'object_name': obj.name,
'driver_path': fcurve.data_path,
'array_index': fcurve.array_index,
},
}
try:
obj.path_resolve(fcurve.data_path)
except ValueError:
# If the RNA path of the driver fails to resolve to some value,
# that means the driver is pointing at nothing; A deleted modifier,
# constraint, bone, whatever.
blenlog.add(
description=f"Driver RNA path leads to nothing: '{fcurve.data_path}'.\nThis can happen when removing modifiers, constraints, bones, etc. that previously had drivers on them. Such driver can be safely deleted, else they will spam the console.",
name=obj.name,
category=cat_leftover,
**kwargs
)
counter += 1
continue
if not fcurve.driver.is_valid:
blenlog.add(
description=f"Invalid Driver: '{fcurve.data_path}'.\nThis can happen when a driver var target datablock is removed, an expression is invalid, etc.",
name=obj.name,
category=cat_invalid,
**kwargs
)
counter += 1
return counter
report_leftover_drivers = report_invalid_drivers
class BLENLOG_OT_report_invalid_drivers(bpy.types.Operator):
"""Report drivers that point to nothing"""
bl_idname = "blenlog.report_invalid_drivers"
bl_label = "Report Leftover Drivers"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
def execute(self, context):
counter = report_invalid_drivers(context, bpy.data.objects)
if counter > 0:
self.report({'WARNING'}, f"Found {counter} invalid drivers.")
else:
self.report({'INFO'}, f"No invalid drivers found.")
return {'FINISHED'}
class BLENLOG_OT_delete_driver(bpy.types.Operator):
"""Delete a driver on a local object"""
bl_idname = "blenlog.delete_driver"
bl_label = "Delete Driver"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
object_name: StringProperty()
driver_path: StringProperty()
array_index: IntProperty()
def execute(self, context):
obj = bpy.data.objects.get((self.object_name, None))
if not obj:
self.report({'INFO'}, f'Object "{self.object_name}" had already been removed.')
return {'CANCELLED'}
if not obj.animation_data or not obj.animation_data.drivers:
self.report(
{'INFO'}, f'All drivers of object "{self.object_name}" had already been removed.'
)
return {'CANCELLED'}
logs = context.scene.blender_log
driver = obj.animation_data.drivers.find(self.driver_path, index=self.array_index)
if driver:
obj.animation_data.drivers.remove(driver)
self.report({'INFO'}, f'Removed driver "{self.driver_path}" from object "{obj.name}"')
else:
self.report(
{'INFO'},
f'Driver "{self.driver_path} on object "{obj.name}" had already been removed.',
)
logs.remove(logs.active_log)
return {'FINISHED'}
registry = [
BLENLOG_OT_report_invalid_drivers,
BLENLOG_OT_delete_driver,
]
@@ -0,0 +1,254 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
# TODO: This pie menu was moved to the 3D Viewport Pie Menus add-on, could be considered for removal here.
import bpy
from typing import List, Optional
from bpy.props import StringProperty
from bpy_extras import id_map_utils
from .relink_overridden_asset import OUTLINER_OT_relink_overridden_asset, outliner_get_active_id
from .. import hotkeys
from ..id_types import get_datablock_icon, get_library_icon, get_id_storage_by_type_str
### Pie Menu UI
class IDMAN_MT_relationship_pie(bpy.types.Menu):
# bl_label is displayed at the center of the pie menu
bl_label = 'Datablock Relationships'
bl_idname = 'IDMAN_MT_relationship_pie'
@staticmethod
def get_id(context) -> Optional[bpy.types.ID]:
return outliner_get_active_id(context)
def draw(self, context):
layout = self.layout
pie = layout.menu_pie()
# <
pie.operator(OUTLINER_OT_blenlog_list_datablock_users.bl_idname, icon='LOOP_BACK')
# >
pie.operator(OUTLINER_OT_blenlog_list_datablock_deps.bl_idname, icon='LOOP_FORWARDS')
# V
pie.operator('outliner.orphans_purge', icon='ORPHAN_DATA')
id = self.get_id(context)
if id:
# ^
remap = pie.operator(
'outliner.remap_users', icon='FILE_REFRESH', text="Remap Users"
)
remap.id_type = id.id_type
remap.id_name_source = id.name
if id.library:
remap.library_path_source = id.library.filepath
# ^>
id = OUTLINER_OT_relink_overridden_asset.get_id(context)
if id:
pie.operator('object.relink_overridden_asset', icon='LIBRARY_DATA_OVERRIDE')
else:
pie.separator()
# <^
if id and id.override_library:
pie.operator(
'outliner.liboverride_troubleshoot_operation',
icon='UV_SYNC_SELECT',
text="Resync Override Hierarchy",
).type = 'OVERRIDE_LIBRARY_RESYNC_HIERARCHY_ENFORCE'
else:
pie.separator()
else:
pie.separator()
pie.separator()
pie.separator()
# v>
if OUTLINER_OT_blenlog_instancer_to_collection.should_draw(context):
pie.operator(OUTLINER_OT_blenlog_instancer_to_collection.bl_idname, icon='LINKED')
else:
pie.separator()
### Relationship visualization operators
class RelationshipOperatorMixin:
datablock_name: StringProperty()
datablock_storage: StringProperty()
library_filepath: StringProperty()
def get_datablock(self, context) -> Optional[bpy.types.ID]:
if self.datablock_name and self.datablock_storage:
storage = getattr(bpy.data, self.datablock_storage)
lib_path = self.library_filepath or None
return storage.get((self.datablock_name, lib_path))
elif context.area.type == 'OUTLINER':
return outliner_get_active_id(context)
@classmethod
def poll(cls, context):
return context.area.type == 'OUTLINER' and len(context.selected_ids) > 0
def invoke(self, context, _event):
return context.window_manager.invoke_props_dialog(self, width=600)
def get_datablocks_to_display(self, id: bpy.types.ID) -> List[bpy.types.ID]:
raise NotImplementedError
def get_label(self):
return "Listing datablocks that reference this:"
def draw(self, context):
layout = self.layout
layout.use_property_decorate = False
layout.use_property_split = True
datablock = self.get_datablock(context)
if not datablock:
layout.alert = True
layout.label(
text=f"Failed to find datablock: {self.datablock_storage}, {self.datablock_name}, {self.library_filepath}"
)
return
row = layout.row()
split = row.split()
row = split.row()
row.alignment = 'RIGHT'
row.label(text=self.get_label())
id_row = split.row(align=True)
name_row = id_row.row()
name_row.enabled = False
name_row.prop(datablock, 'name', icon=get_datablock_icon(datablock), text="")
fake_user_row = id_row.row()
fake_user_row.prop(datablock, 'use_fake_user', text="")
layout.separator()
datablocks = self.get_datablocks_to_display(datablock)
if not datablocks:
layout.label(text="There are none.")
return
for user in self.get_datablocks_to_display(datablock):
if user == datablock:
# Scenes are users of themself for technical reasons,
# I think it's confusing to display that.
continue
row = layout.row()
name_row = row.row()
name_row.enabled = False
name_row.prop(user, 'name', icon=get_datablock_icon(user), text="")
op_row = row.row()
op = op_row.operator(type(self).bl_idname, text="", icon='LOOP_FORWARDS')
op.datablock_name = user.name
storage = get_id_storage_by_type_str(user.id_type)[1]
if not storage:
print("Error: Can't find storage: ", user.name, user.id_type)
op.datablock_storage = storage
if user.library:
op.library_filepath = user.library.filepath
name_row.prop(
user.library,
'filepath',
icon=get_library_icon(user.library.filepath),
text="",
)
def execute(self, context):
return {'FINISHED'}
class OUTLINER_OT_blenlog_list_datablock_users(RelationshipOperatorMixin, bpy.types.Operator):
"""Show list of users of this datablock"""
bl_idname = "object.blenlog_list_datablock_users"
bl_label = "List Datablock Users"
datablock_name: StringProperty()
datablock_storage: StringProperty()
library_filepath: StringProperty()
def get_datablocks_to_display(self, datablock: bpy.types.ID) -> List[bpy.types.ID]:
user_map = bpy.data.user_map()
users = user_map[datablock]
return sorted(users, key=lambda u: (str(type(u)), u.name))
class OUTLINER_OT_blenlog_list_datablock_deps(RelationshipOperatorMixin, bpy.types.Operator):
"""Show list of dependencies of this datablock"""
bl_idname = "object.blenlog_list_datablock_deps"
bl_label = "List Datablock Dependencies"
def get_label(self):
return "Listing datablocks that are referenced by this:"
def get_datablocks_to_display(self, datablock: bpy.types.ID) -> List[bpy.types.ID]:
dependencies = id_map_utils.get_id_reference_map().get(datablock)
if not dependencies:
return []
return sorted(dependencies, key=lambda u: (str(type(u)), u.name))
### Instance Collection To Scene
class OUTLINER_OT_blenlog_instancer_to_collection(bpy.types.Operator):
"""Replace an Empty that instances a collection, with the collection itself"""
bl_idname = "outliner.blenlog_instancer_to_collection"
bl_label = "Instancer Empty To Collection"
bl_options = {'UNDO'}
@staticmethod
def should_draw(context):
return (
context.area.ui_type == 'OUTLINER'
and context.id
and type(context.id) == bpy.types.Object
and context.id.type == 'EMPTY'
and context.id.instance_type == 'COLLECTION'
and context.id.instance_collection
and context.id.instance_collection not in set(context.scene.collection.children)
)
@classmethod
def poll(cls, context):
return cls.should_draw(context)
def execute(self, context):
coll = context.id.instance_collection
bpy.data.objects.remove(context.id)
context.scene.collection.children.link(coll)
return {'FINISHED'}
registry = [
IDMAN_MT_relationship_pie,
OUTLINER_OT_blenlog_list_datablock_users,
OUTLINER_OT_blenlog_list_datablock_deps,
OUTLINER_OT_blenlog_instancer_to_collection,
]
addon_hotkeys = []
def register():
addon_hotkeys.append(
hotkeys.addon_hotkey_register(
op_idname='wm.call_menu_pie',
keymap_name='Outliner',
key_id='Y',
op_kwargs={'name': IDMAN_MT_relationship_pie.bl_idname},
add_on_conflict=True,
warn_on_conflict=True,
)
)
def unregister():
for keymap, kmi in addon_hotkeys[:]:
keymap.keymap_items.remove(kmi)
@@ -0,0 +1,149 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.props import StringProperty
from pathlib import Path
def report_missing_libraries(context, libraries=[]):
if not libraries:
libraries = bpy.data.libraries
blenlog = context.scene.blender_log
cat_missing = "Missing Library"
blenlog.clear_category(cat_missing)
for lib in libraries:
if lib.is_missing:
blenlog.add(
name=lib.filepath,
description="Library file is not found on file system.",
category=cat_missing,
category_icon='LIBRARY_DATA_BROKEN',
# operator='outliner.lib_operation', # This operator demands to be run in the outliner for no particular reason.
# op_kwargs={'type': 'RELOCATE'},
)
return blenlog.categories.get(cat_missing)
def report_absolute_libraries(context, libraries=[]):
if not libraries:
libraries = bpy.data.libraries
blenlog = context.scene.blender_log
cat_absolute = "Absolute Library"
blenlog.clear_category(cat_absolute)
for lib in libraries:
if not lib.filepath.startswith("//"):
blenlog.add(
name=lib.filepath,
description=f"{lib.filepath}\nLibrary path is not relative to this .blend, but absolute.",
category=cat_absolute,
category_icon='FILEBROWSER',
# operator='outliner.lib_operation',
# op_kwargs={'type': 'RELOCATE'},
)
return blenlog.categories.get(cat_absolute)
def report_libraries_out_of_folder(context, project_path: Path or str, libraries=[]):
if type(project_path) == str:
project_path = Path(project_path)
if not libraries:
libraries = bpy.data.libraries
blenlog = context.scene.blender_log
cat_not_prod = "Library Outside Project"
blenlog.clear_category(cat_not_prod)
for lib in libraries:
abs_path = Path(bpy.path.abspath(lib.filepath)).resolve()
if project_path not in abs_path.parents:
blenlog.add(
name=lib.filepath,
description=f"{lib.filepath}\nLibrary is not a part of this project.",
category=cat_not_prod,
category_icon='ERROR',
# operator='outliner.lib_operation',
# op_kwargs={'type': 'RELOCATE'},
)
return blenlog.categories.get(cat_not_prod)
class BLENLOG_OT_report_missing_libraries(bpy.types.Operator):
"""Report libraries whose files don't exist on the system"""
bl_idname = "blenlog.report_missing_libraries"
bl_label = "Report Missing Libraries"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
category = report_missing_libraries(context, bpy.data.libraries)
if len(category.logs) > 0:
self.report({'WARNING'}, f"Found {len(category.logs)} missing libraries.")
else:
self.report({'INFO'}, f"No missing libraries found.")
return {'FINISHED'}
class BLENLOG_OT_report_absolute_libraries(bpy.types.Operator):
"""Report libraries whose filepath is referenced absolute rather than relative"""
bl_idname = "blenlog.report_absolute_libraries"
bl_label = "Report Absolute Libraries"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
category = report_absolute_libraries(context, bpy.data.libraries)
if len(category.logs) > 0:
self.report({'WARNING'}, f"Found {len(category.logs)} absolute libraries.")
else:
self.report({'INFO'}, f"No absolute libraries found.")
return {'FINISHED'}
class BLENLOG_OT_report_libraries_out_of_folder(bpy.types.Operator):
"""Report libraries whose filepath is outside of a specified folder"""
bl_idname = "blenlog.report_libraries_out_of_folder"
bl_label = "Report Libraries Out of Folder"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
project_root_path: StringProperty(
name="Project Root Path",
subtype='DIR_PATH',
description="Your project's root directory. Any libraries outside of this will be reported",
)
def execute(self, context):
category = report_libraries_out_of_folder(
context, bpy.data.libraries, self.project_root_path
)
if len(category.logs) > 0:
self.report(
{'WARNING'}, f"Found {len(category.logs)} libraries outside of the project root."
)
else:
self.report({'INFO'}, f"No libraries outside of project found.")
return {'FINISHED'}
registry = [
BLENLOG_OT_report_missing_libraries,
BLENLOG_OT_report_absolute_libraries,
BLENLOG_OT_report_libraries_out_of_folder,
]
@@ -0,0 +1,155 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.props import StringProperty
from ..id_types import get_id
def get_blender_number_suffix(name):
if name[-4] == "." and str.isdecimal(name[-3:]):
return name[-4:]
return ""
def name_without_number(name):
suffix = get_blender_number_suffix(name)
if suffix:
return name[:-4]
class BLENLOG_OT_rename_obdata(bpy.types.Operator):
"""Disable fake user flag on the collection"""
bl_idname = "blenlog.rename_object_data"
bl_label = "Rename Object Data"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
obj_name: StringProperty()
def execute(self, context):
obj = bpy.data.objects.get((self.obj_name, None))
if not obj:
self.report({'WARNING'}, "Object no longer exists.")
else:
if obj.data.name != obj.name:
obj.data.name = obj.name
if hasattr(obj.data, 'shape_keys') and obj.data.shape_keys:
if obj.data.shape_keys.name != obj.name:
obj.data.shape_keys.name = obj.name
self.report({'INFO'}, "Object data renamed.")
context.scene.blender_log.remove_active()
return {'FINISHED'}
class BLENLOG_OT_report_obdata_names(bpy.types.Operator):
"""Report objects with data or shape keys not named the same as the object"""
bl_idname = "blenlog.report_obdata_name_mismatch"
bl_label = "Report Mis-Named Object Datas"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
def execute(self, context):
blenlog = context.scene.blender_log
category = "Object Data Name Mismatch"
blenlog.clear_category(category)
counter = 0
for obj in bpy.data.objects:
if not obj.data:
continue
# Skip if obj or data is linked
if obj.library or obj.override_library or obj.data.library or obj.data.override_library:
continue
if obj.data.name != obj.name:
blenlog.add(
name=obj.name + " (Data)",
category=category,
description="Object data is not named the same as the containing object. This is unavoidable for multi-user object datas though.",
icon='FILE_TEXT',
operator=BLENLOG_OT_rename_obdata.bl_idname,
op_kwargs={'obj_name': obj.name},
op_icon='GREASEPENCIL',
)
counter += 1
if not hasattr(obj.data, 'shape_keys'):
continue
if not obj.data.shape_keys:
continue
if obj.data.shape_keys.name != obj.name:
blenlog.add(
name=obj.name + " (Shape Key Data)",
category=category,
description="Shape Key datablock is not named the same as the containing object. This is unavoidable for multi-user object datas though.",
icon='FILE_TEXT',
operator=BLENLOG_OT_rename_obdata.bl_idname,
op_kwargs={'obj_name': obj.name},
op_icon='GREASEPENCIL',
)
counter += 1
if counter == 0:
self.report({'INFO'}, "No objects with mismatched data names.")
else:
self.report({'WARNING'}, f"Found {counter} mismatched datablock names.")
return {'FINISHED'}
class BLENLOG_OT_rename_id(bpy.types.Operator):
"""Rename a local ID"""
bl_idname = "blenlog.rename_id"
bl_label = "Rename ID"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
id_name: StringProperty()
id_type: StringProperty()
new_name: StringProperty(name="Name")
def invoke(self, context, _event):
if not self.new_name:
self.new_name = self.id_name
if get_blender_number_suffix(self.new_name):
self.new_name = name_without_number(self.new_name)
return context.window_manager.invoke_props_dialog(self)
def draw(self, context):
self.layout.prop(self, 'new_name')
if get_id(self.new_name, self.id_type):
self.layout.alert = True
self.layout.label(text="This name is already taken.", icon='ERROR')
def execute(self, context):
id = get_id(self.id_name, self.id_type)
if not id:
self.report({'ERROR'}, f"ID no longer exists: {self.id_name}.")
return {'CANCELLED'}
existing_id = get_id(self.new_name, self.id_type)
if existing_id:
self.report({'ERROR'}, f"ID name already taken: {self.new_name}.")
return {'CANCELLED'}
if id.name != self.new_name:
id.name = self.new_name
self.report(
{'INFO'},
f"{self.id_type.title()} successfully renamed from {self.id_name} to {self.new_name}.",
)
context.scene.blender_log.remove_active()
return {'FINISHED'}
registry = [
BLENLOG_OT_report_obdata_names,
BLENLOG_OT_rename_obdata,
BLENLOG_OT_rename_id,
]
@@ -0,0 +1,191 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.props import StringProperty
from .names import get_blender_number_suffix
from ..id_types import get_id
def get_desired_override_name(id):
override = id.override_library
if not override:
return id.name
suffix = get_blender_number_suffix(override.hierarchy_root.name)
return override.reference.name + suffix
class BLENLOG_OT_report_library_overrides(bpy.types.Operator):
"""Report various issues relating to library overrides"""
bl_idname = "blenlog.report_library_overrides"
bl_label = "Report Library Overrides"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
def execute(self, context):
blenlog = context.scene.blender_log
leftovers = report_leftover_overrides(context)
if leftovers:
self.report(
{'WARNING'}, f"There are override leftover collections in the file: {leftovers}"
)
cat_name_taken = "Override Name Occupied"
blenlog.clear_category(cat_name_taken)
cat_name_wrong = "Override Name Mismatch"
blenlog.clear_category(cat_name_wrong)
cat_name_conflict = "Override Name Conflict"
blenlog.clear_category(cat_name_conflict)
objects = [obj for obj in bpy.data.objects if obj.override_library]
collections = [coll for coll in bpy.data.collections if coll.override_library]
iter_stuff = [
('OBJECT', bpy.data.objects, objects),
('COLLECTION', bpy.data.collections, collections),
]
counter = 0
for id_type, propcoll, ids in iter_stuff:
for id in ids:
desired_name = get_desired_override_name(id)
if id.name == desired_name:
continue
counter += 1
occupied = propcoll.get((desired_name, None))
if occupied:
if get_desired_override_name(occupied) == occupied.name:
blenlog.add(
description=f"Inherent override name conflict! {id.name} should be named {desired_name}, which is already taken by an object that is named correctly. This issue cannot be fixed locally. The number suffix in the name must be removed in the original library ({id.override_library.reference.library.filepath}), or one of the overridden objects must be deleted.",
icon='LIBRARY_DATA_OVERRIDE',
name=id.name,
category=cat_name_conflict,
)
else:
blenlog.add(
description=f"Desired overridden {id_type} name '{desired_name}' is already taken from {id.name}. All names should be fixed recursively such that each ID is named after its reference library ID, plus the number suffix of the override hierarchy root.",
icon='LIBRARY_DATA_OVERRIDE',
name=id.name,
category=cat_name_taken,
operator=BLENLOG_OT_recursive_override_name_fix.bl_idname,
op_kwargs={'id_name': id.name, 'id_type': id_type},
)
else:
blenlog.add(
description=f"Overridden object name doesn't match referenced library object name.",
icon='LIBRARY_DATA_OVERRIDE',
name=id.name,
category=cat_name_wrong,
operator='blenlog.rename_id',
op_kwargs={
'id_name': id.name,
'id_type': id_type,
'new_name': desired_name,
},
)
if counter > 0:
self.report({'WARNING'}, f"Found {counter} wrong override names.")
else:
self.report({'INFO'}, f"All overrides are named correctly.")
return {'FINISHED'}
def report_leftover_overrides(context):
blenlog = context.scene.blender_log
category = 'Leftover Overrides'
blenlog.clear_category(category)
leftovers = [
c
for c in bpy.data.collections
if c.name in {'OVERRIDE_RESYNC_LEFTOVERS', 'OVERRIDE_HIDDEN'}
]
for leftover in leftovers:
blenlog.add(
description=f"Override Resync Leftovers are left behind when an override data hierarchy became ambiguous. This should be extremely rare. Check your overrides for any issues, then you can delete these leftovers.",
icon='LIBRARY_DATA_OVERRIDE',
name=leftover.name,
category=category,
operator=BLENLOG_OT_delete_collection_hierarchy.bl_idname,
op_kwargs={
'coll_name': leftover.name,
},
)
return leftovers
class BLENLOG_OT_delete_collection_hierarchy(bpy.types.Operator):
"""Delete a collection hierarchy"""
bl_idname = "blenlog.delete_collection_hierarchy"
bl_label = "Delete Collection Hierarchy"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
coll_name: StringProperty()
def execute(self, context):
coll = bpy.data.objects.get((self.coll_name, None))
if not coll:
self.report({'INFO'}, f'Collection "{self.coll_name}" had already been removed.')
return {'CANCELLED'}
bpy.data.collections.remove(coll)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=False, do_recursive=True)
self.report(
{'INFO'},
f"Removed collection {self.coll_name} and purged the blend file of any unused datablocks.",
)
logs = context.scene.blender_log
logs.remove(logs.active_log)
return {'FINISHED'}
class BLENLOG_OT_recursive_override_name_fix(bpy.types.Operator):
"""Recursively rename override object names that occupy each other's names, to the correct suffixes. Useful when the object names of duplicated overrides get tangled up"""
bl_idname = "blenlog.recursive_override_name_fix"
bl_label = "Recursive Override Name Fix"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
id_name: StringProperty()
id_type: StringProperty()
def execute(self, context):
blenlog = context.scene.blender_log
id = get_id(self.id_name, self.id_type)
if not id:
self.report({'ERROR'}, f"{self.id_type} '{self.id_name}' no longer exists.")
blenlog.remove_active()
return {'CANCELLED'}
override_recursive_rename(id)
blenlog.remove_active()
return {'FINISHED'}
def override_recursive_rename(override_id):
"""Try to rename an override object to its desired name, which is the name of its
referenced link ID, plus this override's root hierarchy number suffix, if any."""
desired_name = get_desired_override_name(override_id)
if desired_name == override_id.name:
return
occupying = get_id(desired_name, override_id.id_type)
if occupying:
override_recursive_rename(occupying)
print("Renaming ", override_id.name, "to", desired_name)
override_id.name = desired_name
registry = [
BLENLOG_OT_report_library_overrides,
BLENLOG_OT_delete_collection_hierarchy,
BLENLOG_OT_recursive_override_name_fix,
]
@@ -0,0 +1,502 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from typing import List, Dict, Set, Optional, Tuple
from bpy.types import Collection, Object, Operator
def outliner_get_active_id(context):
"""Helper function for Blender 3.6 and 4.0 cross-compatibility."""
if not context.area.type == 'OUTLINER':
return
if hasattr(context, 'id'):
# Blender 4.0: Active ID is explicitly exposed to PyAPI, yay.
return context.id
elif len(context.selected_ids) > 0:
# Blender 3.6 and below: We can only hope first selected ID happens to be the active one.
return context.selected_ids[0]
class OUTLINER_OT_relink_overridden_asset(Operator):
"""Relink an overridden asset. Can be useful to recover assets from all sorts of broken states, but may lose un-keyed overridden values. Should preserve bone constraints, active actions of armatures, and any outside references to objects within the asset. Will also purge the .blend file and unlink the OVERRIDE_HIDDEN collection if present, out of necessity"""
bl_idname = "object.relink_overridden_asset"
bl_label = "Relink Overridden Asset"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return cls.get_id(context)
def invoke(self, context, _event):
return context.window_manager.invoke_props_dialog(self)
@staticmethod
def get_id(context) -> Optional[bpy.types.ID]:
if context.area.type == 'OUTLINER':
active_id = outliner_get_active_id(context)
if not active_id:
return
if active_id.override_library:
return active_id
else:
if context.object and context.object.override_library:
return context.object
elif context.collection and context.collection.override_library:
return context.collection
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.label(text="Relink this asset? Un-keyed values may get reset!")
id = self.get_id(context)
layout.prop(id.override_library, 'hierarchy_root')
def execute(self, context):
id = self.get_id(context)
old_hierarchy_root = id.override_library.hierarchy_root
relink_single_override_hierarchy(context, old_hierarchy_root)
return {'FINISHED'}
def relink_all_override_hierarchies(context):
hierarchy_roots = get_override_hierarchy_roots()
new_hierarchy_roots = []
for hierarchy_root in hierarchy_roots:
print("Relinking override hierarchy: ", hierarchy_root.name)
new_hierarchy_root = recreate_override_hierarchy(context, hierarchy_root)
relink_data(new_hierarchy_root, hierarchy_root)
insert_missing_keys(new_hierarchy_root, hierarchy_root)
empty_map = remap_users_to_temp_empties(new_hierarchy_root, hierarchy_root)
clear_collection_hierarchy_fake_user(hierarchy_root)
remap_users_from_temp_empties(empty_map, new_hierarchy_root)
new_hierarchy_roots.append(new_hierarchy_root)
nuke_override_hidden()
better_purge(context)
for new_hierarchy_root in new_hierarchy_roots:
restore_names(new_hierarchy_root)
def get_override_hierarchy_roots():
hierarchy_roots = set()
for coll in bpy.data.collections:
if coll.override_library:
parents = get_parent_collections(coll)
if any([parent.library or parent.override_library for parent in parents]):
# If this is a collection nested inside another override library, it is NOT considered a hierarchy root in this scene.
continue
hierarchy_roots.add(coll.override_library.hierarchy_root)
return hierarchy_roots
def relink_single_override_hierarchy(context, hierarchy_root: Collection):
new_hierarchy_root = recreate_override_hierarchy(context, hierarchy_root)
relink_data(new_hierarchy_root, hierarchy_root)
insert_missing_keys(new_hierarchy_root, hierarchy_root)
empty_map = remap_users_to_temp_empties(new_hierarchy_root, hierarchy_root)
clear_collection_hierarchy_fake_user(hierarchy_root)
nuke_override_hidden()
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_recursive=True, do_linked_ids=True)
remap_users_from_temp_empties(empty_map, new_hierarchy_root)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_recursive=True, do_linked_ids=True)
restore_names(new_hierarchy_root)
def relink_data(new_hierarchy_root, old_hierarchy_root):
new_to_old_obj_map = map_new_to_old_objects(new_hierarchy_root, old_hierarchy_root)
for new_obj, old_obj in new_to_old_obj_map.items():
# Re-link Object Constraints.
if old_obj:
for old_con in old_obj.constraints:
if old_con.name not in new_obj.constraints:
new_obj.constraints.copy(old_con)
# Mark Object with added constraints as editable.
new_obj.override_library.is_system_override = False
if new_obj.type == 'ARMATURE':
# Re-link Action.
if old_obj.animation_data and old_obj.animation_data.action:
new_obj.animation_data_create()
new_obj.animation_data.action = old_obj.animation_data.action
# Re-link Pose Constraints.
for pb_old in old_obj.pose.bones:
pb_new = new_obj.pose.bones[pb_old.name]
for old_con in pb_old.constraints:
if old_con.name not in pb_new.constraints:
pb_new.constraints.copy(old_con)
def map_new_to_old_objects(
new_hierarchy_root: Collection,
old_hierarchy_root: Collection,
) -> Dict[Object, Object]:
"""Use the common linked ID reference of two override collection hierarchies to
construct a name-agnostic object mapping from one to the other."""
assert (
new_hierarchy_root.override_library.reference.library
== old_hierarchy_root.override_library.reference.library
), "The two collections must be an override of the same linked collection."
new_to_old_obj_map = {}
old_link_map = map_objects_of_linked_to_override_hierarchy(old_hierarchy_root)
for new_obj in new_hierarchy_root.all_objects:
if not new_obj.override_library:
# Some objects could still be directly linked, ie. rig widgets.
continue
ref = old_link_map.get(new_obj.override_library.reference)
if ref:
new_to_old_obj_map[new_obj] = ref
return new_to_old_obj_map
def recreate_override_hierarchy(context, old_hierarchy_root: Collection) -> Collection:
"""Create a fresh overridden copy of an existing overridden collection,
replacing it in existing collections with the fresh copy.
- All collection assignments are preserved
- Only Armature objects are marked as editable
"""
linked_hierarchy_root = old_hierarchy_root.override_library.reference
parent_colls = collection_unlink_from_parents(old_hierarchy_root)
assert (
parent_colls
), "Expected the override hierarchy root to be assigned to at least one parent collection."
override_hierarchy_root = linked_hierarchy_root.override_hierarchy_create(
context.scene, context.view_layer
)
# By default, this gets linked to the scene's root. We don't want that.
context.scene.collection.children.unlink(override_hierarchy_root)
# Link the collection to the parent collections.
for parent_coll in parent_colls:
parent_coll.children.link(override_hierarchy_root)
for obj in override_hierarchy_root.all_objects:
if obj.type == 'ARMATURE':
obj.override_library.is_system_override = False
return override_hierarchy_root
def get_overridden_but_not_animated_properties(
hierarchy_root: Collection,
) -> Dict[Object, List[str]]:
obj_to_prop_list_map = {}
for obj in hierarchy_root.all_objects:
props_that_need_keying = []
if not obj.override_library or not obj.override_library.reference:
continue
all_overridden_props = [prop.rna_path for prop in obj.override_library.properties]
driven_props = []
animated_props = []
if obj.animation_data and obj.animation_data.drivers:
driven_props = [fcurve.data_path for fcurve in obj.animation_data.drivers]
if obj.animation_data and obj.animation_data.action:
animated_props = [fcurve.data_path for fcurve in obj.animation_data.action.fcurves]
for overridden_prop in all_overridden_props:
if overridden_prop not in driven_props and overridden_prop not in animated_props:
props_that_need_keying.append(overridden_prop)
if props_that_need_keying:
obj_to_prop_list_map[obj.override_library.reference] = props_that_need_keying
return obj_to_prop_list_map
def insert_missing_keys(new_hierarchy_root, old_hierarchy_root):
old_overridden_not_animated = get_overridden_but_not_animated_properties(old_hierarchy_root)
new_overridden_not_animated = get_overridden_but_not_animated_properties(new_hierarchy_root)
old_link_map = map_objects_of_linked_to_override_hierarchy(old_hierarchy_root)
new_link_map = map_objects_of_linked_to_override_hierarchy(new_hierarchy_root)
for linked_obj, old_prop_list in old_overridden_not_animated.items():
if not old_prop_list or linked_obj not in new_overridden_not_animated:
continue
new_prop_list = new_overridden_not_animated[linked_obj]
missing = []
for rna_path in old_prop_list:
if rna_path in ['animation_data.action']:
# This should be overridden by now, not sure why it shows up here...
continue
if "is_active" in rna_path:
continue
owner_path, prop_name = rna_path_split_owner(rna_path)
if prop_name in ["", "name", "mute", "lock", "nla_tracks"]:
continue
if rna_path not in new_prop_list:
missing.append(rna_path)
if missing:
old_override_obj = old_link_map[linked_obj]
new_override_obj = new_link_map[linked_obj]
print(f"{old_override_obj.name} had manually overridden but not animated RNA paths: ")
for rna_path in missing:
old_value = old_override_obj.path_resolve(rna_path)
owner_path, prop_name = rna_path_split_owner(rna_path)
new_owner = new_override_obj.path_resolve(owner_path)
setattr(new_owner, prop_name, old_value)
success = new_owner.keyframe_insert(prop_name)
if success:
print(" Inserted keyframe:", rna_path, old_value)
else:
print(" Failed to insert keyframe ", rna_path, old_value)
def rna_path_split_owner(rna_path: str) -> Tuple[str, str]:
"""Split the last part of an RNA path from the rest.
This supports 2 cases:
Either the path ends in `.some_prop`
Or it ends in a custom property name which looks `["like this"]`.
"""
if rna_path.endswith('"]'):
owner, prop = rna_path.rsplit('["', maxsplit=1)
prop = '["' + prop
return owner, prop
elif "." in rna_path:
return rna_path.rsplit(".", maxsplit=1)
else:
return rna_path, ""
def remap_users_to_temp_empties(new_hierarchy_root, old_hierarchy_root) -> Dict[Object, Object]:
# We need to remap users from the old to the new objects, but doing
# that in a straight forward way causes a crash.
# So, let's create placeholder objects for each old object, that will
# get user remapped to, then delete all the old stuff, then user remap from the placeholders to the new objects.
empty_map = {}
old_objs = list(old_hierarchy_root.all_objects) + get_objects_in_override_hidden(
new_hierarchy_root
)
for old_obj in old_objs:
if not old_obj.override_library or not old_obj.override_library.reference:
continue
# Create an empty object corresponding to each old object...
name = "REMAP_" + str(old_obj.name)
empty = bpy.data.objects.new(name=name, object_data=None)
empty.use_fake_user = True
old_obj.user_remap(empty)
empty_map[old_obj.override_library.reference] = empty
return empty_map
def remap_users_from_temp_empties(empty_map, new_hierarchy_root):
for new_obj in list(new_hierarchy_root.all_objects):
if not new_obj.override_library:
continue
# Map users from empty to new obj, then delete the empty
empty = empty_map.get(new_obj.override_library.reference)
if not empty:
continue
empty.user_remap(new_obj)
empty_map.pop(new_obj.override_library.reference)
bpy.data.objects.remove(empty)
for empty in empty_map.values():
# This usually won't do anything, but since we gave them fake users, let's keep it here just in case.
bpy.data.objects.remove(empty)
def rename_override_objects():
"""Try renaming overridden objects back to the name of the linked ID they are overriding."""
for o in bpy.data.objects:
if not o.override_library:
continue
desired_name = o.override_library.reference.name
if o.name == desired_name:
continue
occupier = bpy.data.objects.get((desired_name, None))
if occupier:
new_name = occupier.name + ".temp"
occupier.name = new_name
print("Renaming ob: ", o.name, " -> ", desired_name)
o.name = desired_name
if occupier:
occupier.name = o.name
def get_mapping_from_linked_to_overriding_ids() -> Dict[bpy.types.ID, List[bpy.types.ID]]:
"""Build a mapping from linked datablocks to their override IDs."""
override_map = {}
for o in bpy.data.objects:
if o.override_library:
linked_id = o.override_library.reference
if linked_id not in override_map:
override_map[linked_id] = []
override_map[linked_id].append(o)
return override_map
def reassign_objects_to_collections():
"""This function would re-assign objects to the right collections;
This is blocked by the PyAPI though, so this code doesn't actually work."""
override_map = get_mapping_from_linked_to_overriding_ids()
for coll in bpy.context.scene.collection.children_recursive:
if not coll.override_library:
continue
linked_coll = coll.override_library.reference
for linked_id in linked_coll.objects:
override_ids = override_map.get(linked_id)
if not override_ids:
continue
if len(override_ids) == 1:
override = override_ids[0]
if not override.name in coll.objects:
coll.objects.link(override)
else:
print("Multiple overriding IDs, not sure which one to assign:", linked_id)
def get_parent_collections(target_coll: bpy.types.Collection) -> Set[bpy.types.Collection]:
"""Return a set of the parents of a collection."""
parent_colls = set()
for parent_coll in [scene.collection for scene in bpy.data.scenes] + list(bpy.data.collections):
for child_coll in parent_coll.children:
if child_coll == target_coll:
parent_colls.add(parent_coll)
return parent_colls
def collection_unlink_from_parents(coll: bpy.types.Collection) -> Set[bpy.types.Collection]:
"""Unlink a collection from all of its parents, and return a set of those parents."""
parent_colls = get_parent_collections(coll)
for parent_coll in parent_colls:
parent_coll.children.unlink(coll)
return parent_colls
def clear_collection_hierarchy_fake_user(coll: bpy.types.Collection):
"""Set the Fake User flag of a collection and all of its children to False,
so that it can be purged."""
for coll in [coll] + coll.children_recursive:
coll.use_fake_user = False
def map_objects_of_linked_to_override_hierarchy(
root_override: bpy.types.Collection,
) -> Dict[bpy.types.Object, bpy.types.Object]:
"""Map linked objects to their overrides, given a hierarchy root of that override."""
obj_map = {}
for obj in root_override.all_objects:
if not obj.override_library:
continue
obj_map[obj.override_library.reference] = obj
return obj_map
def restore_names(override_root: bpy.types.Collection):
for obj in override_root.all_objects:
if obj.override_library and obj.name != obj.override_library.reference.name:
obj.name = obj.override_library.reference.name
for coll in [override_root] + override_root.children_recursive:
if coll.override_library and coll.name != coll.override_library.reference.name:
coll.name = coll.override_library.reference.name
def __cleanup_override_hidden(override_root: bpy.types.Collection):
"""This sadly doesn't work.
It was meant to unlink only those objects from the OVERRIDE_HIDDEN collection,
which have copies in the passet override_root collection (override referencing same linked ID)
But I don't have time to troubleshoot it; It's easier to just nuke the OVERRIDE_HIDDEN collection.
"""
override_hidden = bpy.data.collections.get('OVERRIDE_HIDDEN')
if not override_hidden:
return
link_map = map_objects_of_linked_to_override_hierarchy(override_hidden)
print("LINK MAP:")
for key, value in link_map.items():
print(key, " : ", value)
objs_to_remove = []
for obj in override_root.all_objects:
if not obj.override_library:
continue
hidden_obj = link_map.get(obj.override_library.reference)
if not hidden_obj:
continue
print("MATCH: ", obj, " : ", hidden_obj)
objs_to_remove.append(hidden_obj)
for obj in objs_to_remove:
override_hidden.objects.unlink(obj)
def nuke_override_hidden():
nukelist = [c for c in bpy.data.collections if 'OVERRIDE_HIDDEN' in c.name]
for coll in nukelist:
bpy.data.collections.remove(coll)
def get_objects_in_override_hidden(
linked_collection: bpy.types.Collection,
) -> List[bpy.types.Object]:
override_hidden_list = [c for c in bpy.data.collections if 'OVERRIDE_HIDDEN' in c.name]
if not override_hidden_list:
return []
all_linked_objs = list(linked_collection.all_objects)
ret = []
for coll in override_hidden_list:
for obj in coll.all_objects:
if not obj.override_library:
continue
if obj.override_library.reference in all_linked_objs:
ret.append(obj)
return ret
def draw_relink_ui(self, context):
self.layout.separator()
self.layout.operator(OUTLINER_OT_relink_overridden_asset.bl_idname, text="Purge & Re-link")
registry = [
OUTLINER_OT_relink_overridden_asset,
]
def register():
bpy.types.VIEW3D_MT_object_liboverride.append(draw_relink_ui)
bpy.types.OUTLINER_MT_liboverride.append(draw_relink_ui)
def unregister():
bpy.types.OUTLINER_MT_liboverride.append(draw_relink_ui)
bpy.types.OUTLINER_MT_liboverride.remove(draw_relink_ui)
@@ -0,0 +1,263 @@
# SPDX-FileCopyrightText: 2025 Blender Studio Tools Authors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import bpy
from bpy.props import StringProperty, CollectionProperty
from ..id_types import get_id, get_id_storage_by_type_str, get_datablock_icon, get_library_icon
class BLENLOG_OT_report_fake_users(bpy.types.Operator):
"""Report Fake User IDs. Ignores Text and Brush IDs"""
bl_idname = "blenlog.report_fake_users"
bl_label = "Report Fake Users"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
def execute(self, context):
user_map = bpy.data.user_map()
blenlog = context.scene.blender_log
category = "Fake User ID"
blenlog.clear_category(category)
for id, users in user_map.items():
if id.library or id.override_library:
continue
if id.id_type not in {'BRUSH', 'TEXT'} and id.use_fake_user:
blenlog.add(
name=f"{id.id_type}: {id.name} (Users: {len(users)})",
category=category,
description="Datablocks with fake users can cause further referenced datablocks to linger in the file. It is recommended not to use fake users, in order to keep files clear of trash data.",
icon='FAKE_USER_ON',
operator=BLENLOG_OT_clear_fake_user.bl_idname,
op_kwargs={'id_name': id.name, 'id_type': id.id_type},
op_icon='FAKE_USER_OFF',
)
return {'FINISHED'}
class BLENLOG_OT_remap_users(bpy.types.Operator):
"""Remap users of an ID to another of the same type"""
bl_idname = "blenlog.remap_users"
bl_label = "Remap Users"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
redundant_id: StringProperty()
id_type: StringProperty()
preserved_id: StringProperty()
def execute(self, context):
redundant_id = get_id(self.redundant_id, self.id_type)
if not redundant_id:
self.report({'ERROR'}, f"ID no longer exists: {self.redundant_id}.")
return {'CANCELLED'}
preserved_id = get_id(self.preserved_id, self.id_type)
if not preserved_id:
self.report({'ERROR'}, f"ID no longer exists: {self.preserved_id}.")
return {'CANCELLED'}
redundant_id.user_remap(preserved_id)
redundant_id.use_fake_user = False
self.report({'INFO'}, f"{self.redundant_id} has been replaced with {self.preserved_id}")
context.scene.blender_log.remove_active()
return {'FINISHED'}
### Remap Users
class RemapTarget(bpy.types.PropertyGroup):
pass
# TODO: This code also exists in the 3D Viewport Pie Menus add-on. Keep code in sync at least?
class BLENLOG_OT_remap_users_ui(bpy.types.Operator):
"""Remap users of a selected ID to any other ID of the same type"""
bl_idname = "outliner.remap_users"
bl_label = "Remap Users"
bl_options = {'INTERNAL', 'UNDO'}
def update_library_path(self, context):
# Prepare the ID selector.
blenlog_remap_targets = context.scene.blenlog_remap_targets
blenlog_remap_targets.clear()
source_id = get_id(self.id_name_source, self.id_type, self.library_path_source)
for id in get_id_storage_by_type_str(self.id_type)[0]:
if id == source_id:
continue
if (self.library_path == 'Local Data' and not id.library) or (
id.library and (self.library_path == id.library.filepath)
):
id_entry = blenlog_remap_targets.add()
id_entry.name = id.name
library_path: StringProperty(
name="Library",
description="Library path, if we want to remap to a linked ID",
update=update_library_path,
)
id_type: StringProperty(description="ID type, eg. 'OBJECT' or 'MESH'")
library_path_source: StringProperty()
id_name_source: StringProperty(
name="Source ID Name", description="Name of the ID we're remapping the users of"
)
id_name_target: StringProperty(
name="Target ID Name", description="Name of the ID we're remapping users to"
)
def invoke(self, context, _event):
# Populate the blenlog_remap_targets string list with possible options based on
# what was passed to the operator.
assert (
self.id_type and self.id_name_source
), "Error: UI must provide ID and ID type to this operator."
# Prepare the library selector.
blenlog_remap_target_libs = context.scene.blenlog_remap_target_libs
blenlog_remap_target_libs.clear()
local = blenlog_remap_target_libs.add()
local.name = "Local Data"
source_id = get_id(self.id_name_source, self.id_type, self.library_path_source)
for lib in bpy.data.libraries:
for id in lib.users_id:
if type(id) == type(source_id):
lib_entry = blenlog_remap_target_libs.add()
lib_entry.name = lib.filepath
break
self.library_path = "Local Data"
if source_id.name[-4] == ".":
storage = get_id_storage_by_type_str(self.id_type)[0]
suggestion = storage.get(source_id.name[:-4])
if suggestion:
self.id_name_target = suggestion.name
if suggestion.library:
self.library_path = suggestion.library.filepath
return context.window_manager.invoke_props_dialog(self, width=800)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
scene = context.scene
row = layout.row()
id = get_id(self.id_name_source, self.id_type, self.library_path_source)
id_icon = get_datablock_icon(id)
split = row.split()
split.row().label(text="Anything that was referencing this:")
row = split.row()
row.prop(self, 'id_name_source', text="", icon=id_icon)
row.enabled = False
layout.separator()
col = layout.column()
col.label(text="Will now reference this instead: ")
if len(scene.blenlog_remap_target_libs) > 1:
col.prop_search(
self,
'library_path',
scene,
'blenlog_remap_target_libs',
icon=get_library_icon(self.library_path),
)
col.prop_search(
self,
'id_name_target',
scene,
'blenlog_remap_targets',
text="Datablock",
icon=id_icon,
)
def execute(self, context):
source_id = get_id(self.id_name_source, self.id_type, self.library_path_source)
target_id = get_id(self.id_name_target, self.id_type, self.library_path)
assert source_id and target_id, "Error: Failed to find source or target."
source_id.user_remap(target_id)
return {'FINISHED'}
class BLENLOG_OT_clear_fake_user(bpy.types.Operator):
"""Clear the fake user flag of an ID."""
bl_idname = "blenlog.clear_fake_user"
bl_label = "Clear Fake User"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
id_name: StringProperty()
id_type: StringProperty()
def execute(self, context):
id = get_id(self.id_name, self.id_type)
if not id:
self.report({'INFO'}, f"{self.id_type} {self.id_name} had already been removed.")
else:
id.use_fake_user = False
self.report(
{'INFO'}, f"{self.id_type} {self.id_name} no longer marked with a fake user."
)
context.scene.blender_log.remove_active()
return {'FINISHED'}
class BLENLOG_OT_report_missing_IDs(bpy.types.Operator):
"""Report Fake User IDs. Ignores Text and Brush IDs"""
bl_idname = "blenlog.report_missing_ids"
bl_label = "Report Missing IDs"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
def execute(self, context):
user_map = bpy.data.user_map()
blenlog = context.scene.blender_log
category = "Missing ID"
blenlog.clear_category(category)
for id, users in user_map.items():
if id.library or id.override_library:
continue
if id.id_type not in {'BRUSH', 'TEXT'} and id.use_fake_user:
blenlog.add(
name=f"{id.id_type}: {id.name} (Users: {len(users)})",
category=category,
description="A linked ID was being referenced locally, and then removed from its library. The missing ID can be remapped to another.",
icon='LIBRARY_DATA_BROKEN',
operator=BLENLOG_OT_clear_fake_user.bl_idname,
op_kwargs={'id_name': id.name, 'id_type': id.id_type},
op_icon='FAKE_USER_OFF',
)
return {'FINISHED'}
registry = [
BLENLOG_OT_report_fake_users,
BLENLOG_OT_remap_users,
RemapTarget,
BLENLOG_OT_remap_users_ui,
BLENLOG_OT_clear_fake_user,
]
def register():
bpy.types.Scene.blenlog_remap_targets = CollectionProperty(type=RemapTarget)
bpy.types.Scene.blenlog_remap_target_libs = CollectionProperty(type=RemapTarget)
def unregister():
del bpy.types.Scene.blenlog_remap_targets
del bpy.types.Scene.blenlog_remap_target_libs
+77
View File
@@ -0,0 +1,77 @@
import bpy
from bpy.types import AddonPreferences
from bpy.props import BoolProperty, StringProperty
from .ui import change_ui_category
from .util import get_addon_prefs
from .operators import better_delete
class BlenLog_Prefs(AddonPreferences):
bl_idname = __package__
def update_sidebar_panel(self, context):
change_ui_category(self.sidebar_panel)
sidebar_panel: StringProperty(
name="Sidebar Panel",
description="Define which sidebar panel the Blender Log should appear in",
default="Blender Log",
update=update_sidebar_panel,
)
purge_on_save: BoolProperty(
name="Purge On Save",
description="Run a recursive purge on file save, rather than simply not saving unused datablocks, which is Blender's default behaviour. This ensures your file is never saved with any garbage orphan data",
default=False,
)
def update_deletion_pie(self, context):
if self.use_deletion_pie:
better_delete.register_hotkeys()
else:
better_delete.unregister_hotkeys()
use_deletion_pie: BoolProperty(
name="Delete Pie On X",
description="Overwrite the X hotkey in the 3D View and the Outliner for more truthful deletion behaviours",
default=False,
update=update_deletion_pie
)
display_stack_trace: BoolProperty(
name="Display Stack Trace",
description="Whether to display the Python Stack Trace of a log entry. Only useful for Python developers",
default=False,
)
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout = layout.column(align=True)
layout.label(text="Cosmetic:")
layout.prop(self, 'sidebar_panel')
layout.separator()
layout.label(text="Debug:")
layout.prop(self, 'display_stack_trace')
layout.separator()
layout.label(text="Mistake Avoidance:")
layout.prop(self, 'purge_on_save')
layout.prop(self, 'use_deletion_pie')
registry = [BlenLog_Prefs]
@bpy.app.handlers.persistent
def delayed_register(_):
prefs = get_addon_prefs(bpy.context)
prefs.sidebar_panel = prefs.sidebar_panel
def register():
bpy.app.handlers.load_post.append(delayed_register)
def unregister():
bpy.app.handlers.load_post.remove(delayed_register)
+187
View File
@@ -0,0 +1,187 @@
from bpy.types import PropertyGroup
from bpy.props import (
StringProperty,
IntProperty,
CollectionProperty,
PointerProperty,
)
import bpy, json
from .util import get_pretty_stack
class BlenderLog_Entry(PropertyGroup):
"""Container for storing information about a single metarig warning/error.
A CollectionProperty of CloudRigLogEntries are added to the armature datablock
in cloud_generator.register().
This CollectionProperty is then populated by a BlenderLog_Manager instance created by
CloudRig_Generator, which is created by the Generate operator.
"""
name: StringProperty(name="Name", description="Name of issue", default="")
category: StringProperty(
name="Category", description="For internal categorization of log entries", default=""
)
icon: StringProperty(name="Icon", description="Icon for this log entry", default='ERROR')
description: StringProperty(name="Description", description="Description of issue", default="")
pretty_stack: StringProperty(
name="Pretty Stack",
description="Stack trace in the code of where this log entry was added. For internal use only",
)
operator: StringProperty(
name="Operator", description="Operator that can fix the issue", default=''
)
op_kwargs: StringProperty(
name="Operator Arguments",
description="Keyword arguments that will be passed to the operator. This should be a string that can be eval()'d into a python dict",
default='',
)
op_text: StringProperty(
name="Operator Text",
description="Text to display on the operator button",
default='',
)
op_icon: StringProperty(
name="Operator Icon",
description="Icon to display on the operator button",
default='',
)
class BlenderLog_Category(PropertyGroup):
name: StringProperty()
icon: StringProperty()
active_log_index: IntProperty()
logs: CollectionProperty(type=BlenderLog_Entry)
@property
def active_log(self):
if self.active_log_index > len(self.logs) - 1:
return
return self.logs[self.active_log_index]
def get_index(self, log):
for i, l in enumerate(self.logs):
if l == log:
return i
def clear(self):
self.logs.clear()
self.active_log_index = 0
class BlenderLog_Manager(PropertyGroup):
"""Class to manage BlenderLog_Entry CollectionProperty on metarigs.
This class is instanced once per rig generation, by the CloudRig_Generator class.
"""
categories: CollectionProperty(type=BlenderLog_Category)
active_cat_index: IntProperty()
@property
def active_category(self):
if self.active_cat_index > len(self.categories) - 1:
return
return self.categories[self.active_cat_index]
@property
def active_log(self):
return self.active_category.active_log
@property
def all_logs(self):
for cat in self.categories:
for log in cat.logs:
yield log
def add(
self,
name: str,
*,
description="No description.",
icon='ERROR',
category="Uncategorized",
category_icon="",
operator='',
op_kwargs={},
op_text="",
op_icon="",
):
"""Low-level function to add a log entry to the metarig object's data."""
cat_entry = self.categories.get(category)
if not cat_entry:
cat_entry = self.categories.add()
cat_entry.name = category
cat_entry.icon = category_icon or icon
entry = cat_entry.logs.add()
entry.pretty_stack = get_pretty_stack()
entry.name = name
entry.description = description
entry.category = category
entry.icon = icon
entry.operator = operator
entry.op_kwargs = json.dumps(op_kwargs)
entry.op_text = op_text
entry.op_icon = op_icon
return entry
def remove(self, log):
removed = False
for cat in self.categories:
for other_log in cat.logs:
if log == other_log:
cat.logs.remove(cat.get_index(log))
removed = True
break
if removed:
break
if removed and len(cat.logs) == 0:
self.clear_category(cat.name)
def remove_active(self):
self.remove(self.active_log)
def remove_category(self, cat):
self.categories.remove(self.get_index(cat))
def get_category(self, cat_name: str):
for cat in self.categories:
if cat.name == cat_name:
return cat
def get_index(self, cat):
for i, c in enumerate(self.categories):
if c == cat:
return i
def clear_category(self, cat_name: str):
cat = self.get_category(cat_name)
if cat:
cat.clear()
self.categories.remove(self.get_index(cat))
registry = [
BlenderLog_Entry,
BlenderLog_Category,
BlenderLog_Manager,
]
def register():
bpy.types.Scene.blender_log = PointerProperty(type=BlenderLog_Manager)
def unregister():
del bpy.types.Scene.blender_log
+226
View File
@@ -0,0 +1,226 @@
from bpy.types import Panel, UIList, Operator, Menu
import bpy, json
from .util import draw_label_with_linebreak, get_addon_prefs
# TODO: Button to copy log name, or ability to provide an object name and a button to select that object.
class BLENLOG_PT_log_panel(Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Blender Log'
bl_label = "Blender Log"
def draw(self, context):
blenlog = context.scene.blender_log
layout = self.layout
layout.label(text="Log Categories")
row = layout.row()
row.template_list(
'BLENLOG_UL_cat_list',
'',
blenlog,
'categories',
blenlog,
'active_cat_index',
)
ops_col = row.column()
ops_col.menu(BLENLOG_MT_log_checks.bl_idname, text="", icon='VIEWZOOM')
cat = blenlog.active_category
if not cat:
return
ops_col.operator(BLENLOG_OT_remove_category.bl_idname, text="", icon='REMOVE')
layout.operator(BLENLOG_OT_quick_fix_category.bl_idname, icon='AUTO')
layout.separator()
layout.label(text="Entries of Category: " + cat.name)
row = layout.row()
row.template_list(
'BLENLOG_UL_log_list',
'',
cat,
'logs',
cat,
'active_log_index',
)
log = cat.active_log
if not log:
return
layout.use_property_split = False
draw_label_with_linebreak(context, layout, log.description)
if log.operator != '':
row = layout.row()
split = row.split(factor=0.2)
split.label(text="Quick Fix:")
kwargs = {}
if log.op_text:
kwargs['text'] = log.op_text
if log.op_icon:
kwargs['icon'] = log.op_icon
op = split.operator(log.operator, **kwargs)
if op:
kwargs = json.loads(log.op_kwargs)
for key in kwargs.keys():
setattr(op, key, kwargs[key])
else:
row = split.row()
row.alert = True
row.label(text="Missing operator: " + log.operator)
class BLENLOG_PT_stack_trace(Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_parent_id = 'BLENLOG_PT_log_panel'
bl_label = "Python Stack Trace"
bl_options = {'DEFAULT_CLOSED'}
# @classmethod
# def poll(cls, context):
# prefs = get_addon_prefs(context)
# generator = context.object.cloudrig.generator
# if not generator.active_log:
# return False
# display_mode = generator.active_log.display_stack_trace
# return display_mode == 'ALWAYS' or (
# display_mode == 'ADVANCED' and is_advanced_mode(context)
# )
def draw(self, context):
generator = context.object.cloudrig.generator
draw_label_with_linebreak(
context, self.layout, generator.active_log.pretty_stack, alert=True
)
class BLENLOG_UL_log_list(UIList):
"""UI code for list of BlenderLog_Entries."""
def draw_item(self, _context, layout, _data, item, _icon_value, _active_data, _active_propname):
log = item
row = layout.row()
if log.icon:
row.label(text=log.name, icon=log.icon)
else:
row.label(text=log.name)
class BLENLOG_UL_cat_list(UIList):
"""UI code for list of BlenderLog_Categories."""
def draw_item(self, _context, layout, _data, item, _icon_value, _active_data, _active_propname):
cat = item
row = layout.row()
row.label(text=f"{cat.name} ({len(cat.logs)})", icon=cat.icon)
class BLENLOG_MT_log_checks(Menu):
bl_label = "Global Checks"
bl_idname = 'BLENLOG_MT_log_checks'
def draw(self, context):
layout = self.layout
layout.operator(
'blenlog.report_fake_users',
text="Report Fake User Datablocks",
icon='FAKE_USER_ON',
)
layout.operator(
'blenlog.report_obdata_name_mismatch',
text="Report Mis-Named Object Data",
icon='FILE_TEXT',
)
layout.operator(
'blenlog.report_leftover_drivers',
text="Report Leftover Drivers",
icon='DRIVER_TRANSFORM',
)
layout.operator(
'blenlog.report_library_overrides',
text="Report Library Override Issues",
icon='LIBRARY_DATA_OVERRIDE',
)
class BLENLOG_OT_quick_fix_category(Operator):
"""Run the automatic fixing operator for each entry in this category that has one"""
bl_idname = "blenlog.fix_category"
bl_label = "Quick-Fix Issues"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
active_cat = context.scene.blender_log.active_category
return any([log.operator for log in active_cat.logs])
def execute(self, context):
active_cat = context.scene.blender_log.active_category
for i, log in reversed(list(enumerate(active_cat.logs))):
active_cat.active_log_index = i
op_idname = log.operator
if not op_idname:
continue
op_kwargs = json.loads(log.op_kwargs)
op_category, op_name = op_idname.split(".")
op_callable = getattr(getattr(bpy.ops, op_category), op_name)
op_callable(**op_kwargs)
return {'FINISHED'}
class BLENLOG_OT_remove_category(Operator):
"""Remove active log category"""
bl_idname = "blenlog.remove_category"
bl_label = "Remove Category"
bl_options = {'INTERNAL', 'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
return context.scene.blender_log.active_category
def execute(self, context):
context.scene.blender_log.remove_category(context.scene.blender_log.active_category)
return {'FINISHED'}
registry = [
BLENLOG_UL_log_list,
BLENLOG_UL_cat_list,
BLENLOG_MT_log_checks,
BLENLOG_PT_log_panel,
BLENLOG_OT_quick_fix_category,
BLENLOG_OT_remove_category,
]
@bpy.app.handlers.persistent
def update_ui_category(_):
prefs = get_addon_prefs(bpy.context)
change_ui_category(prefs.sidebar_panel)
def change_ui_category(category):
if BLENLOG_PT_log_panel.bl_category != category:
bpy.utils.unregister_class(BLENLOG_PT_log_panel)
BLENLOG_PT_log_panel.bl_category = category
bpy.utils.register_class(BLENLOG_PT_log_panel)
def register():
bpy.app.handlers.depsgraph_update_post.append(update_ui_category)
def unregister():
bpy.app.handlers.depsgraph_update_post.remove(update_ui_category)
+136
View File
@@ -0,0 +1,136 @@
import bpy, sys, traceback, addon_utils
from bpy.types import Object
from . import __package__ as base_package
# NOTE: This file should not import anything from this add-on!
def get_pretty_stack() -> str:
"""Make a pretty looking string out of the current execution stack,
or the exception stack if this is called from a stack which is handling an exception.
(Python is cool in that way - We can tell when this function is being called by
a stack which originated in a try/except block!)
"""
ret = ""
exc_type, exc_value, tb = sys.exc_info()
if exc_value:
# If the stack we're currently on is handling an exception,
# use the stack of that exception instead of our stack
stack = traceback.extract_tb(exc_value.__traceback__)
else:
stack = traceback.extract_stack()
lines = []
after_generator = False
for i, frame in enumerate(stack):
if 'generator' in frame.filename:
after_generator = True
if not after_generator:
continue
if frame.name in (
"log",
"add_log",
"log_fatal_error",
"raise_generation_error",
):
break
# Shorten the file name; All files are in blender's "scripts" folder, so
# that part of the path contains no useful information, just clutter.
short_file = frame.filename
if 'scripts' in short_file:
short_file = frame.filename.split("scripts")[1]
if i > 0 and frame.filename == stack[i - 1].filename:
short_file = " " * int(len(frame.filename) / 2)
lines.append(f"{short_file} -> {frame.name} -> line {frame.lineno}")
ret += f" {chr(8629)}\n".join(lines)
ret += f":\n {frame.line}\n"
if exc_value:
ret += f"{exc_type.__name__}: {exc_value}"
return ret
def get_datablock_type_icon(datablock):
"""Return the icon string representing a datablock type"""
# It's beautiful.
# There's no proper way to get the icon of a datablock, so we use the
# RNA definition of the id_type property of the DriverTarget class,
# which is an enum with a mapping of each datablock type to its icon.
# TODO: It would unfortunately be nicer to just make my own mapping.
if not hasattr(datablock, "type"):
# shape keys...
return 'NONE'
typ = datablock.type
if datablock.type == 'SHADER':
typ = 'NODETREE'
return bpy.types.DriverTarget.bl_rna.properties['id_type'].enum_items[typ].icon
def get_sidebar_size(context):
for region in context.area.regions:
if region.type == 'UI':
return region.width
def draw_label_with_linebreak(context, layout, text, alert=False):
"""Attempt to simulate a proper textbox by only displaying as many
characters in a single label as fits in the UI.
This only works well on specific UI zoom levels.
"""
if text == "":
return
col = layout.column(align=True)
col.alert = alert
paragraphs = text.split("\n")
# Try to determine maximum allowed characters per line, based on pixel width of the area.
# Not a great metric, but I couldn't find anything better.
max_line_length = get_sidebar_size(context) / 8
for p in paragraphs:
lines = [""]
for word in p.split(" "):
if len(lines[-1]) + len(word) + 1 > max_line_length:
lines.append("")
lines[-1] += word + " "
for line in lines:
col.label(text=line)
return col
def get_object_hierarchy_recursive(obj: Object, all_objects=[]):
if obj not in all_objects:
all_objects.append(obj)
for c in obj.children:
get_object_hierarchy_recursive(c, all_objects)
return all_objects
def check_addon(context, addon_name: str) -> bool:
"""Same as addon_utils.check() but account for workspace-specific disabling.
Return whether an addon is enabled in this context.
"""
addon_enabled_in_userprefs = addon_utils.check(addon_name)[1]
if addon_enabled_in_userprefs and context.workspace.use_filter_by_owner:
# Not sure why it's called owner_ids, but it contains a list of enabled addons in this workspace.
addon_enabled_in_workspace = addon_name in context.workspace.owner_ids
return addon_enabled_in_workspace
return addon_enabled_in_userprefs
def get_addon_prefs(context=None):
if not context:
context = bpy.context
if base_package.startswith('bl_ext'):
# 4.2
return context.preferences.addons[base_package].preferences
else:
return context.preferences.addons[base_package.split(".")[0]].preferences