dbusMenu.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. // This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension
  2. //
  3. // This program is free software; you can redistribute it and/or
  4. // modify it under the terms of the GNU General Public License
  5. // as published by the Free Software Foundation; either version 2
  6. // of the License, or (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. import Clutter from 'gi://Clutter';
  17. import GLib from 'gi://GLib';
  18. import GObject from 'gi://GObject';
  19. import GdkPixbuf from 'gi://GdkPixbuf';
  20. import Gio from 'gi://Gio';
  21. import St from 'gi://St';
  22. import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
  23. import * as Signals from 'resource:///org/gnome/shell/misc/signals.js';
  24. import * as DBusInterfaces from './interfaces.js';
  25. import * as PromiseUtils from './promiseUtils.js';
  26. import * as Util from './util.js';
  27. import {DBusProxy} from './dbusProxy.js';
  28. Gio._promisify(GdkPixbuf.Pixbuf, 'new_from_stream_async');
  29. // ////////////////////////////////////////////////////////////////////////
  30. // PART ONE: "ViewModel" backend implementation.
  31. // Both code and design are inspired by libdbusmenu
  32. // ////////////////////////////////////////////////////////////////////////
  33. /**
  34. * Saves menu property values and handles type checking and defaults
  35. */
  36. export class PropertyStore {
  37. constructor(initialProperties) {
  38. this._props = new Map();
  39. if (initialProperties) {
  40. for (const [prop, value] of Object.entries(initialProperties))
  41. this.set(prop, value);
  42. }
  43. }
  44. set(name, value) {
  45. if (name in PropertyStore.MandatedTypes && value &&
  46. !value.is_of_type(PropertyStore.MandatedTypes[name]))
  47. Util.Logger.warn(`Cannot set property ${name}: type mismatch!`);
  48. else if (value)
  49. this._props.set(name, value);
  50. else
  51. this._props.delete(name);
  52. }
  53. get(name) {
  54. const prop = this._props.get(name);
  55. if (prop)
  56. return prop;
  57. else if (name in PropertyStore.DefaultValues)
  58. return PropertyStore.DefaultValues[name];
  59. else
  60. return null;
  61. }
  62. }
  63. // we list all the properties we know and use here, so we won' have to deal with unexpected type mismatches
  64. PropertyStore.MandatedTypes = {
  65. 'visible': GLib.VariantType.new('b'),
  66. 'enabled': GLib.VariantType.new('b'),
  67. 'label': GLib.VariantType.new('s'),
  68. 'type': GLib.VariantType.new('s'),
  69. 'children-display': GLib.VariantType.new('s'),
  70. 'icon-name': GLib.VariantType.new('s'),
  71. 'icon-data': GLib.VariantType.new('ay'),
  72. 'toggle-type': GLib.VariantType.new('s'),
  73. 'toggle-state': GLib.VariantType.new('i'),
  74. };
  75. PropertyStore.DefaultValues = {
  76. 'visible': GLib.Variant.new_boolean(true),
  77. 'enabled': GLib.Variant.new_boolean(true),
  78. 'label': GLib.Variant.new_string(''),
  79. 'type': GLib.Variant.new_string('standard'),
  80. // elements not in here must return null
  81. };
  82. /**
  83. * Represents a single menu item
  84. */
  85. export class DbusMenuItem extends Signals.EventEmitter {
  86. // will steal the properties object
  87. constructor(client, id, properties, childrenIds) {
  88. super();
  89. this._client = client;
  90. this._id = id;
  91. this._propStore = new PropertyStore(properties);
  92. this._children_ids = childrenIds;
  93. }
  94. propertyGet(propName) {
  95. const prop = this.propertyGetVariant(propName);
  96. return prop ? prop.get_string()[0] : null;
  97. }
  98. propertyGetVariant(propName) {
  99. return this._propStore.get(propName);
  100. }
  101. propertyGetBool(propName) {
  102. const prop = this.propertyGetVariant(propName);
  103. return prop ? prop.get_boolean() : false;
  104. }
  105. propertyGetInt(propName) {
  106. const prop = this.propertyGetVariant(propName);
  107. return prop ? prop.get_int32() : 0;
  108. }
  109. propertySet(prop, value) {
  110. this._propStore.set(prop, value);
  111. this.emit('property-changed', prop, this.propertyGetVariant(prop));
  112. }
  113. getChildrenIds() {
  114. return this._children_ids.concat(); // clone it!
  115. }
  116. addChild(pos, childId) {
  117. this._children_ids.splice(pos, 0, childId);
  118. this.emit('child-added', this._client.getItem(childId), pos);
  119. }
  120. removeChild(childId) {
  121. // find it
  122. let pos = -1;
  123. for (let i = 0; i < this._children_ids.length; ++i) {
  124. if (this._children_ids[i] === childId) {
  125. pos = i;
  126. break;
  127. }
  128. }
  129. if (pos < 0) {
  130. Util.Logger.critical("Trying to remove child which doesn't exist");
  131. } else {
  132. this._children_ids.splice(pos, 1);
  133. this.emit('child-removed', this._client.getItem(childId));
  134. }
  135. }
  136. moveChild(childId, newPos) {
  137. // find the old position
  138. let oldPos = -1;
  139. for (let i = 0; i < this._children_ids.length; ++i) {
  140. if (this._children_ids[i] === childId) {
  141. oldPos = i;
  142. break;
  143. }
  144. }
  145. if (oldPos < 0) {
  146. Util.Logger.critical("tried to move child which wasn't in the list");
  147. return;
  148. }
  149. if (oldPos !== newPos) {
  150. this._children_ids.splice(oldPos, 1);
  151. this._children_ids.splice(newPos, 0, childId);
  152. this.emit('child-moved', oldPos, newPos, this._client.getItem(childId));
  153. }
  154. }
  155. getChildren() {
  156. return this._children_ids.map(el => this._client.getItem(el));
  157. }
  158. handleEvent(event, data, timestamp) {
  159. if (!data)
  160. data = GLib.Variant.new_int32(0);
  161. this._client.sendEvent(this._id, event, data, timestamp);
  162. }
  163. getId() {
  164. return this._id;
  165. }
  166. sendAboutToShow() {
  167. this._client.sendAboutToShow(this._id);
  168. }
  169. }
  170. /**
  171. * The client does the heavy lifting of actually reading layouts and distributing events
  172. */
  173. export const DBusClient = GObject.registerClass({
  174. Signals: {'ready-changed': {}},
  175. }, class AppIndicatorsDBusClient extends DBusProxy {
  176. static get interfaceInfo() {
  177. if (!this._interfaceInfo) {
  178. this._interfaceInfo = Gio.DBusInterfaceInfo.new_for_xml(
  179. DBusInterfaces.DBusMenu);
  180. }
  181. return this._interfaceInfo;
  182. }
  183. static get baseItems() {
  184. if (!this._baseItems) {
  185. this._baseItems = {
  186. 'children-display': GLib.Variant.new_string('submenu'),
  187. };
  188. }
  189. return this._baseItems;
  190. }
  191. static destroy() {
  192. delete this._interfaceInfo;
  193. }
  194. _init(busName, objectPath) {
  195. const {interfaceInfo} = AppIndicatorsDBusClient;
  196. super._init(busName, objectPath, interfaceInfo,
  197. Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES);
  198. this._items = new Map();
  199. this._items.set(0, new DbusMenuItem(this, 0, DBusClient.baseItems, []));
  200. this._flagItemsUpdateRequired = false;
  201. // will be set to true if a layout update is needed once active
  202. this._flagLayoutUpdateRequired = false;
  203. // property requests are queued
  204. this._propertiesRequestedFor = new Set(/* ids */);
  205. this._layoutUpdated = false;
  206. this._active = false;
  207. }
  208. async initAsync(cancellable) {
  209. await super.initAsync(cancellable);
  210. this._requestLayoutUpdate();
  211. }
  212. _onNameOwnerChanged() {
  213. if (this.isReady)
  214. this._requestLayoutUpdate();
  215. }
  216. get isReady() {
  217. return this._layoutUpdated && !!this.gNameOwner;
  218. }
  219. get cancellable() {
  220. return this._cancellable;
  221. }
  222. getRoot() {
  223. return this._items.get(0);
  224. }
  225. _requestLayoutUpdate() {
  226. const cancellable = new Util.CancellableChild(this._cancellable);
  227. this._beginLayoutUpdate(cancellable);
  228. }
  229. async _requestProperties(propertyId, cancellable) {
  230. this._propertiesRequestedFor.add(propertyId);
  231. if (this._propertiesRequest && this._propertiesRequest.pending())
  232. return;
  233. // if we don't have any requests queued, we'll need to add one
  234. this._propertiesRequest = new PromiseUtils.IdlePromise(
  235. GLib.PRIORITY_DEFAULT_IDLE, cancellable);
  236. await this._propertiesRequest;
  237. const requestedProperties = Array.from(this._propertiesRequestedFor);
  238. this._propertiesRequestedFor.clear();
  239. const [result] = await this.GetGroupPropertiesAsync(requestedProperties,
  240. [], cancellable);
  241. result.forEach(([id, properties]) => {
  242. const item = this._items.get(id);
  243. if (!item)
  244. return;
  245. for (const [prop, value] of Object.entries(properties))
  246. item.propertySet(prop, value);
  247. });
  248. }
  249. // Traverses the list of cached menu items and removes everyone that is not in the list
  250. // so we don't keep alive unused items
  251. _gcItems() {
  252. const tag = new Date().getTime();
  253. const toTraverse = [0];
  254. while (toTraverse.length > 0) {
  255. const item = this.getItem(toTraverse.shift());
  256. item._dbusClientGcTag = tag;
  257. Array.prototype.push.apply(toTraverse, item.getChildrenIds());
  258. }
  259. this._items.forEach((i, id) => {
  260. if (i._dbusClientGcTag !== tag)
  261. this._items.delete(id);
  262. });
  263. }
  264. // the original implementation will only request partial layouts if somehow possible
  265. // we try to save us from multiple kinds of race conditions by always requesting a full layout
  266. _beginLayoutUpdate(cancellable) {
  267. this._layoutUpdateUpdateAsync(cancellable).catch(e => {
  268. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  269. logError(e);
  270. });
  271. }
  272. // the original implementation will only request partial layouts if somehow possible
  273. // we try to save us from multiple kinds of race conditions by always requesting a full layout
  274. async _layoutUpdateUpdateAsync(cancellable) {
  275. // we only read the type property, because if the type changes after reading all properties,
  276. // the view would have to replace the item completely which we try to avoid
  277. if (this._layoutUpdateCancellable)
  278. this._layoutUpdateCancellable.cancel();
  279. this._layoutUpdateCancellable = cancellable;
  280. try {
  281. const [revision_, root] = await this.GetLayoutAsync(0, -1,
  282. ['type', 'children-display'], cancellable);
  283. this._updateLayoutState(true);
  284. this._doLayoutUpdate(root, cancellable);
  285. this._gcItems();
  286. this._flagLayoutUpdateRequired = false;
  287. this._flagItemsUpdateRequired = false;
  288. } catch (e) {
  289. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  290. this._updateLayoutState(false);
  291. throw e;
  292. } finally {
  293. if (this._layoutUpdateCancellable === cancellable)
  294. this._layoutUpdateCancellable = null;
  295. }
  296. }
  297. _updateLayoutState(state) {
  298. const wasReady = this.isReady;
  299. this._layoutUpdated = state;
  300. if (this.isReady !== wasReady)
  301. this.emit('ready-changed');
  302. }
  303. _doLayoutUpdate(item, cancellable) {
  304. const [id, properties, children] = item;
  305. const childrenUnpacked = children.map(c => c.deep_unpack());
  306. const childrenIds = childrenUnpacked.map(([c]) => c);
  307. // make sure all our children exist
  308. childrenUnpacked.forEach(c => this._doLayoutUpdate(c, cancellable));
  309. // make sure we exist
  310. const menuItem = this._items.get(id);
  311. if (menuItem) {
  312. // we do, update our properties if necessary
  313. for (const [prop, value] of Object.entries(properties))
  314. menuItem.propertySet(prop, value);
  315. // make sure our children are all at the right place, and exist
  316. const oldChildrenIds = menuItem.getChildrenIds();
  317. for (let i = 0; i < childrenIds.length; ++i) {
  318. // try to recycle an old child
  319. let oldChild = -1;
  320. for (let j = 0; j < oldChildrenIds.length; ++j) {
  321. if (oldChildrenIds[j] === childrenIds[i]) {
  322. [oldChild] = oldChildrenIds.splice(j, 1);
  323. break;
  324. }
  325. }
  326. if (oldChild < 0) {
  327. // no old child found, so create a new one!
  328. menuItem.addChild(i, childrenIds[i]);
  329. } else {
  330. // old child found, reuse it!
  331. menuItem.moveChild(childrenIds[i], i);
  332. }
  333. }
  334. // remove any old children that weren't reused
  335. oldChildrenIds.forEach(c => menuItem.removeChild(c));
  336. if (!this._flagItemsUpdateRequired)
  337. return id;
  338. }
  339. // we don't, so let's create us
  340. let newMenuItem = menuItem;
  341. if (!newMenuItem) {
  342. newMenuItem = new DbusMenuItem(this, id, properties, childrenIds);
  343. this._items.set(id, newMenuItem);
  344. }
  345. this._requestProperties(id, cancellable).catch(e => {
  346. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  347. Util.Logger.warn(`Could not get menu properties menu proxy: ${e}`);
  348. });
  349. return id;
  350. }
  351. async _doPropertiesUpdateAsync(cancellable) {
  352. if (this._propertiesUpdateCancellable)
  353. this._propertiesUpdateCancellable.cancel();
  354. this._propertiesUpdateCancellable = cancellable;
  355. try {
  356. const requests = [];
  357. this._items.forEach((_, id) =>
  358. requests.push(this._requestProperties(id, cancellable)));
  359. await Promise.all(requests);
  360. } finally {
  361. if (this._propertiesUpdateCancellable === cancellable)
  362. this._propertiesUpdateCancellable = null;
  363. }
  364. }
  365. _doPropertiesUpdate() {
  366. const cancellable = new Util.CancellableChild(this._cancellable);
  367. this._doPropertiesUpdateAsync(cancellable).catch(e => {
  368. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  369. Util.Logger.warn(`Could not get menu properties menu proxy: ${e}`);
  370. });
  371. }
  372. set active(active) {
  373. const wasActive = this._active;
  374. this._active = active;
  375. if (active && wasActive !== active) {
  376. if (this._flagLayoutUpdateRequired) {
  377. this._requestLayoutUpdate();
  378. } else if (this._flagItemsUpdateRequired) {
  379. this._doPropertiesUpdate();
  380. this._flagItemsUpdateRequired = false;
  381. }
  382. }
  383. }
  384. _onSignal(_sender, signal, params) {
  385. if (signal === 'LayoutUpdated') {
  386. if (!this._active) {
  387. this._flagLayoutUpdateRequired = true;
  388. return;
  389. }
  390. this._requestLayoutUpdate();
  391. } else if (signal === 'ItemsPropertiesUpdated') {
  392. if (!this._active) {
  393. this._flagItemsUpdateRequired = true;
  394. return;
  395. }
  396. this._onPropertiesUpdated(params.deep_unpack());
  397. }
  398. }
  399. getItem(id) {
  400. const item = this._items.get(id);
  401. if (!item)
  402. Util.Logger.warn(`trying to retrieve item for non-existing id ${id} !?`);
  403. return item || null;
  404. }
  405. // we don't need to cache and burst-send that since it will not happen that frequently
  406. async sendAboutToShow(id) {
  407. /* Some indicators (you, dropbox!) don't use the right signature
  408. * and don't return a boolean, so we need to support both cases */
  409. try {
  410. const ret = await this.gConnection.call(this.gName, this.gObjectPath,
  411. this.gInterfaceName, 'AboutToShow', new GLib.Variant('(i)', [id]),
  412. null, Gio.DBusCallFlags.NONE, -1, this._cancellable);
  413. if ((ret.is_of_type(new GLib.VariantType('(b)')) &&
  414. ret.get_child_value(0).get_boolean()) ||
  415. ret.is_of_type(new GLib.VariantType('()')))
  416. this._requestLayoutUpdate();
  417. } catch (e) {
  418. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  419. logError(e);
  420. }
  421. }
  422. sendEvent(id, event, params, timestamp) {
  423. if (!this.gNameOwner)
  424. return;
  425. this.EventAsync(id, event, params, timestamp, this._cancellable).catch(e => {
  426. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  427. logError(e);
  428. });
  429. }
  430. _onPropertiesUpdated([changed, removed]) {
  431. changed.forEach(([id, props]) => {
  432. const item = this._items.get(id);
  433. if (!item)
  434. return;
  435. for (const [prop, value] of Object.entries(props))
  436. item.propertySet(prop, value);
  437. });
  438. removed.forEach(([id, propNames]) => {
  439. const item = this._items.get(id);
  440. if (!item)
  441. return;
  442. propNames.forEach(propName => item.propertySet(propName, null));
  443. });
  444. }
  445. });
  446. // ////////////////////////////////////////////////////////////////////////
  447. // PART TWO: "View" frontend implementation.
  448. // ////////////////////////////////////////////////////////////////////////
  449. // https://bugzilla.gnome.org/show_bug.cgi?id=731514
  450. // GNOME 3.10 and 3.12 can't open a nested submenu.
  451. // Patches have been written, but it's not clear when (if?) they will be applied.
  452. // We also don't know whether they will be backported to 3.10, so we will work around
  453. // it in the meantime. Offending versions can be clearly identified:
  454. const NEED_NESTED_SUBMENU_FIX = '_setOpenedSubMenu' in PopupMenu.PopupMenu.prototype;
  455. /**
  456. * Creates new wrapper menu items and injects methods for managing them at runtime.
  457. *
  458. * Many functions in this object will be bound to the created item and executed as event
  459. * handlers, so any `this` will refer to a menu item create in createItem
  460. */
  461. const MenuItemFactory = {
  462. createItem(client, dbusItem) {
  463. // first, decide whether it's a submenu or not
  464. let shellItem;
  465. if (dbusItem.propertyGet('children-display') === 'submenu')
  466. shellItem = new PopupMenu.PopupSubMenuMenuItem('FIXME');
  467. else if (dbusItem.propertyGet('type') === 'separator')
  468. shellItem = new PopupMenu.PopupSeparatorMenuItem('');
  469. else
  470. shellItem = new PopupMenu.PopupMenuItem('FIXME');
  471. shellItem._dbusItem = dbusItem;
  472. shellItem._dbusClient = client;
  473. if (shellItem instanceof PopupMenu.PopupMenuItem) {
  474. shellItem._icon = new St.Icon({
  475. style_class: 'popup-menu-icon',
  476. xAlign: Clutter.ActorAlign.END,
  477. });
  478. shellItem.add_child(shellItem._icon);
  479. shellItem.label.x_expand = true;
  480. }
  481. // initialize our state
  482. MenuItemFactory._updateLabel.call(shellItem);
  483. MenuItemFactory._updateOrnament.call(shellItem);
  484. MenuItemFactory._updateImage.call(shellItem);
  485. MenuItemFactory._updateVisible.call(shellItem);
  486. MenuItemFactory._updateSensitive.call(shellItem);
  487. // initially create children
  488. if (shellItem instanceof PopupMenu.PopupSubMenuMenuItem) {
  489. dbusItem.getChildren().forEach(c =>
  490. shellItem.menu.addMenuItem(MenuItemFactory.createItem(client, c)));
  491. }
  492. // now, connect various events
  493. Util.connectSmart(dbusItem, 'property-changed',
  494. shellItem, MenuItemFactory._onPropertyChanged);
  495. Util.connectSmart(dbusItem, 'child-added',
  496. shellItem, MenuItemFactory._onChildAdded);
  497. Util.connectSmart(dbusItem, 'child-removed',
  498. shellItem, MenuItemFactory._onChildRemoved);
  499. Util.connectSmart(dbusItem, 'child-moved',
  500. shellItem, MenuItemFactory._onChildMoved);
  501. Util.connectSmart(shellItem, 'activate',
  502. shellItem, MenuItemFactory._onActivate);
  503. shellItem.connect('destroy', () => {
  504. shellItem._dbusItem = null;
  505. shellItem._dbusClient = null;
  506. shellItem._icon = null;
  507. });
  508. if (shellItem.menu) {
  509. Util.connectSmart(shellItem.menu, 'open-state-changed',
  510. shellItem, MenuItemFactory._onOpenStateChanged);
  511. }
  512. return shellItem;
  513. },
  514. _onOpenStateChanged(menu, open) {
  515. if (open) {
  516. if (NEED_NESTED_SUBMENU_FIX) {
  517. // close our own submenus
  518. if (menu._openedSubMenu)
  519. menu._openedSubMenu.close(false);
  520. // register ourselves and close sibling submenus
  521. if (menu._parent._openedSubMenu && menu._parent._openedSubMenu !== menu)
  522. menu._parent._openedSubMenu.close(true);
  523. menu._parent._openedSubMenu = menu;
  524. }
  525. this._dbusItem.handleEvent('opened', null, 0);
  526. this._dbusItem.sendAboutToShow();
  527. } else {
  528. if (NEED_NESTED_SUBMENU_FIX) {
  529. // close our own submenus
  530. if (menu._openedSubMenu)
  531. menu._openedSubMenu.close(false);
  532. }
  533. this._dbusItem.handleEvent('closed', null, 0);
  534. }
  535. },
  536. _onActivate(_item, event) {
  537. const timestamp = event.get_time();
  538. if (timestamp && this._dbusClient.indicator)
  539. this._dbusClient.indicator.provideActivationToken(timestamp);
  540. this._dbusItem.handleEvent('clicked', GLib.Variant.new('i', 0),
  541. timestamp);
  542. },
  543. _onPropertyChanged(dbusItem, prop, _value) {
  544. if (prop === 'toggle-type' || prop === 'toggle-state')
  545. MenuItemFactory._updateOrnament.call(this);
  546. else if (prop === 'label')
  547. MenuItemFactory._updateLabel.call(this);
  548. else if (prop === 'enabled')
  549. MenuItemFactory._updateSensitive.call(this);
  550. else if (prop === 'visible')
  551. MenuItemFactory._updateVisible.call(this);
  552. else if (prop === 'icon-name' || prop === 'icon-data')
  553. MenuItemFactory._updateImage.call(this);
  554. else if (prop === 'type' || prop === 'children-display')
  555. MenuItemFactory._replaceSelf.call(this);
  556. else
  557. Util.Logger.debug(`Unhandled property change: ${prop}`);
  558. },
  559. _onChildAdded(dbusItem, child, position) {
  560. if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) {
  561. Util.Logger.warn('Tried to add a child to non-submenu item. Better recreate it as whole');
  562. MenuItemFactory._replaceSelf.call(this);
  563. } else {
  564. this.menu.addMenuItem(MenuItemFactory.createItem(this._dbusClient, child), position);
  565. }
  566. },
  567. _onChildRemoved(dbusItem, child) {
  568. if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) {
  569. Util.Logger.warn('Tried to remove a child from non-submenu item. Better recreate it as whole');
  570. MenuItemFactory._replaceSelf.call(this);
  571. } else {
  572. // find it!
  573. this.menu._getMenuItems().forEach(item => {
  574. if (item._dbusItem === child)
  575. item.destroy();
  576. });
  577. }
  578. },
  579. _onChildMoved(dbusItem, child, oldpos, newpos) {
  580. if (!(this instanceof PopupMenu.PopupSubMenuMenuItem)) {
  581. Util.Logger.warn('Tried to move a child in non-submenu item. Better recreate it as whole');
  582. MenuItemFactory._replaceSelf.call(this);
  583. } else {
  584. MenuUtils.moveItemInMenu(this.menu, child, newpos);
  585. }
  586. },
  587. _updateLabel() {
  588. const label = this._dbusItem.propertyGet('label').replace(/_([^_])/, '$1');
  589. if (this.label) // especially on GS3.8, the separator item might not even have a hidden label
  590. this.label.set_text(label);
  591. },
  592. _updateOrnament() {
  593. if (!this.setOrnament)
  594. return; // separators and alike might not have gotten the polyfill
  595. if (this._dbusItem.propertyGet('toggle-type') === 'checkmark' &&
  596. this._dbusItem.propertyGetInt('toggle-state'))
  597. this.setOrnament(PopupMenu.Ornament.CHECK);
  598. else if (this._dbusItem.propertyGet('toggle-type') === 'radio' &&
  599. this._dbusItem.propertyGetInt('toggle-state'))
  600. this.setOrnament(PopupMenu.Ornament.DOT);
  601. else
  602. this.setOrnament(PopupMenu.Ornament.NONE);
  603. },
  604. async _updateImage() {
  605. if (!this._icon)
  606. return; // might be missing on submenus / separators
  607. const iconName = this._dbusItem.propertyGet('icon-name');
  608. const iconData = this._dbusItem.propertyGetVariant('icon-data');
  609. if (iconName) {
  610. this._icon.icon_name = iconName;
  611. } else if (iconData) {
  612. try {
  613. const inputStream = Gio.MemoryInputStream.new_from_bytes(
  614. iconData.get_data_as_bytes());
  615. this._icon.gicon = await GdkPixbuf.Pixbuf.new_from_stream_async(
  616. inputStream, this._dbusClient.cancellable);
  617. } catch (e) {
  618. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  619. logError(e);
  620. }
  621. }
  622. },
  623. _updateVisible() {
  624. this.visible = this._dbusItem.propertyGetBool('visible');
  625. },
  626. _updateSensitive() {
  627. this.setSensitive(this._dbusItem.propertyGetBool('enabled'));
  628. },
  629. _replaceSelf(newSelf) {
  630. // create our new self if needed
  631. if (!newSelf)
  632. newSelf = MenuItemFactory.createItem(this._dbusClient, this._dbusItem);
  633. // first, we need to find our old position
  634. let pos = -1;
  635. const family = this._parent._getMenuItems();
  636. for (let i = 0; i < family.length; ++i) {
  637. if (family[i] === this)
  638. pos = i;
  639. }
  640. if (pos < 0)
  641. throw new Error("DBusMenu: can't replace non existing menu item");
  642. // add our new self while we're still alive
  643. this._parent.addMenuItem(newSelf, pos);
  644. // now destroy our old self
  645. this.destroy();
  646. },
  647. };
  648. /**
  649. * Utility functions not necessarily belonging into the item factory
  650. */
  651. const MenuUtils = {
  652. moveItemInMenu(menu, dbusItem, newpos) {
  653. // HACK: we're really getting into the internals of the PopupMenu implementation
  654. // First, find our wrapper. Children tend to lie. We do not trust the old positioning.
  655. const family = menu._getMenuItems();
  656. for (let i = 0; i < family.length; ++i) {
  657. if (family[i]._dbusItem === dbusItem) {
  658. // now, remove it
  659. menu.box.remove_child(family[i]);
  660. // and add it again somewhere else
  661. if (newpos < family.length && family[newpos] !== family[i])
  662. menu.box.insert_child_below(family[i], family[newpos]);
  663. else
  664. menu.box.add(family[i]);
  665. // skip the rest
  666. return;
  667. }
  668. }
  669. },
  670. };
  671. /**
  672. * Processes DBus events, creates the menu items and handles the actions
  673. *
  674. * Something like a mini-god-object
  675. */
  676. export class Client extends Signals.EventEmitter {
  677. constructor(busName, path, indicator) {
  678. super();
  679. this._busName = busName;
  680. this._busPath = path;
  681. this._client = new DBusClient(busName, path);
  682. this._rootMenu = null; // the shell menu
  683. this._rootItem = null; // the DbusMenuItem for the root
  684. this.indicator = indicator;
  685. this.cancellable = new Util.CancellableChild(this.indicator.cancellable);
  686. this._client.initAsync(this.cancellable).catch(e => {
  687. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  688. logError(e);
  689. });
  690. Util.connectSmart(this._client, 'ready-changed', this,
  691. () => this.emit('ready-changed'));
  692. }
  693. get isReady() {
  694. return this._client.isReady;
  695. }
  696. // this will attach the client to an already existing menu that will be used as the root menu.
  697. // it will also connect the client to be automatically destroyed when the menu dies.
  698. attachToMenu(menu) {
  699. this._rootMenu = menu;
  700. this._rootItem = this._client.getRoot();
  701. this._itemsBeingAdded = new Set();
  702. // cleanup: remove existing children (just in case)
  703. this._rootMenu.removeAll();
  704. if (NEED_NESTED_SUBMENU_FIX)
  705. menu._setOpenedSubMenu = this._setOpenedSubmenu.bind(this);
  706. // connect handlers
  707. Util.connectSmart(menu, 'open-state-changed', this, this._onMenuOpened);
  708. Util.connectSmart(menu, 'destroy', this, this.destroy);
  709. Util.connectSmart(this._rootItem, 'child-added', this, this._onRootChildAdded);
  710. Util.connectSmart(this._rootItem, 'child-removed', this, this._onRootChildRemoved);
  711. Util.connectSmart(this._rootItem, 'child-moved', this, this._onRootChildMoved);
  712. // Dropbox requires us to call AboutToShow(0) first
  713. this._rootItem.sendAboutToShow();
  714. // fill the menu for the first time
  715. const children = this._rootItem.getChildren();
  716. children.forEach(child =>
  717. this._onRootChildAdded(this._rootItem, child));
  718. }
  719. _setOpenedSubmenu(submenu) {
  720. if (!submenu)
  721. return;
  722. if (submenu._parent !== this._rootMenu)
  723. return;
  724. if (submenu === this._openedSubMenu)
  725. return;
  726. if (this._openedSubMenu && this._openedSubMenu.isOpen)
  727. this._openedSubMenu.close(true);
  728. this._openedSubMenu = submenu;
  729. }
  730. _onRootChildAdded(dbusItem, child, position) {
  731. // Menu additions can be expensive, so let's do it in different chunks
  732. const basePriority = this.isOpen ? GLib.PRIORITY_DEFAULT : GLib.PRIORITY_LOW;
  733. const idlePromise = new PromiseUtils.IdlePromise(
  734. basePriority + this._itemsBeingAdded.size, this.cancellable);
  735. this._itemsBeingAdded.add(child);
  736. idlePromise.then(() => {
  737. if (!this._itemsBeingAdded.has(child))
  738. return;
  739. this._rootMenu.addMenuItem(
  740. MenuItemFactory.createItem(this, child), position);
  741. }).catch(e => {
  742. if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
  743. logError(e);
  744. }).finally(() => this._itemsBeingAdded.delete(child));
  745. }
  746. _onRootChildRemoved(dbusItem, child) {
  747. // children like to play hide and seek
  748. // but we know how to find it for sure!
  749. const item = this._rootMenu._getMenuItems().find(it =>
  750. it._dbusItem === child);
  751. if (item)
  752. item.destroy();
  753. else
  754. this._itemsBeingAdded.delete(child);
  755. }
  756. _onRootChildMoved(dbusItem, child, oldpos, newpos) {
  757. MenuUtils.moveItemInMenu(this._rootMenu, dbusItem, newpos);
  758. }
  759. _onMenuOpened(menu, state) {
  760. if (!this._rootItem)
  761. return;
  762. this._client.active = state;
  763. if (state) {
  764. if (this._openedSubMenu && this._openedSubMenu.isOpen)
  765. this._openedSubMenu.close();
  766. this._rootItem.handleEvent('opened', null, 0);
  767. this._rootItem.sendAboutToShow();
  768. } else {
  769. this._rootItem.handleEvent('closed', null, 0);
  770. }
  771. }
  772. destroy() {
  773. this.emit('destroy');
  774. if (this._client)
  775. this._client.destroy();
  776. this._client = null;
  777. this._rootItem = null;
  778. this._rootMenu = null;
  779. this.indicator = null;
  780. this._itemsBeingAdded = null;
  781. }
  782. }