Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
home:darix:playground
gnome-shell-extension-appindicator
_service:obs_scm:gnome-shell-extension-appindic...
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:gnome-shell-extension-appindicator-v34+git1.860086c.obscpio of Package gnome-shell-extension-appindicator
07070100000000000081A40000000200000002000000015F6B6B1600000343000000000000000000000000000000000000003F00000000gnome-shell-extension-appindicator-v34+git1.860086c/AUTHORS.mdThis extension is based on [patches made by Giovanni Campagna](https://bugzilla.gnome.org/show_bug.cgi?id=652122). Authors ordered by first contribution: * Jonas Kümmerlin <rgcjonas@gmail.com> * Damián Nohales <damiannohales@gmail.com> * Dincer Kavraal <dkavraal@gmail.com> * Thomas Schaberreiter <thomassc@ee.oulu.fi> * Hugo Josefson <hugo@josefson.org> * ozamorowski <ozamorowski@gmail.com> * Anthony Ruhier <anthony.ruhier@gmail.com> * Emilien Devos <unixfox@users.noreply.github.com> * Jan Niklas Hasse <jhasse@bixense.com> * Romeo Calota <kicsyromy@gmail.com> * JasonLG1979 <jasonlevigray3@gmail.com> * Martin Wallin <guzzard@gmail.com> * Andrea Azzarone <andrea.azzarone@canonical.com> * Marco Trevisan (Treviño) <mail@3v1n0.net> <!-- created with: git log --reverse --pretty="%an <%ae>%n%cn <%ce>" | awk '!seen[$0]++' --> 07070100000001000081A40000000200000002000000015F6B6B16000046AC000000000000000000000000000000000000003C00000000gnome-shell-extension-appindicator-v34+git1.860086c/LICENSE GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. 07070100000002000081A40000000200000002000000015F6B6B1600000153000000000000000000000000000000000000003D00000000gnome-shell-extension-appindicator-v34+git1.860086c/Makefile# simple helper makefile, handles schema compilation, translations and zip file creation .PHONY= zip-file # files that go into the zip ZIP= $(wildcard *.js) metadata.json $(wildcard interfaces-xml/*) zip-file: $(ZIP) mkdir -p build rm -f build/appindicator-support.zip zip build/appindicator-support.zip $(ZIP) clean: rm -rf build 07070100000003000081A40000000200000002000000015F6B6B1600000CDD000000000000000000000000000000000000003E00000000gnome-shell-extension-appindicator-v34+git1.860086c/README.md# AppIndicator/KStatusNotifierItem support for GNOME Shell This extension integrates Ubuntu AppIndicators and KStatusNotifierItems (KDE's blessed successor of the systray) into GNOME Shell. [<img alt="" height="100" src="https://raw.githubusercontent.com/andyholmes/gnome-shell-extensions-badge/master/get-it-on-ego.svg?sanitize=true">](https://extensions.gnome.org/extension/615/appindicator-support/) ## Features * Show indicator icons in the panel. * Reveal indicator menus upon click. * Double clicking an icon will activate the application window (if implemented by the indicator). * Middle mouse click an icon to send a 'SecondaryActivate' event to the application. Support needs to be implemented in the application. [Info 1](https://bugs.launchpad.net/unity/+bug/812933), [Info 2](https://developer.ubuntu.com/api/devel/ubuntu-13.10/c/AppIndicator3-0.1.html). ## Missing features * Tooltips: Not implemented in `libappindicator` nor in Unity and I've yet to see any indicator using it for anything relevant (KDE ones maybe?). Also, the GNOME designers decided not to have tooltips in the shell and I'd like to honor that decision. ## Known issues * ClassicMenu Indicator takes ages to load and has been reported to freeze the shell forever. This is probably caused by the insane amount of embedded PNG icons. Try at your own risk. ## Installation Normal users are recommended to get the extension from [extensions.gnome.org](https://extensions.gnome.org/extension/615/appindicator-support/). Alternatively, you can check out a version from git and symlink `~/.local/share/gnome-shell/extensions/appindicatorsupport@rgcjonas.gmail.com` to your clone: ``` ln -s $PWD ~/.local/share/gnome-shell/extensions/appindicatorsupport@rgcjonas.gmail.com gnome-extensions enable appindicatorsupport@rgcjonas.gmail.com ``` You may need to restart GNOME Shell (<kbd>Alt</kbd>+<kbd>F2</kbd>, <kbd>r</kbd>, <kbd>⏎</kbd>) after that. ## Guidelines for bug reports Unfortunately, this extension is not completely bug free and will probably never be. In order to successfully resolve remaining issues, you need to provide some data: * Your distribution, Shell version and extension version (something like "latest git" or "latest from extensions.gnome.org" is sufficient). * The indicator that caused the bug (if applicable). * Instructions how to reproduce it. **This is the single most important point**. Bugs which [cannot be reproduced](http://xkcd.com/583/) cannot be fixed. Bug reports which do not provide the necessary information may be closed as "invalid" without prior notice. ## Release process This section serves as reminder for the current maintainer and as instruction set for an eventual sucessor. * The maintainer decides when to release a new version. * Versions are tagged (and signed). Version numbers sould be kept in sync with the versions submitted to `extensions.gnome.org`. This implies that version numbers are integers which will be incremented with each release. * The maintainer will tag a new version and generate a zip file using `make`. * The zip file will be tested to ensure that nothing was missed when packaging it. * Only if it passed, it is uploaded to `extensions.gnome.org` and the tag is pushed. This release process has been in place since v9. 07070100000004000081A40000000200000002000000015F6B6B1600006318000000000000000000000000000000000000004400000000gnome-shell-extension-appindicator-v34+git1.860086c/appIndicator.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Clutter = imports.gi.Clutter const Cogl = imports.gi.Cogl const GdkPixbuf = imports.gi.GdkPixbuf const Gio = imports.gi.Gio const GLib = imports.gi.GLib const GObject = imports.gi.GObject const Gtk = imports.gi.Gtk const St = imports.gi.St const Shell = imports.gi.Shell const Extension = imports.misc.extensionUtils.getCurrentExtension(); const Signals = imports.signals const DBusMenu = Extension.imports.dbusMenu; const IconCache = Extension.imports.iconCache; const Util = Extension.imports.util; const Interfaces = Extension.imports.interfaces; const MAX_UPDATE_FREQUENCY = 100; // In ms const SNICategory = { APPLICATION: 'ApplicationStatus', COMMUNICATIONS: 'Communications', SYSTEM: 'SystemServices', HARDWARE: 'Hardware' }; var SNIStatus = { PASSIVE: 'Passive', ACTIVE: 'Active', NEEDS_ATTENTION: 'NeedsAttention' }; const SNIconType = { NORMAL: 0, ATTENTION: 1, OVERLAY: 2, }; /** * the AppIndicator class serves as a generic container for indicator information and functions common * for every displaying implementation (IndicatorMessageSource and IndicatorStatusIcon) */ var AppIndicator = class AppIndicators_AppIndicator { constructor(bus_name, object) { this.busName = bus_name this._uniqueId = bus_name + object this._accumuledSignals = new Set(); let interface_info = Gio.DBusInterfaceInfo.new_for_xml(Interfaces.StatusNotifierItem) //HACK: we cannot use Gio.DBusProxy.makeProxyWrapper because we need // to specify G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES this._cancellable = new Gio.Cancellable(); this._proxy = new Gio.DBusProxy({ g_connection: Gio.DBus.session, g_interface_name: interface_info.name, g_interface_info: interface_info, g_name: bus_name, g_object_path: object, g_flags: Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES }) this._proxy.init_async(GLib.PRIORITY_DEFAULT, this._cancellable, ((initable, result) => { try { initable.init_finish(result); this._checkIfReady(); if (!this.isReady && !this.menuPath) { let checks = 0; this._delayCheck = GLib.timeout_add_seconds( GLib.PRIORITY_DEFAULT_IDLE, 1, () => { Util.refreshPropertyOnProxy(this._proxy, 'Menu'); return !this.isReady && ++checks < 3; }); } } catch(e) { if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) Util.Logger.warn(`While intializing proxy for ${bus_name} ${object}: ${e}`); } })) Util.connectSmart(this._proxy, 'g-properties-changed', this, '_onPropertiesChanged') Util.connectSmart(this._proxy, 'g-signal', this, this._onProxySignal) Util.connectSmart(this._proxy, 'notify::g-name-owner', this, '_nameOwnerChanged') } _checkIfReady() { let wasReady = this.isReady; let isReady = false; if (this._proxy.g_name_owner && this.menuPath) isReady = true; this.isReady = isReady; this._setupProxyPropertyList(); if (this.isReady && !wasReady) { if (this._delayCheck) { GLib.Source.remove(this._delayCheck); delete this._delayCheck; } this.emit('ready'); return true; } return false; } _nameOwnerChanged() { if (!this._proxy.g_name_owner) this._checkIfReady(); } _addExtraProperty(name) { if (this._proxyPropertyList.includes(name)) return; if (!(name in this._proxy)) { Object.defineProperty(this._proxy, name, { configurable: false, enumerable: true, get: () => { const v = this._proxy.get_cached_property(name); return v ? v.deep_unpack() : null; } }); } this._proxyPropertyList.push(name); } _setupProxyPropertyList() { let interfaceProps = this._proxy.g_interface_info.properties; this._proxyPropertyList = (this._proxy.get_cached_property_names() || []).filter(p => interfaceProps.some(propinfo => propinfo.name == p)); if (this._proxyPropertyList.length) { this._addExtraProperty('XAyatanaLabel'); this._addExtraProperty('XAyatanaLabelGuide'); this._addExtraProperty('XAyatanaOrderingIndex'); } } // The Author of the spec didn't like the PropertiesChanged signal, so he invented his own _translateNewSignals(signal) { let prop = null; if (signal.startsWith('New')) prop = signal.substr(3) else if (signal.startsWith('XAyatanaNew')) prop = 'XAyatana' + signal.substr(11) if (!prop) return; [prop, `${prop}Name`, `${prop}Pixmap`].filter(p => this._proxyPropertyList.includes(p)).forEach(p => Util.refreshPropertyOnProxy(this._proxy, p, { skipEqualtyCheck: p.endsWith('Pixmap'), }) ); } _onProxySignal(_proxy, _sender, signal, _params) { this._accumuledSignals.add(signal); if (this._signalsAccumulatorId) return; this._signalsAccumulatorId = GLib.timeout_add( GLib.PRIORITY_DEFAULT_IDLE, MAX_UPDATE_FREQUENCY, () => { this._accumuledSignals.forEach((s) => this._translateNewSignals(s)); this._accumuledSignals.clear(); delete this._signalsAccumulatorId; }); } //public property getters get title() { return this._proxy.Title; } get id() { return this._proxy.Id; } get uniqueId() { return this._uniqueId; } get status() { return this._proxy.Status; } get label() { return this._proxy.XAyatanaLabel; } get menuPath() { if (this._proxy.Menu == '/NO_DBUSMENU') return null; return this._proxy.Menu || '/MenuBar'; } get attentionIcon() { return [ this._proxy.AttentionIconName, this._proxy.AttentionIconPixmap, this._proxy.IconThemePath ] } get icon() { return [ this._proxy.IconName, this._proxy.IconPixmap, this._proxy.IconThemePath ] } get overlayIcon() { return [ this._proxy.OverlayIconName, this._proxy.OverlayIconPixmap, this._proxy.IconThemePath ] } _onPropertiesChanged(proxy, changed, invalidated) { let props = Object.keys(changed.unpack()); let signalsToEmit = new Set(); props.forEach((property) => { // some property changes require updates on our part, // a few need to be passed down to the displaying code // all these can mean that the icon has to be changed if (property == 'Status' || property.startsWith('Icon') || property.startsWith('AttentionIcon')) { signalsToEmit.add('icon') } // same for overlays if (property.startsWith('OverlayIcon')) signalsToEmit.add('overlay-icon') // this may make all of our icons invalid if (property == 'IconThemePath') { signalsToEmit.add('icon') signalsToEmit.add('overlay-icon') } // the label will be handled elsewhere if (property == 'XAyatanaLabel') signalsToEmit.add('label') if (property == 'Menu') { if (!this._checkIfReady() && this.isReady) signalsToEmit.add('menu') } // status updates may cause the indicator to be hidden if (property == 'Status') signalsToEmit.add('status') }); signalsToEmit.forEach(s => this.emit(s)); } reset() { this.emit('reset'); } destroy() { this.emit('destroy') this.disconnectAll() this._cancellable.cancel(); Util.cancelRefreshPropertyOnProxy(this._proxy); delete this._cancellable; delete this._proxy if (this._signalsAccumulatorId) { GLib.Source.remove(this._signalsAccumulatorId); delete this._signalsAccumulatorId; } if (this._delayCheck) { GLib.Source.remove(this._delayCheck); delete this._delayCheck; } } open() { // we can't use WindowID because we're not able to get the x11 window id from a MetaWindow // nor can we call any X11 functions. Luckily, the Activate method usually works fine. // parameters are "an hint to the item where to show eventual windows" [sic] // ... and don't seem to have any effect. this._proxy.ActivateRemote(0, 0) } secondaryActivate() { this._proxy.SecondaryActivateRemote(0, 0) } scroll(dx, dy) { if (dx != 0) this._proxy.ScrollRemote(Math.floor(dx), 'horizontal') if (dy != 0) this._proxy.ScrollRemote(Math.floor(dy), 'vertical') } }; Signals.addSignalMethods(AppIndicator.prototype); var IconActor = GObject.registerClass( class AppIndicators_IconActor extends St.Icon { _init(indicator, icon_size) { super._init({ reactive: true, style_class: 'system-status-icon', fallback_icon_name: 'image-loading-symbolic', }); this.name = this.constructor.name; this.add_style_class_name('appindicator-icon'); this.set_style('padding:0'); let themeContext = St.ThemeContext.get_for_stage(global.stage); this.height = icon_size * themeContext.scale_factor; this._indicator = indicator this._iconSize = icon_size this._iconCache = new IconCache.IconCache() this._cancellable = new Gio.Cancellable(); this._loadingIcons = new Set(); Util.connectSmart(this._indicator, 'icon', this, '_updateIcon') Util.connectSmart(this._indicator, 'overlay-icon', this, '_updateOverlayIcon') Util.connectSmart(this._indicator, 'reset', this, '_invalidateIcon') Util.connectSmart(this, 'scroll-event', this, '_handleScrollEvent') Util.connectSmart(themeContext, 'notify::scale-factor', this, (tc) => { this.height = icon_size * tc.scale_factor; this._invalidateIcon(); }); Util.connectSmart(this._indicator, 'ready', this, () => { this._updateIconClass(); this._invalidateIcon(); }) Util.connectSmart(Gtk.IconTheme.get_default(), 'changed', this, '_invalidateIcon') if (indicator.isReady) this._invalidateIcon() this.connect('destroy', () => { this._iconCache.destroy(); this._cancellable.cancel(); if (this._callbackIdle) { GLib.source_remove(this._callbackIdle); delete this._callbackIdle; } }); } _updateIconClass() { this.add_style_class_name( `appindicator-icon-${this._indicator.id.toLowerCase().replace(/_|\s/g, '-')}`); } // Will look the icon up in the cache, if it's found // it will return it. Otherwise, it will create it and cache it. _cacheOrCreateIconByName(iconSize, iconName, themePath, callback) { let {scale_factor} = St.ThemeContext.get_for_stage(global.stage); let id = `${iconName}@${iconSize * scale_factor}${themePath || ''}`; let gicon = this._iconCache.get(id); if (gicon) { callback(gicon); return; } if (this._loadingIcons.has(id)) { Util.Logger.debug(`${this._indicator.id}, Icon ${id} Is still loading, ignoring the request`); return; } else if (this._loadingIcons.size > 0) { this._cancellable.cancel(); this._cancellable = new Gio.Cancellable(); this._loadingIcons.clear(); } this._loadingIcons.add(id); let path = this._getIconInfo(iconName, themePath, iconSize, scale_factor); this._createIconByName(path, (gicon) => { this._loadingIcons.delete(id); if (gicon) gicon = this._iconCache.add(id, gicon); callback(gicon); }); } _createIconByPath(path, width, height, callback) { let file = Gio.File.new_for_path(path); file.read_async(GLib.PRIORITY_DEFAULT, this._cancellable, (file, res) => { try { let inputStream = file.read_finish(res); GdkPixbuf.Pixbuf.new_from_stream_at_scale_async( inputStream, height, width, true, this._cancellable, (_p, res) => { try { callback(GdkPixbuf.Pixbuf.new_from_stream_finish(res)); this.icon_size = width > 0 ? width : this._iconSize; } catch (e) { if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) { Util.Logger.warn(`${this._indicator.id}, Impossible to create image from path '${path}': ${e}`); callback(null); } } }); } catch (e) { if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) { Util.Logger.warn(`${this._indicator.id}, Impossible to read image from path '${path}': ${e}`); callback(null); } } }); } _createIconByName(path, callback) { if (!path) { if (this._callbackIdle) return; this._callbackIdle = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => { delete this._callbackIdle; callback(null); return false; }); return; } else if (this._callbackIdle) { GLib.source_remove(this._callbackIdle); delete this._callbackIdle; } GdkPixbuf.Pixbuf.get_file_info_async(path, this._cancellable, (_p, res) => { try { let [format, width, height] = GdkPixbuf.Pixbuf.get_file_info_finish(res); if (!format) { Util.Logger.critical(`${this._indicator.id}, Invalid image format: ${path}`); callback(null); return; } if (width >= height * 1.5) { /* Hello indicator-multiload! */ this._createIconByPath(path, width, -1, callback); } else { callback(new Gio.FileIcon({ file: Gio.File.new_for_path(path) })); this.icon_size = this._iconSize; } } catch (e) { if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) { Util.Logger.warn(`${this._indicator.id}, Impossible to read image info from path '${path}': ${e}`); callback(null); } } }); } _getIconInfo(name, themePath, size, scale) { let path = null; if (name && name[0] == "/") { //HACK: icon is a path name. This is not specified by the api but at least inidcator-sensors uses it. path = name; } else if (name) { // we manually look up the icon instead of letting st.icon do it for us // this allows us to sneak in an indicator provided search path and to avoid ugly upscaled icons // indicator-application looks up a special "panel" variant, we just replicate that here name = name + "-panel"; // icon info as returned by the lookup let iconInfo = null; // we try to avoid messing with the default icon theme, so we'll create a new one if needed let icon_theme = null; if (themePath) { icon_theme = new Gtk.IconTheme(); Gtk.IconTheme.get_default().get_search_path().forEach((path) => { icon_theme.append_search_path(path); }); icon_theme.append_search_path(themePath); icon_theme.set_screen(imports.gi.Gdk.Screen.get_default()); } else { icon_theme = Gtk.IconTheme.get_default(); } if (icon_theme) { // try to look up the icon in the icon theme iconInfo = icon_theme.lookup_icon_for_scale(name, size, scale, Gtk.IconLookupFlags.GENERIC_FALLBACK); // no icon? that's bad! if (iconInfo === null) { let msg = `${this._indicator.id}, Impossible to lookup icon for '${name}' in`; Util.Logger.warn(`${msg} ${themePath ? `path ${themePath}` : 'default theme'}`); } else { // we have an icon // get the icon path path = iconInfo.get_filename(); } } } return path; } argbToRgba(src) { let dest = new Uint8Array(src.length); for (let i = 0; i < src.length; i += 4) { let srcAlpha = src[i] dest[i] = src[i + 1]; /* red */ dest[i + 1] = src[i + 2]; /* green */ dest[i + 2] = src[i + 3]; /* blue */ dest[i + 3] = srcAlpha; /* alpha */ } return dest; } _createIconFromPixmap(iconSize, iconPixmapArray, snIconType) { let {scale_factor} = St.ThemeContext.get_for_stage(global.stage); iconSize = iconSize * scale_factor // the pixmap actually is an array of pixmaps with different sizes // we use the one that is smaller or equal the iconSize // maybe it's empty? that's bad. if (!iconPixmapArray || iconPixmapArray.length < 1) return null let sortedIconPixmapArray = iconPixmapArray.sort((pixmapA, pixmapB) => { // we sort smallest to biggest let areaA = pixmapA[0] * pixmapA[1] let areaB = pixmapB[0] * pixmapB[1] return areaA - areaB }) let qualifiedIconPixmapArray = sortedIconPixmapArray.filter((pixmap) => { // we prefer any pixmap that is equal or bigger than our requested size return pixmap[0] >= iconSize && pixmap[1] >= iconSize; }) let iconPixmap = qualifiedIconPixmapArray.length > 0 ? qualifiedIconPixmapArray[0] : sortedIconPixmapArray.pop() let [ width, height, bytes ] = iconPixmap let rowstride = width * 4 // hopefully this is correct try { return GdkPixbuf.Pixbuf.new_from_bytes( this.argbToRgba(bytes), GdkPixbuf.Colorspace.RGB, true, 8, width, height, rowstride); } catch (e) { // the image data was probably bogus. We don't really know why, but it _does_ happen. Util.Logger.warn(`${this._indicator.id}, Impossible to create image from data: ${e}`) return null } } // The .inUse flag will be set to true if the used gicon matches the cached // one (as in some cases it may be equal, but not the same object). // So when it's not need anymore we make sure to check the .inUse property // and set it to false so that it can be picked up by the garbage collector. _setGicon(iconType, gicon) { if (iconType != SNIconType.OVERLAY) { if (gicon) { this.gicon = new Gio.EmblemedIcon({ gicon }); if (!(gicon instanceof GdkPixbuf.Pixbuf)) gicon.inUse = (this.gicon.get_icon() == gicon); } else { this.gicon = null; Util.Logger.critical(`unable to update icon for ${this._indicator.id}`); } } else { if (gicon) { this._emblem = new Gio.Emblem({ icon: gicon }); if (!(gicon instanceof GdkPixbuf.Pixbuf)) gicon.inUse = true; } else { this._emblem = null; Util.Logger.debug(`unable to update icon emblem for ${this._indicator.id}`); } } if (this.gicon) { if (!this.gicon.get_emblems().some(e => e.equal(this._emblem))) { this.gicon.clear_emblems(); if (this._emblem) this.gicon.add_emblem(this._emblem); } } } _updateIconByType(iconType, iconSize) { let icon; switch (iconType) { case SNIconType.ATTENTION: icon = this._indicator.attentionIcon; break; case SNIconType.NORMAL: icon = this._indicator.icon; break; case SNIconType.OVERLAY: icon = this._indicator.overlayIcon; break; } let [name, pixmap, theme] = icon; if (name && name.length) { this._cacheOrCreateIconByName(iconSize, name, theme, (gicon) => { if (!gicon && pixmap) { gicon = this._createIconFromPixmap(iconSize, pixmap, iconType); } this._setGicon(iconType, gicon); }); } else if (pixmap) { let gicon = this._createIconFromPixmap(iconSize, pixmap, iconType); this._setGicon(iconType, gicon); } } // updates the base icon _updateIcon() { if (this.gicon instanceof Gio.EmblemedIcon) { let { gicon } = this.gicon; if (gicon.inUse) gicon.inUse = false } // we might need to use the AttentionIcon*, which have precedence over the normal icons let iconType = this._indicator.status == SNIStatus.NEEDS_ATTENTION ? SNIconType.ATTENTION : SNIconType.NORMAL; this._updateIconByType(iconType, this._iconSize); } _updateOverlayIcon() { if (this._emblem) { let { icon } = this._emblem; if (icon.inUse) icon.inUse = false; } // KDE hardcodes the overlay icon size to 10px (normal icon size 16px) // we approximate that ratio for other sizes, too. // our algorithms will always pick a smaller one instead of stretching it. let iconSize = Math.floor(this._iconSize / 1.6) this._updateIconByType(SNIconType.OVERLAY, iconSize); } _handleScrollEvent(actor, event) { if (actor != this) return Clutter.EVENT_PROPAGATE if (event.get_source() != this) return Clutter.EVENT_PROPAGATE if (event.type() != Clutter.EventType.SCROLL) return Clutter.EVENT_PROPAGATE // Since Clutter 1.10, clutter will always send a smooth scrolling event // with explicit deltas, no matter what input device is used // In fact, for every scroll there will be a smooth and non-smooth scroll // event, and we can choose which one we interpret. if (event.get_scroll_direction() == Clutter.ScrollDirection.SMOOTH) { let [ dx, dy ] = event.get_scroll_delta() this._indicator.scroll(dx, dy) } return Clutter.EVENT_STOP } // called when the icon theme changes _invalidateIcon() { this._iconCache.clear() this._updateIcon() this._updateOverlayIcon() } }); 07070100000005000081A40000000200000002000000015F6B6B1600006E08000000000000000000000000000000000000004000000000gnome-shell-extension-appindicator-v34+git1.860086c/dbusMenu.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Atk = imports.gi.Atk const Clutter = imports.gi.Clutter const Gio = imports.gi.Gio const GLib = imports.gi.GLib const GdkPixbuf = imports.gi.GdkPixbuf const PopupMenu = imports.ui.popupMenu const Signals = imports.signals const St = imports.gi.St const Extension = imports.misc.extensionUtils.getCurrentExtension() const DBusInterfaces = Extension.imports.interfaces const Util = Extension.imports.util ////////////////////////////////////////////////////////////////////////// // PART ONE: "ViewModel" backend implementation. // Both code and design are inspired by libdbusmenu ////////////////////////////////////////////////////////////////////////// /** * Saves menu property values and handles type checking and defaults */ var PropertyStore = class AppIndicators_PropertyStore { constructor(initial_properties) { this._props = new Map(); if (initial_properties) { for (let i in initial_properties) { this.set(i, initial_properties[i]) } } } set(name, value) { if (name in PropertyStore.MandatedTypes && value && !value.is_of_type(PropertyStore.MandatedTypes[name])) Util.Logger.warn("Cannot set property "+name+": type mismatch!") else if (value) this._props.set(name, value); else this._props.delete(name); } get(name) { let prop = this._props.get(name); if (prop) return prop; else if (name in PropertyStore.DefaultValues) return PropertyStore.DefaultValues[name] else return null } }; // we list all the properties we know and use here, so we won' have to deal with unexpected type mismatches PropertyStore.MandatedTypes = { 'visible' : GLib.VariantType.new("b"), 'enabled' : GLib.VariantType.new("b"), 'label' : GLib.VariantType.new("s"), 'type' : GLib.VariantType.new("s"), 'children-display' : GLib.VariantType.new("s"), 'icon-name' : GLib.VariantType.new("s"), 'icon-data' : GLib.VariantType.new("ay"), 'toggle-type' : GLib.VariantType.new("s"), 'toggle-state' : GLib.VariantType.new("i") } PropertyStore.DefaultValues = { 'visible': GLib.Variant.new_boolean(true), 'enabled': GLib.Variant.new_boolean(true), 'label' : GLib.Variant.new_string(''), 'type' : GLib.Variant.new_string("standard") // elements not in here must return null } /** * Represents a single menu item */ var DbusMenuItem = class AppIndicators_DbusMenuItem { // will steal the properties object constructor(client, id, properties, children_ids) { this._client = client this._id = id this._propStore = new PropertyStore(properties) this._children_ids = children_ids } property_get(prop_name) { let prop = this.property_get_variant(prop_name) return prop ? prop.get_string()[0] : null } property_get_variant(prop_name) { return this._propStore.get(prop_name) } property_get_bool(prop_name) { let prop = this.property_get_variant(prop_name) return prop ? prop.get_boolean() : false } property_get_int(prop_name) { let prop = this.property_get_variant(prop_name) return prop ? prop.get_int32() : 0 } property_set(prop, value) { this._propStore.set(prop, value) this.emit('property-changed', prop, this.property_get_variant(prop)) } get_children_ids() { return this._children_ids.concat() // clone it! } add_child(pos, child_id) { this._children_ids.splice(pos, 0, child_id) this.emit('child-added', this._client.get_item(child_id), pos) } remove_child(child_id) { // find it let pos = -1 for (let i = 0; i < this._children_ids.length; ++i) { if (this._children_ids[i] == child_id) { pos = i break } } if (pos < 0) { Util.Logger.critical("Trying to remove child which doesn't exist") } else { this._children_ids.splice(pos, 1) this.emit('child-removed', this._client.get_item(child_id)) } } move_child(child_id, newpos) { // find the old position let oldpos = -1 for (let i = 0; i < this._children_ids.length; ++i) { if (this._children_ids[i] == child_id) { oldpos = i break } } if (oldpos < 0) { Util.Logger.critical("tried to move child which wasn't in the list") return } if (oldpos != newpos) { this._children_ids.splice(oldpos, 1) this._children_ids.splice(newpos, 0, child_id) this.emit('child-moved', oldpos, newpos, this._client.get_item(child_id)) } } get_children() { return this._children_ids.map(el => this._client.get_item(el)); } handle_event(event, data, timestamp) { if (!data) data = GLib.Variant.new_int32(0) this._client.send_event(this._id, event, data, timestamp) } get_id() { return this._id } send_about_to_show() { this._client.send_about_to_show(this._id) } } Signals.addSignalMethods(DbusMenuItem.prototype) const BusClientProxy = Gio.DBusProxy.makeProxyWrapper(DBusInterfaces.DBusMenu); /** * The client does the heavy lifting of actually reading layouts and distributing events */ var DBusClient = class AppIndicators_DBusClient { constructor(busName, busPath) { this._cancellable = new Gio.Cancellable(); this._proxy = new BusClientProxy(Gio.DBus.session, busName, busPath, this._clientReady.bind(this), this._cancellable) this._items = new Map([ [ 0, new DbusMenuItem(this, 0, { 'children-display': GLib.Variant.new_string('submenu'), }, []), ] ]); // will be set to true if a layout update is requested while one is already in progress // then the handler that completes the layout update will request another update this._flagLayoutUpdateRequired = false this._flagLayoutUpdateInProgress = false // property requests are queued this._propertiesRequestedFor = new Set(/* ids */); Util.connectSmart(this._proxy, 'notify::g-name-owner', this, () => { if (this.isReady) this._requestLayoutUpdate(); }); } get isReady() { return !!this._proxy.g_name_owner; } get_root() { return this._items.get(0); } _requestLayoutUpdate() { if (this._flagLayoutUpdateInProgress) this._flagLayoutUpdateRequired = true else this._beginLayoutUpdate() } _requestProperties(id) { // if we don't have any requests queued, we'll need to add one if (!this._propertiesRequestId) { this._propertiesRequestId = GLib.idle_add( GLib.PRIORITY_DEFAULT_IDLE, () => this._beginRequestProperties()) } this._propertiesRequestedFor.add(id); } _beginRequestProperties() { this._proxy.GetGroupPropertiesRemote( Array.from(this._propertiesRequestedFor), [], this._cancellable, this._endRequestProperties.bind(this)) this._propertiesRequestedFor.clear(); delete this._propertiesRequestId; return false } _endRequestProperties(result, error) { if (error) { if (!error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) Util.Logger.warn(`Could not retrieve properties: ${error}`); return } // for some funny reason, the result array is hidden in an array result[0].forEach(([id, properties]) => { let item = this._items.get(id); if (!item) return for (let prop in properties) item.property_set(prop, properties[prop]) }); } // Traverses the list of cached menu items and removes everyone that is not in the list // so we don't keep alive unused items _gcItems() { let tag = new Date().getTime() let toTraverse = [ 0 ] while (toTraverse.length > 0) { let item = this.get_item(toTraverse.shift()) item._dbusClientGcTag = tag Array.prototype.push.apply(toTraverse, item.get_children_ids()) } this._items.forEach((i, id) => { if (i._dbusClientGcTag != tag) this._items.delete(id); }); } // the original implementation will only request partial layouts if somehow possible // we try to save us from multiple kinds of race conditions by always requesting a full layout _beginLayoutUpdate() { // we only read the type property, because if the type changes after reading all properties, // the view would have to replace the item completely which we try to avoid this._proxy.GetLayoutRemote(0, -1, [ 'type', 'children-display' ], this._cancellable, this._endLayoutUpdate.bind(this)) this._flagLayoutUpdateRequired = false this._flagLayoutUpdateInProgress = true } _endLayoutUpdate(result, error) { if (error) { if (!error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) Util.Logger.warn(`While reading menu layout on proxy ${this._proxy.g_name_owner}: ${error}`); return } let [ revision, root ] = result this._doLayoutUpdate(root) this._gcItems() if (this._flagLayoutUpdateRequired) this._beginLayoutUpdate() else this._flagLayoutUpdateInProgress = false } _doLayoutUpdate(item) { let [ id, properties, children ] = item let childrenUnpacked = children.map(c => c.deep_unpack()) let childrenIds = childrenUnpacked.map(c => c[0]) // make sure all our children exist childrenUnpacked.forEach(c => this._doLayoutUpdate(c)); // make sure we exist const menuItem = this._items.get(id); if (menuItem) { // we do, update our properties if necessary for (let prop in properties) { menuItem.property_set(prop, properties[prop]) } // make sure our children are all at the right place, and exist let oldChildrenIds = menuItem.get_children_ids() for (let i = 0; i < childrenIds.length; ++i) { // try to recycle an old child let oldChild = -1 for (let j = 0; j < oldChildrenIds.length; ++j) { if (oldChildrenIds[j] == childrenIds[i]) { oldChild = oldChildrenIds.splice(j, 1)[0] break } } if (oldChild < 0) { // no old child found, so create a new one! menuItem.add_child(i, childrenIds[i]) } else { // old child found, reuse it! menuItem.move_child(childrenIds[i], i) } } // remove any old children that weren't reused oldChildrenIds.forEach(child_id => menuItem.remove_child(child_id)); } else { // we don't, so let's create us this._items.set(id, new DbusMenuItem(this, id, properties, childrenIds)); this._requestProperties(id) } return id } _clientReady(result, error) { if (error) { if (!error.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) Util.Logger.warn(`Could not initialize menu proxy: ${error}`); return; } this._requestLayoutUpdate() // listen for updated layouts and properties this._proxy.connectSignal("LayoutUpdated", this._onLayoutUpdated.bind(this)) this._proxy.connectSignal("ItemsPropertiesUpdated", this._onPropertiesUpdated.bind(this)) } get_item(id) { let item = this._items.get(id); if (!item) Util.Logger.warn(`trying to retrieve item for non-existing id ${id} !?`); return item || null; } // we don't need to cache and burst-send that since it will not happen that frequently send_about_to_show(id) { /* Some indicators (you, dropbox!) don't use the right signature * and don't return a boolean, so we need to support both cases */ let connection = this._proxy.get_connection(); connection.call(this._proxy.get_name(), this._proxy.get_object_path(), this._proxy.get_interface_name(), 'AboutToShow', new GLib.Variant("(i)", [id]), null, Gio.DBusCallFlags.NONE, -1, null, (proxy, res) => { try { let ret = proxy.call_finish(res); if ((ret.is_of_type(new GLib.VariantType('(b)')) && ret.get_child_value(0).get_boolean()) || ret.is_of_type(new GLib.VariantType('()'))) { this._requestLayoutUpdate(); } } catch (e) { Util.Logger.warn("Impossible to send about-to-show to menu: " + e); } }); } send_event(id, event, params, timestamp) { if (!this._proxy) return this._proxy.EventRemote(id, event, params, timestamp, this._cancellable, () => { /* we don't care */ }) } _onLayoutUpdated() { this._requestLayoutUpdate() } _onPropertiesUpdated(proxy, name, [changed, removed]) { changed.forEach(([id, props]) => { let item = this._items.get(id); if (!item) return for (let prop in props) item.property_set(prop, props[prop]) }); removed.forEach(([id, propNames]) => { let item = this._items.get(id); if (!item) return propNames.forEach(propName => item.property_set(propName, null)); }); } destroy() { this.emit('destroy') if (this._propertiesRequestId) { GLib.Source.remove(this._propertiesRequestId); delete this._propertiesRequestId; } this._cancellable.cancel(); Signals._disconnectAll.apply(this._proxy) this._proxy = null } } Signals.addSignalMethods(DBusClient.prototype) ////////////////////////////////////////////////////////////////////////// // PART TWO: "View" frontend implementation. ////////////////////////////////////////////////////////////////////////// // https://bugzilla.gnome.org/show_bug.cgi?id=731514 // GNOME 3.10 and 3.12 can't open a nested submenu. // Patches have been written, but it's not clear when (if?) they will be applied. // We also don't know whether they will be backported to 3.10, so we will work around // it in the meantime. Offending versions can be clearly identified: const NEED_NESTED_SUBMENU_FIX = '_setOpenedSubMenu' in PopupMenu.PopupMenu.prototype /** * Creates new wrapper menu items and injects methods for managing them at runtime. * * Many functions in this object will be bound to the created item and executed as event * handlers, so any `this` will refer to a menu item create in createItem */ const MenuItemFactory = { createItem: function(client, dbusItem) { // first, decide whether it's a submenu or not if (dbusItem.property_get("children-display") == "submenu") var shellItem = new PopupMenu.PopupSubMenuMenuItem("FIXME") else if (dbusItem.property_get("type") == "separator") var shellItem = new PopupMenu.PopupSeparatorMenuItem('') else var shellItem = new PopupMenu.PopupMenuItem("FIXME") shellItem._dbusItem = dbusItem shellItem._dbusClient = client if (shellItem instanceof PopupMenu.PopupMenuItem) { shellItem._icon = new St.Icon({ style_class: 'popup-menu-icon', x_align: St.Align.END }) shellItem.add_child(shellItem._icon); shellItem.label.x_expand = true; } // initialize our state MenuItemFactory._updateLabel.call(shellItem) MenuItemFactory._updateOrnament.call(shellItem) MenuItemFactory._updateImage.call(shellItem) MenuItemFactory._updateVisible.call(shellItem) MenuItemFactory._updateSensitive.call(shellItem) // initially create children if (shellItem instanceof PopupMenu.PopupSubMenuMenuItem) { let children = dbusItem.get_children() for (let i = 0; i < children.length; ++i) { shellItem.menu.addMenuItem(MenuItemFactory.createItem(client, children[i])) } } // now, connect various events Util.connectSmart(dbusItem, 'property-changed', shellItem, MenuItemFactory._onPropertyChanged) Util.connectSmart(dbusItem, 'child-added', shellItem, MenuItemFactory._onChildAdded) Util.connectSmart(dbusItem, 'child-removed', shellItem, MenuItemFactory._onChildRemoved) Util.connectSmart(dbusItem, 'child-moved', shellItem, MenuItemFactory._onChildMoved) Util.connectSmart(shellItem, 'activate', shellItem, MenuItemFactory._onActivate) if (shellItem.menu) Util.connectSmart(shellItem.menu, "open-state-changed", shellItem, MenuItemFactory._onOpenStateChanged) return shellItem }, _onOpenStateChanged(menu, open) { if (open) { if (NEED_NESTED_SUBMENU_FIX) { // close our own submenus if (menu._openedSubMenu) menu._openedSubMenu.close(false) // register ourselves and close sibling submenus if (menu._parent._openedSubMenu && menu._parent._openedSubMenu !== menu) menu._parent._openedSubMenu.close(true) menu._parent._openedSubMenu = menu } this._dbusItem.handle_event("opened", null, 0) this._dbusItem.send_about_to_show() } else { if (NEED_NESTED_SUBMENU_FIX) { // close our own submenus if (menu._openedSubMenu) menu._openedSubMenu.close(false) } this._dbusItem.handle_event("closed", null, 0) } }, _onActivate() { this._dbusItem.handle_event("clicked", GLib.Variant.new("i", 0), 0) }, _onPropertyChanged(dbusItem, prop, value) { if (prop == "toggle-type" || prop == "toggle-state") MenuItemFactory._updateOrnament.call(this) else if (prop == "label") MenuItemFactory._updateLabel.call(this) else if (prop == "enabled") MenuItemFactory._updateSensitive.call(this) else if (prop == "visible") MenuItemFactory._updateVisible.call(this) else if (prop == "icon-name" || prop == "icon-data") MenuItemFactory._updateImage.call(this) else if (prop == "type" || prop == "children-display") MenuItemFactory._replaceSelf.call(this) //else // Util.Logger.debug("Unhandled property change: "+prop) }, _onChildAdded(dbusItem, child, position) { if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) { Util.Logger.warn("Tried to add a child to non-submenu item. Better recreate it as whole") MenuItemFactory._replaceSelf.call(this) } else { this.menu.addMenuItem(MenuItemFactory.createItem(this._dbusClient, child), position) } }, _onChildRemoved(dbusItem, child) { if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) { Util.Logger.warn("Tried to remove a child from non-submenu item. Better recreate it as whole") MenuItemFactory._replaceSelf.call(this) } else { // find it! this.menu._getMenuItems().forEach((item) => { if (item._dbusItem == child) item.destroy() }) } }, _onChildMoved(dbusItem, child, oldpos, newpos) { if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) { Util.Logger.warn("Tried to move a child in non-submenu item. Better recreate it as whole") MenuItemFactory._replaceSelf.call(this) } else { MenuUtils.moveItemInMenu(this.menu, child, newpos) } }, _updateLabel() { let label = this._dbusItem.property_get("label").replace(/_([^_])/, "$1") if (this.label) // especially on GS3.8, the separator item might not even have a hidden label this.label.set_text(label) }, _updateOrnament() { if (!this.setOrnament) return // separators and alike might not have gotten the polyfill if (this._dbusItem.property_get("toggle-type") == "checkmark" && this._dbusItem.property_get_int("toggle-state")) this.setOrnament(PopupMenu.Ornament.CHECK) else if (this._dbusItem.property_get("toggle-type") == "radio" && this._dbusItem.property_get_int("toggle-state")) this.setOrnament(PopupMenu.Ornament.DOT) else this.setOrnament(PopupMenu.Ornament.NONE) }, _updateImage() { if (!this._icon) return // might be missing on submenus / separators let iconName = this._dbusItem.property_get("icon-name") let iconData = this._dbusItem.property_get_variant("icon-data") if (iconName) this._icon.icon_name = iconName else if (iconData) this._icon.gicon = GdkPixbuf.Pixbuf.new_from_stream(Gio.MemoryInputStream.new_from_bytes(iconData.get_data_as_bytes()), null) }, _updateVisible() { this.visible = this._dbusItem.property_get_bool("visible") }, _updateSensitive() { this.setSensitive(this._dbusItem.property_get_bool("enabled")) }, _replaceSelf(newSelf) { // create our new self if needed if (!newSelf) newSelf = MenuItemFactory.createItem(this._dbusClient, this._dbusItem) // first, we need to find our old position let pos = -1 let family = this._parent._getMenuItems() for (let i = 0; i < family.length; ++i) { if (family[i] === this) pos = i } if (pos < 0) throw new Error("DBusMenu: can't replace non existing menu item") // add our new self while we're still alive this._parent.addMenuItem(newSelf, pos) // now destroy our old self this.destroy() } } /** * Utility functions not necessarily belonging into the item factory */ const MenuUtils = { moveItemInMenu(menu, dbusItem, newpos) { //HACK: we're really getting into the internals of the PopupMenu implementation // First, find our wrapper. Children tend to lie. We do not trust the old positioning. let family = menu._getMenuItems() for (let i = 0; i < family.length; ++i) { if (family[i]._dbusItem == dbusItem) { // now, remove it menu.box.remove_child(family[i]) // and add it again somewhere else if (newpos < family.length && family[newpos] != family[i]) menu.box.insert_child_below(family[i], family[newpos]) else menu.box.add(family[i]) // skip the rest return } } } } /** * Processes DBus events, creates the menu items and handles the actions * * Something like a mini-god-object */ var Client = class AppIndicators_Client { constructor(busName, path) { this._busName = busName this._busPath = path this._client = new DBusClient(busName, path) this._rootMenu = null // the shell menu this._rootItem = null // the DbusMenuItem for the root } get isReady() { return this._client.isReady; } // this will attach the client to an already existing menu that will be used as the root menu. // it will also connect the client to be automatically destroyed when the menu dies. attachToMenu(menu) { this._rootMenu = menu this._rootItem = this._client.get_root() // cleanup: remove existing children (just in case) this._rootMenu.removeAll() if (NEED_NESTED_SUBMENU_FIX) menu._setOpenedSubMenu = this._setOpenedSubmenu.bind(this) // connect handlers Util.connectSmart(menu, 'open-state-changed', this, '_onMenuOpened') Util.connectSmart(menu, 'destroy', this, 'destroy') Util.connectSmart(this._rootItem, 'child-added', this, '_onRootChildAdded') Util.connectSmart(this._rootItem, 'child-removed', this, '_onRootChildRemoved') Util.connectSmart(this._rootItem, 'child-moved', this, '_onRootChildMoved') // Dropbox requires us to call AboutToShow(0) first this._rootItem.send_about_to_show() // fill the menu for the first time this._rootItem.get_children().forEach(child => this._rootMenu.addMenuItem(MenuItemFactory.createItem(this, child)) ); } _setOpenedSubmenu(submenu) { if (!submenu) return if (submenu._parent != this._rootMenu) return if (submenu === this._openedSubMenu) return if (this._openedSubMenu && this._openedSubMenu.isOpen) this._openedSubMenu.close(true) this._openedSubMenu = submenu } _onRootChildAdded(dbusItem, child, position) { this._rootMenu.addMenuItem(MenuItemFactory.createItem(this, child), position) } _onRootChildRemoved(dbusItem, child) { // children like to play hide and seek // but we know how to find it for sure! this._rootMenu._getMenuItems().forEach((item) => { if (item._dbusItem == child) item.destroy() }) } _onRootChildMoved(dbusItem, child, oldpos, newpos) { MenuUtils.moveItemInMenu(this._rootMenu, dbusItem, newpos) } _onMenuOpened(menu, state) { if (!this._rootItem) return if (state) { if (this._openedSubMenu && this._openedSubMenu.isOpen) this._openedSubMenu.close() this._rootItem.handle_event("opened", null, 0) this._rootItem.send_about_to_show() } else { this._rootItem.handle_event("closed", null, 0) } } destroy() { this.emit('destroy') if (this._client) this._client.destroy() this._client = null this._rootItem = null this._rootMenu = null } } Signals.addSignalMethods(Client.prototype) 07070100000006000081A40000000200000002000000015F6B6B1600001209000000000000000000000000000000000000004100000000gnome-shell-extension-appindicator-v34+git1.860086c/extension.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Gio = imports.gi.Gio; const GLib = imports.gi.GLib; const Gtk = imports.gi.Gtk; const Gdk = imports.gi.Gdk; const Main = imports.ui.main; const Mainloop = imports.mainloop; const Extension = imports.misc.extensionUtils.getCurrentExtension() const StatusNotifierWatcher = Extension.imports.statusNotifierWatcher const Util = Extension.imports.util let statusNotifierWatcher = null; let isEnabled = false; let watchDog = null; let startupPreparedId = 0; let waitForThemeId = 0; let startupComplete = false; let displayAvailable = false; function init() { watchDog = new NameWatchdog(); watchDog.onVanished = maybe_enable_after_name_available; //HACK: we want to leave the watchdog alive when disabling the extension, // but if we are being reloaded, we destroy it since it could be considered // a leak and spams our log, too. if (typeof global['--appindicator-extension-on-reload'] == 'function') global['--appindicator-extension-on-reload']() global['--appindicator-extension-on-reload'] = () => { Util.Logger.debug("Reload detected, destroying old watchdog") watchDog.destroy(); } } //FIXME: when entering/leaving the lock screen, the extension might be enabled/disabled rapidly. // This will create very bad side effects in case we were not done unowning the name while trying // to own it again. Since g_bus_unown_name doesn't fire any callback when it's done, we need to // monitor the bus manually to find out when the name vanished so we can reclaim it again. function maybe_enable_after_name_available() { // by the time we get called whe might not be enabled if (isEnabled && (!watchDog.nameAcquired || !watchDog.isPresent) && statusNotifierWatcher === null) statusNotifierWatcher = new StatusNotifierWatcher.StatusNotifierWatcher(watchDog); } function inner_enable() { if (startupComplete && displayAvailable) { isEnabled = true; maybe_enable_after_name_available(); } } function enable() { // If the desktop is still starting up, we must wait until it is ready if (Main.layoutManager._startingUp) { startupPreparedId = Main.layoutManager.connect('startup-complete', () => { Main.layoutManager.disconnect(startupPreparedId); startupComplete = true; inner_enable(); }); } else { startupComplete = true; } // Ensure that the default Gdk Screen is available if (Gtk.IconTheme.get_default() == null) { waitForThemeId = Gdk.DisplayManager.get().connect('display-opened', () => { Gdk.DisplayManager.get().disconnect(waitForThemeId); displayAvailable = true; inner_enable(); }); } else { displayAvailable = true; } inner_enable(); } function disable() { isEnabled = false; if (statusNotifierWatcher !== null) { statusNotifierWatcher.destroy(); statusNotifierWatcher = null; } } /** * NameWatchdog will monitor the ork.kde.StatusNotifierWatcher bus name for us */ var NameWatchdog = class AppIndicators_NameWatchdog { constructor() { this.onAppeared = null; this.onVanished = null; // will be set in the handlers which are guaranteed to be called at least once this.isPresent = false; this._watcher_id = Gio.DBus.session.watch_name("org.kde.StatusNotifierWatcher", 0, this._appeared_handler.bind(this), this._vanished_handler.bind(this)); } destroy() { Gio.DBus.session.unwatch_name(this._watcher_id); } _appeared_handler() { this.isPresent = true; if (this.onAppeared) this.onAppeared(); } _vanished_handler() { this.isPresent = false; if (this.onVanished) this.onVanished(); } } 07070100000007000081A40000000200000002000000015F6B6B160000118A000000000000000000000000000000000000004100000000gnome-shell-extension-appindicator-v34+git1.860086c/iconCache.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const GLib = imports.gi.GLib const Gio = imports.gi.Gio const Util = imports.misc.extensionUtils.getCurrentExtension().imports.util; // The icon cache caches icon objects in case they're reused shortly aftwerwards. // This is necessary for some indicators like skype which rapidly switch between serveral icons. // Without caching, the garbage collection would never be able to handle the amount of new icon data. // If the lifetime of an icon is over, the cache will destroy the icon. (!) // The presence of an inUse property set to true on the icon will extend the lifetime. const GC_INTERVAL = 60; // seconds const LIFETIME_TIMESPAN = 10; // seconds // how to use: see IconCache.add, IconCache.get var IconCache = class AppIndicators_IconCache { constructor() { this._cache = new Map(); this._lifetime = new Map(); //we don't want to attach lifetime to the object } add(id, icon) { if (!(icon instanceof Gio.Icon)) { Util.Logger.critical('IconCache: Only Gio.Icons are supported'); return null; } if (!id) { Util.Logger.critical('IconCache: Invalid ID provided'); return null; } let oldIcon = this._cache.get(id); if (!oldIcon || !oldIcon.equals(icon)) { Util.Logger.debug(`IconCache: adding ${id}: ${icon}`); this._cache.set(id, icon); } else { icon = oldIcon; } this._renewLifetime(id); this._checkGC(); return icon; } _remove(id) { Util.Logger.debug(`IconCache: removing ${id}`); this._cache.get(id).run_dispose(); this._cache.delete(id); this._lifetime.delete(id); } _renewLifetime(id) { this._lifetime.set(id, new Date().getTime() + LIFETIME_TIMESPAN * 1000); } forceDestroy(id) { if (this._cache.has(id)) { this._remove(id); this._checkGC(); } } // marks all the icons as removable, if something doesn't claim them before weakClear() { this._cache.forEach((icon) => icon.inUse = false); this._checkGC(); } // removes everything from the cache clear() { this._cache.forEach((_icon, id) => this._remove(id)); this._checkGC(); } // returns an object from the cache, or null if it can't be found. get(id) { let icon = this._cache.get(id); if (icon) { Util.Logger.debug(`IconCache: retrieving ${id}: ${icon}`); this._renewLifetime(id); return icon; } return null; } _checkGC() { let cacheIsEmpty = this._cache.size == 0; if (!cacheIsEmpty && !this._gcTimeout) { Util.Logger.debug("IconCache: garbage collector started"); this._gcTimeout = GLib.timeout_add_seconds( GLib.PRIORITY_LOW, GC_INTERVAL, () => this._gc()); } else if (cacheIsEmpty && this._gcTimeout) { Util.Logger.debug("IconCache: garbage collector stopped"); GLib.Source.remove(this._gcTimeout); delete this._gcTimeout; } } _gc() { let time = new Date().getTime(); this._cache.forEach((icon, id) => { if (icon.inUse) { Util.Logger.debug(`IconCache: ${id} is in use.`); } else if (this._lifetime.get(id) < time) { this._remove(id); } else { Util.Logger.debug(`IconCache: ${id} survived this round.`); } }); return true; } destroy() { this.clear(); } }; 07070100000008000041ED0000000200000002000000025F6B6B1600000000000000000000000000000000000000000000004800000000gnome-shell-extension-appindicator-v34+git1.860086c/indicator-test-tool07070100000009000081ED0000000200000002000000015F6B6B1600000B3D000000000000000000000000000000000000005000000000gnome-shell-extension-appindicator-v34+git1.860086c/indicator-test-tool/ksni.py#!/usr/bin/env python2 # -*- coding: utf-8 -*- import sys from PyQt4 import Qt from PyQt4.QtCore import QObject, QString from PyKDE4.kdeui import KStatusNotifierItem, KMenu App = Qt.QApplication(sys.argv) class Notifier(QObject): def __init__(self, parent=None): QObject.__init__(self, parent) self.tray = KStatusNotifierItem("ksni-test-tool", self) self.tray.setCategory(KStatusNotifierItem.Communications) self.tray.setIconByName(QString("/usr/share/icons/oxygen/16x16/categories/applications-internet.png")) self.tray.setAttentionIconByName(QString("accessories-text-editor")) self.tray.setStatus(KStatusNotifierItem.Active) self.tray.setToolTipIconByName(QString("/usr/share/icons/oxygen/16x16/categories/applications-internet.png")) self.menu = KMenu("KSNI Test Tool") self.menu.addAction("Hello", self.onHelloClicked) self.menu.addAction("Change Status", self.toggleStatus) self.menu.addAction("Hide for some seconds", self.hideForAWhile) self.menu.addAction("Switch to pixmap icon", self.usePixmap) self.menu.addSeparator() self.menu.addAction("Set overlay pixmap", self.setOverlayPixmap) self.menu.addAction("Set overlay icon name", self.setOverlayName) self.menu.addAction("Remove overlay icon", self.removeOverlay) self.tray.setContextMenu(self.menu) self.tray.activateRequested.connect(self.onActivated) self.tray.scrollRequested.connect(self.onScroll) def onActivated(self, show, point): print "Activate() called, show="+str(show)+", point="+str(point) def onScroll(self, delta, orientation): print "Scroll() called, delta="+str(delta)+", orientation="+str(orientation) def onHelloClicked(self): print "Hello World!" def toggleStatus(self): if (self.tray.status() == KStatusNotifierItem.Active): self.tray.setStatus(KStatusNotifierItem.NeedsAttention) else: self.tray.setStatus(KStatusNotifierItem.Active) def hideForAWhile(self): self.tray.setStatus(KStatusNotifierItem.Passive) Qt.QTimer.singleShot(2000, self.toggleStatus) def usePixmap(self): self.tray.setIconByName(QString("")) self.tray.setIconByPixmap(Qt.QIcon.fromTheme("accessories-calculator")) def setOverlayPixmap(self): self.tray.setOverlayIconByName(QString("")) self.tray.setOverlayIconByPixmap(Qt.QIcon.fromTheme("dialog-information")) def setOverlayName(self): self.tray.setOverlayIconByPixmap(Qt.QIcon()) self.tray.setOverlayIconByName(QString("dialog-error")) def removeOverlay(self): self.tray.setOverlayIconByName(QString("")) self.tray.setOverlayIconByPixmap(Qt.QIcon()) if __name__ == '__main__': notifer = Notifier() App.exec_() 0707010000000A000081ED0000000200000002000000015F6B6B16000023D9000000000000000000000000000000000000005400000000gnome-shell-extension-appindicator-v34+git1.860086c/indicator-test-tool/testTool.js#!/usr/bin/gjs /* * This creates an appindicator which contains all common menu items * * Requires libappindicator3 introspection data */ imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; const AppIndicator = imports.gi.AppIndicator3; const GLib = imports.gi.GLib; const Gio = imports.gi.Gio; const DEFAULT_ICON = 'start-here'; const ATTENTION_ICON = 'starred'; const iconsPool = [ 'emoji-recent-symbolic', 'emoji-flags-symbolic', 'emoji-objects-symbolic', 'emoji-nature-symbolic', 'emoji-body-symbolic', 'emoji-activities-symbolic', 'emoji-people-symbolic', 'emoji-travel-symbolic', 'emoji-symbols-symbolic', 'emoji-food-symbolic', ]; const ScrollType = { UP: 0, DOWN: 1, }; (() => { var app = new Gtk.Application({ application_id: null }); var window = null; app.connect("activate", () => { window.present(); }); app.connect("startup", () => { window = new Gtk.ApplicationWindow({ title: "test", application: app }); let getRandomIcon = () => iconsPool[Math.floor(Math.random() * (iconsPool.length - 1))]; let setRandomIconPath = () => { let iconName = getRandomIcon(); let iconInfo = Gtk.IconTheme.get_default().lookup_icon(iconName, 16, Gtk.IconLookupFlags.GENERIC_FALLBACK); let iconFile = Gio.File.new_for_path(iconInfo.get_filename()); let [, extension] = iconFile.get_basename().split('.'); let newName = `${iconName}-${Math.floor(Math.random() * 100)}.${extension}`; let newFile = Gio.File.new_for_path( `${GLib.dir_make_tmp('indicator-test-XXXXXX')}/${newName}`); iconFile.copy(newFile, Gio.FileCopyFlagsOVERWRITE, null, null); indicator.set_icon_theme_path(newFile.get_parent().get_path()); indicator.set_icon(newFile.get_basename()); } var menu = new Gtk.Menu(); var item = Gtk.MenuItem.new_with_label("A standard item"); menu.append(item); item = Gtk.MenuItem.new_with_label("Foo"); menu.append(item); item = Gtk.ImageMenuItem.new_with_label("Calculator"); item.image = Gtk.Image.new_from_icon_name("gnome-calculator", Gtk.IconSize.MENU); menu.append(item); item = Gtk.CheckMenuItem.new_with_label("Check me!"); menu.append(item); item = Gtk.MenuItem.new_with_label("Blub"); let sub = new Gtk.Menu(); item.set_submenu(sub); menu.append(item); item = Gtk.MenuItem.new_with_label("Blubdablub"); sub.append(item); item = new Gtk.SeparatorMenuItem(); menu.append(item); item = Gtk.MenuItem.new_with_label("Foo"); menu.append(item); let submenu = new Gtk.Menu(); item.set_submenu(submenu); item = Gtk.MenuItem.new_with_label("Hello"); submenu.append(item); item = Gtk.MenuItem.new_with_label("Nested"); submenu.append(item); let submenu1 = new Gtk.Menu(); item.set_submenu(submenu1); item = Gtk.MenuItem.new_with_label("Another nested"); submenu.append(item); let submenu2 = new Gtk.Menu(); item.set_submenu(submenu2); item = Gtk.MenuItem.new_with_label("Some other item"); submenu1.append(item); item = Gtk.MenuItem.new_with_label("abcdefg"); submenu2.append(item); item = new Gtk.SeparatorMenuItem(); menu.append(item); var group = []; for (let i = 0; i < 5; ++i) { item = Gtk.RadioMenuItem.new_with_label(group, "Example Radio "+i); group = Gtk.RadioMenuItem.prototype.get_group.apply(item)//.get_group(); if (i == 1) item.set_active(true); menu.append(item); } item = new Gtk.SeparatorMenuItem(); menu.append(item); item = Gtk.MenuItem.new_with_label("Set Label"); item.connect('activate', () => { indicator.set_label(''+new Date().getTime(), 'Blub'); }); menu.append(item); item = Gtk.MenuItem.new_with_label("Unset Label"); item.connect('activate', () => { indicator.set_label('', ''); }) menu.append(item); item = Gtk.MenuItem.new_with_label("Autodestroy Label"); item.connect('activate', () => { let i = 30; GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1, () => { indicator.set_label(i > 0 ? `Label timeout ${i--}` : '', ''); return (i >= 0); }); }) menu.append(item); item = Gtk.MenuItem.new_with_label('Set Random icon'); item.connect('activate', () => indicator.set_icon(getRandomIcon())); menu.append(item); item = Gtk.MenuItem.new_with_label('Set Random custom theme icon'); item.connect('activate', setRandomIconPath); menu.append(item); item = Gtk.CheckMenuItem.new_with_label('Toggle Label and Icon'); item.connect('activate', (item) => { if (item.get_active()) { indicator.set_label(`${new Date().getTime()}`, 'Blub'); item.connect('activate', () => indicator.set_icon(getRandomIcon())); } else { indicator.set_label('', ''); indicator.set_icon(DEFAULT_ICON); } }) menu.append(item); let toggleBrandingItem = item; item = Gtk.CheckMenuItem.new_with_label('Toggle Attention'); let toggleAttentionId = item.connect('activate', () => { indicator.set_status(indicator.get_status() != AppIndicator.IndicatorStatus.ATTENTION ? AppIndicator.IndicatorStatus.ATTENTION : AppIndicator.IndicatorStatus.ACTIVE); }); menu.append(item); let toggleAttentionItem = item; item = new Gtk.SeparatorMenuItem(); menu.append(item); /* Double separaptors test */ item = new Gtk.SeparatorMenuItem(); menu.append(item); /* Simulate similar behavior of #226 and #236 */ item = Gtk.CheckMenuItem.new_with_label('Crazy icons updates'); item.connect('activate', (item) => { if (item.get_active()) { item._timeoutID = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 16, () => { setRandomIconPath(); indicator.set_label(`${new Date().getSeconds()}`, ''); return GLib.SOURCE_CONTINUE; }); } else { GLib.source_remove(item._timeoutID); delete item._timeoutID; } }); menu.append(item); item = Gtk.MenuItem.new_with_label("Hide for some time"); item.connect('activate', () => { indicator.set_status(AppIndicator.IndicatorStatus.PASSIVE); GLib.timeout_add(0, 5000, () => { indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE); return false; }); }); menu.append(item); item = Gtk.MenuItem.new_with_label("Close in 5 seconds"); item.connect('activate', () => { GLib.timeout_add(0, 5000, () => { app.quit(); return false; }); }); menu.append(item); menu.show_all(); var indicator = AppIndicator.Indicator.new("Hello", "indicator-test", AppIndicator.IndicatorCategory.APPLICATION_STATUS); indicator.set_status(AppIndicator.IndicatorStatus.ACTIVE); indicator.set_icon(DEFAULT_ICON); indicator.set_attention_icon(ATTENTION_ICON); indicator.set_menu(menu); indicator.set_secondary_activate_target(toggleBrandingItem); indicator.connect("connection-changed", (indicator, connected) => { print(`Signal "connection-changed" emitted. Connected: ${connected}`); }); indicator.connect("new-attention-icon", (indicator) => { print(`Signal "new-attention-icon" emitted.`); }); indicator.connect("new-icon", (indicator) => { let icon = "<none>"; if (indicator.get_status() == AppIndicator.IndicatorStatus.ATTENTION) icon = indicator.get_attention_icon(); else if (indicator.get_status() == AppIndicator.IndicatorStatus.ACTIVE) icon = indicator.get_icon(); print(`Signal "new-icon" emitted. Icon: ${icon}`); }); indicator.connect("new-icon-theme-path", (indicator, path) => { print(`Signal "new-icon-theme-path" emitted. Path: ${path}`); }); indicator.connect("new-label", (indicator, label, guide) => { print(`Signal "new-label" emitted. Label: ${label}, Guide: ${guide}`); }); indicator.connect("new-status", (indicator, status) => { print(`Signal "new-status" emitted. Status: ${status}`); toggleAttentionItem.block_signal_handler(toggleAttentionId); toggleAttentionItem.set_active(status == 'NeedsAttention'); toggleAttentionItem.unblock_signal_handler(toggleAttentionId); }); indicator.connect("scroll-event", (indicator, steps, direction) => { print(`Signal "scroll-event" emitted. Steps: ${steps}, Direction: ${direction}`); let currentIndex = iconsPool.indexOf(indicator.get_icon()); let iconIndex; if (direction == ScrollType.UP) { iconIndex = (currentIndex + 1) % iconsPool.length; } else { iconIndex = (currentIndex <= 0 ? iconsPool.length : currentIndex) - 1; } indicator.set_icon(iconsPool[iconIndex]); }); }); app.run(ARGV); })(); 0707010000000B000081A40000000200000002000000015F6B6B1600001505000000000000000000000000000000000000004B00000000gnome-shell-extension-appindicator-v34+git1.860086c/indicatorStatusIcon.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Clutter = imports.gi.Clutter; const GObject = imports.gi.GObject; const St = imports.gi.St; const Main = imports.ui.main; const Panel = imports.ui.panel; const PanelMenu = imports.ui.panelMenu; const PopupMenu = imports.ui.popupMenu; const Config = imports.misc.config; const ExtensionUtils = imports.misc.extensionUtils; const Extension = ExtensionUtils.getCurrentExtension(); const AppIndicator = Extension.imports.appIndicator const DBusMenu = Extension.imports.dbusMenu; const Util = Extension.imports.util; /* * IndicatorStatusIcon implements an icon in the system status area */ var IndicatorStatusIcon = GObject.registerClass( class AppIndicators_IndicatorStatusIcon extends PanelMenu.Button { _init(indicator) { super._init(0.5, indicator._uniqueId); this._indicator = indicator; this._iconBox = new AppIndicator.IconActor(indicator, Panel.PANEL_ICON_SIZE); this._box = new St.BoxLayout({ style_class: 'panel-status-indicators-box' }); this._box.add_style_class_name('appindicator-box'); this.add_child(this._box); this._box.add_child(this._iconBox); Util.connectSmart(this, 'button-press-event', this, '_boxClicked') Util.connectSmart(this._indicator, 'ready', this, '_display') Util.connectSmart(this._indicator, 'menu', this, '_updateMenu') Util.connectSmart(this._indicator, 'label', this, '_updateLabel') Util.connectSmart(this._indicator, 'status', this, '_updateStatus') Util.connectSmart(this._indicator, 'reset', this, () => { this._updateStatus(); this._updateLabel(); }); this.connect('destroy', () => { if (this._menuClient) { this._menuClient.destroy(); this._menuClient = null; } }) if (this._indicator.isReady) this._display() } _updateLabel() { var label = this._indicator.label; if (label) { if (!this._label || !this._labelBin) { this._labelBin = new St.Bin({ y_align: ExtensionUtils.versionCheck(['3.34'], Config.PACKAGE_VERSION) ? St.Align.MIDDLE : Clutter.ActorAlign.CENTER, }); this._label = new St.Label(); this._labelBin.add_actor(this._label); this._box.add_actor(this._labelBin); } this._label.set_text(label); if (!this._box.contains(this._labelBin)) this._box.add_actor(this._labelBin); //FIXME: why is it suddenly necessary? } else { if (this._label) { this._labelBin.destroy_all_children(); this._box.remove_actor(this._labelBin); this._labelBin.destroy(); delete this._labelBin; delete this._label; } } } _updateStatus() { this.visible = this._indicator.status != AppIndicator.SNIStatus.PASSIVE; } _updateMenu() { if (this._menuClient) { this._menuClient.destroy(); this._menuClient = null; this.menu.removeAll(); } if (this._indicator.menuPath) { this._menuClient = new DBusMenu.Client(this._indicator.busName, this._indicator.menuPath); this._menuClient.attachToMenu(this.menu); } } _display() { this._updateLabel(); this._updateStatus(); this._updateMenu(); Main.panel.addToStatusArea("appindicator-"+this._indicator.uniqueId, this, 1, 'right') } _boxClicked(actor, event) { // if middle mouse button clicked send SecondaryActivate dbus event and do not show appindicator menu if (event.get_button() == 2) { Main.panel.menuManager._closeMenu(true, Main.panel.menuManager.activeMenu); this._indicator.secondaryActivate(); return; } //HACK: event should be a ClutterButtonEvent but we get only a ClutterEvent (why?) // because we can't access click_count, we'll create our own double click detector. var treshold = Clutter.Settings.get_default().double_click_time; var now = new Date().getTime(); if (this._lastClicked && (now - this._lastClicked) < treshold) { this._lastClicked = null; //reset double click detector this._indicator.open(); } else { this._lastClicked = now; } } }); 0707010000000C000041ED0000000200000002000000025F6B6B1600000000000000000000000000000000000000000000004300000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces-xml0707010000000D000081A40000000200000002000000015F6B6B160000099B000000000000000000000000000000000000005000000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces-xml/DBusMenu.xml<interface name="com.canonical.dbusmenu"> <!-- Properties --> <property name="Version" type="u" access="read" /> <property name="TextDirection" type="s" access="read" /> <property name="Status" type="s" access="read" /> <property name="IconThemePath" type="as" access="read" /> <!-- Functions --> <method name="GetLayout"> <arg type="i" name="parentId" direction="in" /> <arg type="i" name="recursionDepth" direction="in" /> <arg type="as" name="propertyNames" direction="in" /> <arg type="u" name="revision" direction="out" /> <arg type="(ia{sv}av)" name="layout" direction="out" /> </method> <method name="GetGroupProperties"> <arg type="ai" name="ids" direction="in" /> <arg type="as" name="propertyNames" direction="in" /> <arg type="a(ia{sv})" name="properties" direction="out" /> </method> <method name="GetProperty"> <arg type="i" name="id" direction="in" /> <arg type="s" name="name" direction="in" /> <arg type="v" name="value" direction="out" /> </method> <method name="Event"> <arg type="i" name="id" direction="in" /> <arg type="s" name="eventId" direction="in" /> <arg type="v" name="data" direction="in" /> <arg type="u" name="timestamp" direction="in" /> </method> <method name="EventGroup"> <arg type="a(isvu)" name="events" direction="in" /> <arg type="ai" name="idErrors" direction="out" /> </method> <method name="AboutToShow"> <arg type="i" name="id" direction="in" /> <arg type="b" name="needUpdate" direction="out" /> </method> <method name="AboutToShowGroup"> <arg type="ai" name="ids" direction="in" /> <arg type="ai" name="updatesNeeded" direction="out" /> <arg type="ai" name="idErrors" direction="out" /> </method> <!-- Signals --> <signal name="ItemsPropertiesUpdated"> <arg type="a(ia{sv})" name="updatedProps" direction="out" /> <arg type="a(ias)" name="removedProps" direction="out" /> </signal> <signal name="LayoutUpdated"> <arg type="u" name="revision" direction="out" /> <arg type="i" name="parent" direction="out" /> </signal> <signal name="ItemActivationRequested"> <arg type="i" name="id" direction="out" /> <arg type="u" name="timestamp" direction="out" /> </signal> </interface> 0707010000000E000081A40000000200000002000000015F6B6B1600000211000000000000000000000000000000000000005200000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces-xml/Properties.xml<interface name="org.freedesktop.DBus.Properties"> <method name="Get"> <arg type="s" direction="in" /> <arg type="s" direction="in" /> <arg type="v" direction="out" /> </method> <method name="GetAll"> <arg type="s" direction="in" /> <arg type="a{sv}" direction="out" /> </method> <signal name="PropertiesChanged"> <arg type="s" direction="out" /> <arg type="a{sv}" direction="out" /> <arg type="as" direction="out" /> </signal> </interface> 0707010000000F000081A40000000200000002000000015F6B6B1600000F68000000000000000000000000000000000000005A00000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces-xml/StatusNotifierItem.xml<!-- Based on: https://invent.kde.org/frameworks/knotifications/-/blob/master/src/org.kde.StatusNotifierItem.xml --> <interface name="org.kde.StatusNotifierItem"> <property name="Category" type="s" access="read"/> <property name="Id" type="s" access="read"/> <property name="Title" type="s" access="read"/> <property name="Status" type="s" access="read"/> <property name="WindowId" type="i" access="read"/> <!-- An additional path to add to the theme search path to find the icons specified above. --> <property name="IconThemePath" type="s" access="read"/> <property name="Menu" type="o" access="read"/> <property name="ItemIsMenu" type="b" access="read"/> <!-- main icon --> <!-- names are preferred over pixmaps --> <property name="IconName" type="s" access="read"/> <!--struct containing width, height and image data--> <property name="IconPixmap" type="a(iiay)" access="read"> <annotation name="org.qtproject.QtDBus.QtTypeName" value="KDbusImageVector"/> </property> <property name="OverlayIconName" type="s" access="read"/> <property name="OverlayIconPixmap" type="a(iiay)" access="read"> <annotation name="org.qtproject.QtDBus.QtTypeName" value="KDbusImageVector"/> </property> <!-- Requesting attention icon --> <property name="AttentionIconName" type="s" access="read"/> <!--same definition as image--> <property name="AttentionIconPixmap" type="a(iiay)" access="read"> <annotation name="org.qtproject.QtDBus.QtTypeName" value="KDbusImageVector"/> </property> <property name="AttentionMovieName" type="s" access="read"/> <!-- tooltip data --> <!--(iiay) is an image--> <!-- We disable this as we don't support tooltip, so no need to go through it <property name="ToolTip" type="(sa(iiay)ss)" access="read"> <annotation name="org.qtproject.QtDBus.QtTypeName" value="KDbusToolTipStruct"/> </property> --> <!-- interaction: the systemtray wants the application to do something --> <method name="ContextMenu"> <!-- we're passing the coordinates of the icon, so the app knows where to put the popup window --> <arg name="x" type="i" direction="in"/> <arg name="y" type="i" direction="in"/> </method> <method name="Activate"> <arg name="x" type="i" direction="in"/> <arg name="y" type="i" direction="in"/> </method> <method name="SecondaryActivate"> <arg name="x" type="i" direction="in"/> <arg name="y" type="i" direction="in"/> </method> <method name="Scroll"> <arg name="delta" type="i" direction="in"/> <arg name="orientation" type="s" direction="in"/> </method> <!-- Signals: the client wants to change something in the status--> <signal name="NewTitle"> </signal> <signal name="NewIcon"> </signal> <signal name="NewAttentionIcon"> </signal> <signal name="NewOverlayIcon"> </signal> <!-- We disable this as we don't support tooltip, so no need to go through it <signal name="NewToolTip"> </signal> --> <signal name="NewStatus"> <arg name="status" type="s"/> </signal> <!-- The following items are not supported by specs, but widely used --> <signal name="NewIconThemePath"> <arg type="s" name="icon_theme_path" direction="out" /> </signal> <signal name="NewMenu"></signal> <!-- ayatana labels --> <!-- These are commented out because GDBusProxy would otherwise require them, but they are not available for KDE indicators --> <!--<signal name="XAyatanaNewLabel"> <arg type="s" name="label" direction="out" /> <arg type="s" name="guide" direction="out" /> </signal> <property name="XAyatanaLabel" type="s" access="read" /> <property name="XAyatanaLabelGuide" type="s" access="read" />--> </interface> 07070100000010000081A40000000200000002000000015F6B6B16000003E0000000000000000000000000000000000000005D00000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces-xml/StatusNotifierWatcher.xml<interface name="org.kde.StatusNotifierWatcher"> <!-- methods --> <method name="RegisterStatusNotifierItem"> <arg name="service" type="s" direction="in"/> </method> <method name="RegisterStatusNotifierHost"> <arg name="service" type="s" direction="in"/> </method> <!-- properties --> <property name="RegisteredStatusNotifierItems" type="as" access="read"> <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="QStringList"/> </property> <property name="IsStatusNotifierHostRegistered" type="b" access="read"/> <property name="ProtocolVersion" type="i" access="read"/> <!-- signals --> <signal name="StatusNotifierItemRegistered"> <arg type="s"/> </signal> <signal name="StatusNotifierItemUnregistered"> <arg type="s"/> </signal> <signal name="StatusNotifierHostRegistered"> </signal> <signal name="StatusNotifierHostUnregistered"> </signal> </interface> 07070100000011000081A40000000200000002000000015F6B6B1600000820000000000000000000000000000000000000004200000000gnome-shell-extension-appindicator-v34+git1.860086c/interfaces.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. var StatusNotifierItem = loadInterfaceXml("StatusNotifierItem.xml") const Properties = loadInterfaceXml("Properties.xml") var StatusNotifierWatcher = loadInterfaceXml("StatusNotifierWatcher.xml") var DBusMenu = loadInterfaceXml("DBusMenu.xml") // loads a xml file into an in-memory string function loadInterfaceXml(filename) { let extension = imports.misc.extensionUtils.getCurrentExtension() let interfaces_dir = extension.dir.get_child("interfaces-xml") let file = interfaces_dir.get_child(filename) let [ result, contents ] = imports.gi.GLib.file_get_contents(file.get_path()) if (result) { //HACK: The "" + trick is important as hell because file_get_contents returns // an object (WTF?) but Gio.makeProxyWrapper requires `typeof() == "string"` // Otherwise, it will try to check `instanceof XML` and fail miserably because there // is no `XML` on very recent SpiderMonkey releases (or, if SpiderMonkey is old enough, // will spit out a TypeError soon). if (contents instanceof Uint8Array) contents = imports.byteArray.toString(contents); return "<node>" + contents + "</node>" } else { throw new Error("AppIndicatorSupport: Could not load file: "+filename) } } 07070100000012000081A40000000200000002000000015F6B6B160000015D000000000000000000000000000000000000004200000000gnome-shell-extension-appindicator-v34+git1.860086c/metadata.json{ "shell-version": [ "3.33", "3.34", "3.36", "3.38" ], "uuid": "appindicatorsupport@rgcjonas.gmail.com", "name": "KStatusNotifierItem/AppIndicator Support", "description": "Adds KStatusNotifierItem support to the Shell", "url": "https://github.com/ubuntu/gnome-shell-extension-appindicator" } 07070100000013000081A40000000200000002000000015F6B6B16000022BF000000000000000000000000000000000000004D00000000gnome-shell-extension-appindicator-v34+git1.860086c/statusNotifierWatcher.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Gio = imports.gi.Gio const GLib = imports.gi.GLib const Gtk = imports.gi.Gtk const Mainloop = imports.mainloop const ShellConfig = imports.misc.config const Signals = imports.signals const Extension = imports.misc.extensionUtils.getCurrentExtension() const AppIndicator = Extension.imports.appIndicator const IndicatorStatusIcon = Extension.imports.indicatorStatusIcon const Interfaces = Extension.imports.interfaces const Util = Extension.imports.util // TODO: replace with org.freedesktop and /org/freedesktop when approved const KDE_PREFIX = 'org.kde'; const WATCHER_BUS_NAME = KDE_PREFIX + '.StatusNotifierWatcher'; const WATCHER_INTERFACE = WATCHER_BUS_NAME; const WATCHER_OBJECT = '/StatusNotifierWatcher'; const DEFAULT_ITEM_OBJECT_PATH = '/StatusNotifierItem'; const BUS_ADDRESS_REGEX = /([a-zA-Z0-9._-]+\.[a-zA-Z0-9.-]+)|(:[0-9]+\.[0-9]+)$/ /* * The StatusNotifierWatcher class implements the StatusNotifierWatcher dbus object */ var StatusNotifierWatcher = class AppIndicators_StatusNotifierWatcher { constructor(watchDog) { this._watchDog = watchDog; this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(Interfaces.StatusNotifierWatcher, this); this._dbusImpl.export(Gio.DBus.session, WATCHER_OBJECT); this._cancellable = new Gio.Cancellable; this._everAcquiredName = false; this._ownName = Gio.DBus.session.own_name(WATCHER_BUS_NAME, Gio.BusNameOwnerFlags.NONE, this._acquiredName.bind(this), this._lostName.bind(this)); this._items = new Map(); this._nameWatcher = new Map(); this._serviceWatcher = new Map(); this._seekStatusNotifierItems(); } _acquiredName() { this._watchDog.nameAcquired = true; } _lostName() { if (this._everAcquiredName) Util.Logger.debug('Lost name' + WATCHER_BUS_NAME); else Util.Logger.warn('Failed to acquire ' + WATCHER_BUS_NAME); this._watchDog.nameAcquired = false; } // create a unique index for the _items dictionary _getItemId(bus_name, obj_path) { return bus_name + obj_path; } _registerItem(service, bus_name, obj_path) { let id = this._getItemId(bus_name, obj_path); if (this._items.has(id)) { Util.Logger.warn(`Item ${id} is already registered`); return; } Util.Logger.debug(`Registering StatusNotifierItem ${id}`); let indicator = new AppIndicator.AppIndicator(bus_name, obj_path); let visual = new IndicatorStatusIcon.IndicatorStatusIcon(indicator); indicator.connect('destroy', () => visual.destroy()); this._items.set(id, indicator); this._dbusImpl.emit_signal('StatusNotifierItemRegistered', GLib.Variant.new('(s)', service)); this._nameWatcher.set(id, Gio.DBus.session.watch_name(bus_name, Gio.BusNameWatcherFlags.NONE, null, () => this._itemVanished(id))); if (service != bus_name && service.match(BUS_ADDRESS_REGEX)) { this._serviceWatcher.set(id, Gio.DBus.session.watch_name(service, Gio.BusNameWatcherFlags.NONE, null, () => this._itemVanished(id))); } this._dbusImpl.emit_property_changed('RegisteredStatusNotifierItems', GLib.Variant.new('as', this.RegisteredStatusNotifierItems)); } _ensureItemRegistered(service, bus_name, obj_path) { let id = this._getItemId(bus_name, obj_path); let item = this._items.get(id); if (item) { //delete the old one and add the new indicator Util.Logger.debug(`Attempting to re-register ${id}; resetting instead`); item.reset(); return; } this._registerItem(service, bus_name, obj_path) } _seekStatusNotifierItems() { // Some indicators (*coff*, dropbox, *coff*) do not re-register again // when the plugin is enabled/disabled, thus we need to manually look // for the objects in the session bus that implements the // StatusNotifierItem interface... Util.traverseBusNames(Gio.DBus.session, this._cancellable, (bus, name, cancellable) => { Util.introspectBusObject(bus, name, cancellable, (node_info) => { return Util.dbusNodeImplementsInterfaces(node_info, ['org.kde.StatusNotifierItem']); }, (name, path) => { let id = this._getItemId(name, path); if (!this._items.has(id)) { Util.Logger.debug(`Using Brute-force mode for StatusNotifierItem ${id}`); this._registerItem(path, name, path); } }) }); } RegisterStatusNotifierItemAsync(params, invocation) { // it would be too easy if all application behaved the same // instead, ayatana patched gnome apps to send a path // while kde apps send a bus name let [service] = params; let bus_name = null, obj_path = null; if (service.charAt(0) == '/') { // looks like a path bus_name = invocation.get_sender(); obj_path = service; } else if (service.match(BUS_ADDRESS_REGEX)) { bus_name = Util.getUniqueBusNameSync(invocation.get_connection(), service); obj_path = DEFAULT_ITEM_OBJECT_PATH; } if (!bus_name || !obj_path) { let error = "Impossible to register an indicator for parameters '"+ service.toString()+"'"; Util.Logger.warn(error); invocation.return_dbus_error('org.gnome.gjs.JSError.ValueError', error); return; } this._ensureItemRegistered(service, bus_name, obj_path); invocation.return_value(null); } _itemVanished(id) { // FIXME: this is useless if the path name disappears while the bus stays alive (not unheard of) if (this._items.has(id)) { this._remove(id); } } _remove(id) { this._items.get(id).destroy(); this._items.delete(id); Gio.DBus.session.unwatch_name(this._nameWatcher.get(id)); this._nameWatcher.delete(id); if (this._serviceWatcher.has(id)) { Gio.DBus.session.unwatch_name(this._serviceWatcher.get(id)); this._serviceWatcher.delete(id); } this._dbusImpl.emit_signal('StatusNotifierItemUnregistered', GLib.Variant.new('(s)', id)); this._dbusImpl.emit_property_changed('RegisteredStatusNotifierItems', GLib.Variant.new('as', this.RegisteredStatusNotifierItems)); } RegisterStatusNotifierHostAsync(_service, invocation) { invocation.return_error_literal( Gio.DBusError, Gio.DBusError.NOT_SUPPORTED, 'Registering additional notification hosts is not supported'); } IsNotificationHostRegistered() { return true; } get RegisteredStatusNotifierItems() { return Array.from(this._items.keys()); } get IsStatusNotifierHostRegistered() { return true; } get ProtocolVersion() { return 0; } destroy() { if (!this._isDestroyed) { // this doesn't do any sync operation and doesn't allow us to hook up the event of being finished // which results in our unholy debounce hack (see extension.js) Gio.DBus.session.unown_name(this._ownName); this._cancellable.cancel(); this._dbusImpl.unexport(); this._nameWatcher.forEach(n => Gio.DBus.session.unwatch_name(n)); delete this._nameWatcher; this._serviceWatcher.forEach(s => Gio.DBus.session.unwatch_name(s)); delete this._serviceWatcher; this._items.forEach(i => i.destroy()); delete this._items; this._isDestroyed = true; } } }; 07070100000014000081A40000000200000002000000015F6B6B1600002A4B000000000000000000000000000000000000003C00000000gnome-shell-extension-appindicator-v34+git1.860086c/util.js// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. const Gio = imports.gi.Gio const GLib = imports.gi.GLib const GObject = imports.gi.GObject const Extension = imports.misc.extensionUtils.getCurrentExtension(); const Params = imports.misc.params; const Signals = imports.signals var refreshPropertyOnProxy = function(proxy, propertyName, params) { if (!proxy._proxyCancellables) proxy._proxyCancellables = new Map(); params = Params.parse(params, { skipEqualtyCheck: false, }); let cancellable = cancelRefreshPropertyOnProxy(proxy, { propertyName, addNew: true }); proxy.g_connection.call( proxy.g_name, proxy.g_object_path, 'org.freedesktop.DBus.Properties', 'Get', GLib.Variant.new('(ss)', [ proxy.g_interface_name, propertyName ]), GLib.VariantType.new('(v)'), Gio.DBusCallFlags.NONE, -1, cancellable, (conn, result) => { try { let valueVariant = conn.call_finish(result).deep_unpack()[0]; proxy._proxyCancellables.delete(propertyName); if (!params.skipEqualtyCheck && proxy.get_cached_property(propertyName).equal(valueVariant)) return; proxy.set_cached_property(propertyName, valueVariant) // synthesize a batched property changed event if (!proxy._proxyChangedProperties) proxy._proxyChangedProperties = {}; proxy._proxyChangedProperties[propertyName] = valueVariant; if (!proxy._proxyPropertiesEmitId) { proxy._proxyPropertiesEmitId = GLib.timeout_add( GLib.PRIORITY_DEFAULT_IDLE, 16, () => { delete proxy._proxyPropertiesEmitId; proxy.emit('g-properties-changed', GLib.Variant.new('a{sv}', proxy._proxyChangedProperties), []); delete proxy._proxyChangedProperties; return GLib.SOURCE_REMOVE; }); } } catch (e) { if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) { // the property may not even exist, silently ignore it Logger.debug(`While refreshing property ${propertyName}: ${e}`); proxy._proxyCancellables.delete(propertyName); delete proxy._proxyChangedProperties[propertyName]; } } }); } var cancelRefreshPropertyOnProxy = function(proxy, params) { if (!proxy._proxyCancellables) return; params = Params.parse(params, { propertyName: undefined, addNew: false, }); if (params.propertyName !== undefined) { let cancellable = proxy._proxyCancellables.get(params.propertyName); if (cancellable) { cancellable.cancel(); if (!params.addNew) proxy._proxyCancellables.delete(params.propertyName); } if (params.addNew) { cancellable = new Gio.Cancellable(); proxy._proxyCancellables.set(params.propertyName, cancellable); return cancellable; } } else { if (proxy._proxyPropertiesEmitId) { GLib.source_remove(proxy._proxyPropertiesEmitId); delete proxy._proxyPropertiesEmitId; } proxy._proxyCancellables.forEach(c => c.cancel()); delete proxy._proxyChangedProperties; delete proxy._proxyCancellables; } } var getUniqueBusNameSync = function(bus, name) { if (name[0] == ':') return name; if (!bus) bus = Gio.DBus.session; let variant_name = new GLib.Variant("(s)", [name]); let [unique] = bus.call_sync("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner", variant_name, null, Gio.DBusCallFlags.NONE, -1, null).deep_unpack(); return unique; } var traverseBusNames = function(bus, cancellable, callback) { if (!bus) bus = Gio.DBus.session; if (typeof(callback) !== "function") throw new Error("No traversal callback provided"); bus.call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames", null, new GLib.VariantType("(as)"), 0, -1, cancellable, function (bus, task) { if (task.had_error()) return; let [names] = bus.call_finish(task).deep_unpack(); let unique_names = new Set(); for (let name of names) { try { unique_names.add(getUniqueBusNameSync(bus, name)); } catch (e) { Logger.debug(`Impossible to get the unique name of ${name}: ${e}`); } } unique_names.forEach((name) => callback(bus, name, cancellable)); }); } var introspectBusObject = function(bus, name, cancellable, filterFunction, targetCallback, path) { if (!path) path = "/"; if (typeof targetCallback !== "function") throw new Error("No introspection callback defined"); bus.call (name, path, "org.freedesktop.DBus.Introspectable", "Introspect", null, new GLib.VariantType("(s)"), Gio.DBusCallFlags.NONE, -1, cancellable, function (bus, task) { if (task.had_error()) return; let introspection = bus.call_finish(task).deep_unpack().toString(); let node_info = Gio.DBusNodeInfo.new_for_xml(introspection); if ((typeof filterFunction === "function" && filterFunction(node_info) === true) || !filterFunction) { targetCallback(name, path); } if (path === "/") path = "" for (let sub_nodes of node_info.nodes) { let sub_path = path+"/"+sub_nodes.path; introspectBusObject (bus, name, cancellable, filterFunction, targetCallback, sub_path); } }); } var dbusNodeImplementsInterfaces = function(node_info, interfaces) { if (!(node_info instanceof Gio.DBusNodeInfo) || !Array.isArray(interfaces)) return false; for (let iface of interfaces) { if (node_info.lookup_interface(iface) !== null) return true; } return false; } const connectSmart3A = function(src, signal, handler) { let id = src.connect(signal, handler) if (src.connect && (!(src instanceof GObject.Object) || GObject.signal_lookup('destroy', src))) { let destroy_id = src.connect('destroy', () => { src.disconnect(id) src.disconnect(destroy_id) }) } } const connectSmart4A = function(src, signal, target, method) { if (typeof method === 'string') method = target[method].bind(target) if (typeof method === 'function') method = method.bind(target) let signal_id = src.connect(signal, method) // GObject classes might or might not have a destroy signal // JS Classes will not complain when connecting to non-existent signals let src_destroy_id = src.connect && (!(src instanceof GObject.Object) || GObject.signal_lookup('destroy', src)) ? src.connect('destroy', on_destroy) : 0 let tgt_destroy_id = target.connect && (!(target instanceof GObject.Object) || GObject.signal_lookup('destroy', target)) ? target.connect('destroy', on_destroy) : 0 function on_destroy() { src.disconnect(signal_id) if (src_destroy_id) src.disconnect(src_destroy_id) if (tgt_destroy_id) target.disconnect(tgt_destroy_id) } } /** * Connect signals to slots, and remove the connection when either source or * target are destroyed * * Usage: * Util.connectSmart(srcOb, 'signal', tgtObj, 'handler') * or * Util.connectSmart(srcOb, 'signal', () => { ... }) */ var connectSmart = function() { if (arguments.length == 4) return connectSmart4A.apply(null, arguments) else return connectSmart3A.apply(null, arguments) } /** * Helper class for logging stuff */ var Logger = class AppIndicators_Logger { static _logStructured(logLevel, message, extraFields = {}) { if (!Object.values(GLib.LogLevelFlags).includes(logLevel)) { _logStructured(GLib.LogLevelFlags.LEVEL_WARNING, 'logLevel is not a valid GLib.LogLevelFlags'); return; } let domain = Extension.metadata.name; let fields = { 'SYSLOG_IDENTIFIER': Extension.metadata.uuid, 'MESSAGE': `${message}`, }; let thisFile = null; let { stack } = new Error(); for (let stackLine of stack.split('\n')) { stackLine = stackLine.replace('resource:///org/gnome/Shell/', ''); let [code, line] = stackLine.split(':'); let [func, file] = code.split(/@(.+)/); if (!thisFile || thisFile === file) { thisFile = file; continue; } fields = Object.assign(fields, { 'CODE_FILE': file || '', 'CODE_LINE': line || '', 'CODE_FUNC': func || '', }); break; } GLib.log_structured(domain, logLevel, Object.assign(fields, extraFields)); } static debug(message) { Logger._logStructured(GLib.LogLevelFlags.LEVEL_DEBUG, message); } static message(message) { Logger._logStructured(GLib.LogLevelFlags.LEVEL_MESSAGE, message); } static warn(message) { Logger._logStructured(GLib.LogLevelFlags.LEVEL_WARNING, message); } static error(message) { Logger._logStructured(GLib.LogLevelFlags.LEVEL_ERROR, message); } static critical(message) { Logger._logStructured(GLib.LogLevelFlags.LEVEL_CRITICAL, message); } }; 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!267 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor