Bug 18732 - Add the linux system tray icon crate and its ksni dependency, r=aleca,babolivier,heather
authorHeather Ellsworth <heather@thunderbird.net>
Mon, 22 Jul 2024 09:30:58 +0000 (11 months ago)
changeset 42094 9f64153706e876165e108388fa23c278f238f4bd
parent 42093 1d67b7139d5fb0eab7f9bda392f120f3a957eedb
child 42095 d8300a0ffdb65cff369dd86120f3977e52352aa2
push id22349
push userikey@thunderbird.net
push dateMon, 22 Jul 2024 09:33:14 +0000 (11 months ago)
treeherdercomm-central@9f64153706e8 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersaleca, babolivier, heather
bugs18732
Bug 18732 - Add the linux system tray icon crate and its ksni dependency, r=aleca,babolivier,heather This initial version of the system tray crate is geared specifically for use on Linux via the Status Notifier Item specification. However in the interests of collapsing similar codepaths we've left just enough space to allow expanding this into a more general purpose entry point for all supported platforms. Note that it was very difficult to support x86 (32-bit) builds due to needing build environment changes with regards to libpthread, so at this point the feature is explicitly requiring a 64-bit build of Thunderbird. This can be alleviated in time with future iterations to ksni and experimenting with `zdbus` to drop the `libdbus-sys` dependency, opening up the door to many other D-BUS services in Thunderbird. Note that this is a collaborative effort between Heather Elssworth and myself, with Heather having completed the original groundwork and research. I focused more on the integration aspects and threading model. This feature wasn't possible without Heather's work. Differential Revision: https://phabricator.services.mozilla.com/D215249
mail/locales/en-US/messenger/menubar.ftl
mailnews/base/src/MailNotificationManager.sys.mjs
mailnews/base/src/components.conf
mailnews/base/src/moz.build
mailnews/base/src/nsMessengerUnixIntegration.cpp
mailnews/base/src/nsMessengerUnixIntegration.h
rust/Cargo.lock
rust/Cargo.toml
rust/gkrust/Cargo.toml
rust/gkrust/src/lib.rs
rust/gtest/Cargo.toml
rust/gtest/lib.rs
rust/sys_tray/Cargo.toml
rust/sys_tray/src/actions.rs
rust/sys_tray/src/lib.rs
rust/sys_tray/src/linux/mod.rs
rust/sys_tray/src/linux/system_tray.rs
rust/sys_tray/src/locales.rs
third_party/rust/ansi_term/.cargo-checksum.json
third_party/rust/ansi_term/Cargo.lock
third_party/rust/ansi_term/Cargo.toml
third_party/rust/ansi_term/LICENCE
third_party/rust/ansi_term/README.md
third_party/rust/ansi_term/examples/256_colours.rs
third_party/rust/ansi_term/examples/basic_colours.rs
third_party/rust/ansi_term/examples/rgb_colours.rs
third_party/rust/ansi_term/src/ansi.rs
third_party/rust/ansi_term/src/debug.rs
third_party/rust/ansi_term/src/difference.rs
third_party/rust/ansi_term/src/display.rs
third_party/rust/ansi_term/src/lib.rs
third_party/rust/ansi_term/src/style.rs
third_party/rust/ansi_term/src/util.rs
third_party/rust/ansi_term/src/windows.rs
third_party/rust/ansi_term/src/write.rs
third_party/rust/atty/.cargo-checksum.json
third_party/rust/atty/CHANGELOG.md
third_party/rust/atty/Cargo.lock
third_party/rust/atty/Cargo.toml
third_party/rust/atty/LICENSE
third_party/rust/atty/README.md
third_party/rust/atty/examples/atty.rs
third_party/rust/atty/rustfmt.toml
third_party/rust/atty/src/lib.rs
third_party/rust/clap-2.34.0/.cargo-checksum.json
third_party/rust/clap-2.34.0/CHANGELOG.md
third_party/rust/clap-2.34.0/CONTRIBUTORS.md
third_party/rust/clap-2.34.0/Cargo.toml
third_party/rust/clap-2.34.0/LICENSE-MIT
third_party/rust/clap-2.34.0/README.md
third_party/rust/clap-2.34.0/SPONSORS.md
third_party/rust/clap-2.34.0/clap-test.rs
third_party/rust/clap-2.34.0/justfile
third_party/rust/clap-2.34.0/src/app/help.rs
third_party/rust/clap-2.34.0/src/app/meta.rs
third_party/rust/clap-2.34.0/src/app/mod.rs
third_party/rust/clap-2.34.0/src/app/parser.rs
third_party/rust/clap-2.34.0/src/app/settings.rs
third_party/rust/clap-2.34.0/src/app/usage.rs
third_party/rust/clap-2.34.0/src/app/validator.rs
third_party/rust/clap-2.34.0/src/args/any_arg.rs
third_party/rust/clap-2.34.0/src/args/arg.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/base.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/flag.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/mod.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/option.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/positional.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/switched.rs
third_party/rust/clap-2.34.0/src/args/arg_builder/valued.rs
third_party/rust/clap-2.34.0/src/args/arg_matcher.rs
third_party/rust/clap-2.34.0/src/args/arg_matches.rs
third_party/rust/clap-2.34.0/src/args/group.rs
third_party/rust/clap-2.34.0/src/args/macros.rs
third_party/rust/clap-2.34.0/src/args/matched_arg.rs
third_party/rust/clap-2.34.0/src/args/mod.rs
third_party/rust/clap-2.34.0/src/args/settings.rs
third_party/rust/clap-2.34.0/src/args/subcommand.rs
third_party/rust/clap-2.34.0/src/completions/bash.rs
third_party/rust/clap-2.34.0/src/completions/elvish.rs
third_party/rust/clap-2.34.0/src/completions/fish.rs
third_party/rust/clap-2.34.0/src/completions/macros.rs
third_party/rust/clap-2.34.0/src/completions/mod.rs
third_party/rust/clap-2.34.0/src/completions/powershell.rs
third_party/rust/clap-2.34.0/src/completions/shell.rs
third_party/rust/clap-2.34.0/src/completions/zsh.rs
third_party/rust/clap-2.34.0/src/errors.rs
third_party/rust/clap-2.34.0/src/fmt.rs
third_party/rust/clap-2.34.0/src/lib.rs
third_party/rust/clap-2.34.0/src/macros.rs
third_party/rust/clap-2.34.0/src/map.rs
third_party/rust/clap-2.34.0/src/osstringext.rs
third_party/rust/clap-2.34.0/src/strext.rs
third_party/rust/clap-2.34.0/src/suggestions.rs
third_party/rust/clap-2.34.0/src/usage_parser.rs
third_party/rust/dbus-0.6.5/.cargo-checksum.json
third_party/rust/dbus-0.6.5/Cargo.toml
third_party/rust/dbus-0.6.5/LICENSE-APACHE
third_party/rust/dbus-0.6.5/LICENSE-MIT
third_party/rust/dbus-0.6.5/examples/adv_server.rs
third_party/rust/dbus-0.6.5/examples/argument_guide.md
third_party/rust/dbus-0.6.5/examples/client.rs
third_party/rust/dbus-0.6.5/examples/properties.rs
third_party/rust/dbus-0.6.5/examples/properties_msgitem.rs
third_party/rust/dbus-0.6.5/examples/rtkit.rs
third_party/rust/dbus-0.6.5/examples/server.rs
third_party/rust/dbus-0.6.5/examples/unity_focused_window.rs
third_party/rust/dbus-0.6.5/src/arg/array_impl.rs
third_party/rust/dbus-0.6.5/src/arg/basic_impl.rs
third_party/rust/dbus-0.6.5/src/arg/mod.rs
third_party/rust/dbus-0.6.5/src/arg/msgarg.rs
third_party/rust/dbus-0.6.5/src/arg/variantstruct_impl.rs
third_party/rust/dbus-0.6.5/src/connection.rs
third_party/rust/dbus-0.6.5/src/connection2.rs
third_party/rust/dbus-0.6.5/src/crossroads/crossroads.rs
third_party/rust/dbus-0.6.5/src/crossroads/handlers.rs
third_party/rust/dbus-0.6.5/src/crossroads/info.rs
third_party/rust/dbus-0.6.5/src/crossroads/mod.rs
third_party/rust/dbus-0.6.5/src/crossroads/stdimpl.rs
third_party/rust/dbus-0.6.5/src/dispatcher.rs
third_party/rust/dbus-0.6.5/src/lib.rs
third_party/rust/dbus-0.6.5/src/matchrule.rs
third_party/rust/dbus-0.6.5/src/message.rs
third_party/rust/dbus-0.6.5/src/methoddisp.rs
third_party/rust/dbus-0.6.5/src/objpath.rs
third_party/rust/dbus-0.6.5/src/prop.rs
third_party/rust/dbus-0.6.5/src/signalargs.rs
third_party/rust/dbus-0.6.5/src/stdintf.rs
third_party/rust/dbus-0.6.5/src/strings.rs
third_party/rust/dbus-0.6.5/src/tree/factory.rs
third_party/rust/dbus-0.6.5/src/tree/leaves.rs
third_party/rust/dbus-0.6.5/src/tree/methodtype.rs
third_party/rust/dbus-0.6.5/src/tree/mod.rs
third_party/rust/dbus-0.6.5/src/tree/objectpath.rs
third_party/rust/dbus-0.6.5/src/tree/utils.rs
third_party/rust/dbus-0.6.5/src/watch.rs
third_party/rust/dbus-codegen/.cargo-checksum.json
third_party/rust/dbus-codegen/Cargo.lock
third_party/rust/dbus-codegen/Cargo.toml
third_party/rust/dbus-codegen/LICENSE-APACHE
third_party/rust/dbus-codegen/LICENSE-MIT
third_party/rust/dbus-codegen/README.md
third_party/rust/dbus-codegen/data/org.freedesktop.DBus.xml
third_party/rust/dbus-codegen/data/standard_interfaces.xml
third_party/rust/dbus-codegen/examples/adv_server_codegen.rs
third_party/rust/dbus-codegen/src/generate.rs
third_party/rust/dbus-codegen/src/lib.rs
third_party/rust/dbus-codegen/src/main.rs
third_party/rust/dbus-tree/.cargo-checksum.json
third_party/rust/dbus-tree/Cargo.lock
third_party/rust/dbus-tree/Cargo.toml
third_party/rust/dbus-tree/LICENSE-APACHE
third_party/rust/dbus-tree/LICENSE-MIT
third_party/rust/dbus-tree/examples/adv_server.rs
third_party/rust/dbus-tree/examples/server.rs
third_party/rust/dbus-tree/src/factory.rs
third_party/rust/dbus-tree/src/leaves.rs
third_party/rust/dbus-tree/src/lib.rs
third_party/rust/dbus-tree/src/methodtype.rs
third_party/rust/dbus-tree/src/objectpath.rs
third_party/rust/dbus-tree/src/utils.rs
third_party/rust/dbus/.cargo-checksum.json
third_party/rust/dbus/Cargo.lock
third_party/rust/dbus/Cargo.toml
third_party/rust/dbus/README.md
third_party/rust/dbus/changes-in-0.7.md
third_party/rust/dbus/examples/adv_server.rs
third_party/rust/dbus/examples/argument_guide.md
third_party/rust/dbus/examples/client.rs
third_party/rust/dbus/examples/match_signal.rs
third_party/rust/dbus/examples/monitor.rs
third_party/rust/dbus/examples/properties.rs
third_party/rust/dbus/examples/properties_msgitem.rs
third_party/rust/dbus/examples/rtkit.rs
third_party/rust/dbus/examples/server.rs
third_party/rust/dbus/examples/unity_focused_window.rs
third_party/rust/dbus/src/arg/array_impl.rs
third_party/rust/dbus/src/arg/basic_impl.rs
third_party/rust/dbus/src/arg/messageitem.rs
third_party/rust/dbus/src/arg/mod.rs
third_party/rust/dbus/src/arg/msgarg.rs
third_party/rust/dbus/src/arg/variantstruct_impl.rs
third_party/rust/dbus/src/blocking.rs
third_party/rust/dbus/src/blocking/generated_org_freedesktop_dbus.rs
third_party/rust/dbus/src/blocking/generated_org_freedesktop_standard_interfaces.rs
third_party/rust/dbus/src/channel.rs
third_party/rust/dbus/src/channel/ffichannel.rs
third_party/rust/dbus/src/channel/nativechannel.rs
third_party/rust/dbus/src/connection.rs
third_party/rust/dbus/src/connection2.rs
third_party/rust/dbus/src/crossroads/crossroads.rs
third_party/rust/dbus/src/crossroads/handlers.rs
third_party/rust/dbus/src/crossroads/info.rs
third_party/rust/dbus/src/crossroads/mod.rs
third_party/rust/dbus/src/crossroads/stdimpl.rs
third_party/rust/dbus/src/dispatcher.rs
third_party/rust/dbus/src/error.rs
third_party/rust/dbus/src/ffidisp.rs
third_party/rust/dbus/src/ffidisp/connection.rs
third_party/rust/dbus/src/ffidisp/stdintf.rs
third_party/rust/dbus/src/ffidisp/watch.rs
third_party/rust/dbus/src/filters.rs
third_party/rust/dbus/src/lib.rs
third_party/rust/dbus/src/matchrule.rs
third_party/rust/dbus/src/message.rs
third_party/rust/dbus/src/message/matchrule.rs
third_party/rust/dbus/src/message/parser.rs
third_party/rust/dbus/src/message/signalargs.rs
third_party/rust/dbus/src/methoddisp.rs
third_party/rust/dbus/src/nonblock.rs
third_party/rust/dbus/src/nonblock/generated_org_freedesktop_dbus.rs
third_party/rust/dbus/src/nonblock/generated_org_freedesktop_standard_interfaces.rs
third_party/rust/dbus/src/objpath.rs
third_party/rust/dbus/src/prop.rs
third_party/rust/dbus/src/signalargs.rs
third_party/rust/dbus/src/stdintf.rs
third_party/rust/dbus/src/strings.rs
third_party/rust/dbus/src/tree/factory.rs
third_party/rust/dbus/src/tree/leaves.rs
third_party/rust/dbus/src/tree/methodtype.rs
third_party/rust/dbus/src/tree/mod.rs
third_party/rust/dbus/src/tree/objectpath.rs
third_party/rust/dbus/src/tree/utils.rs
third_party/rust/dbus/src/watch.rs
third_party/rust/hermit-abi-0.1.19/.cargo-checksum.json
third_party/rust/hermit-abi-0.1.19/Cargo.toml
third_party/rust/hermit-abi-0.1.19/LICENSE-APACHE
third_party/rust/hermit-abi-0.1.19/LICENSE-MIT
third_party/rust/hermit-abi-0.1.19/README.md
third_party/rust/hermit-abi-0.1.19/rust-toolchain
third_party/rust/hermit-abi-0.1.19/src/lib.rs
third_party/rust/hermit-abi-0.1.19/src/tcplistener.rs
third_party/rust/hermit-abi-0.1.19/src/tcpstream.rs
third_party/rust/ksni/.cargo-checksum.json
third_party/rust/ksni/CHANGELOG.md
third_party/rust/ksni/Cargo.lock
third_party/rust/ksni/Cargo.toml
third_party/rust/ksni/README.md
third_party/rust/ksni/UNLICENSE
third_party/rust/ksni/build.rs
third_party/rust/ksni/dbus_interfaces/DBusMenu.xml
third_party/rust/ksni/dbus_interfaces/StatusNotifierItem.xml
third_party/rust/ksni/dbus_interfaces/StatusNotifierWatcher.xml
third_party/rust/ksni/examples/example.rs
third_party/rust/ksni/examples/screenshot_of_example_in_gnome.png
third_party/rust/ksni/src/dbus_ext.rs
third_party/rust/ksni/src/dbus_interface.rs
third_party/rust/ksni/src/error.rs
third_party/rust/ksni/src/freedesktop.rs
third_party/rust/ksni/src/lib.rs
third_party/rust/ksni/src/menu.rs
third_party/rust/ksni/src/service.rs
third_party/rust/ksni/src/tray.rs
third_party/rust/strsim-0.8.0/.cargo-checksum.json
third_party/rust/strsim-0.8.0/CHANGELOG.md
third_party/rust/strsim-0.8.0/Cargo.toml
third_party/rust/strsim-0.8.0/LICENSE
third_party/rust/strsim-0.8.0/README.md
third_party/rust/strsim-0.8.0/appveyor.yml
third_party/rust/strsim-0.8.0/benches/benches.rs
third_party/rust/strsim-0.8.0/dev
third_party/rust/strsim-0.8.0/src/lib.rs
third_party/rust/strsim-0.8.0/tests/lib.rs
third_party/rust/textwrap-0.11.0/.cargo-checksum.json
third_party/rust/textwrap-0.11.0/Cargo.toml
third_party/rust/textwrap-0.11.0/LICENSE
third_party/rust/textwrap-0.11.0/README.md
third_party/rust/textwrap-0.11.0/benches/linear.rs
third_party/rust/textwrap-0.11.0/examples/layout.rs
third_party/rust/textwrap-0.11.0/examples/termwidth.rs
third_party/rust/textwrap-0.11.0/src/indentation.rs
third_party/rust/textwrap-0.11.0/src/lib.rs
third_party/rust/textwrap-0.11.0/src/splitting.rs
third_party/rust/textwrap-0.11.0/tests/version-numbers.rs
third_party/rust/vec_map/.cargo-checksum.json
third_party/rust/vec_map/Cargo.toml
third_party/rust/vec_map/LICENSE-APACHE
third_party/rust/vec_map/LICENSE-MIT
third_party/rust/vec_map/README.md
third_party/rust/vec_map/src/lib.rs
--- a/mail/locales/en-US/messenger/menubar.ftl
+++ b/mail/locales/en-US/messenger/menubar.ftl
@@ -74,16 +74,23 @@ menu-quit =
             [windows] x
            *[other] Q
         }
 
 # This menu-quit-mac string is only used on macOS.
 menu-quit-mac =
     .label = Quit { -brand-shorter-name }
 
+system-tray-menu-quit =
+    .label =
+        { PLATFORM() ->
+            [windows] Exit { -brand-full-name }
+           *[other] Quit { -brand-full-name }
+        }
+
 # Localization note: Do not translate unless your locale's keyboard layout
 # does not include this key, as it determines the keyboard shortcut for
 # shutting down the application.
 quit-app-shortcut =
     .key = Q
 
 ## Mail Toolbar
 
--- a/mailnews/base/src/MailNotificationManager.sys.mjs
+++ b/mailnews/base/src/MailNotificationManager.sys.mjs
@@ -46,26 +46,24 @@ export class MailNotificationManager {
     );
     MailServices.mailSession.AddFolderListener(
       this,
       Ci.nsIFolderListener.intPropertyChanged
     );
 
     // Ensure that OS integration is defined before we attempt to initialize the
     // system tray icon.
-    ChromeUtils.defineLazyGetter(this, "_osIntegration", () => {
-      try {
-        return Cc["@mozilla.org/messenger/osintegration;1"].getService(
-          Ci.nsIMessengerOSIntegration
-        );
-      } catch (e) {
-        // We don't have OS integration on all platforms.
-        return null;
-      }
-    });
+    try {
+      this._osIntegration = Cc[
+        "@mozilla.org/messenger/osintegration;1"
+      ].getService(Ci.nsIMessengerOSIntegration);
+    } catch (e) {
+      // We don't have OS integration on all platforms, i.e. 32-bit Linux.
+      this._osIntegration = null;
+    }
 
     if (["macosx", "win"].includes(AppConstants.platform)) {
       // We don't have indicator for unread count on Linux yet.
       Cc["@mozilla.org/newMailNotificationService;1"]
         .getService(Ci.mozINewMailNotificationService)
         .addListener(this, Ci.mozINewMailNotificationService.count);
 
       Services.obs.addObserver(this, "unread-im-count-changed");
--- a/mailnews/base/src/components.conf
+++ b/mailnews/base/src/components.conf
@@ -330,18 +330,27 @@ if buildconfig.substs["OS_ARCH"] == "Dar
     Classes += [
         {
             "cid": "{746b28a5-d239-4719-b1a2-cf8093332ae3}",
             "contract_ids": ["@mozilla.org/messenger/osintegration;1"],
             "type": "nsMessengerOSXIntegration",
             "headers": ["/comm/mailnews/base/src/nsMessengerOSXIntegration.h"],
         },
     ]
-
-if buildconfig.substs["OS_ARCH"] == "WINNT":
+elif buildconfig.substs["OS_ARCH"] == "WINNT":
     Classes += [
         {
             "cid": "{a74dd1d6-2ec4-4985-98f3-f69e18d20811}",
             "contract_ids": ["@mozilla.org/messenger/osintegration;1"],
             "type": "nsMessengerWinIntegration",
             "headers": ["/comm/mailnews/base/src/nsMessengerWinIntegration.h"],
         },
     ]
+elif buildconfig.substs["OS_ARCH"] == "Linux" and buildconfig.substs["TARGET_CPU"] == "x86_64":
+    Classes += [
+        {
+            "cid": "{d9e45fee-1dd1-11b2-938c-9147855ed837}",
+            "contract_ids": ["@mozilla.org/messenger/osintegration;1"],
+            "headers": ["/comm/mailnews/base/src/nsMessengerUnixIntegration.h"],
+            'legacy_constructor': 'nsLinuxSysTrayHandlerConstructor',
+        },
+    ]
+
--- a/mailnews/base/src/moz.build
+++ b/mailnews/base/src/moz.build
@@ -96,17 +96,16 @@ SOURCES += [
 if CONFIG["OS_ARCH"] == "WINNT":
     SOURCES += [
         "nsMessengerWinIntegration.cpp",
         # This file cannot be built in unified mode because of name clashes with Windows headers.
         "nsUserInfoWin.cpp",
     ]
 elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
     SOURCES += [
-        "nsMessengerUnixIntegration.cpp",
         "nsUserInfoUnix.cpp",
     ]
 elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "cocoa":
     SOURCES += [
         "nsMessengerOSXIntegration.mm",
         "nsUserInfoMac.mm",
     ]
 
deleted file mode 100644
--- a/mailnews/base/src/nsMessengerUnixIntegration.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsMessengerUnixIntegration.h"
-#include "nsString.h"
-
-/**
- * This is only a placeholder for now, register it in components.conf later if
- * needed.
- */
-nsMessengerUnixIntegration::nsMessengerUnixIntegration() {}
-
-NS_IMPL_ISUPPORTS(nsMessengerUnixIntegration, nsIMessengerOSIntegration)
-
-NS_IMETHODIMP
-nsMessengerUnixIntegration::UpdateUnreadCount(uint32_t unreadCount,
-                                              const nsAString& unreadTooltip) {
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsMessengerUnixIntegration::OnExit() { return NS_OK; }
--- a/mailnews/base/src/nsMessengerUnixIntegration.h
+++ b/mailnews/base/src/nsMessengerUnixIntegration.h
@@ -2,21 +2,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef __nsMessengerUnixIntegration_h
 #define __nsMessengerUnixIntegration_h
 
 #include "nsIMessengerOSIntegration.h"
-
-class nsMessengerUnixIntegration : public nsIMessengerOSIntegration {
- public:
-  nsMessengerUnixIntegration();
+#include "nsID.h"
 
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIMESSENGEROSINTEGRATION
-
- private:
-  virtual ~nsMessengerUnixIntegration() {}
-};
+extern "C" {
+// Implemented in Rust.
+MOZ_EXPORT nsresult nsLinuxSysTrayHandlerConstructor(REFNSIID aIID,
+                                                     void** aResult);
+}  // extern "C"
 
 #endif  // __nsMessengerUnixIntegration_h
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -82,16 +82,25 @@ name = "android_system_properties"
 version = "0.1.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
 dependencies = [
  "libc",
 ]
 
 [[package]]
+name = "ansi_term"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
 name = "anyhow"
 version = "1.0.69"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800"
 
 [[package]]
 name = "app_services_logger"
 version = "0.1.0"
@@ -215,32 +224,43 @@ checksum = "64f46ca51dca4837f1520754d1c8
 
 [[package]]
 name = "atomic_refcell"
 version = "0.1.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "857253367827bd9d0fd973f0ef15506a96e79e41b0ad7aa691203a4e3214f6c8"
 
 [[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi 0.1.19",
+ "libc",
+ "winapi",
+]
+
+[[package]]
 name = "audio-mixer"
 version = "0.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "4f1245ab2f85c284bac1ac1f03565539644566295ef6eb9c4eae42e9a40c51b2"
 dependencies = [
  "bitflags 1.999.999",
 ]
 
 [[package]]
 name = "audio_thread_priority"
 version = "0.32.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e3632611da7e79f8fc8fd75840f1ccfa7792dbf1e25d00791344a4450dd8834f"
 dependencies = [
  "cfg-if",
- "dbus",
+ "dbus 0.6.5",
  "libc",
  "log",
  "mach",
  "windows-sys",
 ]
 
 [[package]]
 name = "audioipc2"
@@ -710,16 +730,31 @@ source = "registry+https://github.com/ru
 checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1"
 dependencies = [
  "glob",
  "libc",
  "libloading",
 ]
 
 [[package]]
+name = "clap"
+version = "2.34.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
+dependencies = [
+ "ansi_term",
+ "atty",
+ "bitflags 1.999.999",
+ "strsim 0.8.0",
+ "textwrap 0.11.0",
+ "unicode-width",
+ "vec_map",
+]
+
+[[package]]
 name = "cmake"
 version = "0.1.999"
 
 [[package]]
 name = "codespan-reporting"
 version = "0.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
@@ -1104,17 +1139,17 @@ name = "darling_core"
 version = "0.20.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb"
 dependencies = [
  "fnv",
  "ident_case",
  "proc-macro2",
  "quote",
- "strsim",
+ "strsim 0.10.0",
  "syn",
 ]
 
 [[package]]
 name = "darling_macro"
 version = "0.20.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a"
@@ -1161,16 +1196,47 @@ version = "0.6.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "48b5f0f36f1eebe901b0e6bee369a77ed3396334bf3f09abd46454a576f71819"
 dependencies = [
  "libc",
  "libdbus-sys",
 ]
 
 [[package]]
+name = "dbus"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f8bcdd56d2e5c4ed26a529c5a9029f5db8290d433497506f958eae3be148eb6"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "winapi",
+]
+
+[[package]]
+name = "dbus-codegen"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a49da9fdfbe872d4841d56605dc42efa5e6ca3291299b87f44e1cde91a28617c"
+dependencies = [
+ "clap",
+ "dbus 0.9.6",
+ "xml-rs",
+]
+
+[[package]]
+name = "dbus-tree"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f456e698ae8e54575e19ddb1f9b7bce2298568524f215496b248eb9498b4f508"
+dependencies = [
+ "dbus 0.9.6",
+]
+
+[[package]]
 name = "debugid"
 version = "0.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d"
 dependencies = [
  "uuid",
 ]
 
@@ -2095,16 +2161,17 @@ dependencies = [
  "profiler_helper",
  "qcms",
  "rsdparsa_capi",
  "rure",
  "rusqlite",
  "rust_minidump_writer_linux",
  "static_prefs",
  "storage",
+ "sys_tray",
  "unic-langid",
  "unic-langid-ffi",
  "unicode-bidi",
  "unicode-bidi-ffi",
  "uniffi",
  "uniffi-example-arithmetic",
  "uniffi-example-custom-types",
  "uniffi-example-geometry",
@@ -2134,16 +2201,17 @@ dependencies = [
  "l10nregistry-ffi-gtest",
  "lmdb-rkv-sys",
  "moz_task-gtest",
  "mozglue-static",
  "mozilla-central-workspace-hack",
  "mp4parse-gtest",
  "nsstring-gtest",
  "swgl",
+ "sys_tray",
  "xpcom-gtest",
 ]
 
 [[package]]
 name = "gkrust-shared"
 version = "0.1.0"
 dependencies = [
  "aa-stroke",
@@ -2452,16 +2520,25 @@ dependencies = [
 [[package]]
 name = "heck"
 version = "0.4.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
 
 [[package]]
 name = "hermit-abi"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "hermit-abi"
 version = "0.2.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"
 dependencies = [
  "libc",
 ]
 
 [[package]]
@@ -2803,16 +2880,28 @@ dependencies = [
 
 [[package]]
 name = "khronos_api"
 version = "3.1.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
 
 [[package]]
+name = "ksni"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4934310bdd016e55725482b8d35ac0c16fd058c1b955d8959aa2d953b918c85b"
+dependencies = [
+ "dbus 0.9.6",
+ "dbus-codegen",
+ "dbus-tree",
+ "thiserror",
+]
+
+[[package]]
 name = "kvstore"
 version = "0.1.0"
 dependencies = [
  "atomic_refcell",
  "crossbeam-utils",
  "cstr",
  "lazy_static",
  "libc",
@@ -3668,17 +3757,17 @@ dependencies = [
 ]
 
 [[package]]
 name = "num_cpus"
 version = "1.15.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
 dependencies = [
- "hermit-abi",
+ "hermit-abi 0.2.6",
  "libc",
 ]
 
 [[package]]
 name = "objc"
 version = "0.2.7"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
@@ -4773,16 +4862,22 @@ dependencies = [
  "libc",
  "nserror",
  "nsstring",
  "xpcom",
 ]
 
 [[package]]
 name = "strsim"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
+
+[[package]]
+name = "strsim"
 version = "0.10.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
 
 [[package]]
 name = "style"
 version = "0.0.1"
 dependencies = [
@@ -4967,16 +5062,33 @@ source = "registry+https://github.com/ru
 checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
 dependencies = [
  "proc-macro2",
  "quote",
  "syn",
 ]
 
 [[package]]
+name = "sys_tray"
+version = "0.1.0"
+dependencies = [
+ "cstr",
+ "fluent",
+ "ksni",
+ "log",
+ "moz_task",
+ "mozbuild",
+ "nserror",
+ "nsstring",
+ "thin-vec",
+ "unic-langid",
+ "xpcom",
+]
+
+[[package]]
 name = "tabs"
 version = "0.1.0"
 source = "git+https://github.com/mozilla/application-services?rev=8fd08c6f2f8acd38579bd3142fecda9272957b72#8fd08c6f2f8acd38579bd3142fecda9272957b72"
 dependencies = [
  "anyhow",
  "error-support",
  "interrupt-support",
  "lazy_static",
@@ -5014,16 +5126,25 @@ version = "1.4.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
 dependencies = [
  "winapi-util",
 ]
 
 [[package]]
 name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "unicode-width",
+]
+
+[[package]]
+name = "textwrap"
 version = "0.16.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "23d434d3f8967a09480fb04132ebe0a3e088c173e6d0ee7897abbdf4eab0f8b9"
 dependencies = [
  "smawk",
 ]
 
 [[package]]
@@ -5371,17 +5492,17 @@ dependencies = [
  "cargo_metadata",
  "fs-err",
  "glob",
  "goblin 0.8.1",
  "heck",
  "once_cell",
  "paste",
  "serde",
- "textwrap",
+ "textwrap 0.16.1",
  "toml",
  "uniffi_meta",
  "uniffi_testing",
  "uniffi_udl",
 ]
 
 [[package]]
 name = "uniffi_build"
@@ -5464,17 +5585,17 @@ dependencies = [
 
 [[package]]
 name = "uniffi_udl"
 version = "0.27.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b92f984bb0d9a06778f256aec963e1e9a80714014f7a90fb0e01008821fe5a97"
 dependencies = [
  "anyhow",
- "textwrap",
+ "textwrap 0.16.1",
  "uniffi_meta",
  "uniffi_testing",
  "weedle2",
 ]
 
 [[package]]
 name = "url"
 version = "2.5.1"
@@ -5508,16 +5629,22 @@ dependencies = [
  "getrandom",
 ]
 
 [[package]]
 name = "vcpkg"
 version = "0.2.999"
 
 [[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
+[[package]]
 name = "version_check"
 version = "0.9.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
 
 [[package]]
 name = "viaduct"
 version = "0.1.0"
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -5,17 +5,17 @@ license = "MPL-2.0"
 description = "Thunderbird extensions to mozilla-central-workspace-hack"
 
 [features]
 gkrust = []
 gkrust-gtest = ["gkrust"]
 
 
 [workspace]
-members = ['xpcom_async', 'moz_http', 'gkrust', 'ews_xpcom', 'gtest']
+members = ['xpcom_async', 'moz_http', 'gkrust', 'ews_xpcom', 'gtest', 'sys_tray']
 
 [workspace.dependencies]
 uniffi = { version = "0.27.3" }
 uniffi_bindgen = { version = "0.27.3" }
 rusqlite = { version = "0.31.0" }
 glean = { version = "=60.3.0" }
 
 [patch.crates-io]
--- a/rust/gkrust/Cargo.toml
+++ b/rust/gkrust/Cargo.toml
@@ -12,16 +12,17 @@ bench = false
 doc = false
 plugin = false
 harness = false
 
 [dependencies]
 mozilla-central-workspace-hack = { version = "0.1", features = ['gkrust'], optional = true }
 gkrust-shared = { version = "0.1.0", path = "../../../toolkit/library/rust/shared" }
 ews_xpcom = { version = "0.1.0", path = "../ews_xpcom" }
+sys_tray = { version = "0.1.0", path = "../sys_tray" }
 aa-stroke = { git = "https://github.com/FirefoxGraphics/aa-stroke", rev = "d94278ed9c7020f50232689a26d1277eb0eb74d2" }
 app_services_logger = { path = "../../../services/common/app_services_logger" }
 audio_thread_priority = { version = "0.32" }
 audioipc2-client = { git = "https://github.com/mozilla/audioipc", rev = "3495905752a4263827f5d43737f9ca3ed0243ce0", optional = true }
 audioipc2-server = { git = "https://github.com/mozilla/audioipc", rev = "3495905752a4263827f5d43737f9ca3ed0243ce0", optional = true }
 authrs_bridge = { path = "../../../dom/webauthn/authrs_bridge" }
 binary_http = { path = "../../../netwerk/protocol/http/binary_http" }
 bitsdownload = { path = "../../../toolkit/components/bitsdownload", optional = true }
--- a/rust/gkrust/src/lib.rs
+++ b/rust/gkrust/src/lib.rs
@@ -1,8 +1,9 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 // Add new crates to Cargo.toml and build them here to get into gkrust/libxul
 extern crate gkrust_shared;
+extern crate sys_tray;
 
 extern crate ews_xpcom;
--- a/rust/gtest/Cargo.toml
+++ b/rust/gtest/Cargo.toml
@@ -3,16 +3,17 @@ name = "gkrust-gtest"
 version = "0.1.0"
 authors = ["The Mozilla Project Developers"]
 license = "MPL-2.0"
 description = "Testing code for libgkrust"
 
 [dependencies]
 mozilla-central-workspace-hack = { version = "0.1", features = ["gkrust-gtest"], optional = true }
 ews_xpcom = { version = "0.1.0", path = "../ews_xpcom" }
+sys_tray = { version = "0.1.0", path = "../sys_tray" }
 bench-collections-gtest = { path = "../../../xpcom/rust/gtest/bench-collections" }
 l10nregistry-ffi-gtest = { path = "../../../intl/l10n/rust/gtest" }
 moz_task-gtest = { path = "../../../xpcom/rust/gtest/moz_task" }
 mp4parse-gtest = { path = "../../../dom/media/gtest" }
 nsstring-gtest = { path = "../../../xpcom/rust/gtest/nsstring" }
 xpcom-gtest = { path = "../../../xpcom/rust/gtest/xpcom" }
 gkrust-shared = { path = "../../../toolkit/library/rust/shared" }
 gecko-fuzz-targets = { path = "../../../tools/fuzzing/rust", optional = true }
--- a/rust/gtest/lib.rs
+++ b/rust/gtest/lib.rs
@@ -10,8 +10,9 @@ extern crate gecko_fuzz_targets;
 extern crate gkrust_shared;
 extern crate l10nregistry_ffi_gtest;
 extern crate moz_task_gtest;
 extern crate mp4parse_gtest;
 extern crate nsstring_gtest;
 extern crate xpcom_gtest;
 
 extern crate ews_xpcom;
+extern crate sys_tray;
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "sys_tray"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+cstr = "0.2"
+fluent = "0.16"
+log = "0.4"
+moz_task = { path = "../../../xpcom/rust/moz_task" }
+mozbuild = { path = "../../../build/rust/mozbuild" }
+nserror = { path = "../../../xpcom/rust/nserror" }
+nsstring = { path = "../../../xpcom/rust/nsstring" }
+thin-vec = "0.2"
+unic-langid = "0.9"
+xpcom = { path = "../../../xpcom/rust/xpcom" }
+
+[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]
+ksni = "0.2.2"
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/src/actions.rs
@@ -0,0 +1,44 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+//! Action handling for the tray icon implementation
+
+use cstr::cstr;
+use nserror::nsresult;
+use xpcom::get_service;
+use xpcom::interfaces::nsIAppStartup;
+
+/// Actions from the tray menu
+/// Note: For thread safety we *must* safely support Copy!
+#[derive(Clone, Copy, Debug)]
+pub enum Action {
+    /// Quit menu has been pressed
+    Quit,
+}
+
+/// Handle the given action in the tray menu
+///
+/// This private handler is always executed on the main thread
+/// and should not be directly called outside of the current
+/// threading design.
+pub(crate) fn handle_action(action: Action) -> Result<(), nsresult> {
+    match &action {
+        Action::Quit => request_quit(),
+    }
+}
+
+/// Request the application quit
+///
+/// This can only be called on the main thread.
+fn request_quit() -> Result<(), nsresult> {
+    let mut _cancelled = false;
+    let service = get_service::<nsIAppStartup>(cstr!("@mozilla.org/toolkit/app-startup;1"))
+        .ok_or(nserror::NS_ERROR_NO_INTERFACE)?;
+    unsafe {
+        service
+            .Quit(nsIAppStartup::eAttemptQuit, 0, &mut _cancelled as *mut bool)
+            .to_result()?;
+    }
+    Ok(())
+}
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/src/lib.rs
@@ -0,0 +1,12 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub mod actions;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub mod linux;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub use actions::*;
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+pub mod locales;
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/src/linux/mod.rs
@@ -0,0 +1,102 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+use fluent::FluentBundle;
+use ksni::Handle;
+use nserror::{nsresult, NS_OK};
+use std::os::raw::c_void;
+use system_tray::{SystemTray, TrayItem, XdgIcon};
+use xpcom::{nsIID, xpcom_method, RefPtr};
+
+use crate::{locales, Action};
+
+pub mod system_tray;
+
+/// Construct a new xpcom object for tray handling on Linux
+///
+/// Note eventually this will move back into the main crate
+/// when we can handle all tray types.
+///
+/// # Safety
+///
+/// Reliant on the xpcom system, exports as a C function
+#[no_mangle]
+pub unsafe extern "C" fn nsLinuxSysTrayHandlerConstructor(
+    iid: &nsIID,
+    result: *mut *mut c_void,
+) -> nsresult {
+    let instance = LinuxSysTrayHandler::new();
+    instance.QueryInterface(iid, result)
+}
+
+/// System tray implementation for Linux
+#[xpcom::xpcom(implement(nsIMessengerOSIntegration), atomic)]
+pub struct LinuxSysTrayHandler {
+    handle: Handle<SystemTray>,
+}
+
+impl LinuxSysTrayHandler {
+    /// Construct a new system tray
+    pub fn new() -> RefPtr<LinuxSysTrayHandler> {
+        let locs = locales::app_locales().expect("Failed to retrieve application locales");
+        let resource = locales::fl_resource().expect("Failed to parse fluent templates");
+        let mut bundle = FluentBundle::new(locs);
+        bundle
+            .add_resource(resource)
+            .expect("Failed to add resources to bundle");
+
+        // Grab the quit message
+        let msg = bundle
+            .get_message("system-tray-menu-quit")
+            .expect("Message doesn't exist.");
+        let mut errors = vec![];
+        let label = msg.get_attribute("label").expect("Message doesn't exist.");
+        let quit_msg = bundle.format_pattern(label.value(), None, &mut errors);
+        if !errors.is_empty() {
+            log::error!("translation issues: {errors:?}");
+        }
+
+        // Determine correct image
+        let icon = if XdgIcon::requires_symbolic() {
+            system_tray::locate_icon_on_system("TB-symbolic.svg").map(XdgIcon::Path)
+        } else {
+            system_tray::locate_icon_on_system("default256.png").map(XdgIcon::Path)
+        }
+        .ok()
+        .unwrap_or_else(|| XdgIcon::for_desktop("thunderbird"));
+
+        // Build our menu structure
+        let menus = [TrayItem::ActionItem {
+            label: quit_msg.into(),
+            icon: None,
+            action: Action::Quit,
+            enabled: true,
+            visible: true,
+        }];
+
+        // Get it executed
+        let tray = SystemTray::new("Thunderbird", icon, "Thunderbird Daily").with_items(menus);
+        let service = ksni::TrayService::new(tray);
+        let handle = service.handle();
+        service.spawn();
+        LinuxSysTrayHandler::allocate(InitLinuxSysTrayHandler { handle })
+    }
+
+    // Update the unread method count (unimplemented as yet)
+    xpcom_method!(update_unread_count => UpdateUnreadCount(unreadCount: u32, unreadToolTip: *const nsstring::nsAString));
+    fn update_unread_count(
+        &self,
+        _count: u32,
+        _tooltip: &nsstring::nsAString,
+    ) -> Result<(), nsresult> {
+        Ok(())
+    }
+
+    // Handle any cleanups
+    xpcom_method!(on_exit => OnExit());
+    fn on_exit(&self) -> Result<(), nsresult> {
+        self.handle.shutdown();
+        Ok(())
+    }
+}
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/src/linux/system_tray.rs
@@ -0,0 +1,211 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+use std::fs;
+use std::{env, fmt, sync::OnceLock};
+
+use nserror::nsresult;
+use xpcom::interfaces::nsIThread;
+use xpcom::RefPtr;
+
+use crate::Action;
+
+/// Status Notifier Item (Tray Area Icon) model
+pub struct SystemTray {
+    /// unique identity
+    id: &'static str,
+
+    /// application title
+    title: String,
+
+    /// the main icon to use
+    icon: XdgIcon,
+
+    /// Menu items
+    items: Vec<TrayItem>,
+}
+
+/// Locate an icon resource on disk
+pub(crate) fn locate_icon_on_system(path: &'static str) -> Result<String, nsresult> {
+    let our_binary = env::current_exe().map_err(|_| nserror::NS_ERROR_FILE_NOT_FOUND)?;
+    let binary_dir = our_binary
+        .parent()
+        .ok_or(nserror::NS_ERROR_FILE_NOT_FOUND)?;
+
+    let path = binary_dir
+        .join("chrome")
+        .join("icons")
+        .join("default")
+        .join(path);
+    let result = fs::canonicalize(path).map_err(|_| nserror::NS_ERROR_FILE_NOT_FOUND)?;
+
+    Ok(result.to_string_lossy().to_string())
+}
+
+/// Encapsulate standard vs symbolic differences
+///
+/// Certain desktop environments (notably GNOME) support
+/// named "-symbolic" icons, ie monochrome icons that can
+/// be styled using CSS where appropriate.
+///
+/// In order to facilitate better integration we attempt to pick
+/// a `-symbolic` icon automatically when using the GNOME Desktop
+/// or indeed a GNOME-*based* desktop (via `XDG_CURRENT_DESKTOP` var)
+///
+/// Note, it is entirely up to the SNI host implementation to correctly
+/// implement XDG Icon Theme lookup logic, splitting on hyphenated fragments
+/// in the icon name and checking existence of an icon in the cache.
+pub enum XdgIcon {
+    /// Standard freedesktop icon name
+    Standard(&'static str),
+
+    /// A symbolic icon
+    Symbolic(&'static str),
+
+    /// Path to an image on disk
+    Path(String),
+}
+
+impl XdgIcon {
+    /// Determine if the DE prefers symbolic icons (i.e. GNOME + GNOME-based)
+    pub fn requires_symbolic() -> bool {
+        static SYMBOLICS: OnceLock<bool> = OnceLock::new();
+
+        let b = SYMBOLICS.get_or_init(|| {
+            env::var("XDG_CURRENT_DESKTOP")
+                .unwrap_or_default()
+                .replace(';', ":")
+                .split(':')
+                .map(|s| s.to_lowercase())
+                .any(|i| i == "gnome")
+        });
+
+        *b
+    }
+
+    /// Generate the correct icon variant for the current desktop environment
+    pub fn for_desktop(name: &'static str) -> Self {
+        if Self::requires_symbolic() {
+            XdgIcon::Symbolic(name)
+        } else {
+            XdgIcon::Standard(name)
+        }
+    }
+}
+
+impl fmt::Display for XdgIcon {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            XdgIcon::Standard(n) => f.write_str(n),
+            XdgIcon::Symbolic(n) => f.write_fmt(format_args!("{n}-symbolic")),
+            XdgIcon::Path(p) => f.write_str(p),
+        }
+    }
+}
+
+/// Encapsulate the `[ksni::MenuItem]` types to control actions
+pub enum TrayItem {
+    /// Actionable (single click) item
+    ActionItem {
+        /// Display label
+        label: String,
+
+        /// Icon name
+        icon: Option<XdgIcon>,
+
+        /// The action to perform when selecting this item
+        action: Action,
+
+        /// Is this enabled?
+        enabled: bool,
+
+        /// And is it visible?
+        visible: bool,
+    },
+}
+
+impl From<&TrayItem> for ksni::MenuItem<SystemTray> {
+    fn from(value: &TrayItem) -> Self {
+        match value {
+            TrayItem::ActionItem {
+                label,
+                action,
+                enabled,
+                visible,
+                icon,
+            } => {
+                let act = *action;
+                Self::Standard(ksni::menu::StandardItem {
+                    label: label.clone(),
+                    enabled: *enabled,
+                    visible: *visible,
+                    activate: Box::new(move |tray| {
+                        tray.dispatch_action(act)
+                            .expect("Couldn't send to main thread");
+                    }),
+                    icon_name: icon.as_ref().map(|i| i.to_string()).unwrap_or_default(),
+                    ..Default::default()
+                })
+            }
+        }
+    }
+}
+
+impl SystemTray {
+    /// Dispatchs the provided action to the main thread
+    ///
+    /// The main thread's `handle_action` function will then further process the
+    /// action, calling other XPCOM interfaces, etc.
+    fn dispatch_action(&self, action: Action) -> Result<(), nsresult> {
+        // Now, dispatch to the main thread
+        let main_thread: RefPtr<nsIThread> = moz_task::get_main_thread()?;
+        moz_task::dispatch_onto("linux_sys_tray_dispatch", main_thread.coerce(), move || {
+            if let Err(e) = crate::handle_action(action) {
+                eprintln!("Failed to execute action: {action:?}: {e}");
+            }
+        })?;
+
+        Ok(())
+    }
+
+    /// Create a new tray icon with the given title
+    pub fn new(id: &'static str, icon: XdgIcon, title: impl AsRef<str>) -> Self {
+        Self {
+            id,
+            icon,
+            title: title.as_ref().to_string(),
+            items: vec![],
+        }
+    }
+
+    /// Create with the given items
+    pub fn with_items(self, items: impl IntoIterator<Item = TrayItem>) -> Self {
+        Self {
+            items: items.into_iter().collect::<Vec<_>>(),
+            ..self
+        }
+    }
+}
+
+impl ksni::Tray for SystemTray {
+    fn id(&self) -> String {
+        self.id.to_string()
+    }
+
+    fn title(&self) -> String {
+        self.title.clone()
+    }
+
+    fn status(&self) -> ksni::Status {
+        ksni::Status::Active
+    }
+
+    fn icon_name(&self) -> String {
+        self.icon.to_string()
+    }
+
+    fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
+        self.items.iter().map(|i| i.into()).collect::<Vec<_>>()
+    }
+}
new file mode 100644
--- /dev/null
+++ b/rust/sys_tray/src/locales.rs
@@ -0,0 +1,50 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Return the set of locales according to LocaleService
+
+use cstr::cstr;
+use fluent::FluentResource;
+use nserror::nsresult;
+use nsstring::nsCString;
+use thin_vec::ThinVec;
+use unic_langid::LanguageIdentifier;
+use xpcom::get_service;
+use xpcom::interfaces::mozILocaleService;
+
+static MENUBAR_FILE: &str = include_str!(mozbuild::srcdir_path!(
+    "/comm/mail/locales/en-US/messenger/menubar.ftl"
+));
+
+static BRANDING_FILE: &str = include_str!(mozbuild::srcdir_path!(
+    "/comm/mail/branding/thunderbird/locales/en-US/brand.ftl"
+));
+
+// Ask mozILocaleService for the known locale list
+fn supported_locales() -> Result<ThinVec<nsCString>, nsresult> {
+    let service = get_service::<mozILocaleService>(cstr!("@mozilla.org/intl/localeservice;1"))
+        .ok_or(nserror::NS_ERROR_NO_INTERFACE)?;
+    let mut locales = ThinVec::new();
+    unsafe {
+        service.GetAppLocalesAsBCP47(&mut locales).to_result()?;
+    }
+    Ok(locales)
+}
+
+/// Convert mozILocaleService known locales into fluent usable locales
+pub(crate) fn app_locales() -> Result<Vec<LanguageIdentifier>, nsresult> {
+    let locales = supported_locales()?
+        .into_iter()
+        .filter_map(|i| LanguageIdentifier::from_bytes(&i).ok())
+        .collect::<Vec<_>>();
+    Ok(locales)
+}
+
+/// Load our fluent resource
+pub(crate) fn fl_resource() -> Result<FluentResource, nsresult> {
+    let ftl_template = MENUBAR_FILE.to_owned() + BRANDING_FILE;
+    let resource = FluentResource::try_new(ftl_template).map_err(|_| nserror::NS_ERROR_FAILURE)?;
+
+    Ok(resource)
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.lock":"31bb7b361278d99a00595cbd916c444e6fd193b5f0b1ea0cf2d9454440739501","Cargo.toml":"4ca681d6949661455ac88541ffa68ebc7db50cb2b6e9a2134e6d0687da4997c3","LICENCE":"2762990c7fbba9d550802a2593c1d857dcd52596bb0f9f192a97e9a7ac5f4f9e","README.md":"8d983e1bb3cc99724010d9073a5be6452cd49bd57a877525fd0a5dd41e6591d5","examples/256_colours.rs":"5f2845068bc2d93cff4a61f18ffa44fbbbc91be771dfd686d537d343f37041da","examples/basic_colours.rs":"d610795f3743d10d90ec4e5ab32cc09fb16640896cecd2f93fca434a0920397c","examples/rgb_colours.rs":"8399e5131e959a56c932036b790e601fb4ad658856112daf87f933889b443f2c","src/ansi.rs":"988fb87936064fa006fcc9474ac62099c8d6e98d38bb80cec2cd864066482a08","src/debug.rs":"61343f8bf13695020102c033aeaacd9ccd3ec830eacbf9011127e61829451d20","src/difference.rs":"9b4b8f91c72932bfda262abdceff0ec124a5a8dd27d07bd4d2e5e7889135c6c9","src/display.rs":"c04f2397d1d1d86a5e2188c2840c505cb0baeaf9706a88d4bbe56eadc67811b9","src/lib.rs":"b85df4b9b8832cda777db049efa2ec84b9847438fa3feaf8540e597ce2532a47","src/style.rs":"1042fc973f5ea8bbb2a2faec334aad530520b53edc9b3296174ae38c1060490b","src/util.rs":"07c127f732887573a1c9126fc0288e13e7a8f1f803513b95e50aac2905171b0d","src/windows.rs":"7ce7dd6738b9728fcd3908c284b6f29a9bdfb34af761b4c7385cf7e3e1b20e64","src/write.rs":"c9ec03764ad1ecea8b680243c9cafc5e70919fcea7500cc18246ffd8f6bb4b33"},"package":"d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/Cargo.lock
@@ -0,0 +1,168 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "aho-corasick"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "ansi_term"
+version = "0.12.1"
+dependencies = [
+ "doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "regex 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde 1.0.94 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
+ "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "doc-comment"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "itoa"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "lazy_static"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "memchr"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "proc-macro2"
+version = "0.4.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "quote"
+version = "0.6.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "regex"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)",
+ "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "regex-syntax 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)",
+ "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "ryu"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "serde"
+version = "1.0.94"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "serde_derive 1.0.94 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.94"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.39 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde 1.0.94 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "syn"
+version = "0.15.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "thread_local"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "unicode-xid"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "winapi"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[metadata]
+"checksum aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d"
+"checksum doc-comment 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "923dea538cea0aa3025e8685b20d6ee21ef99c4f77e954a30febbaac5ec73a97"
+"checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f"
+"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+"checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e"
+"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
+"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
+"checksum regex 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88c3d9193984285d544df4a30c23a4e62ead42edf70a4452ceb76dac1ce05c26"
+"checksum regex-syntax 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "b143cceb2ca5e56d5671988ef8b15615733e7ee16cd348e064333b251b89343f"
+"checksum ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997"
+"checksum serde 1.0.94 (registry+https://github.com/rust-lang/crates.io-index)" = "076a696fdea89c19d3baed462576b8f6d663064414b5c793642da8dfeb99475b"
+"checksum serde_derive 1.0.94 (registry+https://github.com/rust-lang/crates.io-index)" = "ef45eb79d6463b22f5f9e16d283798b7c0175ba6050bc25c1a946c122727fe7b"
+"checksum serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)" = "051c49229f282f7c6f3813f8286cc1e3323e8051823fce42c7ea80fe13521704"
+"checksum syn 0.15.39 (registry+https://github.com/rust-lang/crates.io-index)" = "b4d960b829a55e56db167e861ddb43602c003c7be0bee1d345021703fac2fb7c"
+"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
+"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
+"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0"
+"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/Cargo.toml
@@ -0,0 +1,43 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "ansi_term"
+version = "0.12.1"
+authors = ["ogham@bsago.me", "Ryan Scheel (Havvy) <ryan.havvy@gmail.com>", "Josh Triplett <josh@joshtriplett.org>"]
+description = "Library for ANSI terminal colours and styles (bold, underline)"
+homepage = "https://github.com/ogham/rust-ansi-term"
+documentation = "https://docs.rs/ansi_term"
+readme = "README.md"
+license = "MIT"
+repository = "https://github.com/ogham/rust-ansi-term"
+
+[lib]
+name = "ansi_term"
+[dependencies.serde]
+version = "1.0.90"
+features = ["derive"]
+optional = true
+[dev-dependencies.doc-comment]
+version = "0.3"
+
+[dev-dependencies.regex]
+version = "1.1.9"
+
+[dev-dependencies.serde_json]
+version = "1.0.39"
+
+[features]
+derive_serde_style = ["serde"]
+[target."cfg(target_os=\"windows\")".dependencies.winapi]
+version = "0.3.4"
+features = ["consoleapi", "errhandlingapi", "fileapi", "handleapi", "processenv"]
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/LICENCE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Benjamin Sago
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/README.md
@@ -0,0 +1,183 @@
+# rust-ansi-term [![ansi-term on crates.io](http://meritbadge.herokuapp.com/ansi-term)](https://crates.io/crates/ansi_term) [![Build status](https://img.shields.io/travis/ogham/rust-ansi-term/master.svg?style=flat)](https://travis-ci.org/ogham/rust-ansi-term) [![Build status](https://img.shields.io/appveyor/ci/ogham/rust-ansi-term/master.svg?style=flat&logo=AppVeyor&logoColor=silver)](https://ci.appveyor.com/project/ogham/rust-ansi-term) [![Coverage status](https://coveralls.io/repos/ogham/rust-ansi-term/badge.svg?branch=master&service=github)](https://coveralls.io/github/ogham/rust-ansi-term?branch=master)
+
+This is a library for controlling colours and formatting, such as red bold text or blue underlined text, on ANSI terminals.
+
+### [View the Rustdoc](https://docs.rs/ansi_term/)
+
+
+# Installation
+
+This crate works with [Cargo](http://crates.io). Add the following to your `Cargo.toml` dependencies section:
+
+```toml
+[dependencies]
+ansi_term = "0.12"
+```
+
+
+## Basic usage
+
+There are three main types in this crate that you need to be concerned with: `ANSIString`, `Style`, and `Colour`.
+
+A `Style` holds stylistic information: foreground and background colours, whether the text should be bold, or blinking, or other properties.
+The `Colour` enum represents the available colours.
+And an `ANSIString` is a string paired with a `Style`.
+
+`Color` is also available as an alias to `Colour`.
+
+To format a string, call the `paint` method on a `Style` or a `Colour`, passing in the string you want to format as the argument.
+For example, here’s how to get some red text:
+
+```rust
+use ansi_term::Colour::Red;
+
+println!("This is in red: {}", Red.paint("a red string"));
+```
+
+It’s important to note that the `paint` method does *not* actually return a string with the ANSI control characters surrounding it.
+Instead, it returns an `ANSIString` value that has a `Display` implementation that, when formatted, returns the characters.
+This allows strings to be printed with a minimum of `String` allocations being performed behind the scenes.
+
+If you *do* want to get at the escape codes, then you can convert the `ANSIString` to a string as you would any other `Display` value:
+
+```rust
+use ansi_term::Colour::Red;
+
+let red_string = Red.paint("a red string").to_string();
+```
+
+**Note for Windows 10 users:** On Windows 10, the application must enable ANSI support first:
+
+```rust,ignore
+let enabled = ansi_term::enable_ansi_support();
+```
+
+## Bold, underline, background, and other styles
+
+For anything more complex than plain foreground colour changes, you need to construct `Style` values themselves, rather than beginning with a `Colour`.
+You can do this by chaining methods based on a new `Style`, created with `Style::new()`.
+Each method creates a new style that has that specific property set.
+For example:
+
+```rust
+use ansi_term::Style;
+
+println!("How about some {} and {}?",
+         Style::new().bold().paint("bold"),
+         Style::new().underline().paint("underline"));
+```
+
+For brevity, these methods have also been implemented for `Colour` values, so you can give your styles a foreground colour without having to begin with an empty `Style` value:
+
+```rust
+use ansi_term::Colour::{Blue, Yellow};
+
+println!("Demonstrating {} and {}!",
+         Blue.bold().paint("blue bold"),
+         Yellow.underline().paint("yellow underline"));
+
+println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
+```
+
+The complete list of styles you can use are:
+`bold`, `dimmed`, `italic`, `underline`, `blink`, `reverse`, `hidden`, and `on` for background colours.
+
+In some cases, you may find it easier to change the foreground on an existing `Style` rather than starting from the appropriate `Colour`.
+You can do this using the `fg` method:
+
+```rust
+use ansi_term::Style;
+use ansi_term::Colour::{Blue, Cyan, Yellow};
+
+println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
+println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
+```
+
+You can turn a `Colour` into a `Style` with the `normal` method.
+This will produce the exact same `ANSIString` as if you just used the `paint` method on the `Colour` directly, but it’s useful in certain cases: for example, you may have a method that returns `Styles`, and need to represent both the “red bold” and “red, but not bold” styles with values of the same type. The `Style` struct also has a `Default` implementation if you want to have a style with *nothing* set.
+
+```rust
+use ansi_term::Style;
+use ansi_term::Colour::Red;
+
+Red.normal().paint("yet another red string");
+Style::default().paint("a completely regular string");
+```
+
+
+## Extended colours
+
+You can access the extended range of 256 colours by using the `Colour::Fixed` variant, which takes an argument of the colour number to use.
+This can be included wherever you would use a `Colour`:
+
+```rust
+use ansi_term::Colour::Fixed;
+
+Fixed(134).paint("A sort of light purple");
+Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
+```
+
+The first sixteen of these values are the same as the normal and bold standard colour variants.
+There’s nothing stopping you from using these as `Fixed` colours instead, but there’s nothing to be gained by doing so either.
+
+You can also access full 24-bit colour by using the `Colour::RGB` variant, which takes separate `u8` arguments for red, green, and blue:
+
+```rust
+use ansi_term::Colour::RGB;
+
+RGB(70, 130, 180).paint("Steel blue");
+```
+
+## Combining successive coloured strings
+
+The benefit of writing ANSI escape codes to the terminal is that they *stack*: you do not need to end every coloured string with a reset code if the text that follows it is of a similar style.
+For example, if you want to have some blue text followed by some blue bold text, it’s possible to send the ANSI code for blue, followed by the ANSI code for bold, and finishing with a reset code without having to have an extra one between the two strings.
+
+This crate can optimise the ANSI codes that get printed in situations like this, making life easier for your terminal renderer.
+The `ANSIStrings` struct takes a slice of several `ANSIString` values, and will iterate over each of them, printing only the codes for the styles that need to be updated as part of its formatting routine.
+
+The following code snippet uses this to enclose a binary number displayed in red bold text inside some red, but not bold, brackets:
+
+```rust
+use ansi_term::Colour::Red;
+use ansi_term::{ANSIString, ANSIStrings};
+
+let some_value = format!("{:b}", 42);
+let strings: &[ANSIString<'static>] = &[
+    Red.paint("["),
+    Red.bold().paint(some_value),
+    Red.paint("]"),
+];
+
+println!("Value: {}", ANSIStrings(strings));
+```
+
+There are several things to note here.
+Firstly, the `paint` method can take *either* an owned `String` or a borrowed `&str`.
+Internally, an `ANSIString` holds a copy-on-write (`Cow`) string value to deal with both owned and borrowed strings at the same time.
+This is used here to display a `String`, the result of the `format!` call, using the same mechanism as some statically-available `&str` slices.
+Secondly, that the `ANSIStrings` value works in the same way as its singular counterpart, with a `Display` implementation that only performs the formatting when required.
+
+## Byte strings
+
+This library also supports formatting `[u8]` byte strings; this supports applications working with text in an unknown encoding.
+`Style` and `Colour` support painting `[u8]` values, resulting in an `ANSIByteString`.
+This type does not implement `Display`, as it may not contain UTF-8, but it does provide a method `write_to` to write the result to any value that implements `Write`:
+
+```rust
+use ansi_term::Colour::Green;
+
+Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
+```
+
+Similarly, the type `ANSIByteStrings` supports writing a list of `ANSIByteString` values with minimal escape sequences:
+
+```rust
+use ansi_term::Colour::Green;
+use ansi_term::ANSIByteStrings;
+
+ANSIByteStrings(&[
+    Green.paint("user data 1\n".as_bytes()),
+    Green.bold().paint("user data 2\n".as_bytes()),
+]).write_to(&mut std::io::stdout()).unwrap();
+```
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/examples/256_colours.rs
@@ -0,0 +1,73 @@
+extern crate ansi_term;
+use ansi_term::Colour;
+
+// This example prints out the 256 colours.
+// They're arranged like this:
+//
+// - 0 to 8 are the eight standard colours.
+// - 9 to 15 are the eight bold colours.
+// - 16 to 231 are six blocks of six-by-six colour squares.
+// - 232 to 255 are shades of grey.
+
+fn main() {
+
+    // First two lines
+    for c in 0..8 {
+        glow(c, c != 0);
+        print!(" ");
+    }
+    print!("\n");
+    for c in 8..16 {
+        glow(c, c != 8);
+        print!(" ");
+    }
+    print!("\n\n");
+
+    // Six lines of the first three squares
+    for row in 0..6 {
+        for square in 0..3 {
+            for column in 0..6 {
+                glow(16 + square * 36 + row * 6 + column, row >= 3);
+                print!(" ");
+            }
+
+            print!("  ");
+        }
+
+        print!("\n");
+    }
+    print!("\n");
+
+    // Six more lines of the other three squares
+    for row in 0..6 {
+        for square in 0..3 {
+            for column in 0..6 {
+                glow(124 + square * 36 + row * 6 + column, row >= 3);
+                print!(" ");
+            }
+
+            print!("  ");
+        }
+
+        print!("\n");
+    }
+    print!("\n");
+
+    // The last greyscale lines
+    for c in 232..=243 {
+        glow(c, false);
+        print!(" ");
+    }
+    print!("\n");
+    for c in 244..=255 {
+        glow(c, true);
+        print!(" ");
+    }
+    print!("\n");
+}
+
+fn glow(c: u8, light_bg: bool) {
+    let base = if light_bg { Colour::Black } else { Colour::White };
+    let style = base.on(Colour::Fixed(c));
+    print!("{}", style.paint(&format!(" {:3} ", c)));
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/examples/basic_colours.rs
@@ -0,0 +1,18 @@
+extern crate ansi_term;
+use ansi_term::{Style, Colour::*};
+
+// This example prints out the 16 basic colours.
+
+fn main() {
+    let normal = Style::default();
+
+    println!("{} {}", normal.paint("Normal"), normal.bold().paint("bold"));
+    println!("{} {}", Black.paint("Black"),   Black.bold().paint("bold"));
+    println!("{} {}", Red.paint("Red"),       Red.bold().paint("bold"));
+    println!("{} {}", Green.paint("Green"),   Green.bold().paint("bold"));
+    println!("{} {}", Yellow.paint("Yellow"), Yellow.bold().paint("bold"));
+    println!("{} {}", Blue.paint("Blue"),     Blue.bold().paint("bold"));
+    println!("{} {}", Purple.paint("Purple"), Purple.bold().paint("bold"));
+    println!("{} {}", Cyan.paint("Cyan"),     Cyan.bold().paint("bold"));
+    println!("{} {}", White.paint("White"),   White.bold().paint("bold"));
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/examples/rgb_colours.rs
@@ -0,0 +1,23 @@
+extern crate ansi_term;
+use ansi_term::{Style, Colour};
+
+// This example prints out a colour gradient in a grid by calculating each
+// character’s red, green, and blue components, and using 24-bit colour codes
+// to display them.
+
+const WIDTH:  i32 = 80;
+const HEIGHT: i32 = 24;
+
+fn main() {
+    for row in 0 .. HEIGHT {
+        for col in 0 .. WIDTH {
+            let r = (row * 255 / HEIGHT) as u8;
+            let g = (col * 255 / WIDTH) as u8;
+            let b = 128;
+
+            print!("{}", Style::default().on(Colour::RGB(r, g, b)).paint(" "));
+        }
+
+        print!("\n");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/ansi.rs
@@ -0,0 +1,374 @@
+use style::{Colour, Style};
+
+use std::fmt;
+
+use write::AnyWrite;
+
+
+// ---- generating ANSI codes ----
+
+impl Style {
+
+    /// Write any bytes that go *before* a piece of text to the given writer.
+    fn write_prefix<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
+
+        // If there are actually no styles here, then don’t write *any* codes
+        // as the prefix. An empty ANSI code may not affect the terminal
+        // output at all, but a user may just want a code-free string.
+        if self.is_plain() {
+            return Ok(());
+        }
+
+        // Write the codes’ prefix, then write numbers, separated by
+        // semicolons, for each text style we want to apply.
+        write!(f, "\x1B[")?;
+        let mut written_anything = false;
+
+        {
+            let mut write_char = |c| {
+                if written_anything { write!(f, ";")?; }
+                written_anything = true;
+                write!(f, "{}", c)?;
+                Ok(())
+            };
+
+            if self.is_bold           { write_char('1')? }
+            if self.is_dimmed         { write_char('2')? }
+            if self.is_italic         { write_char('3')? }
+            if self.is_underline      { write_char('4')? }
+            if self.is_blink          { write_char('5')? }
+            if self.is_reverse        { write_char('7')? }
+            if self.is_hidden         { write_char('8')? }
+            if self.is_strikethrough  { write_char('9')? }
+        }
+
+        // The foreground and background colours, if specified, need to be
+        // handled specially because the number codes are more complicated.
+        // (see `write_background_code` and `write_foreground_code`)
+        if let Some(bg) = self.background {
+            if written_anything { write!(f, ";")?; }
+            written_anything = true;
+            bg.write_background_code(f)?;
+        }
+
+        if let Some(fg) = self.foreground {
+            if written_anything { write!(f, ";")?; }
+            fg.write_foreground_code(f)?;
+        }
+
+        // All the codes end with an `m`, because reasons.
+        write!(f, "m")?;
+
+        Ok(())
+    }
+
+    /// Write any bytes that go *after* a piece of text to the given writer.
+    fn write_suffix<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
+        if self.is_plain() {
+            Ok(())
+        }
+        else {
+            write!(f, "{}", RESET)
+        }
+    }
+}
+
+
+/// The code to send to reset all styles and return to `Style::default()`.
+pub static RESET: &str = "\x1B[0m";
+
+
+
+impl Colour {
+    fn write_foreground_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
+        match *self {
+            Colour::Black      => write!(f, "30"),
+            Colour::Red        => write!(f, "31"),
+            Colour::Green      => write!(f, "32"),
+            Colour::Yellow     => write!(f, "33"),
+            Colour::Blue       => write!(f, "34"),
+            Colour::Purple     => write!(f, "35"),
+            Colour::Cyan       => write!(f, "36"),
+            Colour::White      => write!(f, "37"),
+            Colour::Fixed(num) => write!(f, "38;5;{}", &num),
+            Colour::RGB(r,g,b) => write!(f, "38;2;{};{};{}", &r, &g, &b),
+        }
+    }
+
+    fn write_background_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
+        match *self {
+            Colour::Black      => write!(f, "40"),
+            Colour::Red        => write!(f, "41"),
+            Colour::Green      => write!(f, "42"),
+            Colour::Yellow     => write!(f, "43"),
+            Colour::Blue       => write!(f, "44"),
+            Colour::Purple     => write!(f, "45"),
+            Colour::Cyan       => write!(f, "46"),
+            Colour::White      => write!(f, "47"),
+            Colour::Fixed(num) => write!(f, "48;5;{}", &num),
+            Colour::RGB(r,g,b) => write!(f, "48;2;{};{};{}", &r, &g, &b),
+        }
+    }
+}
+
+
+/// Like `ANSIString`, but only displays the style prefix.
+///
+/// This type implements the `Display` trait, meaning it can be written to a
+/// `std::fmt` formatting without doing any extra allocation, and written to a
+/// string with the `.to_string()` method. For examples, see
+/// [`Style::prefix`](struct.Style.html#method.prefix).
+#[derive(Clone, Copy, Debug)]
+pub struct Prefix(Style);
+
+/// Like `ANSIString`, but only displays the difference between two
+/// styles.
+///
+/// This type implements the `Display` trait, meaning it can be written to a
+/// `std::fmt` formatting without doing any extra allocation, and written to a
+/// string with the `.to_string()` method. For examples, see
+/// [`Style::infix`](struct.Style.html#method.infix).
+#[derive(Clone, Copy, Debug)]
+pub struct Infix(Style, Style);
+
+/// Like `ANSIString`, but only displays the style suffix.
+///
+/// This type implements the `Display` trait, meaning it can be written to a
+/// `std::fmt` formatting without doing any extra allocation, and written to a
+/// string with the `.to_string()` method. For examples, see
+/// [`Style::suffix`](struct.Style.html#method.suffix).
+#[derive(Clone, Copy, Debug)]
+pub struct Suffix(Style);
+
+
+impl Style {
+
+    /// The prefix bytes for this style. These are the bytes that tell the
+    /// terminal to use a different colour or font style.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour::Blue};
+    ///
+    /// let style = Style::default().bold();
+    /// assert_eq!("\x1b[1m",
+    ///            style.prefix().to_string());
+    ///
+    /// let style = Blue.bold();
+    /// assert_eq!("\x1b[1;34m",
+    ///            style.prefix().to_string());
+    ///
+    /// let style = Style::default();
+    /// assert_eq!("",
+    ///            style.prefix().to_string());
+    /// ```
+    pub fn prefix(self) -> Prefix {
+        Prefix(self)
+    }
+
+    /// The infix bytes between this style and `next` style. These are the bytes
+    /// that tell the terminal to change the style to `next`. These may include
+    /// a reset followed by the next colour and style, depending on the two styles.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour::Green};
+    ///
+    /// let style = Style::default().bold();
+    /// assert_eq!("\x1b[32m",
+    ///            style.infix(Green.bold()).to_string());
+    ///
+    /// let style = Green.normal();
+    /// assert_eq!("\x1b[1m",
+    ///            style.infix(Green.bold()).to_string());
+    ///
+    /// let style = Style::default();
+    /// assert_eq!("",
+    ///            style.infix(style).to_string());
+    /// ```
+    pub fn infix(self, next: Style) -> Infix {
+        Infix(self, next)
+    }
+
+    /// The suffix for this style. These are the bytes that tell the terminal
+    /// to reset back to its normal colour and font style.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour::Green};
+    ///
+    /// let style = Style::default().bold();
+    /// assert_eq!("\x1b[0m",
+    ///            style.suffix().to_string());
+    ///
+    /// let style = Green.normal().bold();
+    /// assert_eq!("\x1b[0m",
+    ///            style.suffix().to_string());
+    ///
+    /// let style = Style::default();
+    /// assert_eq!("",
+    ///            style.suffix().to_string());
+    /// ```
+    pub fn suffix(self) -> Suffix {
+        Suffix(self)
+    }
+}
+
+
+impl Colour {
+
+    /// The prefix bytes for this colour as a `Style`. These are the bytes
+    /// that tell the terminal to use a different colour or font style.
+    ///
+    /// See also [`Style::prefix`](struct.Style.html#method.prefix).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour::Green;
+    ///
+    /// assert_eq!("\x1b[0m",
+    ///            Green.suffix().to_string());
+    /// ```
+    pub fn prefix(self) -> Prefix {
+        Prefix(self.normal())
+    }
+
+    /// The infix bytes between this colour and `next` colour. These are the bytes
+    /// that tell the terminal to use the `next` colour, or to do nothing if
+    /// the two colours are equal.
+    ///
+    /// See also [`Style::infix`](struct.Style.html#method.infix).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour::{Red, Yellow};
+    ///
+    /// assert_eq!("\x1b[33m",
+    ///            Red.infix(Yellow).to_string());
+    /// ```
+    pub fn infix(self, next: Colour) -> Infix {
+        Infix(self.normal(), next.normal())
+    }
+
+    /// The suffix for this colour as a `Style`. These are the bytes that
+    /// tell the terminal to reset back to its normal colour and font style.
+    ///
+    /// See also [`Style::suffix`](struct.Style.html#method.suffix).
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour::Purple;
+    ///
+    /// assert_eq!("\x1b[0m",
+    ///            Purple.suffix().to_string());
+    /// ```
+    pub fn suffix(self) -> Suffix {
+        Suffix(self.normal())
+    }
+}
+
+
+impl fmt::Display for Prefix {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let f: &mut fmt::Write = f;
+        self.0.write_prefix(f)
+    }
+}
+
+
+impl fmt::Display for Infix {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        use difference::Difference;
+
+        match Difference::between(&self.0, &self.1) {
+            Difference::ExtraStyles(style) => {
+                let f: &mut fmt::Write = f;
+                style.write_prefix(f)
+            },
+            Difference::Reset => {
+                let f: &mut fmt::Write = f;
+                write!(f, "{}{}", RESET, self.1.prefix())
+            },
+            Difference::NoDifference => {
+                Ok(())   // nothing to write
+            },
+        }
+    }
+}
+
+
+impl fmt::Display for Suffix {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let f: &mut fmt::Write = f;
+        self.0.write_suffix(f)
+    }
+}
+
+
+
+#[cfg(test)]
+mod test {
+    use style::Style;
+    use style::Colour::*;
+
+    macro_rules! test {
+        ($name: ident: $style: expr; $input: expr => $result: expr) => {
+            #[test]
+            fn $name() {
+                assert_eq!($style.paint($input).to_string(), $result.to_string());
+
+                let mut v = Vec::new();
+                $style.paint($input.as_bytes()).write_to(&mut v).unwrap();
+                assert_eq!(v.as_slice(), $result.as_bytes());
+            }
+        };
+    }
+
+    test!(plain:                 Style::default();                  "text/plain" => "text/plain");
+    test!(red:                   Red;                               "hi" => "\x1B[31mhi\x1B[0m");
+    test!(black:                 Black.normal();                    "hi" => "\x1B[30mhi\x1B[0m");
+    test!(yellow_bold:           Yellow.bold();                     "hi" => "\x1B[1;33mhi\x1B[0m");
+    test!(yellow_bold_2:         Yellow.normal().bold();            "hi" => "\x1B[1;33mhi\x1B[0m");
+    test!(blue_underline:        Blue.underline();                  "hi" => "\x1B[4;34mhi\x1B[0m");
+    test!(green_bold_ul:         Green.bold().underline();          "hi" => "\x1B[1;4;32mhi\x1B[0m");
+    test!(green_bold_ul_2:       Green.underline().bold();          "hi" => "\x1B[1;4;32mhi\x1B[0m");
+    test!(purple_on_white:       Purple.on(White);                  "hi" => "\x1B[47;35mhi\x1B[0m");
+    test!(purple_on_white_2:     Purple.normal().on(White);         "hi" => "\x1B[47;35mhi\x1B[0m");
+    test!(yellow_on_blue:        Style::new().on(Blue).fg(Yellow);  "hi" => "\x1B[44;33mhi\x1B[0m");
+    test!(yellow_on_blue_2:      Cyan.on(Blue).fg(Yellow);          "hi" => "\x1B[44;33mhi\x1B[0m");
+    test!(cyan_bold_on_white:    Cyan.bold().on(White);             "hi" => "\x1B[1;47;36mhi\x1B[0m");
+    test!(cyan_ul_on_white:      Cyan.underline().on(White);        "hi" => "\x1B[4;47;36mhi\x1B[0m");
+    test!(cyan_bold_ul_on_white: Cyan.bold().underline().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m");
+    test!(cyan_ul_bold_on_white: Cyan.underline().bold().on(White); "hi" => "\x1B[1;4;47;36mhi\x1B[0m");
+    test!(fixed:                 Fixed(100);                        "hi" => "\x1B[38;5;100mhi\x1B[0m");
+    test!(fixed_on_purple:       Fixed(100).on(Purple);             "hi" => "\x1B[45;38;5;100mhi\x1B[0m");
+    test!(fixed_on_fixed:        Fixed(100).on(Fixed(200));         "hi" => "\x1B[48;5;200;38;5;100mhi\x1B[0m");
+    test!(rgb:                   RGB(70,130,180);                   "hi" => "\x1B[38;2;70;130;180mhi\x1B[0m");
+    test!(rgb_on_blue:           RGB(70,130,180).on(Blue);          "hi" => "\x1B[44;38;2;70;130;180mhi\x1B[0m");
+    test!(blue_on_rgb:           Blue.on(RGB(70,130,180));          "hi" => "\x1B[48;2;70;130;180;34mhi\x1B[0m");
+    test!(rgb_on_rgb:            RGB(70,130,180).on(RGB(5,10,15));  "hi" => "\x1B[48;2;5;10;15;38;2;70;130;180mhi\x1B[0m");
+    test!(bold:                  Style::new().bold();               "hi" => "\x1B[1mhi\x1B[0m");
+    test!(underline:             Style::new().underline();          "hi" => "\x1B[4mhi\x1B[0m");
+    test!(bunderline:            Style::new().bold().underline();   "hi" => "\x1B[1;4mhi\x1B[0m");
+    test!(dimmed:                Style::new().dimmed();             "hi" => "\x1B[2mhi\x1B[0m");
+    test!(italic:                Style::new().italic();             "hi" => "\x1B[3mhi\x1B[0m");
+    test!(blink:                 Style::new().blink();              "hi" => "\x1B[5mhi\x1B[0m");
+    test!(reverse:               Style::new().reverse();            "hi" => "\x1B[7mhi\x1B[0m");
+    test!(hidden:                Style::new().hidden();             "hi" => "\x1B[8mhi\x1B[0m");
+    test!(stricken:              Style::new().strikethrough();      "hi" => "\x1B[9mhi\x1B[0m");
+
+    #[test]
+    fn test_infix() {
+        assert_eq!(Style::new().dimmed().infix(Style::new()).to_string(), "\x1B[0m");
+        assert_eq!(White.dimmed().infix(White.normal()).to_string(), "\x1B[0m\x1B[37m");
+        assert_eq!(White.normal().infix(White.bold()).to_string(), "\x1B[1m");
+        assert_eq!(White.normal().infix(Blue.normal()).to_string(), "\x1B[34m");
+        assert_eq!(Blue.bold().infix(Blue.bold()).to_string(), "");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/debug.rs
@@ -0,0 +1,134 @@
+use std::fmt;
+
+use style::Style;
+
+/// Styles have a special `Debug` implementation that only shows the fields that
+/// are set. Fields that haven’t been touched aren’t included in the output.
+///
+/// This behaviour gets bypassed when using the alternate formatting mode
+/// `format!("{:#?}")`.
+///
+///     use ansi_term::Colour::{Red, Blue};
+///     assert_eq!("Style { fg(Red), on(Blue), bold, italic }",
+///                format!("{:?}", Red.on(Blue).bold().italic()));
+impl fmt::Debug for Style {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        if fmt.alternate() {
+            fmt.debug_struct("Style")
+               .field("foreground",    &self.foreground)
+               .field("background",    &self.background)
+               .field("blink",         &self.is_blink)
+               .field("bold",          &self.is_bold)
+               .field("dimmed",        &self.is_dimmed)
+               .field("hidden",        &self.is_hidden)
+               .field("italic",        &self.is_italic)
+               .field("reverse",       &self.is_reverse)
+               .field("strikethrough", &self.is_strikethrough)
+               .field("underline",     &self.is_underline)
+               .finish()
+        }
+        else if self.is_plain() {
+            fmt.write_str("Style {}")
+        }
+        else {
+            fmt.write_str("Style { ")?;
+
+            let mut written_anything = false;
+
+            if let Some(fg) = self.foreground {
+                if written_anything { fmt.write_str(", ")? }
+                written_anything = true;
+                write!(fmt, "fg({:?})", fg)?
+            }
+
+            if let Some(bg) = self.background {
+                if written_anything { fmt.write_str(", ")? }
+                written_anything = true;
+                write!(fmt, "on({:?})", bg)?
+            }
+
+            {
+                let mut write_flag = |name| {
+                    if written_anything { fmt.write_str(", ")? }
+                    written_anything = true;
+                    fmt.write_str(name)
+                };
+
+                if self.is_blink          { write_flag("blink")? }
+                if self.is_bold           { write_flag("bold")? }
+                if self.is_dimmed         { write_flag("dimmed")? }
+                if self.is_hidden         { write_flag("hidden")? }
+                if self.is_italic         { write_flag("italic")? }
+                if self.is_reverse        { write_flag("reverse")? }
+                if self.is_strikethrough  { write_flag("strikethrough")? }
+                if self.is_underline      { write_flag("underline")? }
+            }
+
+            write!(fmt, " }}")
+        }
+    }
+}
+
+
+#[cfg(test)]
+mod test {
+    use style::Colour::*;
+    use style::Style;
+
+    fn style() -> Style {
+        Style::new()
+    }
+
+    macro_rules! test {
+        ($name: ident: $obj: expr => $result: expr) => {
+            #[test]
+            fn $name() {
+                assert_eq!($result, format!("{:?}", $obj));
+            }
+        };
+    }
+
+    test!(empty:   style()                  => "Style {}");
+    test!(bold:    style().bold()           => "Style { bold }");
+    test!(italic:  style().italic()         => "Style { italic }");
+    test!(both:    style().bold().italic()  => "Style { bold, italic }");
+
+    test!(red:     Red.normal()                     => "Style { fg(Red) }");
+    test!(redblue: Red.normal().on(RGB(3, 2, 4))    => "Style { fg(Red), on(RGB(3, 2, 4)) }");
+
+    test!(everything:
+            Red.on(Blue).blink().bold().dimmed().hidden().italic().reverse().strikethrough().underline() =>
+            "Style { fg(Red), on(Blue), blink, bold, dimmed, hidden, italic, reverse, strikethrough, underline }");
+
+    #[test]
+    fn long_and_detailed() {
+        extern crate regex;
+        let expected_debug = "Style { fg(Blue), bold }";
+        let expected_pretty_repat = r##"(?x)
+        Style\s+\{\s+
+            foreground:\s+Some\(\s+
+                Blue,?\s+
+            \),\s+
+            background:\s+None,\s+
+            blink:\s+false,\s+
+            bold:\s+true,\s+
+            dimmed:\s+false,\s+
+            hidden:\s+false,\s+
+            italic:\s+false,\s+
+            reverse:\s+false,\s+
+            strikethrough:\s+
+            false,\s+
+            underline:\s+false,?\s+
+            \}"##;
+        let re = regex::Regex::new(expected_pretty_repat).unwrap();
+
+        let style = Blue.bold();
+        let style_fmt_debug = format!("{:?}", style);
+        let style_fmt_pretty = format!("{:#?}", style);
+        println!("style_fmt_debug:\n{}", style_fmt_debug);
+        println!("style_fmt_pretty:\n{}", style_fmt_pretty);
+
+        assert_eq!(expected_debug, style_fmt_debug);
+        assert!(re.is_match(&style_fmt_pretty));
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/difference.rs
@@ -0,0 +1,179 @@
+use super::Style;
+
+
+/// When printing out one coloured string followed by another, use one of
+/// these rules to figure out which *extra* control codes need to be sent.
+#[derive(PartialEq, Clone, Copy, Debug)]
+pub enum Difference {
+
+    /// Print out the control codes specified by this style to end up looking
+    /// like the second string's styles.
+    ExtraStyles(Style),
+
+    /// Converting between these two is impossible, so just send a reset
+    /// command and then the second string's styles.
+    Reset,
+
+    /// The before style is exactly the same as the after style, so no further
+    /// control codes need to be printed.
+    NoDifference,
+}
+
+
+impl Difference {
+
+    /// Compute the 'style difference' required to turn an existing style into
+    /// the given, second style.
+    ///
+    /// For example, to turn green text into green bold text, it's redundant
+    /// to write a reset command then a second green+bold command, instead of
+    /// just writing one bold command. This method should see that both styles
+    /// use the foreground colour green, and reduce it to a single command.
+    ///
+    /// This method returns an enum value because it's not actually always
+    /// possible to turn one style into another: for example, text could be
+    /// made bold and underlined, but you can't remove the bold property
+    /// without also removing the underline property. So when this has to
+    /// happen, this function returns None, meaning that the entire set of
+    /// styles should be reset and begun again.
+    pub fn between(first: &Style, next: &Style) -> Difference {
+        use self::Difference::*;
+
+        // XXX(Havvy): This algorithm is kind of hard to replicate without
+        // having the Plain/Foreground enum variants, so I'm just leaving
+        // it commented out for now, and defaulting to Reset.
+
+        if first == next {
+            return NoDifference;
+        }
+
+        // Cannot un-bold, so must Reset.
+        if first.is_bold && !next.is_bold {
+            return Reset;
+        }
+
+        if first.is_dimmed && !next.is_dimmed {
+            return Reset;
+        }
+
+        if first.is_italic && !next.is_italic {
+            return Reset;
+        }
+
+        // Cannot un-underline, so must Reset.
+        if first.is_underline && !next.is_underline {
+            return Reset;
+        }
+
+        if first.is_blink && !next.is_blink {
+            return Reset;
+        }
+
+        if first.is_reverse && !next.is_reverse {
+            return Reset;
+        }
+
+        if first.is_hidden && !next.is_hidden {
+            return Reset;
+        }
+
+        if first.is_strikethrough && !next.is_strikethrough {
+            return Reset;
+        }
+
+        // Cannot go from foreground to no foreground, so must Reset.
+        if first.foreground.is_some() && next.foreground.is_none() {
+            return Reset;
+        }
+
+        // Cannot go from background to no background, so must Reset.
+        if first.background.is_some() && next.background.is_none() {
+            return Reset;
+        }
+
+        let mut extra_styles = Style::default();
+
+        if first.is_bold != next.is_bold {
+            extra_styles.is_bold = true;
+        }
+
+        if first.is_dimmed != next.is_dimmed {
+            extra_styles.is_dimmed = true;
+        }
+
+        if first.is_italic != next.is_italic {
+            extra_styles.is_italic = true;
+        }
+
+        if first.is_underline != next.is_underline {
+            extra_styles.is_underline = true;
+        }
+
+        if first.is_blink != next.is_blink {
+            extra_styles.is_blink = true;
+        }
+
+        if first.is_reverse != next.is_reverse {
+            extra_styles.is_reverse = true;
+        }
+
+        if first.is_hidden != next.is_hidden {
+            extra_styles.is_hidden = true;
+        }
+
+        if first.is_strikethrough != next.is_strikethrough {
+            extra_styles.is_strikethrough = true;
+        }
+
+        if first.foreground != next.foreground {
+            extra_styles.foreground = next.foreground;
+        }
+
+        if first.background != next.background {
+            extra_styles.background = next.background;
+        }
+
+        ExtraStyles(extra_styles)
+    }
+}
+
+
+#[cfg(test)]
+mod test {
+    use super::*;
+    use super::Difference::*;
+    use style::Colour::*;
+    use style::Style;
+
+    fn style() -> Style {
+        Style::new()
+    }
+
+    macro_rules! test {
+        ($name: ident: $first: expr; $next: expr => $result: expr) => {
+            #[test]
+            fn $name() {
+                assert_eq!($result, Difference::between(&$first, &$next));
+            }
+        };
+    }
+
+    test!(nothing:    Green.normal(); Green.normal()  => NoDifference);
+    test!(uppercase:  Green.normal(); Green.bold()    => ExtraStyles(style().bold()));
+    test!(lowercase:  Green.bold();   Green.normal()  => Reset);
+    test!(nothing2:   Green.bold();   Green.bold()    => NoDifference);
+
+    test!(colour_change: Red.normal(); Blue.normal() => ExtraStyles(Blue.normal()));
+
+    test!(addition_of_blink:          style(); style().blink()          => ExtraStyles(style().blink()));
+    test!(addition_of_dimmed:         style(); style().dimmed()         => ExtraStyles(style().dimmed()));
+    test!(addition_of_hidden:         style(); style().hidden()         => ExtraStyles(style().hidden()));
+    test!(addition_of_reverse:        style(); style().reverse()        => ExtraStyles(style().reverse()));
+    test!(addition_of_strikethrough:  style(); style().strikethrough()  => ExtraStyles(style().strikethrough()));
+
+    test!(removal_of_strikethrough:   style().strikethrough(); style()  => Reset);
+    test!(removal_of_reverse:         style().reverse();       style()  => Reset);
+    test!(removal_of_hidden:          style().hidden();        style()  => Reset);
+    test!(removal_of_dimmed:          style().dimmed();        style()  => Reset);
+    test!(removal_of_blink:           style().blink();         style()  => Reset);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/display.rs
@@ -0,0 +1,296 @@
+use std::borrow::Cow;
+use std::fmt;
+use std::io;
+use std::ops::Deref;
+
+use ansi::RESET;
+use difference::Difference;
+use style::{Style, Colour};
+use write::AnyWrite;
+
+
+/// An `ANSIGenericString` includes a generic string type and a `Style` to
+/// display that string.  `ANSIString` and `ANSIByteString` are aliases for
+/// this type on `str` and `\[u8]`, respectively.
+#[derive(PartialEq, Debug)]
+pub struct ANSIGenericString<'a, S: 'a + ToOwned + ?Sized>
+where <S as ToOwned>::Owned: fmt::Debug {
+    style: Style,
+    string: Cow<'a, S>,
+}
+
+
+/// Cloning an `ANSIGenericString` will clone its underlying string.
+///
+/// # Examples
+///
+/// ```
+/// use ansi_term::ANSIString;
+///
+/// let plain_string = ANSIString::from("a plain string");
+/// let clone_string = plain_string.clone();
+/// assert_eq!(clone_string, plain_string);
+/// ```
+impl<'a, S: 'a + ToOwned + ?Sized> Clone for ANSIGenericString<'a, S>
+where <S as ToOwned>::Owned: fmt::Debug {
+    fn clone(&self) -> ANSIGenericString<'a, S> {
+        ANSIGenericString {
+            style: self.style,
+            string: self.string.clone(),
+        }
+    }
+}
+
+// You might think that the hand-written Clone impl above is the same as the
+// one that gets generated with #[derive]. But it’s not *quite* the same!
+//
+// `str` is not Clone, and the derived Clone implementation puts a Clone
+// constraint on the S type parameter (generated using --pretty=expanded):
+//
+//                  ↓_________________↓
+//     impl <'a, S: ::std::clone::Clone + 'a + ToOwned + ?Sized> ::std::clone::Clone
+//     for ANSIGenericString<'a, S> where
+//     <S as ToOwned>::Owned: fmt::Debug { ... }
+//
+// This resulted in compile errors when you tried to derive Clone on a type
+// that used it:
+//
+//     #[derive(PartialEq, Debug, Clone, Default)]
+//     pub struct TextCellContents(Vec<ANSIString<'static>>);
+//                                 ^^^^^^^^^^^^^^^^^^^^^^^^^
+//     error[E0277]: the trait `std::clone::Clone` is not implemented for `str`
+//
+// The hand-written impl above can ignore that constraint and still compile.
+
+
+
+/// An ANSI String is a string coupled with the `Style` to display it
+/// in a terminal.
+///
+/// Although not technically a string itself, it can be turned into
+/// one with the `to_string` method.
+///
+/// # Examples
+///
+/// ```
+/// use ansi_term::ANSIString;
+/// use ansi_term::Colour::Red;
+///
+/// let red_string = Red.paint("a red string");
+/// println!("{}", red_string);
+/// ```
+///
+/// ```
+/// use ansi_term::ANSIString;
+///
+/// let plain_string = ANSIString::from("a plain string");
+/// assert_eq!(&*plain_string, "a plain string");
+/// ```
+pub type ANSIString<'a> = ANSIGenericString<'a, str>;
+
+/// An `ANSIByteString` represents a formatted series of bytes.  Use
+/// `ANSIByteString` when styling text with an unknown encoding.
+pub type ANSIByteString<'a> = ANSIGenericString<'a, [u8]>;
+
+impl<'a, I, S: 'a + ToOwned + ?Sized> From<I> for ANSIGenericString<'a, S>
+where I: Into<Cow<'a, S>>,
+      <S as ToOwned>::Owned: fmt::Debug {
+    fn from(input: I) -> ANSIGenericString<'a, S> {
+        ANSIGenericString {
+            string: input.into(),
+            style:  Style::default(),
+        }
+    }
+}
+
+impl<'a, S: 'a + ToOwned + ?Sized> ANSIGenericString<'a, S>
+    where <S as ToOwned>::Owned: fmt::Debug {
+
+    /// Directly access the style
+    pub fn style_ref(&self) -> &Style {
+        &self.style
+    }
+
+    /// Directly access the style mutably
+    pub fn style_ref_mut(&mut self) -> &mut Style {
+        &mut self.style
+    }
+}
+
+impl<'a, S: 'a + ToOwned + ?Sized> Deref for ANSIGenericString<'a, S>
+where <S as ToOwned>::Owned: fmt::Debug {
+    type Target = S;
+
+    fn deref(&self) -> &S {
+        self.string.deref()
+    }
+}
+
+
+/// A set of `ANSIGenericString`s collected together, in order to be
+/// written with a minimum of control characters.
+#[derive(Debug, PartialEq)]
+pub struct ANSIGenericStrings<'a, S: 'a + ToOwned + ?Sized>
+    (pub &'a [ANSIGenericString<'a, S>])
+    where <S as ToOwned>::Owned: fmt::Debug, S: PartialEq;
+
+/// A set of `ANSIString`s collected together, in order to be written with a
+/// minimum of control characters.
+pub type ANSIStrings<'a> = ANSIGenericStrings<'a, str>;
+
+/// A function to construct an `ANSIStrings` instance.
+#[allow(non_snake_case)]
+pub fn ANSIStrings<'a>(arg: &'a [ANSIString<'a>]) -> ANSIStrings<'a> {
+    ANSIGenericStrings(arg)
+}
+
+/// A set of `ANSIByteString`s collected together, in order to be
+/// written with a minimum of control characters.
+pub type ANSIByteStrings<'a> = ANSIGenericStrings<'a, [u8]>;
+
+/// A function to construct an `ANSIByteStrings` instance.
+#[allow(non_snake_case)]
+pub fn ANSIByteStrings<'a>(arg: &'a [ANSIByteString<'a>]) -> ANSIByteStrings<'a> {
+    ANSIGenericStrings(arg)
+}
+
+
+// ---- paint functions ----
+
+impl Style {
+
+    /// Paints the given text with this colour, returning an ANSI string.
+    #[must_use]
+    pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(self, input: I) -> ANSIGenericString<'a, S>
+    where I: Into<Cow<'a, S>>,
+          <S as ToOwned>::Owned: fmt::Debug {
+        ANSIGenericString {
+            string: input.into(),
+            style:  self,
+        }
+    }
+}
+
+
+impl Colour {
+
+    /// Paints the given text with this colour, returning an ANSI string.
+    /// This is a short-cut so you don’t have to use `Blue.normal()` just
+    /// to get blue text.
+    ///
+    /// ```
+    /// use ansi_term::Colour::Blue;
+    /// println!("{}", Blue.paint("da ba dee"));
+    /// ```
+    #[must_use]
+    pub fn paint<'a, I, S: 'a + ToOwned + ?Sized>(self, input: I) -> ANSIGenericString<'a, S>
+    where I: Into<Cow<'a, S>>,
+          <S as ToOwned>::Owned: fmt::Debug {
+        ANSIGenericString {
+            string: input.into(),
+            style:  self.normal(),
+        }
+    }
+}
+
+
+// ---- writers for individual ANSI strings ----
+
+impl<'a> fmt::Display for ANSIString<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let w: &mut fmt::Write = f;
+        self.write_to_any(w)
+    }
+}
+
+impl<'a> ANSIByteString<'a> {
+    /// Write an `ANSIByteString` to an `io::Write`.  This writes the escape
+    /// sequences for the associated `Style` around the bytes.
+    pub fn write_to<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        let w: &mut io::Write = w;
+        self.write_to_any(w)
+    }
+}
+
+impl<'a, S: 'a + ToOwned + ?Sized> ANSIGenericString<'a, S>
+where <S as ToOwned>::Owned: fmt::Debug, &'a S: AsRef<[u8]> {
+    fn write_to_any<W: AnyWrite<wstr=S> + ?Sized>(&self, w: &mut W) -> Result<(), W::Error> {
+        write!(w, "{}", self.style.prefix())?;
+        w.write_str(self.string.as_ref())?;
+        write!(w, "{}", self.style.suffix())
+    }
+}
+
+
+// ---- writers for combined ANSI strings ----
+
+impl<'a> fmt::Display for ANSIStrings<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let f: &mut fmt::Write = f;
+        self.write_to_any(f)
+    }
+}
+
+impl<'a> ANSIByteStrings<'a> {
+    /// Write `ANSIByteStrings` to an `io::Write`.  This writes the minimal
+    /// escape sequences for the associated `Style`s around each set of
+    /// bytes.
+    pub fn write_to<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
+        let w: &mut io::Write = w;
+        self.write_to_any(w)
+    }
+}
+
+impl<'a, S: 'a + ToOwned + ?Sized + PartialEq> ANSIGenericStrings<'a, S>
+where <S as ToOwned>::Owned: fmt::Debug, &'a S: AsRef<[u8]> {
+    fn write_to_any<W: AnyWrite<wstr=S> + ?Sized>(&self, w: &mut W) -> Result<(), W::Error> {
+        use self::Difference::*;
+
+        let first = match self.0.first() {
+            None => return Ok(()),
+            Some(f) => f,
+        };
+
+        write!(w, "{}", first.style.prefix())?;
+        w.write_str(first.string.as_ref())?;
+
+        for window in self.0.windows(2) {
+            match Difference::between(&window[0].style, &window[1].style) {
+                ExtraStyles(style) => write!(w, "{}", style.prefix())?,
+                Reset              => write!(w, "{}{}", RESET, window[1].style.prefix())?,
+                NoDifference       => {/* Do nothing! */},
+            }
+
+            w.write_str(&window[1].string)?;
+        }
+
+        // Write the final reset string after all of the ANSIStrings have been
+        // written, *except* if the last one has no styles, because it would
+        // have already been written by this point.
+        if let Some(last) = self.0.last() {
+            if !last.style.is_plain() {
+                write!(w, "{}", RESET)?;
+            }
+        }
+
+        Ok(())
+    }
+}
+
+
+// ---- tests ----
+
+#[cfg(test)]
+mod tests {
+    pub use super::super::ANSIStrings;
+    pub use style::Style;
+    pub use style::Colour::*;
+
+    #[test]
+    fn no_control_codes_for_plain() {
+        let one = Style::default().paint("one");
+        let two = Style::default().paint("two");
+        let output = format!("{}", ANSIStrings( &[ one, two ] ));
+        assert_eq!(&*output, "onetwo");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/lib.rs
@@ -0,0 +1,271 @@
+//! This is a library for controlling colours and formatting, such as
+//! red bold text or blue underlined text, on ANSI terminals.
+//!
+//!
+//! ## Basic usage
+//!
+//! There are three main types in this crate that you need to be
+//! concerned with: [`ANSIString`], [`Style`], and [`Colour`].
+//!
+//! A `Style` holds stylistic information: foreground and background colours,
+//! whether the text should be bold, or blinking, or other properties. The
+//! [`Colour`] enum represents the available colours. And an [`ANSIString`] is a
+//! string paired with a [`Style`].
+//!
+//! [`Color`] is also available as an alias to `Colour`.
+//!
+//! To format a string, call the `paint` method on a `Style` or a `Colour`,
+//! passing in the string you want to format as the argument. For example,
+//! here’s how to get some red text:
+//!
+//! ```
+//! use ansi_term::Colour::Red;
+//!
+//! println!("This is in red: {}", Red.paint("a red string"));
+//! ```
+//!
+//! It’s important to note that the `paint` method does *not* actually return a
+//! string with the ANSI control characters surrounding it. Instead, it returns
+//! an [`ANSIString`] value that has a [`Display`] implementation that, when
+//! formatted, returns the characters. This allows strings to be printed with a
+//! minimum of [`String`] allocations being performed behind the scenes.
+//!
+//! If you *do* want to get at the escape codes, then you can convert the
+//! [`ANSIString`] to a string as you would any other `Display` value:
+//!
+//! ```
+//! use ansi_term::Colour::Red;
+//!
+//! let red_string = Red.paint("a red string").to_string();
+//! ```
+//!
+//!
+//! ## Bold, underline, background, and other styles
+//!
+//! For anything more complex than plain foreground colour changes, you need to
+//! construct `Style` values themselves, rather than beginning with a `Colour`.
+//! You can do this by chaining methods based on a new `Style`, created with
+//! [`Style::new()`]. Each method creates a new style that has that specific
+//! property set. For example:
+//!
+//! ```
+//! use ansi_term::Style;
+//!
+//! println!("How about some {} and {}?",
+//!          Style::new().bold().paint("bold"),
+//!          Style::new().underline().paint("underline"));
+//! ```
+//!
+//! For brevity, these methods have also been implemented for `Colour` values,
+//! so you can give your styles a foreground colour without having to begin with
+//! an empty `Style` value:
+//!
+//! ```
+//! use ansi_term::Colour::{Blue, Yellow};
+//!
+//! println!("Demonstrating {} and {}!",
+//!          Blue.bold().paint("blue bold"),
+//!          Yellow.underline().paint("yellow underline"));
+//!
+//! println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
+//! ```
+//!
+//! The complete list of styles you can use are: [`bold`], [`dimmed`], [`italic`],
+//! [`underline`], [`blink`], [`reverse`], [`hidden`], [`strikethrough`], and [`on`] for
+//! background colours.
+//!
+//! In some cases, you may find it easier to change the foreground on an
+//! existing `Style` rather than starting from the appropriate `Colour`.
+//! You can do this using the [`fg`] method:
+//!
+//! ```
+//! use ansi_term::Style;
+//! use ansi_term::Colour::{Blue, Cyan, Yellow};
+//!
+//! println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
+//! println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
+//! ```
+//!
+//! You can turn a `Colour` into a `Style` with the [`normal`] method.
+//! This will produce the exact same `ANSIString` as if you just used the
+//! `paint` method on the `Colour` directly, but it’s useful in certain cases:
+//! for example, you may have a method that returns `Styles`, and need to
+//! represent both the “red bold” and “red, but not bold” styles with values of
+//! the same type. The `Style` struct also has a [`Default`] implementation if you
+//! want to have a style with *nothing* set.
+//!
+//! ```
+//! use ansi_term::Style;
+//! use ansi_term::Colour::Red;
+//!
+//! Red.normal().paint("yet another red string");
+//! Style::default().paint("a completely regular string");
+//! ```
+//!
+//!
+//! ## Extended colours
+//!
+//! You can access the extended range of 256 colours by using the `Colour::Fixed`
+//! variant, which takes an argument of the colour number to use. This can be
+//! included wherever you would use a `Colour`:
+//!
+//! ```
+//! use ansi_term::Colour::Fixed;
+//!
+//! Fixed(134).paint("A sort of light purple");
+//! Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
+//! ```
+//!
+//! The first sixteen of these values are the same as the normal and bold
+//! standard colour variants. There’s nothing stopping you from using these as
+//! `Fixed` colours instead, but there’s nothing to be gained by doing so
+//! either.
+//!
+//! You can also access full 24-bit colour by using the `Colour::RGB` variant,
+//! which takes separate `u8` arguments for red, green, and blue:
+//!
+//! ```
+//! use ansi_term::Colour::RGB;
+//!
+//! RGB(70, 130, 180).paint("Steel blue");
+//! ```
+//!
+//! ## Combining successive coloured strings
+//!
+//! The benefit of writing ANSI escape codes to the terminal is that they
+//! *stack*: you do not need to end every coloured string with a reset code if
+//! the text that follows it is of a similar style. For example, if you want to
+//! have some blue text followed by some blue bold text, it’s possible to send
+//! the ANSI code for blue, followed by the ANSI code for bold, and finishing
+//! with a reset code without having to have an extra one between the two
+//! strings.
+//!
+//! This crate can optimise the ANSI codes that get printed in situations like
+//! this, making life easier for your terminal renderer. The [`ANSIStrings`]
+//! type takes a slice of several [`ANSIString`] values, and will iterate over
+//! each of them, printing only the codes for the styles that need to be updated
+//! as part of its formatting routine.
+//!
+//! The following code snippet uses this to enclose a binary number displayed in
+//! red bold text inside some red, but not bold, brackets:
+//!
+//! ```
+//! use ansi_term::Colour::Red;
+//! use ansi_term::{ANSIString, ANSIStrings};
+//!
+//! let some_value = format!("{:b}", 42);
+//! let strings: &[ANSIString<'static>] = &[
+//!     Red.paint("["),
+//!     Red.bold().paint(some_value),
+//!     Red.paint("]"),
+//! ];
+//!
+//! println!("Value: {}", ANSIStrings(strings));
+//! ```
+//!
+//! There are several things to note here. Firstly, the [`paint`] method can take
+//! *either* an owned [`String`] or a borrowed [`&str`]. Internally, an [`ANSIString`]
+//! holds a copy-on-write ([`Cow`]) string value to deal with both owned and
+//! borrowed strings at the same time. This is used here to display a `String`,
+//! the result of the `format!` call, using the same mechanism as some
+//! statically-available `&str` slices. Secondly, that the [`ANSIStrings`] value
+//! works in the same way as its singular counterpart, with a [`Display`]
+//! implementation that only performs the formatting when required.
+//!
+//! ## Byte strings
+//!
+//! This library also supports formatting `\[u8]` byte strings; this supports
+//! applications working with text in an unknown encoding.  [`Style`] and
+//! [`Colour`] support painting `\[u8]` values, resulting in an [`ANSIByteString`].
+//! This type does not implement [`Display`], as it may not contain UTF-8, but
+//! it does provide a method [`write_to`] to write the result to any value that
+//! implements [`Write`]:
+//!
+//! ```
+//! use ansi_term::Colour::Green;
+//!
+//! Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
+//! ```
+//!
+//! Similarly, the type [`ANSIByteStrings`] supports writing a list of
+//! [`ANSIByteString`] values with minimal escape sequences:
+//!
+//! ```
+//! use ansi_term::Colour::Green;
+//! use ansi_term::ANSIByteStrings;
+//!
+//! ANSIByteStrings(&[
+//!     Green.paint("user data 1\n".as_bytes()),
+//!     Green.bold().paint("user data 2\n".as_bytes()),
+//! ]).write_to(&mut std::io::stdout()).unwrap();
+//! ```
+//!
+//! [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html
+//! [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
+//! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
+//! [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
+//! [`&str`]: https://doc.rust-lang.org/std/primitive.str.html
+//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+//! [`Style`]: struct.Style.html
+//! [`Style::new()`]: struct.Style.html#method.new
+//! [`Color`]: enum.Color.html
+//! [`Colour`]: enum.Colour.html
+//! [`ANSIString`]: type.ANSIString.html
+//! [`ANSIStrings`]: type.ANSIStrings.html
+//! [`ANSIByteString`]: type.ANSIByteString.html
+//! [`ANSIByteStrings`]: type.ANSIByteStrings.html
+//! [`write_to`]: type.ANSIByteString.html#method.write_to
+//! [`paint`]: type.ANSIByteString.html#method.write_to
+//! [`normal`]: enum.Colour.html#method.normal
+//!
+//! [`bold`]: struct.Style.html#method.bold
+//! [`dimmed`]: struct.Style.html#method.dimmed
+//! [`italic`]: struct.Style.html#method.italic
+//! [`underline`]: struct.Style.html#method.underline
+//! [`blink`]: struct.Style.html#method.blink
+//! [`reverse`]: struct.Style.html#method.reverse
+//! [`hidden`]: struct.Style.html#method.hidden
+//! [`strikethrough`]: struct.Style.html#method.strikethrough
+//! [`fg`]: struct.Style.html#method.fg
+//! [`on`]: struct.Style.html#method.on
+
+#![crate_name = "ansi_term"]
+#![crate_type = "rlib"]
+#![crate_type = "dylib"]
+
+#![warn(missing_copy_implementations)]
+#![warn(missing_docs)]
+#![warn(trivial_casts, trivial_numeric_casts)]
+#![warn(unused_extern_crates, unused_qualifications)]
+
+#[cfg(target_os="windows")]
+extern crate winapi;
+#[cfg(test)]
+#[macro_use]
+extern crate doc_comment;
+
+#[cfg(test)]
+doctest!("../README.md");
+
+mod ansi;
+pub use ansi::{Prefix, Infix, Suffix};
+
+mod style;
+pub use style::{Colour, Style};
+
+/// Color is a type alias for `Colour`.
+pub use Colour as Color;
+
+mod difference;
+mod display;
+pub use display::*;
+
+mod write;
+
+mod windows;
+pub use windows::*;
+
+mod util;
+pub use util::*;
+
+mod debug;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/style.rs
@@ -0,0 +1,521 @@
+/// A style is a collection of properties that can format a string
+/// using ANSI escape codes.
+///
+/// # Examples
+///
+/// ```
+/// use ansi_term::{Style, Colour};
+///
+/// let style = Style::new().bold().on(Colour::Black);
+/// println!("{}", style.paint("Bold on black"));
+/// ```
+#[derive(PartialEq, Clone, Copy)]
+#[cfg_attr(feature = "derive_serde_style", derive(serde::Deserialize, serde::Serialize))]
+pub struct Style {
+
+    /// The style's foreground colour, if it has one.
+    pub foreground: Option<Colour>,
+
+    /// The style's background colour, if it has one.
+    pub background: Option<Colour>,
+
+    /// Whether this style is bold.
+    pub is_bold: bool,
+
+    /// Whether this style is dimmed.
+    pub is_dimmed: bool,
+
+    /// Whether this style is italic.
+    pub is_italic: bool,
+
+    /// Whether this style is underlined.
+    pub is_underline: bool,
+
+    /// Whether this style is blinking.
+    pub is_blink: bool,
+
+    /// Whether this style has reverse colours.
+    pub is_reverse: bool,
+
+    /// Whether this style is hidden.
+    pub is_hidden: bool,
+
+    /// Whether this style is struckthrough.
+    pub is_strikethrough: bool
+}
+
+impl Style {
+
+    /// Creates a new Style with no properties set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new();
+    /// println!("{}", style.paint("hi"));
+    /// ```
+    pub fn new() -> Style {
+        Style::default()
+    }
+
+    /// Returns a `Style` with the bold property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().bold();
+    /// println!("{}", style.paint("hey"));
+    /// ```
+    pub fn bold(&self) -> Style {
+        Style { is_bold: true, .. *self }
+    }
+
+    /// Returns a `Style` with the dimmed property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().dimmed();
+    /// println!("{}", style.paint("sup"));
+    /// ```
+    pub fn dimmed(&self) -> Style {
+        Style { is_dimmed: true, .. *self }
+    }
+
+    /// Returns a `Style` with the italic property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().italic();
+    /// println!("{}", style.paint("greetings"));
+    /// ```
+    pub fn italic(&self) -> Style {
+        Style { is_italic: true, .. *self }
+    }
+
+    /// Returns a `Style` with the underline property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().underline();
+    /// println!("{}", style.paint("salutations"));
+    /// ```
+    pub fn underline(&self) -> Style {
+        Style { is_underline: true, .. *self }
+    }
+
+    /// Returns a `Style` with the blink property set.
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().blink();
+    /// println!("{}", style.paint("wazzup"));
+    /// ```
+    pub fn blink(&self) -> Style {
+        Style { is_blink: true, .. *self }
+    }
+
+    /// Returns a `Style` with the reverse property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().reverse();
+    /// println!("{}", style.paint("aloha"));
+    /// ```
+    pub fn reverse(&self) -> Style {
+        Style { is_reverse: true, .. *self }
+    }
+
+    /// Returns a `Style` with the hidden property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().hidden();
+    /// println!("{}", style.paint("ahoy"));
+    /// ```
+    pub fn hidden(&self) -> Style {
+        Style { is_hidden: true, .. *self }
+    }
+
+    /// Returns a `Style` with the strikethrough property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// let style = Style::new().strikethrough();
+    /// println!("{}", style.paint("yo"));
+    /// ```
+    pub fn strikethrough(&self) -> Style {
+        Style { is_strikethrough: true, .. *self }
+    }
+
+    /// Returns a `Style` with the foreground colour property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour};
+    ///
+    /// let style = Style::new().fg(Colour::Yellow);
+    /// println!("{}", style.paint("hi"));
+    /// ```
+    pub fn fg(&self, foreground: Colour) -> Style {
+        Style { foreground: Some(foreground), .. *self }
+    }
+
+    /// Returns a `Style` with the background colour property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour};
+    ///
+    /// let style = Style::new().on(Colour::Blue);
+    /// println!("{}", style.paint("eyyyy"));
+    /// ```
+    pub fn on(&self, background: Colour) -> Style {
+        Style { background: Some(background), .. *self }
+    }
+
+    /// Return true if this `Style` has no actual styles, and can be written
+    /// without any control characters.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    ///
+    /// assert_eq!(true,  Style::default().is_plain());
+    /// assert_eq!(false, Style::default().bold().is_plain());
+    /// ```
+    pub fn is_plain(self) -> bool {
+        self == Style::default()
+    }
+}
+
+impl Default for Style {
+
+    /// Returns a style with *no* properties set. Formatting text using this
+    /// style returns the exact same text.
+    ///
+    /// ```
+    /// use ansi_term::Style;
+    /// assert_eq!(None,  Style::default().foreground);
+    /// assert_eq!(None,  Style::default().background);
+    /// assert_eq!(false, Style::default().is_bold);
+    /// assert_eq!("txt", Style::default().paint("txt").to_string());
+    /// ```
+    fn default() -> Style {
+        Style {
+            foreground: None,
+            background: None,
+            is_bold: false,
+            is_dimmed: false,
+            is_italic: false,
+            is_underline: false,
+            is_blink: false,
+            is_reverse: false,
+            is_hidden: false,
+            is_strikethrough: false,
+        }
+    }
+}
+
+
+// ---- colours ----
+
+/// A colour is one specific type of ANSI escape code, and can refer
+/// to either the foreground or background colour.
+///
+/// These use the standard numeric sequences.
+/// See <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html>
+#[derive(PartialEq, Clone, Copy, Debug)]
+#[cfg_attr(feature = "derive_serde_style", derive(serde::Deserialize, serde::Serialize))]
+pub enum Colour {
+
+    /// Colour #0 (foreground code `30`, background code `40`).
+    ///
+    /// This is not necessarily the background colour, and using it as one may
+    /// render the text hard to read on terminals with dark backgrounds.
+    Black,
+
+    /// Colour #1 (foreground code `31`, background code `41`).
+    Red,
+
+    /// Colour #2 (foreground code `32`, background code `42`).
+    Green,
+
+    /// Colour #3 (foreground code `33`, background code `43`).
+    Yellow,
+
+    /// Colour #4 (foreground code `34`, background code `44`).
+    Blue,
+
+    /// Colour #5 (foreground code `35`, background code `45`).
+    Purple,
+
+    /// Colour #6 (foreground code `36`, background code `46`).
+    Cyan,
+
+    /// Colour #7 (foreground code `37`, background code `47`).
+    ///
+    /// As above, this is not necessarily the foreground colour, and may be
+    /// hard to read on terminals with light backgrounds.
+    White,
+
+    /// A colour number from 0 to 255, for use in 256-colour terminal
+    /// environments.
+    ///
+    /// - Colours 0 to 7 are the `Black` to `White` variants respectively.
+    ///   These colours can usually be changed in the terminal emulator.
+    /// - Colours 8 to 15 are brighter versions of the eight colours above.
+    ///   These can also usually be changed in the terminal emulator, or it
+    ///   could be configured to use the original colours and show the text in
+    ///   bold instead. It varies depending on the program.
+    /// - Colours 16 to 231 contain several palettes of bright colours,
+    ///   arranged in six squares measuring six by six each.
+    /// - Colours 232 to 255 are shades of grey from black to white.
+    ///
+    /// It might make more sense to look at a [colour chart][cc].
+    ///
+    /// [cc]: https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg
+    Fixed(u8),
+
+    /// A 24-bit RGB color, as specified by ISO-8613-3.
+    RGB(u8, u8, u8),
+}
+
+
+impl Colour {
+
+    /// Returns a `Style` with the foreground colour set to this colour.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Red.normal();
+    /// println!("{}", style.paint("hi"));
+    /// ```
+    pub fn normal(self) -> Style {
+        Style { foreground: Some(self), .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// bold property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Green.bold();
+    /// println!("{}", style.paint("hey"));
+    /// ```
+    pub fn bold(self) -> Style {
+        Style { foreground: Some(self), is_bold: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// dimmed property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Yellow.dimmed();
+    /// println!("{}", style.paint("sup"));
+    /// ```
+    pub fn dimmed(self) -> Style {
+        Style { foreground: Some(self), is_dimmed: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// italic property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Blue.italic();
+    /// println!("{}", style.paint("greetings"));
+    /// ```
+    pub fn italic(self) -> Style {
+        Style { foreground: Some(self), is_italic: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// underline property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Purple.underline();
+    /// println!("{}", style.paint("salutations"));
+    /// ```
+    pub fn underline(self) -> Style {
+        Style { foreground: Some(self), is_underline: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// blink property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Cyan.blink();
+    /// println!("{}", style.paint("wazzup"));
+    /// ```
+    pub fn blink(self) -> Style {
+        Style { foreground: Some(self), is_blink: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// reverse property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Black.reverse();
+    /// println!("{}", style.paint("aloha"));
+    /// ```
+    pub fn reverse(self) -> Style {
+        Style { foreground: Some(self), is_reverse: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// hidden property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::White.hidden();
+    /// println!("{}", style.paint("ahoy"));
+    /// ```
+    pub fn hidden(self) -> Style {
+        Style { foreground: Some(self), is_hidden: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// strikethrough property set.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::Fixed(244).strikethrough();
+    /// println!("{}", style.paint("yo"));
+    /// ```
+    pub fn strikethrough(self) -> Style {
+        Style { foreground: Some(self), is_strikethrough: true, .. Style::default() }
+    }
+
+    /// Returns a `Style` with the foreground colour set to this colour and the
+    /// background colour property set to the given colour.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use ansi_term::Colour;
+    ///
+    /// let style = Colour::RGB(31, 31, 31).on(Colour::White);
+    /// println!("{}", style.paint("eyyyy"));
+    /// ```
+    pub fn on(self, background: Colour) -> Style {
+        Style { foreground: Some(self), background: Some(background), .. Style::default() }
+    }
+}
+
+impl From<Colour> for Style {
+
+    /// You can turn a `Colour` into a `Style` with the foreground colour set
+    /// with the `From` trait.
+    ///
+    /// ```
+    /// use ansi_term::{Style, Colour};
+    /// let green_foreground = Style::default().fg(Colour::Green);
+    /// assert_eq!(green_foreground, Colour::Green.normal());
+    /// assert_eq!(green_foreground, Colour::Green.into());
+    /// assert_eq!(green_foreground, Style::from(Colour::Green));
+    /// ```
+    fn from(colour: Colour) -> Style {
+        colour.normal()
+    }
+}
+
+#[cfg(test)]
+#[cfg(feature = "derive_serde_style")]
+mod serde_json_tests {
+    use super::{Style, Colour};
+
+    #[test]
+    fn colour_serialization() {
+
+        let colours = &[
+            Colour::Red,
+            Colour::Blue,
+            Colour::RGB(123, 123, 123),
+            Colour::Fixed(255),
+        ];
+
+        assert_eq!(serde_json::to_string(&colours).unwrap(), String::from("[\"Red\",\"Blue\",{\"RGB\":[123,123,123]},{\"Fixed\":255}]"));
+    }
+
+    #[test]
+    fn colour_deserialization() {
+        let colours = &[
+            Colour::Red,
+            Colour::Blue,
+            Colour::RGB(123, 123, 123),
+            Colour::Fixed(255),
+        ];
+
+        for colour in colours.into_iter() {
+            let serialized = serde_json::to_string(&colour).unwrap();
+            let deserialized: Colour = serde_json::from_str(&serialized).unwrap();
+
+            assert_eq!(colour, &deserialized);
+        }
+    }
+
+    #[test]
+    fn style_serialization() {
+        let style = Style::default();
+
+        assert_eq!(serde_json::to_string(&style).unwrap(), "{\"foreground\":null,\"background\":null,\"is_bold\":false,\"is_dimmed\":false,\"is_italic\":false,\"is_underline\":false,\"is_blink\":false,\"is_reverse\":false,\"is_hidden\":false,\"is_strikethrough\":false}".to_string());
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/util.rs
@@ -0,0 +1,81 @@
+use display::*;
+use std::ops::Deref;
+
+/// Return a substring of the given ANSIStrings sequence, while keeping the formatting.
+pub fn sub_string<'a>(start: usize, len: usize, strs: &ANSIStrings<'a>) -> Vec<ANSIString<'static>> {
+    let mut vec = Vec::new();
+    let mut pos = start;
+    let mut len_rem = len;
+
+    for i in strs.0.iter() {
+        let fragment = i.deref();
+        let frag_len = fragment.len();
+        if pos >= frag_len {
+            pos -= frag_len;
+            continue;
+        }
+        if len_rem <= 0 {
+            break;
+        }
+
+        let end = pos + len_rem;
+        let pos_end = if end >= frag_len { frag_len } else { end };
+
+        vec.push(i.style_ref().paint(String::from(&fragment[pos..pos_end])));
+
+        if end <= frag_len {
+            break;
+        }
+
+        len_rem -= pos_end - pos;
+        pos = 0;
+    }
+
+    vec
+}
+
+/// Return a concatenated copy of `strs` without the formatting, as an allocated `String`.
+pub fn unstyle(strs: &ANSIStrings) -> String {
+    let mut s = String::new();
+
+    for i in strs.0.iter() {
+        s += &i.deref();
+    }
+
+    s
+}
+
+/// Return the unstyled length of ANSIStrings. This is equaivalent to `unstyle(strs).len()`.
+pub fn unstyled_len(strs: &ANSIStrings) -> usize {
+    let mut l = 0;
+    for i in strs.0.iter() {
+        l += i.deref().len();
+    }
+    l
+}
+
+#[cfg(test)]
+mod test {
+    use Colour::*;
+    use display::*;
+    use super::*;
+
+    #[test]
+    fn test() {
+        let l = [
+            Black.paint("first"),
+            Red.paint("-second"),
+            White.paint("-third"),
+        ];
+        let a = ANSIStrings(&l);
+        assert_eq!(unstyle(&a), "first-second-third");
+        assert_eq!(unstyled_len(&a), 18);
+
+        let l2 = [
+            Black.paint("st"),
+            Red.paint("-second"),
+            White.paint("-t"),
+        ];
+        assert_eq!(sub_string(3, 11, &a).as_slice(), &l2);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/windows.rs
@@ -0,0 +1,61 @@
+/// Enables ANSI code support on Windows 10.
+///
+/// This uses Windows API calls to alter the properties of the console that
+/// the program is running in.
+///
+/// https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
+///
+/// Returns a `Result` with the Windows error code if unsuccessful.
+#[cfg(windows)]
+pub fn enable_ansi_support() -> Result<(), u32> {
+    // ref: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#EXAMPLE_OF_ENABLING_VIRTUAL_TERMINAL_PROCESSING @@ https://archive.is/L7wRJ#76%
+
+    use std::ffi::OsStr;
+    use std::iter::once;
+    use std::os::windows::ffi::OsStrExt;
+    use std::ptr::null_mut;
+    use winapi::um::consoleapi::{GetConsoleMode, SetConsoleMode};
+    use winapi::um::errhandlingapi::GetLastError;
+    use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
+    use winapi::um::handleapi::INVALID_HANDLE_VALUE;
+    use winapi::um::winnt::{FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE};
+
+    const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
+
+    unsafe {
+        // ref: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
+        // Using `CreateFileW("CONOUT$", ...)` to retrieve the console handle works correctly even if STDOUT and/or STDERR are redirected
+        let console_out_name: Vec<u16> = OsStr::new("CONOUT$").encode_wide().chain(once(0)).collect();
+        let console_handle = CreateFileW(
+            console_out_name.as_ptr(),
+            GENERIC_READ | GENERIC_WRITE,
+            FILE_SHARE_WRITE,
+            null_mut(),
+            OPEN_EXISTING,
+            0,
+            null_mut(),
+        );
+        if console_handle == INVALID_HANDLE_VALUE
+        {
+            return Err(GetLastError());
+        }
+
+        // ref: https://docs.microsoft.com/en-us/windows/console/getconsolemode
+        let mut console_mode: u32 = 0;
+        if 0 == GetConsoleMode(console_handle, &mut console_mode)
+        {
+            return Err(GetLastError());
+        }
+
+        // VT processing not already enabled?
+        if console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0 {
+            // https://docs.microsoft.com/en-us/windows/console/setconsolemode
+            if 0 == SetConsoleMode(console_handle, console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
+            {
+                return Err(GetLastError());
+            }
+        }
+    }
+
+    return Ok(());
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ansi_term/src/write.rs
@@ -0,0 +1,40 @@
+use std::fmt;
+use std::io;
+
+
+pub trait AnyWrite {
+    type wstr: ?Sized;
+    type Error;
+
+    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error>;
+
+    fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error>;
+}
+
+
+impl<'a> AnyWrite for fmt::Write + 'a {
+    type wstr = str;
+    type Error = fmt::Error;
+
+    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error> {
+        fmt::Write::write_fmt(self, fmt)
+    }
+
+    fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error> {
+        fmt::Write::write_str(self, s)
+    }
+}
+
+
+impl<'a> AnyWrite for io::Write + 'a {
+    type wstr = [u8];
+    type Error = io::Error;
+
+    fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Self::Error> {
+        io::Write::write_fmt(self, fmt)
+    }
+
+    fn write_str(&mut self, s: &Self::wstr) -> Result<(), Self::Error> {
+        io::Write::write_all(self, s)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"CHANGELOG.md":"70db121262d72acc472ad1a90b78c42de570820e65b566c6b9339b62e636d572","Cargo.lock":"6868f02a96413bcba37a06f01c6bf87e6331dea9461681a47a561cec6acd2546","Cargo.toml":"3af88a07af6a4adb84373fc3cd4920884b0b12b338cdb55ef598fd512ee1a790","LICENSE":"99fa95ba4e4cdaf71c27d73260ea069fc4515b3d02fde3020c5b562280006cbc","README.md":"e559a69c0b2bd20bffcede64fd548df6c671b0d1504613c5e3e5d884d759caea","examples/atty.rs":"1551387a71474d9ac1b5153231f884e9e05213badcfaa3494ad2cb7ea958374a","rustfmt.toml":"8e6ea1bcb79c505490034020c98e9b472f4ac4113f245bae90f5e1217b1ec65a","src/lib.rs":"d5abf6a54e8c496c486572bdc91eef10480f6ad126c4287f039df5feff7a9bbb"},"package":"d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/CHANGELOG.md
@@ -0,0 +1,73 @@
+# 0.2.14
+
+* add support for [RustyHermit](https://github.com/hermitcore/libhermit-rs), a Rust-based unikernel [#41](https://github.com/softprops/atty/pull/41)
+
+# 0.2.13
+
+* support older versions of rust that do now support 2018 edition
+
+# 0.2.12
+
+* Redox is now in the unix family so redox cfg is no longer needed [#35](https://github.com/softprops/atty/pull/35)
+
+# 0.2.11
+
+* fix msys detection with `winapi@0.3.5` [#28](https://github.com/softprops/atty/pull/28)
+
+# 0.2.10
+
+* fix wasm regression [#27](https://github.com/softprops/atty/pull/27)
+
+# 0.2.9
+
+* Fix fix pty detection [#25](https://github.com/softprops/atty/pull/25)
+
+# 0.2.8
+
+* Fix an inverted condition on MinGW [#22](https://github.com/softprops/atty/pull/22)
+
+# 0.2.7
+
+* Change `||` to `&&` for whether MSYS is a tty [#24](https://github.com/softprops/atty/pull/24/)
+
+# 0.2.6
+
+* updated winapi dependency to [0.3](https://retep998.github.io/blog/winapi-0.3/) [#18](https://github.com/softprops/atty/pull/18)
+
+# 0.2.5
+
+* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17)
+
+# 0.2.4
+
+* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17)
+
+# 0.2.3
+
+* added support for Redox OS [#14](https://github.com/softprops/atty/pull/14)
+
+# 0.2.2
+
+* use target specific dependencies [#11](https://github.com/softprops/atty/pull/11)
+* Add tty detection for MSYS terminals [#12](https://github.com/softprops/atty/pull/12)
+
+# 0.2.1
+
+* fix windows bug
+
+# 0.2.0
+
+* support for various stream types
+
+# 0.1.2
+
+* windows support (with automated testing)
+* automated code coverage
+
+# 0.1.1
+
+* bumped libc dep from `0.1` to `0.2`
+
+# 0.1.0
+
+* initial release
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/Cargo.lock
@@ -0,0 +1,49 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "atty"
+version = "0.2.14"
+dependencies = [
+ "hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
+ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)",
+ "winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "winapi"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[metadata]
+"checksum hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eff2656d88f158ce120947499e971d743c05dbcbed62e5bd2f38f1698bbc3772"
+"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558"
+"checksum winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "04e3bd221fcbe8a271359c04f21a76db7d0c6028862d1bb5512d85e1e2eb5bb3"
+"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/Cargo.toml
@@ -0,0 +1,34 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "atty"
+version = "0.2.14"
+authors = ["softprops <d.tangren@gmail.com>"]
+exclude = ["/.travis.yml", "/appveyor.yml"]
+description = "A simple interface for querying atty"
+homepage = "https://github.com/softprops/atty"
+documentation = "http://softprops.github.io/atty"
+readme = "README.md"
+keywords = ["terminal", "tty", "isatty"]
+license = "MIT"
+repository = "https://github.com/softprops/atty"
+[target."cfg(target_os = \"hermit\")".dependencies.hermit-abi]
+version = "0.1.6"
+[target."cfg(unix)".dependencies.libc]
+version = "0.2"
+default-features = false
+[target."cfg(windows)".dependencies.winapi]
+version = "0.3"
+features = ["consoleapi", "processenv", "minwinbase", "minwindef", "winbase"]
+[badges.travis-ci]
+repository = "softprops/atty"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2015-2019 Doug Tangren
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/README.md
@@ -0,0 +1,74 @@
+# atty
+
+[![Build Status](https://travis-ci.org/softprops/atty.svg?branch=master)](https://travis-ci.org/softprops/atty) [![Build status](https://ci.appveyor.com/api/projects/status/geggrsnsjsuse8cv?svg=true)](https://ci.appveyor.com/project/softprops/atty) [![Coverage Status](https://coveralls.io/repos/softprops/atty/badge.svg?branch=master&service=github)](https://coveralls.io/github/softprops/atty?branch=master) [![crates.io](https://img.shields.io/crates/v/atty.svg)](https://crates.io/crates/atty) [![Released API docs](https://docs.rs/atty/badge.svg)](http://docs.rs/atty) [![Master API docs](https://img.shields.io/badge/docs-master-green.svg)](https://softprops.github.io/atty)
+
+> are you or are you not a tty?
+
+
+## install
+
+Add the following to your `Cargo.toml`
+
+```toml
+[dependencies]
+atty = "0.2"
+```
+
+## usage
+
+```rust
+use atty::Stream;
+
+fn main() {
+  if atty::is(Stream::Stdout) {
+    println!("I'm a terminal");
+  } else {
+    println!("I'm not");
+  }
+}
+```
+
+## testing
+
+This library has been unit tested on both unix and windows platforms (via appveyor).
+
+
+A simple example program is provided in this repo to test various tty's. By default.
+
+It prints
+
+```bash
+$ cargo run --example atty
+stdout? true
+stderr? true
+stdin? true
+```
+
+To test std in, pipe some text to the program
+
+```bash
+$ echo "test" | cargo run --example atty
+stdout? true
+stderr? true
+stdin? false
+```
+
+To test std out, pipe the program to something
+
+```bash
+$ cargo run --example atty | grep std
+stdout? false
+stderr? true
+stdin? true
+```
+
+To test std err, pipe the program to something redirecting std err
+
+```bash
+$ cargo run --example atty 2>&1 | grep std
+stdout? false
+stderr? false
+stdin? true
+```
+
+Doug Tangren (softprops) 2015-2019
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/examples/atty.rs
@@ -0,0 +1,9 @@
+extern crate atty;
+
+use atty::{is, Stream};
+
+fn main() {
+    println!("stdout? {}", is(Stream::Stdout));
+    println!("stderr? {}", is(Stream::Stderr));
+    println!("stdin? {}", is(Stream::Stdin));
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/rustfmt.toml
@@ -0,0 +1,4 @@
+# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#fn_args_layout
+fn_args_layout = "Vertical"
+# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#merge_imports
+merge_imports = true
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/atty/src/lib.rs
@@ -0,0 +1,210 @@
+//! atty is a simple utility that answers one question
+//! > is this a tty?
+//!
+//! usage is just as simple
+//!
+//! ```
+//! if atty::is(atty::Stream::Stdout) {
+//!   println!("i'm a tty")
+//! }
+//! ```
+//!
+//! ```
+//! if atty::isnt(atty::Stream::Stdout) {
+//!   println!("i'm not a tty")
+//! }
+//! ```
+
+#![cfg_attr(unix, no_std)]
+
+#[cfg(unix)]
+extern crate libc;
+#[cfg(windows)]
+extern crate winapi;
+
+#[cfg(windows)]
+use winapi::shared::minwindef::DWORD;
+#[cfg(windows)]
+use winapi::shared::ntdef::WCHAR;
+
+/// possible stream sources
+#[derive(Clone, Copy, Debug)]
+pub enum Stream {
+    Stdout,
+    Stderr,
+    Stdin,
+}
+
+/// returns true if this is a tty
+#[cfg(all(unix, not(target_arch = "wasm32")))]
+pub fn is(stream: Stream) -> bool {
+    extern crate libc;
+
+    let fd = match stream {
+        Stream::Stdout => libc::STDOUT_FILENO,
+        Stream::Stderr => libc::STDERR_FILENO,
+        Stream::Stdin => libc::STDIN_FILENO,
+    };
+    unsafe { libc::isatty(fd) != 0 }
+}
+
+/// returns true if this is a tty
+#[cfg(target_os = "hermit")]
+pub fn is(stream: Stream) -> bool {
+    extern crate hermit_abi;
+
+    let fd = match stream {
+        Stream::Stdout => hermit_abi::STDOUT_FILENO,
+        Stream::Stderr => hermit_abi::STDERR_FILENO,
+        Stream::Stdin => hermit_abi::STDIN_FILENO,
+    };
+    hermit_abi::isatty(fd)
+}
+
+/// returns true if this is a tty
+#[cfg(windows)]
+pub fn is(stream: Stream) -> bool {
+    use winapi::um::winbase::{
+        STD_ERROR_HANDLE as STD_ERROR, STD_INPUT_HANDLE as STD_INPUT,
+        STD_OUTPUT_HANDLE as STD_OUTPUT,
+    };
+
+    let (fd, others) = match stream {
+        Stream::Stdin => (STD_INPUT, [STD_ERROR, STD_OUTPUT]),
+        Stream::Stderr => (STD_ERROR, [STD_INPUT, STD_OUTPUT]),
+        Stream::Stdout => (STD_OUTPUT, [STD_INPUT, STD_ERROR]),
+    };
+    if unsafe { console_on_any(&[fd]) } {
+        // False positives aren't possible. If we got a console then
+        // we definitely have a tty on stdin.
+        return true;
+    }
+
+    // At this point, we *could* have a false negative. We can determine that
+    // this is true negative if we can detect the presence of a console on
+    // any of the other streams. If another stream has a console, then we know
+    // we're in a Windows console and can therefore trust the negative.
+    if unsafe { console_on_any(&others) } {
+        return false;
+    }
+
+    // Otherwise, we fall back to a very strange msys hack to see if we can
+    // sneakily detect the presence of a tty.
+    unsafe { msys_tty_on(fd) }
+}
+
+/// returns true if this is _not_ a tty
+pub fn isnt(stream: Stream) -> bool {
+    !is(stream)
+}
+
+/// Returns true if any of the given fds are on a console.
+#[cfg(windows)]
+unsafe fn console_on_any(fds: &[DWORD]) -> bool {
+    use winapi::um::{consoleapi::GetConsoleMode, processenv::GetStdHandle};
+
+    for &fd in fds {
+        let mut out = 0;
+        let handle = GetStdHandle(fd);
+        if GetConsoleMode(handle, &mut out) != 0 {
+            return true;
+        }
+    }
+    false
+}
+
+/// Returns true if there is an MSYS tty on the given handle.
+#[cfg(windows)]
+unsafe fn msys_tty_on(fd: DWORD) -> bool {
+    use std::{mem, slice};
+
+    use winapi::{
+        ctypes::c_void,
+        shared::minwindef::MAX_PATH,
+        um::{
+            fileapi::FILE_NAME_INFO, minwinbase::FileNameInfo, processenv::GetStdHandle,
+            winbase::GetFileInformationByHandleEx,
+        },
+    };
+
+    let size = mem::size_of::<FILE_NAME_INFO>();
+    let mut name_info_bytes = vec![0u8; size + MAX_PATH * mem::size_of::<WCHAR>()];
+    let res = GetFileInformationByHandleEx(
+        GetStdHandle(fd),
+        FileNameInfo,
+        &mut *name_info_bytes as *mut _ as *mut c_void,
+        name_info_bytes.len() as u32,
+    );
+    if res == 0 {
+        return false;
+    }
+    let name_info: &FILE_NAME_INFO = &*(name_info_bytes.as_ptr() as *const FILE_NAME_INFO);
+    let s = slice::from_raw_parts(
+        name_info.FileName.as_ptr(),
+        name_info.FileNameLength as usize / 2,
+    );
+    let name = String::from_utf16_lossy(s);
+    // This checks whether 'pty' exists in the file name, which indicates that
+    // a pseudo-terminal is attached. To mitigate against false positives
+    // (e.g., an actual file name that contains 'pty'), we also require that
+    // either the strings 'msys-' or 'cygwin-' are in the file name as well.)
+    let is_msys = name.contains("msys-") || name.contains("cygwin-");
+    let is_pty = name.contains("-pty");
+    is_msys && is_pty
+}
+
+/// returns true if this is a tty
+#[cfg(target_arch = "wasm32")]
+pub fn is(_stream: Stream) -> bool {
+    false
+}
+
+#[cfg(test)]
+mod tests {
+    use super::{is, Stream};
+
+    #[test]
+    #[cfg(windows)]
+    fn is_err() {
+        // appveyor pipes its output
+        assert!(!is(Stream::Stderr))
+    }
+
+    #[test]
+    #[cfg(windows)]
+    fn is_out() {
+        // appveyor pipes its output
+        assert!(!is(Stream::Stdout))
+    }
+
+    #[test]
+    #[cfg(windows)]
+    fn is_in() {
+        assert!(is(Stream::Stdin))
+    }
+
+    #[test]
+    #[cfg(unix)]
+    fn is_err() {
+        assert!(is(Stream::Stderr))
+    }
+
+    #[test]
+    #[cfg(unix)]
+    fn is_out() {
+        assert!(is(Stream::Stdout))
+    }
+
+    #[test]
+    #[cfg(target_os = "macos")]
+    fn is_in() {
+        // macos on travis seems to pipe its input
+        assert!(is(Stream::Stdin))
+    }
+
+    #[test]
+    #[cfg(all(not(target_os = "macos"), unix))]
+    fn is_in() {
+        assert!(is(Stream::Stdin))
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"CHANGELOG.md":"623d43f94b419a5e79f7bc103d4de47f60daf7803d49e63058ba9e24f8f8c6cc","CONTRIBUTORS.md":"9b0d3eee116dda23705b732c19b777ebb2b998a6e4554027ae3f61715376b4bc","Cargo.toml":"e7d0b7019b86f3a6901416714ac94702f666c8de0bf197d717abb8a2f86e7e6a","LICENSE-MIT":"6725d1437fc6c77301f2ff0e7d52914cf4f9509213e1078dc77d9356dbe6eac5","README.md":"6a836ddd7544962b33ae76b03e0f550ace4e4c967aee23e24ce14fc31e58e885","SPONSORS.md":"640b56e535db654d7bf14b1fe63bc837dcfde37a85f14eb4f404663fe1b72af9","clap-test.rs":"b5ca72dedfe1e71c250c42a01a52a3f5f9ea2bb14d9fe09093e73b71880f79fd","justfile":"9ee43d53fda234044fee4edd1ecdac9f19864c7f00a4ea5cb2b6a8a0287c93e3","src/app/help.rs":"037094b39990115fdac105f550c2f6eb1cbbfc8ff8f65b6ca34c65634902c3ab","src/app/meta.rs":"d15a4118e9de562cacf9d2063f1f491e3c3ce4092b4e8ea5d4d92e2631ca247b","src/app/mod.rs":"0aee709776d1be519a5587258b433ba0b54d5ebda14bb0544ce32c0505d5dcec","src/app/parser.rs":"83917c7e8f39f1e5d1807095f0856be3c3450aa88a6abb8e4d7c1d1fe9dbb2c4","src/app/settings.rs":"b29e3f90c282a27865b27674bb5b0a4def2966646f0e70b4f78e587c9649e379","src/app/usage.rs":"65f6b5d6f068a8ded0e78faf59575202bc8729a079e9806d0afeba87fa6ba9fc","src/app/validator.rs":"3124617cbaf959466241f4ba1a9837c1184a7a06325c5cbe3d613a7786febd4e","src/args/any_arg.rs":"5a34d363ce5d74e1829c4feb2a8044e0d3c31d5af2094933cf61d6579e548ecf","src/args/arg.rs":"e9ad38d43bef8d36e96ae6edb2dc6ea2258c6a7287f6479aad5a21b8ed197fd6","src/args/arg_builder/base.rs":"989952f8b827bd60db85bebb09b23de4d3e1296cc1f195e9da447b154f10cd09","src/args/arg_builder/flag.rs":"3c90fc16079b3f921c9e9b3a9607467eb5afddfdc8da53e9528987a43d883e36","src/args/arg_builder/mod.rs":"31844ad665171a2d49d551debd3d1a20e8a77dd74d02f9ff6fc22f63b019db02","src/args/arg_builder/option.rs":"d882e07dc1d6a77aae06fc5dad5502b7a4c1fc6e8124e6ab08b6ec037cb08b85","src/args/arg_builder/positional.rs":"fd6720931b9622a6d6576494dfbe67ae40416b6083d0302c1a0d9e9a86bb2d3d","src/args/arg_builder/switched.rs":"bc4c5acb77741562c4258b643a3dddd6b22e5b1874b71919d333c7d1e03e0ccb","src/args/arg_builder/valued.rs":"5f19d8e84e3d0bd3aee4b6fbb124206a6ab234492fe2ffc7279043e983522765","src/args/arg_matcher.rs":"a3cbe567cab3817c3ec7e37eb36641c9b9af1056b0002748b99a3ce255d65fd5","src/args/arg_matches.rs":"2058c1b0276db9d345b66d0531159fa05677ef865823ac8ec9831473359b64a8","src/args/group.rs":"6f08b7ebcbe2968a6d8462ab7c32dfc36c6b862a00853e9dc13af827196bc923","src/args/macros.rs":"4686d5929c760d2dace4110e96179d6aa7e43d7f911938199b07cb5728dc319b","src/args/matched_arg.rs":"28754509ea5493b66b4a5648d977f7cd9b379507b6eff89d76931be91509e6fe","src/args/mod.rs":"66cc0bb745fafd6387db72caa5ac414514990a07421270bfb5d8aff77ff01600","src/args/settings.rs":"f52313e363c1a928d65a52fbb7abb04b2ae00bd1e319fe267cf809363618fce8","src/args/subcommand.rs":"518418bb276c9758e3f82fc73341d69a242836ce163cd2ef6198075acf6594ba","src/completions/bash.rs":"d086d1e477ed14702650e2e7e0d2d33ba0a977f0a5c9f4e5d3cdb23b6ae5529f","src/completions/elvish.rs":"91e6f6685c258bfa4cdd4d428fa84ec9b59b2133e3d75f0e88072a37454430dc","src/completions/fish.rs":"3a828f824bde8dbe6bfa2d9ea52259b8b534bc547e9d96aec46f56e430b118e4","src/completions/macros.rs":"fd449b9d5fc6c591feb419d209f72cddfff0dd0345a8ec9787c361be6e5275f8","src/completions/mod.rs":"96b1115d6973b68dbbb1b50929f281e4ba9943995bc69dbb0ef08311d623ae33","src/completions/powershell.rs":"738a642a074c74ea28af66de3973b132de97587192c996bed436d54f6dfb6179","src/completions/shell.rs":"f6e132d8ea06ee30435c977f0040a6eb804bfe7a802181041dee8a4f69f64bd1","src/completions/zsh.rs":"0a06b25521714c70bfb943e8a11be62b8010ddb8676a426c2b30b00daccef9fa","src/errors.rs":"7c755e43fa743a9f5071ce30fee224e84684ca7b948ce128844552fbd36cde75","src/fmt.rs":"02c640020993b439133ba6a336f5f6d79d80ca9ede8b81b115c429b0aa2b6944","src/lib.rs":"b55c29b8b6d36b3ff1e4230bbce533d8170139a72a28cf5e0fc26789bbc3383e","src/macros.rs":"86977f1557b943678c1b6feeb4b63b17692e35601075a6be841a40fa0da7acd4","src/map.rs":"0b53139bf9eb768843a478b905929153ae6837082d846d97c81dd0a98d2c5d55","src/osstringext.rs":"92be9bb46ce1673a71bd1e809585621a00e9b38d9eb8caf70f0f29c4a47e0c74","src/strext.rs":"9847933a25ccf757dbcbb1c5a4921a5f8cdaa9dfcd451961bc37d1023d8dd1e1","src/suggestions.rs":"98f6ad3aa5df6cc6c8a1d31a5d1bea9a33cc8fed2b0f5f38255f3878b3cfce37","src/usage_parser.rs":"90b41f753d26cd6dfbf97613a8325c9034c1d98e55cee339c792f0b70baa6595"},"package":"a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/CHANGELOG.md
@@ -0,0 +1,2902 @@
+<a name="v2.34.0"></a>
+## v2.34.0 (2021-11-30)
+
+- Updates to Rust 2018 edition and bumps the MSRV to Rust 1.46
+
+<a name="v2.33.4"></a>
+### v2.33.4 (2021-11-29)
+
+#### Bug Fixes
+
+* **prevents `panic`:**  swallows broken pipe errors on error output ([7a729bc4](https://github.com/kbknapp/clap-rs/commit/7a729bc4df2646b05f6bf15f001124cd39d076ce))
+
+<a name="v2.33.3"></a>
+### v2.33.3 (2020-08-13)
+
+#### Improvements
+
+* Suppress deprecation warnings when using `crate_*` macros.
+
+<a name="v2.33.2"></a>
+### v2.33.2 (2020-08-5)
+
+#### Documentation
+
+* Fixed links to `2.x` examples. Now they point to the right place.
+
+<a name="v2.33.1"></a>
+### v2.33.1 (2020-05-11)
+
+#### Bug Fixes
+
+* Windows: Prevent some panics when parsing invalid Unicode on Windows ([922c645](https://github.com/clap-rs/clap/commit/922c64508389170c9c77f1c8a4e597d14d3ed2f0), closes [#1905](https://github.com/clap-rs/clap/issues/1905))
+
+#### Documentation
+
+*   fixes versions referenced in the README ([d307466a](https://github.com/kbknapp/clap-rs/commit/d307466af1013f172b8ec0252f01a473e2192d6b))
+* **README.md:**
+  *  cuts down the number of examples to reduce confusion ([6e508ee0](https://github.com/kbknapp/clap-rs/commit/6e508ee09e7153de4adf4e88b0aa6418a537dadd))
+
+#### Improvements
+
+* **Deps:**  doesnt compile ansi_term on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155))
+
+#### Minimum Required Rust
+
+* As of this release, `clap` requires `rustc 1.36.0` or greater.
+
+<a name="v2.33.0"></a>
+## v2.33.0 (2019-04-06)
+
+#### New Sponsor
+
+*   Stephen Oats is now a sponsor \o/ ([823457c0](https://github.com/kbknapp/clap-rs/commit/823457c0ef5e994ed7080cf62addbfe1aa3b1833))
+* **SPONSORS.md:**  fixes Josh Triplett's info in the sponsor document ([24cb5740](https://github.com/kbknapp/clap-rs/commit/24cb574090a11159b48bba105d5ec2dfb0a20e4e))
+
+#### Features
+
+* **Completions:**  adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9))
+* There is a new setting to disable automatic building of `--help` and `-h` flags (`AppSettings::DisableAutoHelp`)
+
+#### Improvements
+
+* **arg_matches.rs:**  add Debug implementations ([47192b7a](https://github.com/kbknapp/clap-rs/commit/47192b7a2d84ec716b81ae4af621e008a8762dc9))
+* **macros:**  Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559))
+
+#### Documentation
+
+*   Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c))
+* **README.md:**  use https for all links ([96a7639a](https://github.com/kbknapp/clap-rs/commit/96a7639a36bcb184c3f45348986883115ef1ab3a))
+
+#### Bug Fixes
+
+*   add debug assertion for missing args in subcommand ArgGroup ([2699d9e5](https://github.com/kbknapp/clap-rs/commit/2699d9e51e7eadc258ba64c4e347c5d1fef61343))
+*   Restore compat with Rust 1.21 ([6b263de1](https://github.com/kbknapp/clap-rs/commit/6b263de1d42ede692ec5ee55019ad2fc6386f92e))
+*   Dont mention unused subcommands ([ef92e2b6](https://github.com/kbknapp/clap-rs/commit/ef92e2b639ed305bdade4741f60fa85cb0101c5a))
+* **OsValues:**  Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4))
+* **arg_enum!:**
+  *  Fix comma position for valid values. ([1f1f9ff3](https://github.com/kbknapp/clap-rs/commit/1f1f9ff3fa38a43231ef8be9cfea89a32e53f518))
+  *  Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862))
+* **completions:**  improve correctness of completions when whitespace is involved ([5a08ff29](https://github.com/kbknapp/clap-rs/commit/5a08ff295b2aa6ce29420df6252a0e3ff4441bdc))
+* **help message:**  Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897))
+* **macros:**  fixes broken pattern which prevented calling multi-argument Arg methods ([9e7a352e](https://github.com/kbknapp/clap-rs/commit/9e7a352e13aaf8025d80f2bac5c47fb32528672b))
+* **parser:**  Better interaction between AllowExternalSubcommands and SubcommandRequired ([9601c95a](https://github.com/kbknapp/clap-rs/commit/9601c95a03d2b82bf265c328b4769238f1b79002))
+
+#### Minimum Required Rust
+
+* As of this release, `clap` requires `rustc 1.31.0` or greater.
+
+<a name="v2.32.0"></a>
+## v2.32.0 (2018-06-26)
+
+#### Minimum Required Rust
+
+* As of this release, `clap` requires `rustc 1.21.0` or greater.
+
+
+#### Features
+
+* **Completions:**  adds completion support for Elvish. ([e9d0562a](https://github.com/kbknapp/clap-rs/commit/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9))
+
+#### Improvements
+
+* **macros:**  Support shorthand syntax for ArgGroups ([df9095e7](https://github.com/kbknapp/clap-rs/commit/df9095e75bb1e7896415251d0d4ffd8a0ebcd559))
+
+#### Bug Fixes
+
+* **OsValues:**  Add `ExactSizeIterator` implementation ([356c69e5](https://github.com/kbknapp/clap-rs/commit/356c69e508fd25a9f0ea2d27bf80ae1d9a8d88f4))
+* **arg_enum!:**  Invalid expansions of some trailing-comma patterns ([7023184f](https://github.com/kbknapp/clap-rs/commit/7023184fca04e852c270341548d6a16207d13862))
+* **help message:**  Unconditionally uses long description for subcommands ([6acc8b6a](https://github.com/kbknapp/clap-rs/commit/6acc8b6a621a765cbf513450188000d943676a30), closes [#897](https://github.com/kbknapp/clap-rs/issues/897))
+
+#### Documentation
+
+*   Refer to macOS rather than OSX. ([ab0d767f](https://github.com/kbknapp/clap-rs/commit/ab0d767f3a5a57e2bbb97d0183c2ef63c8c77a6c))
+
+
+
+<a name="v2.31.2"></a>
+### v2.31.2 (2018-03-19)
+
+#### Bug Fixes
+
+* **Fish Completions:**  fixes a bug that only allowed a single completion in in Fish Shell ([e8774a8](https://github.com/kbknapp/clap-rs/pull/1214/commits/e8774a84ee4a319c888036e7c595ab46451d8e48), closes [#1212](https://github.com/kbknapp/clap-rs/issues/1212))
+* **AllowExternalSubcommands**: fixes a bug where external subcommands would be blocked by a similarly named subcommand (suggestions were getting in the way). ([a410e85](https://github.com/kbknapp/clap-rs/pull/1215/commits/a410e855bcd82b05f9efa73fa8b9774dc8842c6b))
+
+#### Documentation
+
+* Fixes some typos in the `README.md` ([c8e685d7](https://github.com/kbknapp/clap-rs/commit/c8e685d76adee2a3cc06cac6952ffcf6f9548089))
+
+<a name="v2.31.1"></a>
+### v2.31.1 (2018-03-06)
+
+
+#### Improvements
+
+* **AllowMissingPositional:**  improves the ability of AllowMissingPositional to allow 'skipping' to the last positional arg with '--' ([df20e6e2](https://github.com/kbknapp/clap-rs/commit/df20e6e24b4e782be0b423b484b9798e3e2efe2f))
+
+
+<a name="v2.31.0"></a>
+## v2.31.0 (2018-03-04)
+
+
+#### Features
+
+* **Arg Indices:**  adds the ability to query argument value indices ([f58d0576](https://github.com/kbknapp/clap-rs/commit/f58d05767ec8133c8eb2de117cb642b9ae29ccbc))
+* **Indices:**  implements an Indices<Item=&usize> iterator ([1e67be44](https://github.com/kbknapp/clap-rs/commit/1e67be44f0ccf161cc84c4e6082382072e89c302))
+* **Raw Args** adds a convenience function to `Arg` that allows implying all of `Arg::last` `Arg::allow_hyphen_values` and `Arg::multiple(true)` ([66a78f29](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
+
+#### Documentation
+
+*   Fix some typos and markdown issues. ([935ba0dd](https://github.com/kbknapp/clap-rs/commit/935ba0dd547a69c3f636c5486795012019408794))
+* **Arg Indices:**  adds the documentation for the arg index querying methods ([50bc0047](https://github.com/kbknapp/clap-rs/commit/50bc00477afa64dc6cdc5de161d3de3ba1d105a7))
+* **CONTRIBUTING.md:**  fix url to clippy upstream repo to point to https://github.com/rust-lang-nursery/rust-clippy instead of https://github.com/Manishearth/rust-clippy ([42407d7f](https://github.com/kbknapp/clap-rs/commit/42407d7f21d794103cda61f49d2615aae0a4bcd9))
+* **Values:**  improves the docs example of the Values iterator ([74075d65](https://github.com/kbknapp/clap-rs/commit/74075d65e8db1ddb5e2a4558009a5729d749d1b6))
+* Updates readme to hint that the `wrap_help` feature is a thing ([fc7ab227](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
+
+### Improvements
+
+*  Cargo.toml: use codegen-units = 1 in release and bench profiles ([19f425ea](https://github.com/kbknapp/clap-rs/commit/66a78f2972786f5fe7c07937a1ac23da2542afd2))
+*  Adds WASM support (clap now compiles on WASM!) ([689949e5](https://github.com/kbknapp/clap-rs/commit/689949e57d390bb61bc69f3ed91f60a2105738d0))
+*  Uses the short help tool-tip for PowerShell completion scripts ([ecda22ce](https://github.com/kbknapp/clap-rs/commit/ecda22ce7210ce56d7b2d1a5445dd1b8a2959656))
+
+
+<a name="v2.30.0"></a>
+## v2.30.0 (2018-02-13)
+
+#### Bug Fixes
+
+* **YAML:** Adds a missing conversion from  `Arg::last` when instantiating from a YAML file ([aab77c81a5](https://github.com/kbknapp/clap-rs/pull/1175/commits/aab77c81a519b045f95946ae0dd3e850f9b93070), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1173))
+
+#### Improvements
+
+* **Bash Completions:**  instead of completing a generic option name, all bash completions fall back to file completions UNLESS `Arg::possible_values` was used ([872f02ae](https://github.com/kbknapp/clap-rs/commit/872f02aea900ffa376850a279eb164645e1234fa))
+* **Deps:**  No longer needlessly compiles `ansi_term` on Windows since its not used ([b57ee946](https://github.com/kbknapp/clap-rs/commit/b57ee94609da3ddc897286cfba968f26ff961491), closes [#1155](https://github.com/kbknapp/clap-rs/issues/1155))
+* **Help Message:** changes the `[values: foo bar baz]` array to `[possible values: foo bar baz]` for consistency with the API ([414707e4e97](https://github.com/kbknapp/clap-rs/pull/1176/commits/414707e4e979d07bfe555247e5d130c546673708), closes [#1160](https://github.com/kbknapp/clap-rs/issues/1160))
+
+
+<a name="v2.29.4"></a>
+### v2.29.4 (2018-02-06)
+
+
+#### Bug Fixes
+
+* **Overrides Self:**  fixes a bug where options with multiple values couldnt ever have multiple values ([d95907cf](https://github.com/kbknapp/clap-rs/commit/d95907cff6d011a901fe35fa00b0f4e18547a1fb))
+
+
+
+<a name="v2.29.3"></a>
+### v2.29.3 (2018-02-05)
+
+
+#### Improvements
+
+* **Overrides:**  clap now supports arguments which override with themselves ([6c7a0010](https://github.com/kbknapp/clap-rs/commit/6c7a001023ca1eac1cc6ffe6c936b4c4a2aa3c45), closes [#976](https://github.com/kbknapp/clap-rs/issues/976))
+
+#### Bug Fixes
+
+* **Requirements:**  fixes an issue where conflicting args would still show up as required ([e06cefac](https://github.com/kbknapp/clap-rs/commit/e06cefac97083838c0a4e1444dcad02a5c3f911e), closes [#1158](https://github.com/kbknapp/clap-rs/issues/1158))
+* Fixes a bug which disallows proper nesting of `--` ([73993fe](https://github.com/kbknapp/clap-rs/commit/73993fe30d135f682e763ec93dcb0814ed518011), closes [#1161](https://github.com/kbknapp/clap-rs/issues/1161))
+
+#### New Settings
+
+* **AllArgsOverrideSelf:**  adds a new convenience setting to allow all args to override themselves ([4670325d](https://github.com/kbknapp/clap-rs/commit/4670325d1bf0369addec2ae2bcb56f1be054c924))
+
+
+
+<a name="v2.29.2"></a>
+### v2.29.2 (2018-01-16)
+
+
+#### Features
+
+* **completions/zsh.rs:**
+  *  Escape possible values for options ([25561dec](https://github.com/kbknapp/clap-rs/commit/25561decf147d329b64634a14d9695673c2fc78f))
+  *  Implement postional argument possible values completion ([f3b0afd2](https://github.com/kbknapp/clap-rs/commit/f3b0afd2bef8b7be97162f8a7802ddf7603dff36))
+  *  Complete positional arguments properly ([e39aeab8](https://github.com/kbknapp/clap-rs/commit/e39aeab8487596046fbdbc6a226e5c8820585245))
+
+#### Bug Fixes
+
+* **completions/zsh.rs:**
+  *  Add missing autoload for is-at-least ([a6522607](https://github.com/kbknapp/clap-rs/commit/a652260795d1519f6ec2a7a09ccc1258499cad7b))
+  *  Don't pass -S to _arguments if Zsh is too old ([16b4f143](https://github.com/kbknapp/clap-rs/commit/16b4f143ff466b7ef18a267bc44ade0f9639109b))
+  *  Maybe fix completions with mixed positionals and subcommands ([1146f0da](https://github.com/kbknapp/clap-rs/commit/1146f0da154d6796fbfcb09db8efa3593cb0d898))
+* **completions/zsh.zsh:**  Remove redundant code from output ([0e185b92](https://github.com/kbknapp/clap-rs/commit/0e185b922ed1e0fd653de00b4cd8d567d72ff68e), closes [#1142](https://github.com/kbknapp/clap-rs/issues/1142))
+
+
+
+<a name="2.29.1"></a>
+### 2.29.1 (2018-01-09)
+
+
+#### Documentation
+
+*   fixes broken links. ([56e734b8](https://github.com/kbknapp/clap-rs/commit/56e734b839303d733d2e5baf7dac39bd7b97b8e4))
+*   updates contributors list ([e1313a5a](https://github.com/kbknapp/clap-rs/commit/e1313a5a0f69d8f4016f73b860a63af8318a6676))
+
+#### Performance
+
+*   further debloating by removing generics from error cases ([eb8d919e](https://github.com/kbknapp/clap-rs/commit/eb8d919e6f3443db279ba0c902f15d76676c02dc))
+*   debloats clap by deduplicating logic and refactors ([03e413d7](https://github.com/kbknapp/clap-rs/commit/03e413d7175d35827cd7d8908d47dbae15a849a3))
+
+#### Bug Fixes
+
+*   fixes the ripgrep benchmark by adding a value to a flag that expects it ([d26ab2b9](https://github.com/kbknapp/clap-rs/commit/d26ab2b97cf9c0ea675b440b7b0eaf6ac3ad01f4))
+* **bash completion:**  Change the bash completion script code generation to support hyphens. ([ba7f1d18](https://github.com/kbknapp/clap-rs/commit/ba7f1d18eba7a07ce7f57e0981986f66c994b639))
+* **completions/zsh.rs:**  Fix completion of long option values ([46365cf8](https://github.com/kbknapp/clap-rs/commit/46365cf8be5331ba04c895eb183e2f230b5aad51))
+
+
+<a name="2.29.0"></a>
+## 2.29.0 (2017-12-02)
+
+
+#### API Additions
+
+* **Arg:**  adds Arg::hide_env_values(bool) which allows one to hide any current env values and display only the key in help messages ([fb41d062](https://github.com/kbknapp/clap-rs/commit/fb41d062eedf37cb4f805c90adca29909bd197d7))
+
+
+
+<a name="2.28.0"></a>
+## 2.28.0 (2017-11-28)
+
+The minimum required Rust is now 1.20. This was done to start using bitflags 1.0 and having >1.0 deps is a *very good* thing!
+
+#### Documentation
+
+*   changes the demo version to 2.28 to stay in sync ([ce6ca492](https://github.com/kbknapp/clap-rs/commit/ce6ca492c7510ab6474075806360b96081b021a9))
+*   Fix URL path to github hosted files ([ce72aada](https://github.com/kbknapp/clap-rs/commit/ce72aada56a9581d4a6cb4bf9bdb861c3906f8df), closes [#1106](https://github.com/kbknapp/clap-rs/issues/1106))
+*   fix typo ([002b07fc](https://github.com/kbknapp/clap-rs/commit/002b07fc98a1c85acb66296b1eec0b2aba906125))
+* **README.md:**  updates the readme and pulls out some redundant sections ([db6caf86](https://github.com/kbknapp/clap-rs/commit/db6caf8663747e679d2f4ed3bd127f33476754aa))
+
+#### Improvements
+
+*   adds '[SUBCOMMAND]' to usage strings with only AppSettings::AllowExternalSubcommands is used with no other subcommands ([e78bb757](https://github.com/kbknapp/clap-rs/commit/e78bb757a3df16e82d539e450c06767a6bfcf859), closes [#1093](https://github.com/kbknapp/clap-rs/issues/1093))
+
+#### API Additions
+
+*   Adds Arg::case_insensitive(bool) which allows matching Arg::possible_values without worrying about ASCII case ([1fec268e](https://github.com/kbknapp/clap-rs/commit/1fec268e51736602e38e67c76266f439e2e0ef12), closes [#1118](https://github.com/kbknapp/clap-rs/issues/1118))
+*   Adds the traits to be used with the clap-derive crate to be able to use Custom Derive ([6f4c3412](https://github.com/kbknapp/clap-rs/commit/6f4c3412415e882f5ca2cc3fbd6d4dce79440828))
+
+#### Bug Fixes
+
+*   Fixes a regression where --help couldn't be overridden ([a283d69f](https://github.com/kbknapp/clap-rs/commit/a283d69fc08aa016ae1bf9ba010012abecc7ba69), closes [#1112](https://github.com/kbknapp/clap-rs/issues/1112))
+*   fixes a bug that allowed options to pass parsing when no value was provided ([2fb75821](https://github.com/kbknapp/clap-rs/commit/2fb758219c7a60d639da67692e100b855a8165ac), closes [#1105](https://github.com/kbknapp/clap-rs/issues/1105))
+*   ignore PropagateGlobalValuesDown deprecation warning ([f61ce3f5](https://github.com/kbknapp/clap-rs/commit/f61ce3f55fe65e16b3db0bd4facdc4575de22767), closes [#1086](https://github.com/kbknapp/clap-rs/issues/1086))
+
+#### Deps
+
+*  Updates `bitflags` to 1.0
+
+
+
+<a name="v2.27.1"></a>
+## v2.27.1 (2017-10-24)
+
+
+#### Bug Fixes
+
+* Adds `term_size` as an optional dependency (with feature `wrap_help`) to fix compile bug
+
+<a name="v2.27.0"></a>
+## v2.27.0 (2017-10-24)
+
+** This release raises the minimum required version of Rust to 1.18 **
+
+** This release also contains a very minor breaking change to fix a bug **
+
+The only CLIs affected will be those using unrestrained multiple values and subcommands where the
+subcommand name can coincide with one of the multiple values.
+
+See the commit [0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31) for full details.
+
+
+#### Bug Fixes
+
+*   Values from global args are now propagated UP and DOWN!
+*   fixes a bug where using AppSettings::AllowHyphenValues would allow invalid arguments even when there is no way for them to be valid ([77ed4684](https://github.com/kbknapp/clap-rs/commit/77ed46841fc0263d7aa32fcc5cc49ef703b37c04), closes [#1066](https://github.com/kbknapp/clap-rs/issues/1066))
+*   when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/))
+*   fixes a bug that prevented number_of_values and default_values to be used together ([5eb342a9](https://github.com/kbknapp/clap-rs/commit/5eb342a99dde07b0f011048efde3e283bc1110fc), closes [#1050](https://github.com/kbknapp/clap-rs/issues/1050), [#1056](https://github.com/kbknapp/clap-rs/issues/1056))
+*   fixes a bug that didn't allow args with default values to have conflicts ([58b5b4be](https://github.com/kbknapp/clap-rs/commit/58b5b4be315280888d50d9b15119b91a9028f050), closes [#1071](https://github.com/kbknapp/clap-rs/issues/1071))
+*   fixes a panic when using global args and calling App::get_matches_from_safe_borrow multiple times ([d86ec797](https://github.com/kbknapp/clap-rs/commit/d86ec79742c77eb3f663fb30e225954515cf25bb), closes [#1076](https://github.com/kbknapp/clap-rs/issues/1076))
+*   fixes issues and potential regressions with global args values not being propagated properly or at all ([a43f9dd4](https://github.com/kbknapp/clap-rs/commit/a43f9dd4aaf1864dd14a3c28dec89ccdd70c61e5), closes [#1010](https://github.com/kbknapp/clap-rs/issues/1010), [#1061](https://github.com/kbknapp/clap-rs/issues/1061), [#978](https://github.com/kbknapp/clap-rs/issues/978))
+*   fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047))
+
+#### Documentation
+
+*   adds addtional blurbs about using multiples with subcommands ([03455b77](https://github.com/kbknapp/clap-rs/commit/03455b7751a757e7b2f6ffaf2d16168539c99661))
+*   updates the docs to reflect changes to global args and that global args values can now be propagated back up the stack ([ead076f0](https://github.com/kbknapp/clap-rs/commit/ead076f03ada4c322bf3e34203925561ec496d87))
+*   add html_root_url attribute ([e67a061b](https://github.com/kbknapp/clap-rs/commit/e67a061bcf567c6518d6c2f58852e01f02764b22))
+*   sync README version numbers with crate version ([5536361b](https://github.com/kbknapp/clap-rs/commit/5536361bcda29887ed86bb68e43d0b603cbc423f))
+
+#### Improvements
+
+*   args that have require_delimiter(true) is now reflected in help and usage strings ([dce61699](https://github.com/kbknapp/clap-rs/commit/dce616998ed9bd95e8ed3bec1f09a4883da47b85), closes [#1052](https://github.com/kbknapp/clap-rs/issues/1052))
+*   if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046))
+
+#### Breaking Changes
+
+*   when an argument requires a value and that value happens to match a subcommand name, its parsed as a value ([0c223f54](https://github.com/kbknapp/clap-rs/commit/0c223f54ed46da406bc8b43a5806e0b227863b31), closes [#1031](https://github.com/kbknapp/clap-rs/issues/1031), breaks [#](https://github.com/kbknapp/clap-rs/issues/), [#](https://github.com/kbknapp/clap-rs/issues/))
+
+#### Deprecations
+
+* **AppSettings::PropagateGlobalValuesDown:**  this setting is no longer required to propagate values down or up ([2bb5ddce](https://github.com/kbknapp/clap-rs/commit/2bb5ddcee61c791ca1aaca494fbeb4bd5e277488))
+
+
+
+<a name="v2.26.2"></a>
+### v2.26.2 (2017-09-14)
+
+
+#### Improvements
+
+*   if all subcommands are hidden, the subcommands section of the help message is no longer displayed ([4ae7b046](https://github.com/kbknapp/clap-rs/commit/4ae7b0464750bc07ec80ece38e43f003fdd1b8ae), closes [#1046](https://github.com/kbknapp/clap-rs/issues/1046))
+
+#### Bug Fixes
+
+*   fixes a bug where default values are not applied if the option supports zero values ([9c248cbf](https://github.com/kbknapp/clap-rs/commit/9c248cbf7d8a825119bc387c23e9a1d1989682b0), closes [#1047](https://github.com/kbknapp/clap-rs/issues/1047))
+
+
+
+<a name="v2.26.1"></a>
+### v2.26.1 (2017-09-14)
+
+
+#### Bug Fixes
+
+*   fixes using require_equals(true) and min_values(0) together ([10ae208f](https://github.com/kbknapp/clap-rs/commit/10ae208f68518eff6e98166724065745f4083174), closes [#1044](https://github.com/kbknapp/clap-rs/issues/1044))
+*   escape special characters in zsh and fish completions ([87e019fc](https://github.com/kbknapp/clap-rs/commit/87e019fc84ba6193a8c4ddc26c61eb99efffcd25))
+*   avoid panic generating default help msg if term width set to 0 due to bug in textwrap 0.7.0 ([b3eadb0d](https://github.com/kbknapp/clap-rs/commit/b3eadb0de516106db4e08f078ad32e8f6d6e7a57))
+*   Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349))
+*   adds a debug assertion to ensure all args added to groups actually exist ([7ad123e2](https://github.com/kbknapp/clap-rs/commit/7ad123e2c02577e3ca30f7e205181e896b157d11), closes [#917](https://github.com/kbknapp/clap-rs/issues/917))
+*   fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ab2f4c9e](https://github.com/kbknapp/clap-rs/commit/ab2f4c9e563e36ec739a4b55d5a5b76fdb9e9fa4), closes [#960](https://github.com/kbknapp/clap-rs/issues/960))
+*   fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21))
+* **Help Message:**  fixes long_about not being usable ([a8257ea0](https://github.com/kbknapp/clap-rs/commit/a8257ea0ffb812e552aca256c4a3d2aebfd8065b), closes [#1043](https://github.com/kbknapp/clap-rs/issues/1043))
+* **Suggestions:**  output for flag after subcommand ([434ea5ba](https://github.com/kbknapp/clap-rs/commit/434ea5ba71395d8c1afcf88e69f0b0d8339b01a1))
+
+
+
+<a name="v2.26.0"></a>
+## v2.26.0 (2017-07-29)
+
+Minimum version of Rust is now v1.13.0 (Stable)
+
+
+#### Improvements
+
+*   bumps unicode-segmentation to v1.2 ([cd7b40a2](https://github.com/kbknapp/clap-rs/commit/cd7b40a21c77bae17ba453c5512cb82b7d1ce474))
+
+
+#### Performance
+
+*   update textwrap to version 0.7.0 ([c2d4e637](https://github.com/kbknapp/clap-rs/commit/c2d4e63756a6f070e38c16dff846e9b0a53d6f93))
+
+
+
+
+<a name="v2.25.1"></a>
+### v2.25.1 (2017-07-21)
+
+#### Improvements
+
+* impl Default for Values + OsValues for any lifetime. ([fb7d6231f1](https://github.com/kbknapp/clap-rs/commit/fb7d6231f13a2f79f411e62dca210b7dc9994c18))
+
+#### Documentation
+
+* Various documentation typos and grammar fixes
+
+<a name="v2.25.0"></a>
+### v2.25.0 (2017-06-20)
+
+
+#### Features
+
+*   use textwrap crate for wrapping help texts ([b93870c1](https://github.com/kbknapp/clap-rs/commit/b93870c10ae3bd90d233c586a33e086803117285))
+
+#### Improvements
+
+* **Suggestions:**  suggests to use flag after subcommand when applicable ([2671ca72](https://github.com/kbknapp/clap-rs/commit/2671ca7260119d4311d21c4075466aafdd9da734))
+* Bumps bitflags crate to v0.9
+
+#### Documentation
+
+*   Change `who's` -> `whose` ([53c1ffe8](https://github.com/kbknapp/clap-rs/commit/53c1ffe87f38b05d8804a0f7832412a952845349))
+
+#### Documentation
+
+* **App::template:**  adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cbea3d5a](https://github.com/kbknapp/clap-rs/commit/cbea3d5acf3271a7a734498c4d99c709941c331e), closes [#949](https://github.com/kbknapp/clap-rs/issues/949))
+* **Arg::allow_hyphen_values:**  updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([f9b0d657](https://github.com/kbknapp/clap-rs/commit/f9b0d657835d3f517f313d70962177dc30acf4a7))
+* **README.md:**
+  *  added a warning about using ~ deps ([821929b5](https://github.com/kbknapp/clap-rs/commit/821929b51bd60213955705900a436c9a64fcb79f), closes [#964](https://github.com/kbknapp/clap-rs/issues/964))
+* **clap_app!:**  adds using the @group specifier to the macro docs ([826048cb](https://github.com/kbknapp/clap-rs/commit/826048cb3cbc0280169303f1498ff0a2b7395883), closes [#932](https://github.com/kbknapp/clap-rs/issues/932))
+
+
+
+<a name="v2.24.2"></a>
+### v2.24.2 (2017-05-15)
+
+
+#### Bug Fixes
+
+*   adds a debug assertion to ensure all args added to groups actually exist ([14f6b8f3](https://github.com/kbknapp/clap-rs/commit/14f6b8f3a2f6df73aeeec9c54a54909b1acfc158), closes [#917](https://github.com/kbknapp/clap-rs/issues/917))
+*   fixes a bug where args that allow values to start with a hyphen couldnt contain a double hyphen -- as a value ([ebf73a09](https://github.com/kbknapp/clap-rs/commit/ebf73a09db6f3c03c19cdd76b1ba6113930e1643), closes [#960](https://github.com/kbknapp/clap-rs/issues/960))
+*   fixes a bug where positional argument help text is misaligned ([54c16836](https://github.com/kbknapp/clap-rs/commit/54c16836dea4651806a2cfad53146a83fa3abf21))
+
+#### Documentation
+
+* **App::template:**  adds details about the necessity to use AppSettings::UnifiedHelpMessage when using {unified} tags in the help template ([cf569438](https://github.com/kbknapp/clap-rs/commit/cf569438f309c199800bb8e46c9f140187de69d7), closes [#949](https://github.com/kbknapp/clap-rs/issues/949))
+* **Arg::allow_hyphen_values:**  updates the docs to include warnings for allow_hyphen_values and multiple(true) used together ([ded5a2f1](https://github.com/kbknapp/clap-rs/commit/ded5a2f15474d4a5bd46a67b130ccb8b6781bd01))
+* **clap_app!:**  adds using the @group specifier to the macro docs ([fe85fcb1](https://github.com/kbknapp/clap-rs/commit/fe85fcb1772b61f13b20b7ea5290e2437a76190c), closes [#932](https://github.com/kbknapp/clap-rs/issues/932))
+
+
+
+<a name="v2.24.0"></a>
+### v2.24.0 (2017-05-07)
+
+
+#### Bug Fixes
+
+*   fixes a bug where args with last(true) and required(true) set were not being printed in the usage string ([3ac533fe](https://github.com/kbknapp/clap-rs/commit/3ac533fedabf713943eedf006f830a5a486bbe80), closes [#944](https://github.com/kbknapp/clap-rs/issues/944))
+*   fixes a bug that was printing the arg name, instead of value name when Arg::last(true) was used ([e1fe8ac3](https://github.com/kbknapp/clap-rs/commit/e1fe8ac3bc1f9cf4e36df0d881f8419755f1787b), closes [#940](https://github.com/kbknapp/clap-rs/issues/940))
+*   fixes a bug where flags were parsed as flags AND positional values when specific combinations of settings were used ([20f83292](https://github.com/kbknapp/clap-rs/commit/20f83292d070038b8cee2a6b47e91f6b0a2f7871), closes [#946](https://github.com/kbknapp/clap-rs/issues/946))
+
+
+
+<a name="v2.24.0"></a>
+## v2.24.0 (2017-05-05)
+
+
+#### Documentation
+
+* **README.md:**  fix some typos ([fa34deac](https://github.com/kbknapp/clap-rs/commit/fa34deac079f334c3af97bb7fb151880ba8887f8))
+
+#### API Additions
+
+* **Arg:**  add `default_value_os` ([d5ef8955](https://github.com/kbknapp/clap-rs/commit/d5ef8955414b1587060f7218385256105b639c88))
+* **arg_matches.rs:**  Added a Default implementation for Values and OsValues iterators. ([0a4384e3](https://github.com/kbknapp/clap-rs/commit/0a4384e350eed74c2a4dc8964c203f21ac64897f))
+
+
+<a name="v2.23.2"></a>
+### v2.23.2 (2017-04-19)
+
+
+#### Bug Fixes
+
+* **PowerShell Completions:**  fixes a bug where powershells completions cant be used if no subcommands are defined ([a8bce558](https://github.com/kbknapp/clap-rs/commit/a8bce55837dc4e0fb187dc93180884a40ae09c6f), closes [#931](https://github.com/kbknapp/clap-rs/issues/931))
+
+#### Improvements
+
+*   bumps term_size to take advantage of better terminal dimension handling ([e05100b7](https://github.com/kbknapp/clap-rs/commit/e05100b73d74066a90876bf38f952adf5e8ee422))
+* **PowerShell Completions:**  massively dedups subcommand names in the generate script to make smaller scripts that are still functionally equiv ([85b0e1cc](https://github.com/kbknapp/clap-rs/commit/85b0e1cc4b9755dda75a93d898d79bc38631552b))
+
+#### Documentation
+
+*   Fix a typo the minimum rust version required ([71dabba3](https://github.com/kbknapp/clap-rs/commit/71dabba3ea0a17c88b0e2199c9d99f0acbf3bc17))
+
+<a name="v2.23.1"></a>
+### v2.23.1 (2017-04-05)
+
+
+#### Bug Fixes
+
+*   fixes a missing newline character in the autogenerated help and version messages in some instances ([5ae9007d](https://github.com/kbknapp/clap-rs/commit/5ae9007d984ae94ae2752df51bcbaeb0ec89bc15))
+
+
+<a name="v2.23.0"></a>
+## v2.23.0 (2017-04-05)
+
+
+#### API Additions
+
+* `App::long_about`
+* `App::long_version`
+* `App::print_long_help`
+* `App::write_long_help`
+* `App::print_long_version`
+* `App::write_long_version`
+* `Arg::long_help`
+
+#### Features
+
+*   allows distinguishing between short and long version messages (-V/short or --version/long) ([59272b06](https://github.com/kbknapp/clap-rs/commit/59272b06cc213289dc604dbc694cb95d383a5d68))
+*   allows distinguishing between short and long help with subcommands in the same manner as args ([6b371891](https://github.com/kbknapp/clap-rs/commit/6b371891a1702173a849d1e95f9fecb168bf6fc4))
+*   allows specifying a short help vs a long help (i.e. varying levels of detail depending on if -h or --help was used) ([ef1b24c3](https://github.com/kbknapp/clap-rs/commit/ef1b24c3a0dff2f58c5e2e90880fbc2b69df20ee))
+* **clap_app!:**  adds support for arg names with hyphens similar to longs with hyphens ([f7a88779](https://github.com/kbknapp/clap-rs/commit/f7a8877978c8f90e6543d4f0d9600c086cf92cd7), closes [#869](https://github.com/kbknapp/clap-rs/issues/869))
+
+#### Bug Fixes
+
+*   fixes a bug that wasn't allowing help and version to be properly overridden ([8b2ceb83](https://github.com/kbknapp/clap-rs/commit/8b2ceb8368bcb70689fadf1c7f4b9549184926c1), closes [#922](https://github.com/kbknapp/clap-rs/issues/922))
+
+#### Documentation
+
+* **clap_app!:**  documents the `--("some-arg")` method for using args with hyphens inside them ([bc08ef3e](https://github.com/kbknapp/clap-rs/commit/bc08ef3e185393073d969d301989b6319c616c1f), closes [#919](https://github.com/kbknapp/clap-rs/issues/919))
+
+
+
+<a name="v2.22.2"></a>
+### v2.22.2 (2017-03-30)
+
+
+#### Bug Fixes
+
+* **Custom Usage Strings:**  fixes the usage string regression when using help templates ([0e4fd96d](https://github.com/kbknapp/clap-rs/commit/0e4fd96d74280d306d09e60ac44f938a82321769))
+
+
+
+<a name="v2.22.1"></a>
+### v2.22.1 (2017-03-24)
+
+
+#### Bug Fixes
+
+* **usage:**  fixes a big regression with custom usage strings ([2c41caba](https://github.com/kbknapp/clap-rs/commit/2c41caba3c7d723a2894e315d04da796b0e97759))
+
+<a name="v2.22.0"></a>
+## v2.22.0 (2017-03-23)
+
+#### API Additions
+
+* **App::name:**  adds the ability to change the name of the App instance after creation ([d49e8292](https://github.com/kbknapp/clap-rs/commit/d49e8292b026b06e2b70447cd9f08299f4fcba76), closes [#908](https://github.com/kbknapp/clap-rs/issues/908))
+* **Arg::hide_default_value:**  adds ability to hide the default value of an argument from the help string ([89e6ea86](https://github.com/kbknapp/clap-rs/commit/89e6ea861e16a1ad56757ca12f6b32d02253e44a), closes [#902](https://github.com/kbknapp/clap-rs/issues/902))
+
+
+<a name="v2.21.3"></a>
+### v2.21.3 (2017-03-23)
+
+#### Bug Fixes
+
+* **yaml:**  adds support for loading author info from yaml ([e04c390c](https://github.com/kbknapp/clap-rs/commit/e04c390c597a55fa27e724050342f16c42f1c5c9))
+
+
+<a name="v2.21.2"></a>
+### v2.21.2 (2017-03-17)
+
+
+#### Improvements
+
+*   add fish subcommand help support ([f8f68cf8](https://github.com/kbknapp/clap-rs/commit/f8f68cf8251669aef4539a25a7c1166f0ac81ea6))
+*   options that use `require_equals(true)` now display the equals sign in help messages, usage strings, and errors" ([c8eb0384](https://github.com/kbknapp/clap-rs/commit/c8eb0384d394d2900ccdc1593099c97808a3fa05), closes [#903](https://github.com/kbknapp/clap-rs/issues/903))
+
+
+#### Bug Fixes
+
+*  setting the max term width now correctly propagates down through child subcommands
+
+
+
+<a name="v2.21.1"></a>
+### v2.21.1 (2017-03-12)
+
+
+#### Bug Fixes
+
+* **ArgRequiredElseHelp:**  fixes the precedence of this error to prioritize over other error messages ([74b751ff](https://github.com/kbknapp/clap-rs/commit/74b751ff2e3631e337b7946347c1119829a41c53), closes [#895](https://github.com/kbknapp/clap-rs/issues/895))
+* **Positionals:**  fixes some regression bugs resulting from old asserts in debug mode. ([9a3bc98e](https://github.com/kbknapp/clap-rs/commit/9a3bc98e9b55e7514b74b73374c5ac8b6e5e0508), closes [#896](https://github.com/kbknapp/clap-rs/issues/896))
+
+
+
+<a name="v2.21.0"></a>
+## v2.21.0 (2017-03-09)
+
+#### Performance
+
+*   doesn't run `arg_post_processing` on multiple values anymore ([ec516182](https://github.com/kbknapp/clap-rs/commit/ec5161828729f6a53f0fccec8648f71697f01f78))
+*   changes internal use of `VecMap` to `Vec` for matched values of `Arg`s ([22bf137a](https://github.com/kbknapp/clap-rs/commit/22bf137ac581684c6ed460d2c3c640c503d62621))
+*   vastly reduces the amount of cloning when adding non-global args minus when they're added from `App::args` which is forced to clone ([8da0303b](https://github.com/kbknapp/clap-rs/commit/8da0303bc02db5fe047cfc0631a9da41d9dc60f7))
+*   refactor to remove unneeded vectors and allocations and checks for significant performance increases ([0efa4119](https://github.com/kbknapp/clap-rs/commit/0efa4119632f134fc5b8b9695b007dd94b76735d))
+
+#### Documentation
+
+*   Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1))
+
+#### Improvements
+
+*   when `AppSettings::SubcommandsNegateReqs` and `ArgsNegateSubcommands` are used, a new more accurate double line usage string is shown ([50f02300](https://github.com/kbknapp/clap-rs/commit/50f02300d81788817acefef0697e157e01b6ca32), closes [#871](https://github.com/kbknapp/clap-rs/issues/871))
+
+#### API Additions
+
+* **Arg::last:**  adds the ability to mark a positional argument as 'last' which means it should be used with `--` syntax and can be accessed early ([6a7aea90](https://github.com/kbknapp/clap-rs/commit/6a7aea9043b83badd9ab038b4ecc4c787716147e), closes [#888](https://github.com/kbknapp/clap-rs/issues/888))
+*   provides `default_value_os` and `default_value_if[s]_os` ([0f2a3782](https://github.com/kbknapp/clap-rs/commit/0f2a378219a6930748d178ba350fe5925be5dad5), closes [#849](https://github.com/kbknapp/clap-rs/issues/849))
+*   provides `App::help_message` and `App::version_message` which allows one to override the auto-generated help/version flag associated help ([389c413](https://github.com/kbknapp/clap-rs/commit/389c413b7023dccab8c76aa00577ea1d048e7a99), closes [#889](https://github.com/kbknapp/clap-rs/issues/889))
+
+#### New Settings
+
+* **InferSubcommands:**  adds a setting to allow one to infer shortened subcommands or aliases (i.e. for subcommmand "test", "t", "te", or "tes" would be allowed assuming no other ambiguities) ([11602032](https://github.com/kbknapp/clap-rs/commit/11602032f6ff05881e3adf130356e37d5e66e8f9), closes [#863](https://github.com/kbknapp/clap-rs/issues/863))
+
+#### Bug Fixes
+
+*   doesn't print the argument sections in the help message if all args in that section are hidden ([ce5ee5f5](https://github.com/kbknapp/clap-rs/commit/ce5ee5f5a76f838104aeddd01c8ec956dd347f50))
+*   doesn't include the various [ARGS] [FLAGS] or [OPTIONS] if the only ones available are hidden ([7b4000af](https://github.com/kbknapp/clap-rs/commit/7b4000af97637703645c5fb2ac8bb65bd546b95b), closes [#882](https://github.com/kbknapp/clap-rs/issues/882))
+*   now correctly shows subcommand as required in the usage string when AppSettings::SubcommandRequiredElseHelp is used ([8f0884c1](https://github.com/kbknapp/clap-rs/commit/8f0884c1764983a49b45de52a1eddf8d721564d8))
+*   fixes some memory leaks when an error is detected and clap exits ([8c2dd287](https://github.com/kbknapp/clap-rs/commit/8c2dd28718262ace4ae0db98563809548e02a86b))
+*   fixes a trait that's marked private accidentlly, but should be crate internal public ([1ae21108](https://github.com/kbknapp/clap-rs/commit/1ae21108015cea87e5360402e1747025116c7878))
+* **Completions:**   fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846))
+
+#### Features
+
+* **Options:**  adds the ability to require the equals syntax with options --opt=val ([f002693d](https://github.com/kbknapp/clap-rs/commit/f002693dec6a6959c4e9590cb7b7bfffd6d6e5bc), closes [#833](https://github.com/kbknapp/clap-rs/issues/833))
+
+
+
+<a name="v2.20.5"></a>
+### v2.20.5 (2017-02-18)
+
+
+#### Bug Fixes
+
+* **clap_app!:**   fixes a critical bug of a missing fragment specifier when using `!property` style tags. ([5635c1f94](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94))
+
+
+<a name="v2.20.4"></a>
+### v2.20.4 (2017-02-15)
+
+
+#### Bug Fixes
+
+* **Completions:**   fixes a bug that tried to propogate global args multiple times when generating multiple completion scripts ([5e9b9cf4](https://github.com/kbknapp/clap-rs/commit/5e9b9cf4dd80fa66a624374fd04e6545635c1f94), closes [#846](https://github.com/kbknapp/clap-rs/issues/846))
+
+#### Documentation
+
+*   Fix examples link in CONTRIBUTING.md ([60cf875d](https://github.com/kbknapp/clap-rs/commit/60cf875d67a252e19bb85054be57696fac2c57a1))
+
+
+<a name="v2.20.3"></a>
+### v2.20.3 (2017-02-03)
+
+
+#### Documentation
+
+* **Macros:**  adds a warning about changing values in Cargo.toml not triggering a rebuild automatically ([112aea3e](https://github.com/kbknapp/clap-rs/commit/112aea3e42ae9e0c0a2d33ebad89496dbdd95e5d), closes [#838](https://github.com/kbknapp/clap-rs/issues/838))
+
+#### Bug Fixes
+
+*   fixes a println->debugln typo ([279aa62e](https://github.com/kbknapp/clap-rs/commit/279aa62eaf08f56ce090ba16b937bc763cbb45be))
+*   fixes bash completions for commands that have an underscore in the name ([7f5cfa72](https://github.com/kbknapp/clap-rs/commit/7f5cfa724f0ac4e098f5fe466c903febddb2d994), closes [#581](https://github.com/kbknapp/clap-rs/issues/581))
+*   fixes a bug where ZSH completions would panic if the binary name had an underscore in it ([891a2a00](https://github.com/kbknapp/clap-rs/commit/891a2a006f775e92c556dda48bb32fac9807c4fb), closes [#581](https://github.com/kbknapp/clap-rs/issues/581))
+*   allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828))
+* fixes a bug where global args weren't included in the generated completion scripts ([9a1e006e](https://github.com/kbknapp/clap-rs/commit/9a1e006eb75ad5a6057ebd119aa90f7e06c0ace8), closes [#841](https://github.com/kbknapp/clap-rs/issues/841))
+
+
+
+<a name="v2.20.2"></a>
+### v2.20.2 (2017-02-03)
+
+#### Bug Fixes
+
+*   fixes a critical bug where subcommand settings were being propogated too far ([74648c94](https://github.com/kbknapp/clap-rs/commit/74648c94b893df542bfa5bb595e68c7bb8167e36), closes [#832](https://github.com/kbknapp/clap-rs/issues/832))
+
+
+#### Improvements
+
+*   adds ArgGroup::multiple to the supported YAML fields for building ArgGroups from YAML ([d8590037](https://github.com/kbknapp/clap-rs/commit/d8590037ce07dafd8cd5b26928aa4a9fd3018288), closes [#840](https://github.com/kbknapp/clap-rs/issues/840))
+
+<a name="v2.20.1"></a>
+### v2.20.1 (2017-01-31)
+
+#### Bug Fixes
+
+*   allow final word to be wrapped in wrap_help ([564c5f0f](https://github.com/kbknapp/clap-rs/commit/564c5f0f1730f4a2c1cdd128664f1a981c31dcd4), closes [#828](https://github.com/kbknapp/clap-rs/issues/828))
+*   actually show character in debug output ([84d8c547](https://github.com/kbknapp/clap-rs/commit/84d8c5476de95b7f37d61888bc4f13688b712434))
+*   include final character in line lenght ([aff4ba18](https://github.com/kbknapp/clap-rs/commit/aff4ba18da8147e1259b04b0bfbc1fcb5c78a3c0))
+
+#### Improvements
+
+*   updates libc and term_size deps for the libc version conflict ([6802ac4a](https://github.com/kbknapp/clap-rs/commit/6802ac4a59c142cda9ec55ca0c45ae5cb9a6ab55))
+
+#### Documentation
+
+*   fix link from app_from_crate! to crate_authors! (#822) ([5b29be9b](https://github.com/kbknapp/clap-rs/commit/5b29be9b073330ab1f7227cdd19fe4aab39d5dcb))
+*   fix spelling of "guaranteed" ([4f30a65b](https://github.com/kbknapp/clap-rs/commit/4f30a65b9c03eb09607eb91a929a6396637dc105))
+
+<a name="v2.20.0"></a>
+
+#### New Settings
+
+* **ArgsNegateSubcommands:**  disables args being allowed between subcommands ([5e2af8c9](https://github.com/kbknapp/clap-rs/commit/5e2af8c96adb5ab75fa2d1536237ebcb41869494), closes [#793](https://github.com/kbknapp/clap-rs/issues/793))
+* **DontCollapseArgsInUsage:** disables the collapsing of positional args into `[ARGS]` in the usage string  ([c2978afc](https://github.com/kbknapp/clap-rs/commit/c2978afc61fb46d5263ab3b2d87ecde1c9ce1553), closes [#769](https://github.com/kbknapp/clap-rs/issues/769))
+* **DisableHelpSubcommand:**  disables building the `help` subcommand  ([a10fc859](https://github.com/kbknapp/clap-rs/commit/a10fc859ee20159fbd9ff4337be59b76467a64f2))
+* **AllowMissingPositional:**  allows one to implement `$ prog [optional] <required>` style CLIs where the second postional argument is required, but the first is optional ([1110fdc7](https://github.com/kbknapp/clap-rs/commit/1110fdc7a345c108820dc45783a9bf893fa4c214), closes [#636](https://github.com/kbknapp/clap-rs/issues/636))
+* **PropagateGlobalValuesDown:**  automatically propagats global arg's values down through *used* subcommands ([985536c8](https://github.com/kbknapp/clap-rs/commit/985536c8ebcc09af98aac835f42a8072ad58c262), closes [#694](https://github.com/kbknapp/clap-rs/issues/694))
+
+#### API Additions
+
+##### Arg
+
+* **Arg::value_terminator:**  adds the ability to terminate multiple values with a given string or char ([be64ce0c](https://github.com/kbknapp/clap-rs/commit/be64ce0c373efc106384baca3f487ea99fe7b8cf), closes [#782](https://github.com/kbknapp/clap-rs/issues/782))
+* **Arg::default_value_if[s]:**  adds new methods for *conditional* default values (such as a particular value from another argument was used) ([eb4010e7](https://github.com/kbknapp/clap-rs/commit/eb4010e7b21724447ef837db11ac441915728f22))
+* **Arg::requires_if[s]:**  adds the ability to *conditionally* require additional args (such as if a particular value was used) ([198449d6](https://github.com/kbknapp/clap-rs/commit/198449d64393c265f0bc327aaeac23ec4bb97226))
+* **Arg::required_if[s]:**  adds the ability for an arg to be *conditionally* required (i.e. "arg X is only required if arg Y was used with value Z") ([ee9cfddf](https://github.com/kbknapp/clap-rs/commit/ee9cfddf345a6b5ae2af42ba72aa5c89e2ca7f59))
+* **Arg::validator_os:**  adds ability to validate values which may contain invalid UTF-8 ([47232498](https://github.com/kbknapp/clap-rs/commit/47232498a813db4f3366ccd3e9faf0bff56433a4))
+
+##### Macros
+
+* **crate_description!:** Uses the `Cargo.toml` description field to fill in the `App::about` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
+* **crate_name!:** Uses the `Cargo.toml` name field to fill in the `App::new` method at compile time ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
+* **app_from_crate!:** Combines `crate_version!`, `crate_name!`, `crate_description!`, and `crate_authors!` into a single macro call to build a default `App` instance from the `Cargo.toml` fields ([4d9a82db](https://github.com/kbknapp/clap-rs/commit/4d9a82db8e875e9b64a9c2a5c6e22c25afc1279d), closes [#778](https://github.com/kbknapp/clap-rs/issues/778))
+
+
+#### Features
+
+* **no_cargo:**  adds a `no_cargo` feature to disable Cargo-env-var-dependent macros for those *not* using `cargo` to build their crates (#786) ([6fdd2f9d](https://github.com/kbknapp/clap-rs/commit/6fdd2f9d693aaf1118fc61bd362273950703f43d))
+
+#### Bug Fixes
+
+* **Options:**  fixes a critical bug where options weren't forced to have a value ([5a5f2b1e](https://github.com/kbknapp/clap-rs/commit/5a5f2b1e9f598a0d0280ef3e98abbbba2bc41132), closes [#665](https://github.com/kbknapp/clap-rs/issues/665))
+*   fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([d3d34a2b](https://github.com/kbknapp/clap-rs/commit/d3d34a2b51ef31004055b0ab574f766d801c3adf), closes [#789](https://github.com/kbknapp/clap-rs/issues/789))
+* **Help Subcommand:**  fixes a bug where the help subcommand couldn't be overriden ([d34ec3e0](https://github.com/kbknapp/clap-rs/commit/d34ec3e032d03e402d8e87af9b2942fe2819b2da), closes [#787](https://github.com/kbknapp/clap-rs/issues/787))
+* **Low Index Multiples:**  fixes a bug which caused combinations of LowIndexMultiples and `Arg::allow_hyphen_values` to fail parsing ([26c670ca](https://github.com/kbknapp/clap-rs/commit/26c670ca16d2c80dc26d5c1ce83380ace6357318))
+
+#### Improvements
+
+* **Default Values:**  improves the error message when default values are involved ([1f33de54](https://github.com/kbknapp/clap-rs/commit/1f33de545036e7fd2f80faba251fca009bd519b8), closes [#774](https://github.com/kbknapp/clap-rs/issues/774))
+* **YAML:**  adds conditional requirements and conditional default values to YAML ([9a4df327](https://github.com/kbknapp/clap-rs/commit/9a4df327893486adb5558ffefba790c634ccdc6e), closes [#764](https://github.com/kbknapp/clap-rs/issues/764))
+*  Support `--("some-arg-name")` syntax for defining long arg names when using `clap_app!` macro ([f41ec962](https://github.com/kbknapp/clap-rs/commit/f41ec962c243a5ffff8b1be1ae2ad63970d3d1d4))
+*  Support `("some app name")` syntax for defining app names when using `clap_app!` macro ([9895b671](https://github.com/kbknapp/clap-rs/commit/9895b671cff784f35cf56abcd8270f7c2ba09699), closes [#759](https://github.com/kbknapp/clap-rs/issues/759))
+* **Help Wrapping:**  long app names (with spaces), authors, and descriptions are now wrapped appropriately ([ad4691b7](https://github.com/kbknapp/clap-rs/commit/ad4691b71a63e951ace346318238d8834e04ad8a), closes [#777](https://github.com/kbknapp/clap-rs/issues/777))
+
+
+#### Documentation
+
+* **Conditional Default Values:**  fixes the failing doc tests of Arg::default_value_ifs ([4ef09101](https://github.com/kbknapp/clap-rs/commit/4ef091019c083b4db1a0c13f1c1e95ac363259f2))
+* **Conditional Requirements:**  adds docs for Arg::requires_ifs ([7f296e29](https://github.com/kbknapp/clap-rs/commit/7f296e29db7d9036e76e5dbcc9c8b20dfe7b25bd))
+* **README.md:**  fix some typos ([f22c21b4](https://github.com/kbknapp/clap-rs/commit/f22c21b422d5b287d1a1ac183a379ee02eebf54f))
+* **src/app/mod.rs:**  fix some typos ([5c9b0d47](https://github.com/kbknapp/clap-rs/commit/5c9b0d47ca78dea285c5b9dec79063d24c3e451a))
+
+<a name="v2.19.3"></a>
+### v2.19.3 (2016-12-28)
+
+
+#### Bug Fixes
+
+*   fixes a bug where calling the help of a subcommand wasn't ignoring required args of parent commands ([a0ee4993](https://github.com/kbknapp/clap-rs/commit/a0ee4993015ea97b06b5bc9f378d8bcb18f1c51c), closes [#789](https://github.com/kbknapp/clap-rs/issues/789))
+
+
+
+<a name="v2.19.2"></a>
+### v2.19.2 (2016-12-08)
+
+#### Bug Fixes
+
+* **ZSH Completions:**  escapes square brackets in ZSH completions ([7e17d5a3](https://github.com/kbknapp/clap-rs/commit/7e17d5a36b2cc2cc77e7b15796b14d639ed3cbf7), closes [#771](https://github.com/kbknapp/clap-rs/issues/771))
+
+#### Documentation
+
+* **Examples:**  adds subcommand examples ([0e0f3354](https://github.com/kbknapp/clap-rs/commit/0e0f33547a6901425afc1d9fbe19f7ae3832d9a4), closes [#766](https://github.com/kbknapp/clap-rs/issues/766))
+* **README.md:**  adds guidance on when to use ~ in version pinning, and clarifies breaking change policy ([591eaefc](https://github.com/kbknapp/clap-rs/commit/591eaefc7319142ba921130e502bb0729feed907), closes [#765](https://github.com/kbknapp/clap-rs/issues/765))
+
+
+
+<a name="v2.19.1"></a>
+### v2.19.1 (2016-12-01)
+
+
+#### Bug Fixes
+
+* **Help Messages:**  fixes help message alignment when specific settings are used on options ([cd94b318](https://github.com/kbknapp/clap-rs/commit/cd94b3188d63b63295a319e90e826bca46befcd2), closes [#760](https://github.com/kbknapp/clap-rs/issues/760))
+
+#### Improvements
+
+* **Bash Completion:**  allows bash completion to fall back to traidtional bash completion upon no matching completing function ([b1b16d56](https://github.com/kbknapp/clap-rs/commit/b1b16d56d8fddf819bdbe24b3724bb6a9f3fa613)))
+
+
+<a name="v2.19.0"></a>
+## v2.19.0 (2016-11-21)
+
+#### Features
+
+*   allows specifying AllowLeadingHyphen style values, but only for specific args vice command wide ([c0d70feb](https://github.com/kbknapp/clap-rs/commit/c0d70febad9996a77a54107054daf1914c50d4ef), closes [#742](https://github.com/kbknapp/clap-rs/issues/742))
+
+#### Bug Fixes
+
+* **Required Unless:**  fixes a bug where having required_unless set doesn't work when conflicts are also set ([d20331b6](https://github.com/kbknapp/clap-rs/commit/d20331b6f7940ac3a4e919999f8bb4780875125d), closes [#753](https://github.com/kbknapp/clap-rs/issues/753))
+* **ZSH Completions:**  fixes an issue where zsh completions caused panics if there were no subcommands ([49e7cdab](https://github.com/kbknapp/clap-rs/commit/49e7cdab76dd1ccc07221e360f07808ec62648aa), closes [#754](https://github.com/kbknapp/clap-rs/issues/754))
+
+#### Improvements
+
+* **Validators:**  improves the error messages for validators ([65eb3385](https://github.com/kbknapp/clap-rs/commit/65eb33859d3ff53e7d3277f02a9d3fd9038a9dfb), closes [#744](https://github.com/kbknapp/clap-rs/issues/744))
+
+#### Documentation
+
+*   updates the docs landing page ([01e1e33f](https://github.com/kbknapp/clap-rs/commit/01e1e33f377934099a4a725fab5cd6c5ff50eaa2))
+*   adds the macro version back to the readme ([45eb9bf1](https://github.com/kbknapp/clap-rs/commit/45eb9bf130329c3f3853aba0342c2fe3c64ff80f))
+*   fix broken docs links ([808e7cee](https://github.com/kbknapp/clap-rs/commit/808e7ceeb86d4a319bdc270f51c23a64621dbfb3))
+* **Compatibility Policy:**  adds an official compatibility policy to ([760d66dc](https://github.com/kbknapp/clap-rs/commit/760d66dc17310b357f257776624151da933cd25d), closes [#740](https://github.com/kbknapp/clap-rs/issues/740))
+* **Contributing:**  updates the readme to improve the readability and contributing sections ([eb51316c](https://github.com/kbknapp/clap-rs/commit/eb51316cdfdc7258d287ba13b67ef2f42bd2b8f6))
+
+<a name="v2.18.0"></a>
+## v2.18.0 (2016-11-05)
+
+
+#### Features
+
+* **Completions:**  adds completion support for PowerShell. ([cff82c88](https://github.com/kbknapp/clap-rs/commit/cff82c880e21064fca63351507b80350df6caadf), closes [#729](https://github.com/kbknapp/clap-rs/issues/729))
+
+
+
+<a name="v2.17.1"></a>
+### v2.17.1 (2016-11-02)
+
+
+#### Bug Fixes
+
+* **Low Index Multiples:**  fixes a bug where using low index multiples was propagated to subcommands ([33924e88](https://github.com/kbknapp/clap-rs/commit/33924e884461983c4e6b5ea1330fecc769a4ade7), closes [#725](https://github.com/kbknapp/clap-rs/issues/725))
+
+
+
+<a name="v2.17.0"></a>
+## v2.17.0 (2016-11-01)
+
+
+#### Features
+
+* **Positional Args:**  allows specifying the second to last positional argument as multiple(true) ([1ced2a74](https://github.com/kbknapp/clap-rs/commit/1ced2a7433ea8937a1b260ea65d708f32ca7c95e), closes [#725](https://github.com/kbknapp/clap-rs/issues/725))
+
+
+
+<a name="v2.16.4"></a>
+### v2.16.4 (2016-10-31)
+
+
+#### Improvements
+
+* **Error Output:**  conflicting errors are now symetrical, meaning more consistent and less confusing ([3d37001d](https://github.com/kbknapp/clap-rs/commit/3d37001d1dc647d73cc597ff172f1072d4beb80d), closes [#718](https://github.com/kbknapp/clap-rs/issues/718))
+
+#### Documentation
+
+*   Fix typo in example `13a_enum_values_automatic` ([c22fbc07](https://github.com/kbknapp/clap-rs/commit/c22fbc07356e556ffb5d1a79ec04597d149b915e))
+* **README.md:**  fixes failing yaml example (#715) ([21fba9e6](https://github.com/kbknapp/clap-rs/commit/21fba9e6cd8c163012999cd0ce271ec8780c5695))
+
+#### Bug Fixes
+
+* **ZSH Completions:**  fixes bug that caused panic on subcommands with aliases ([5c70e1a0](https://github.com/kbknapp/clap-rs/commit/5c70e1a01bc977e44c10015d18bb8e215c32dfc8), closes [#714](https://github.com/kbknapp/clap-rs/issues/714))
+* **debug:**  fixes the debug feature (#716) ([6c11ccf4](https://github.com/kbknapp/clap-rs/commit/6c11ccf443d46258d51f7cda33fbcc81e7fe8e90))
+
+
+
+<a name="v2.16.3"></a>
+### v2.16.3 (2016-10-28)
+
+
+#### Bug Fixes
+
+*   Derive display order after propagation ([9cb6facf](https://github.com/kbknapp/clap-rs/commit/9cb6facf507aff7cddd124b8c29714d2b0e7bd13), closes [#706](https://github.com/kbknapp/clap-rs/issues/706))
+* **yaml-example:**  inconsistent args ([847f7199](https://github.com/kbknapp/clap-rs/commit/847f7199219ead5065561d91d64780d99ae4b587))
+
+
+
+<a name="v2.15.1"></a>
+### v2.16.2 (2016-10-25)
+
+
+#### Bug Fixes
+
+* **Fish Completions:**  fixes a bug where single quotes are not escaped ([780b4a18](https://github.com/kbknapp/clap-rs/commit/780b4a18281b6f7f7071e1b9db2290fae653c406), closes [#704](https://github.com/kbknapp/clap-rs/issues/704))
+
+
+<a name="v2.16.1"></a>
+### v2.16.1 (2016-10-24)
+
+
+#### Bug Fixes
+
+* **Help Message:**  fixes a regression bug where args with multiple(true) threw off alignment ([ebddac79](https://github.com/kbknapp/clap-rs/commit/ebddac791f3ceac193d5ad833b4b734b9643a7af), closes [#702](https://github.com/kbknapp/clap-rs/issues/702))
+
+
+
+<a name="v2.16.0"></a>
+## v2.16.0 (2016-10-23)
+
+
+#### Features
+
+* **Completions:**  adds ZSH completion support ([3e36b0ba](https://github.com/kbknapp/clap-rs/commit/3e36b0bac491d3f6194aee14604caf7be26b3d56), closes [#699](https://github.com/kbknapp/clap-rs/issues/699))
+
+
+
+<a name="v2.15.0"></a>
+## v2.15.0 (2016-10-21)
+
+
+#### Features
+
+* **AppSettings:**  adds new setting `AppSettings::AllowNegativeNumbers` ([ab064546](https://github.com/kbknapp/clap-rs/commit/ab06454677fb6aa9b9f804644fcca2168b1eaee3), closes [#696](https://github.com/kbknapp/clap-rs/issues/696))
+
+#### Documentation
+
+* **app/settings.rs:**  moves variants to roughly alphabetical order ([9ed4d4d7](https://github.com/kbknapp/clap-rs/commit/9ed4d4d7957a23357aef60081e45639ab9e3905f))
+
+
+<a name="v2.14.1"></a>
+### v2.14.1 (2016-10-20)
+
+
+#### Documentation
+
+*   Improve documentation around features ([4ee85b95](https://github.com/kbknapp/clap-rs/commit/4ee85b95d2d16708a016a3ba4e6e2c93b89b7fad))
+*   reword docs for ErrorKind and app::Settings ([3ccde7a4](https://github.com/kbknapp/clap-rs/commit/3ccde7a4b8f7a2ea8b916a5415c04a8ff4b5cb7a))
+*   fix tests that fail when the "suggestions" feature is disabled ([996fc381](https://github.com/kbknapp/clap-rs/commit/996fc381763a48d125c7ea8a58fed057fd0b4ac6))
+*   fix the OsString-using doc-tests ([af9e1a39](https://github.com/kbknapp/clap-rs/commit/af9e1a393ce6cdda46a03c8a4f48df222b015a24))
+*   tag non-rust code blocks as such instead of ignoring them ([0ba9f4b1](https://github.com/kbknapp/clap-rs/commit/0ba9f4b123f281952581b6dec948f7e51dd22890))
+* **ErrorKind:**  improve some errors about subcommands ([9f6217a4](https://github.com/kbknapp/clap-rs/commit/9f6217a424da823343d7b801b9c350dee3cd1906))
+* **yaml:**  make sure the doc-tests don't fail before "missing file" ([8c0f5551](https://github.com/kbknapp/clap-rs/commit/8c0f55516f4910c78c9f8a2bdbd822729574f95b))
+
+#### Improvements
+
+*   Stabilize clap_app! ([cd516006](https://github.com/kbknapp/clap-rs/commit/cd516006e35c37b005f329338560a0a53d1f3e00))
+* **with_defaults:**  Deprecate App::with_defaults() ([26085409](https://github.com/kbknapp/clap-rs/commit/2608540940c8bb66e517b65706bc7dea55510682), closes [#638](https://github.com/kbknapp/clap-rs/issues/638))
+
+#### Bug Fixes
+
+*   fixes a bug that made determining when to auto-wrap long help messages inconsistent ([468baadb](https://github.com/kbknapp/clap-rs/commit/468baadb8398fc1d37897b0c49374aef4cf97dca), closes [#688](https://github.com/kbknapp/clap-rs/issues/688))
+* **Completions:**  fish completions for nested subcommands ([a61eaf8a](https://github.com/kbknapp/clap-rs/commit/a61eaf8aade76cfe90ccc0f7125751ebf60e3254))
+* **features:**  Make lints not enable other nightly-requiring features ([835f75e3](https://github.com/kbknapp/clap-rs/commit/835f75e3ba20999117363ed9f916464d777f36ef))
+
+
+
+<a name="v2.14.0"></a>
+## v2.14.0 (2016-10-05)
+
+
+#### Features
+
+* **arg_aliases:**  Ability to alias arguments ([33b5f6ef](https://github.com/kbknapp/clap-rs/commit/33b5f6ef2c9612ecabb31f96b824793e46bfd3dd), closes [#669](https://github.com/kbknapp/clap-rs/issues/669))
+* **flag_aliases:**  Ability to alias flags ([40d6dac9](https://github.com/kbknapp/clap-rs/commit/40d6dac973927dded6ab423481634ef47ee7bfd7))
+
+#### Bug Fixes
+
+* **UsageParser:**  Handle non-ascii names / options. ([1d6a7c6e](https://github.com/kbknapp/clap-rs/commit/1d6a7c6e7e6aadc527346aa822f19d8587f714f3), closes [#664](https://github.com/kbknapp/clap-rs/issues/664))
+
+#### Documentation
+
+*   typo ([bac417fa](https://github.com/kbknapp/clap-rs/commit/bac417fa1cea3d32308334c7cccfcf54546cd9d8))
+
+
+<a name="v2.13.0"></a>
+## v2.13.0 (2016-09-18)
+
+
+#### Documentation
+
+*   updates README.md with new website information and updated video tutorials info ([0c19c580](https://github.com/kbknapp/clap-rs/commit/0c19c580cf50f1b82ff32f70b36708ae2bcac132))
+*   updates the docs about removing implicit value_delimiter(true) ([c81bc722](https://github.com/kbknapp/clap-rs/commit/c81bc722ebb8a86d22be89b5aec98df9fe222a08))
+* **Default Values:**  adds better examples on using default values ([57a8d9ab](https://github.com/kbknapp/clap-rs/commit/57a8d9abb2f973c235a8a14f8fc031673d7a7460), closes [#418](https://github.com/kbknapp/clap-rs/issues/418))
+
+#### Bug Fixes
+
+* **Value Delimiters:**  fixes the confusion around implicitly setting value delimiters. (default is now `false`) ([09d4d0a9](https://github.com/kbknapp/clap-rs/commit/09d4d0a9038d7ce2df55c2aec95e16f36189fcee), closes [#666](https://github.com/kbknapp/clap-rs/issues/666))
+
+
+
+<a name="v2.12.1"></a>
+### v2.12.1 (2016-09-13)
+
+
+#### Bug Fixes
+
+* **Help Wrapping:**  fixes a regression-bug where the old {n} newline char stopped working ([92ac353b](https://github.com/kbknapp/clap-rs/commit/92ac353b48b7caa2511ad2a046d94da93c236cf6), closes [#661](https://github.com/kbknapp/clap-rs/issues/661))
+
+
+
+<a name="v2.12.0"></a>
+## v2.12.0 (2016-09-13)
+
+
+#### Features
+
+* **Help:**  adds ability to hide the possible values on a per argument basis ([9151ef73](https://github.com/kbknapp/clap-rs/commit/9151ef739871f2e74910c342299c0de196b95dec), closes [#640](https://github.com/kbknapp/clap-rs/issues/640))
+* **help:**  allow for limiting detected terminal width ([a43e28af](https://github.com/kbknapp/clap-rs/commit/a43e28af85c9a9deaedd5ef735f4f13008daab29), closes [#653](https://github.com/kbknapp/clap-rs/issues/653))
+
+#### Documentation
+
+* **Help Wrapping:**  removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611))
+* **Value Delimiters:**  updates the docs for the Arg::multiple method WRT value delimiters and default settings ([f9d17a06](https://github.com/kbknapp/clap-rs/commit/f9d17a060aa53f10d0a6e1a7eed5d989d1a59533))
+* **appsettings:**  Document AppSetting::DisableVersion ([94501965](https://github.com/kbknapp/clap-rs/commit/945019654d2ca67eb2b1d6014fdf80b84d528d30), closes [#589](https://github.com/kbknapp/clap-rs/issues/589))
+
+#### Bug Fixes
+
+* **AllowLeadingHyphen:**  fixes a bug where valid args aren't recognized with this setting ([a9699e4d](https://github.com/kbknapp/clap-rs/commit/a9699e4d7cdc9a06e73b845933ff1fe6d76f016a), closes [#588](https://github.com/kbknapp/clap-rs/issues/588))
+
+#### Improvements
+
+* **Help Wrapping:**
+  *  clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617))
+  *  makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f))
+* **Value Delimiters:**  changes the default value delimiter rules ([f9e69254](https://github.com/kbknapp/clap-rs/commit/f9e692548e8c94de15f909432de301407d6bb834), closes [#655](https://github.com/kbknapp/clap-rs/issues/655))
+* **YAML:**  supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816))
+
+#### Performance
+
+* **help:**  fix redundant contains() checks ([a8afed74](https://github.com/kbknapp/clap-rs/commit/a8afed7428bf0733f8e93bb11ad6c00d9e970fcc))
+
+
+
+<a name="v2.11.3"></a>
+### v2.11.3 (2016-09-07)
+
+
+#### Documentation
+
+* **Help Wrapping:**  removes the verbiage about using `'{n}'` to insert newlines in help text ([c5a2b352](https://github.com/kbknapp/clap-rs/commit/c5a2b352ca600f5b802290ad945731066cd53611))
+
+#### Improvements
+
+* **Help Wrapping:**
+  *  clap now ignores hard newlines in help messages and properly re-aligns text, but still wraps if the term width is too small ([c7678523](https://github.com/kbknapp/clap-rs/commit/c76785239fd42adc8ca04f9202b6fec615aa9f14), closes [#617](https://github.com/kbknapp/clap-rs/issues/617))
+  *  makes some minor changes to when next line help is automatically used ([01cae799](https://github.com/kbknapp/clap-rs/commit/01cae7990a33167ac35103fb36c811b4fe6eb98f))
+* **YAML:**  supports setting Arg::require_delimiter from YAML ([b9b55a39](https://github.com/kbknapp/clap-rs/commit/b9b55a39dfebcdbdc05dca2692927e503db50816))
+
+
+
+
+<a name="v2.11.2"></a>
+### v2.11.2 (2016-09-06)
+
+#### Improvements
+
+* **Help Wrapping:**  makes some minor changes to when next line help is automatically used ([5658b117](https://github.com/kbknapp/clap-rs/commit/5658b117aec3e03adff9c8c52a4c4bc1fcb4e1ff))
+
+
+<a name="v2.11.1"></a>
+### v2.11.1 (2016-09-05)
+
+
+#### Bug Fixes
+
+* **Settings:**  fixes an issue where settings weren't propogated down through grand-child subcommands ([b3efc107](https://github.com/kbknapp/clap-rs/commit/b3efc107515d78517b20798ff3890b8a2b04498e), closes [#638](https://github.com/kbknapp/clap-rs/issues/638))
+
+#### Features
+
+* **Errors:**  Errors with custom description ([58512f2f](https://github.com/kbknapp/clap-rs/commit/58512f2fcb430745f1ee6ee8f1c67f62dc216c73))
+
+#### Improvements
+
+* **help:**  use term_size instead of home-grown solution ([fc7327e9](https://github.com/kbknapp/clap-rs/commit/fc7327e9dcf4258ef2baebf0a8714d9c0622855b))
+
+
+
+<a name="v2.11.0"></a>
+### v2.11.0 (2016-08-28)
+
+
+#### Bug Fixes
+
+* **Groups:**  fixes some usage strings that contain both args in groups and ones that conflict with each other ([3d782def](https://github.com/kbknapp/clap-rs/commit/3d782def57725e2de26ca5a5bc5cc2e40ddebefb), closes [#616](https://github.com/kbknapp/clap-rs/issues/616))
+
+#### Documentation
+
+*   moves docs to docs.rs ([03209d5e](https://github.com/kbknapp/clap-rs/commit/03209d5e1300906f00bafec1869c2047a92e5071), closes [#634](https://github.com/kbknapp/clap-rs/issues/634))
+
+#### Improvements
+
+* **Completions:**  uses standard conventions for bash completion files, namely '{bin}.bash-completion' ([27f5bbfb](https://github.com/kbknapp/clap-rs/commit/27f5bbfbcc9474c2f57c2b92b1feb898ae46ee70), closes [#567](https://github.com/kbknapp/clap-rs/issues/567))
+* **Help:**  automatically moves help text to the next line and wraps when term width is determined to be too small, or help text is too long ([150964c4](https://github.com/kbknapp/clap-rs/commit/150964c4e7124d54476c9d9b4b3f2406f0fd00e5), closes [#597](https://github.com/kbknapp/clap-rs/issues/597))
+* **YAML Errors:**  vastly improves error messages when using YAML ([f43b7c65](https://github.com/kbknapp/clap-rs/commit/f43b7c65941c53adc0616b8646a21dc255862eb2), closes [#574](https://github.com/kbknapp/clap-rs/issues/574))
+
+#### Features
+
+*   adds App::with_defaults to automatically use crate_authors! and crate_version! macros ([5520bb01](https://github.com/kbknapp/clap-rs/commit/5520bb012c127dfd299fd55699443c744d8dcd5b), closes [#600](https://github.com/kbknapp/clap-rs/issues/600))
+
+
+
+<a name="v2.10.4"></a>
+### v2.10.4 (2016-08-25)
+
+
+#### Bug Fixes
+
+* **Help Wrapping:**  fixes a bug where help is wrapped incorrectly and causing a panic with some non-English characters ([d0b442c7](https://github.com/kbknapp/clap-rs/commit/d0b442c7beeecac9764406bc3bd171ced0b8825e), closes [#626](https://github.com/kbknapp/clap-rs/issues/626))
+
+
+
+<a name="v2.10.3"></a>
+### v2.10.3 (2016-08-25)
+
+#### Features
+
+* **Help:**  adds new short hand way to use source formatting and ignore term width in help messages ([7dfdaf20](https://github.com/kbknapp/clap-rs/commit/7dfdaf200ebb5c431351a045b48f5e0f0d3f31db), closes [#625](https://github.com/kbknapp/clap-rs/issues/625))
+
+#### Documentation
+
+* **Term Width:**  adds details about set_term_width(0) ([00b8205d](https://github.com/kbknapp/clap-rs/commit/00b8205d22639d1b54b9c453c55c785aace52cb2))
+
+#### Bug Fixes
+
+* **Unicode:**  fixes two bugs where non-English characters were stripped or caused a panic with help wrapping ([763a5c92](https://github.com/kbknapp/clap-rs/commit/763a5c920e23efc74d190af0cb8b5dd714b2d67a), closes [#626](https://github.com/kbknapp/clap-rs/issues/626))
+
+
+
+<a name="v2.10.2"></a>
+### v2.10.2 (2016-08-22)
+
+
+#### Bug Fixes
+
+*   fixes a bug where the help is printed twice ([a643fb28](https://github.com/kbknapp/clap-rs/commit/a643fb283acd9905dc727c4579c5c9fa2ceaa7e7), closes [#623](https://github.com/kbknapp/clap-rs/issues/623))
+
+
+
+<a name="v2.10.1"></a>
+### v2.10.1 (2016-08-21)
+
+
+#### Bug Fixes
+
+* **Help Subcommand:**  fixes misleading usage string when using multi-level subcommmands ([e203515e](https://github.com/kbknapp/clap-rs/commit/e203515e3ac495b405dbba4f78fb6af148fd282e), closes [#618](https://github.com/kbknapp/clap-rs/issues/618))
+
+#### Features
+
+* **YAML:**  allows using lists or single values with arg declarations ([9ade2cd4](https://github.com/kbknapp/clap-rs/commit/9ade2cd4b268d6d7fe828319ce6a523c641b9c38), closes [#614](https://github.com/kbknapp/clap-rs/issues/614), [#613](https://github.com/kbknapp/clap-rs/issues/613))
+
+
+
+<a name="v2.10.0"></a>
+## v2.10.0 (2016-07-29)
+
+
+#### Features
+
+* **Completions:**  one can generate a basic fish completions script at compile time ([1979d2f2](https://github.com/kbknapp/clap-rs/commit/1979d2f2f3216e57d02a97e624a8a8f6cf867ed9))
+
+#### Bug Fixes
+
+* **parser:**  preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635))
+
+#### Breaking Changes
+
+* **parser:**  preserve external subcommand name ([875df243](https://github.com/kbknapp/clap-rs/commit/875df24316c266920a073c13bbefbf546bc1f635))
+
+#### Documentation
+
+* **YAML:**  fixes example 17's incorrect reference to arg_groups instead of groups ([b6c99e13](https://github.com/kbknapp/clap-rs/commit/b6c99e1377f918e78c16c8faced70a71607da931), closes [#601](https://github.com/kbknapp/clap-rs/issues/601))
+
+
+
+<a name="2.9.3"></a>
+### 2.9.3 (2016-07-24)
+
+
+#### Bug Fixes
+
+*   fixes bug where only first arg in list of required_unless_one is recognized ([1fc3b55b](https://github.com/kbknapp/clap-rs/commit/1fc3b55bd6c8653b02e7c4253749c6b77737d2ac), closes [#575](https://github.com/kbknapp/clap-rs/issues/575))
+* **Settings:**  fixes typo subcommandsrequired->subcommandrequired ([fc72cdf5](https://github.com/kbknapp/clap-rs/commit/fc72cdf591d30f5d9375d0b5cc2a2ff3e812f9f6), closes [#593](https://github.com/kbknapp/clap-rs/issues/593))
+
+#### Features
+
+* **Completions:**  adds the ability to generate completions to io::Write object ([9f62cf73](https://github.com/kbknapp/clap-rs/commit/9f62cf7378ba5acb5ce8c5bac89b4aa60c30755f))
+* **Settings:**  Add unset_setting and unset_settings fns to App (#598) ([0ceba231](https://github.com/kbknapp/clap-rs/commit/0ceba231c6767cd6d88fdb1feeeea41deadf77ff), closes [#590](https://github.com/kbknapp/clap-rs/issues/590))
+
+
+<a name="2.9.2"></a>
+### 2.9.2 (2016-07-03)
+
+
+#### Documentation
+
+* **Completions:**  fixes the formatting of the Cargo.toml excerpt in the completions example ([722f2607](https://github.com/kbknapp/clap-rs/commit/722f2607beaef56b6a0e433db5fd09492d9f028c))
+
+#### Bug Fixes
+
+* **Completions:**  fixes bug where --help and --version short weren't added to the completion list ([e9f2438e](https://github.com/kbknapp/clap-rs/commit/e9f2438e2ce99af0ae570a2eaf541fc7f55b771b), closes [#536](https://github.com/kbknapp/clap-rs/issues/536))
+
+
+
+<a name="2.9.1"></a>
+### 2.9.1 (2016-07-02)
+
+
+#### Improvements
+
+* **Completions:**  allows multiple completions to be built by namespacing with bin name ([57484b2d](https://github.com/kbknapp/clap-rs/commit/57484b2daeaac01c1026e8c84efc8bf099e0eb31))
+
+
+<a name="v2.9.0"></a>
+## v2.9.0 (2016-07-01)
+
+
+#### Documentation
+
+* **Completions:**
+  *  fixes some errors in the completion docs ([9b359bf0](https://github.com/kbknapp/clap-rs/commit/9b359bf06255d3dad8f489308044b60a9d1e6a87))
+  *  adds documentation for completion scripts ([c6c519e4](https://github.com/kbknapp/clap-rs/commit/c6c519e40efd6c4533a9ef5efe8e74fd150391b7))
+
+#### Features
+
+* **Completions:**
+  *  one can now generate a bash completions script at compile time! ([e75b6c7b](https://github.com/kbknapp/clap-rs/commit/e75b6c7b75f729afb9eb1d2a2faf61dca7674634), closes [#376](https://github.com/kbknapp/clap-rs/issues/376))
+  *  completions now include aliases to subcommands, including all subcommand options ([0ab9f840](https://github.com/kbknapp/clap-rs/commit/0ab9f84052a8cf65b5551657f46c0c270841e634), closes [#556](https://github.com/kbknapp/clap-rs/issues/556))
+  *  completions now continue completing even after first completion ([18fc2e5b](https://github.com/kbknapp/clap-rs/commit/18fc2e5b5af63bf54a94b72cec5e1223d49f4806))
+  *  allows matching on possible values in options ([89cc2026](https://github.com/kbknapp/clap-rs/commit/89cc2026ba9ac69cf44c5254360bbf99236d4f89), closes [#557](https://github.com/kbknapp/clap-rs/issues/557))
+
+#### Bug Fixes
+
+* **AllowLeadingHyphen:**  fixes an issue where  isn't ignored like it should be with this setting ([96c24c9a](https://github.com/kbknapp/clap-rs/commit/96c24c9a8fa1f85e06138d3cdd133e51659e19d2), closes [#558](https://github.com/kbknapp/clap-rs/issues/558))
+
+<a name="v2.8.0"></a>
+## v2.8.0 (2016-06-30)
+
+
+#### Features
+
+* **Arg:**  adds new setting `Arg::require_delimiter` which requires val delimiter to parse multiple values ([920b5595](https://github.com/kbknapp/clap-rs/commit/920b5595ed72abfb501ce054ab536067d8df2a66))
+
+#### Bug Fixes
+
+*   Declare term::Winsize as repr(C) ([5d663d90](https://github.com/kbknapp/clap-rs/commit/5d663d905c9829ce6e7a164f1f0896cdd70236dd))
+
+#### Documentation
+
+* **Arg:**  adds docs for ([49af4e38](https://github.com/kbknapp/clap-rs/commit/49af4e38a5dae2ab0a7fc3b4147e2c053d532484))
+
+
+
+<a name="v2.7.1"></a>
+### v2.7.1 (2016-06-29)
+
+
+#### Bug Fixes
+
+* **Options:**
+  *  options with multiple values and using delimiters no longer parse additional values after a trailing space ([cdc500bd](https://github.com/kbknapp/clap-rs/commit/cdc500bdde6abe238c36ade406ddafc2bafff583))
+  *  using options with multiple values and with an = no longer parse args after the trailing space as values ([290f61d0](https://github.com/kbknapp/clap-rs/commit/290f61d07177413cf082ada55526d83405f6d011))
+
+
+
+<a name="v2.7.0"></a>
+## v2.7.0 (2016-06-28)
+
+
+#### Documentation
+
+*   fix typos ([43b3d40b](https://github.com/kbknapp/clap-rs/commit/43b3d40b8c38b1571da75af86b5088be96cccec2))
+* **ArgGroup:**  vastly improves ArgGroup docs by adding better examples ([9e5f4f5d](https://github.com/kbknapp/clap-rs/commit/9e5f4f5d734d630bca5535c3a0aa4fd4f9db3e39), closes [#534](https://github.com/kbknapp/clap-rs/issues/534))
+
+#### Features
+
+* **ArgGroup:**  one can now specify groups which require AT LEAST one of the args ([33689acc](https://github.com/kbknapp/clap-rs/commit/33689acc689b217a8c0ee439f1b1225590c38355), closes [#533](https://github.com/kbknapp/clap-rs/issues/533))
+
+#### Bug Fixes
+
+* **App:**  using `App::print_help` now prints the same as would have been printed by `--help` or the like ([e84cc018](https://github.com/kbknapp/clap-rs/commit/e84cc01836bbe0527e97de6db9889bd9e0fd6ba1), closes [#536](https://github.com/kbknapp/clap-rs/issues/536))
+* **Help:**
+  *  prevents invoking <cmd> help help and displaying incorrect help message ([e3d2893f](https://github.com/kbknapp/clap-rs/commit/e3d2893f377942a2d4cf3c6ff04524d0346e6fdb), closes [#538](https://github.com/kbknapp/clap-rs/issues/538))
+  *  subcommand help messages requested via <cmd> help <sub> now correctly match <cmd> <sub> --help ([08ad1cff](https://github.com/kbknapp/clap-rs/commit/08ad1cff4fec57224ea957a2891a057b323c01bc), closes [#539](https://github.com/kbknapp/clap-rs/issues/539))
+
+#### Improvements
+
+* **ArgGroup:**  Add multiple ArgGroups per Arg ([902e182f](https://github.com/kbknapp/clap-rs/commit/902e182f7a58aff11ff01e0a452abcdbdb2262aa), closes [#426](https://github.com/kbknapp/clap-rs/issues/426))
+* **Usage Strings:**  `[FLAGS]` and `[ARGS]` are no longer blindly added to usage strings ([9b2e45b1](https://github.com/kbknapp/clap-rs/commit/9b2e45b170aff567b038d8b3368880b6046c10c6), closes [#537](https://github.com/kbknapp/clap-rs/issues/537))
+* **arg_enum!:**  allows using meta items like repr(C) with arg_enum!s ([edf9b233](https://github.com/kbknapp/clap-rs/commit/edf9b2331c17a2cbcc13f961add4c55c2778e773), closes [#543](https://github.com/kbknapp/clap-rs/issues/543))
+
+
+
+<a name="v2.6.0"></a>
+## v2.6.0 (2016-06-14)
+
+
+#### Improvements
+
+*   removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115))
+*   allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724))
+*   removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589))
+* **Aliases:**  improves readability of asliases in help messages ([ca511de7](https://github.com/kbknapp/clap-rs/commit/ca511de71f5b8c2ac419f1b188658e8c63b67846), closes [#526](https://github.com/kbknapp/clap-rs/issues/526), [#529](https://github.com/kbknapp/clap-rs/issues/529))
+* **Usage Strings:**  improves the default usage string when only a single positional arg is present ([ec86f2da](https://github.com/kbknapp/clap-rs/commit/ec86f2dada1545a63fc72355e22fcdc4c466c215), closes [#518](https://github.com/kbknapp/clap-rs/issues/518))
+
+#### Features
+
+* **Help:**  allows wrapping at specified term width (Even on Windows!) ([1761dc0d](https://github.com/kbknapp/clap-rs/commit/1761dc0d27d0d621229d792be40c36fbf65c3014), closes [#451](https://github.com/kbknapp/clap-rs/issues/451))
+* **Settings:**
+  *  adds new setting to stop delimiting values with -- or TrailingVarArg ([fc3e0f5a](https://github.com/kbknapp/clap-rs/commit/fc3e0f5afda6d24cdb3c4676614beebe13e1e870), closes [#511](https://github.com/kbknapp/clap-rs/issues/511))
+  *  one can now set an AppSetting which is propogated down through child subcommands ([e2341835](https://github.com/kbknapp/clap-rs/commit/e23418351a3b98bf08dfd7744bc14377c70d59ee), closes [#519](https://github.com/kbknapp/clap-rs/issues/519))
+* **Subcommands:**  adds support for visible aliases ([7b10e7f8](https://github.com/kbknapp/clap-rs/commit/7b10e7f8937a07fdb8d16a6d8df79ce78d080cd3), closes [#522](https://github.com/kbknapp/clap-rs/issues/522))
+
+#### Bug Fixes
+
+*   fixes bug where args are printed out of order with templates ([05abb534](https://github.com/kbknapp/clap-rs/commit/05abb534864764102031a0d402e64ac65867aa87))
+*   fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514))
+*   fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106))
+* **Help:**  `App::before_help` and `App::after_help` now correctly wrap ([1f4da767](https://github.com/kbknapp/clap-rs/commit/1f4da7676e6e71aa8dda799f3eeefad105a47819), closes [#516](https://github.com/kbknapp/clap-rs/issues/516))
+* **Settings:**  fixes bug where new color settings couldn't be converted from strs ([706a7c11](https://github.com/kbknapp/clap-rs/commit/706a7c11b0900be594de6d5a3121938eff197602))
+* **Subcommands:**  subcommands with aliases now display help of the aliased subcommand ([5354d14b](https://github.com/kbknapp/clap-rs/commit/5354d14b51f189885ba110e01e6b76cca3752992), closes [#521](https://github.com/kbknapp/clap-rs/issues/521))
+* **Windows:**  fixes a failing windows build ([01e7dfd6](https://github.com/kbknapp/clap-rs/commit/01e7dfd6c07228c0be6695b3c7bf9370d82860d4))
+* **YAML:**  adds missing YAML methods for App and Arg ([e468faf3](https://github.com/kbknapp/clap-rs/commit/e468faf3f05950fd9f72d84b69aa2061e91c6c64), closes [#528](https://github.com/kbknapp/clap-rs/issues/528))
+
+
+
+<a name="v2.5.2"></a>
+### v2.5.2 (2016-05-31)
+
+
+#### Improvements
+
+*   removes extra newline from help output ([86e61d19](https://github.com/kbknapp/clap-rs/commit/86e61d19a748fb9870fcf1175308984e51ca1115))
+*   allows printing version to any io::Write object ([921f5f79](https://github.com/kbknapp/clap-rs/commit/921f5f7916597f1d028cd4a65bfe76a01c801724))
+*   removes extra newline when printing version ([7e2e2cbb](https://github.com/kbknapp/clap-rs/commit/7e2e2cbb4a8a0f050bb8072a376f742fc54b8589))
+
+#### Bug Fixes
+
+*   fixes bug where args are printed out of order with templates ([3935431d](https://github.com/kbknapp/clap-rs/commit/3935431d5633f577c0826ae2142794b301f4b8ca))
+*   fixes bug where one can't override version or help flags ([90d7d6a2](https://github.com/kbknapp/clap-rs/commit/90d7d6a2ea8240122dd9bf8d82d3c4f5ebb5c703), closes [#514](https://github.com/kbknapp/clap-rs/issues/514))
+*   fixes issue where before_help wasn't printed ([b3faff60](https://github.com/kbknapp/clap-rs/commit/b3faff6030f76a23f26afcfa6a90169002ed7106))
+
+#### Documentation
+
+*   inter-links all types and pages ([3312893d](https://github.com/kbknapp/clap-rs/commit/3312893ddaef3f44d68d8d26ed3d08010be50d97), closes [#505](https://github.com/kbknapp/clap-rs/issues/505))
+*   makes all publicly available types viewable in docs ([52ca6505](https://github.com/kbknapp/clap-rs/commit/52ca6505b4fec7b5c2d53d160c072d395eb21da6))
+
+<a name="v2.5.1"></a>
+### v2.5.1 (2016-05-11)
+
+
+#### Bug Fixes
+
+* **Subcommand Aliases**: fixes lifetime issue when setting multiple aliases at once ([ac42f6cf0](https://github.com/kbknapp/clap-rs/commit/ac42f6cf0de6c4920f703807d63061803930b18d))
+
+<a name="v2.5.0"></a>
+## v2.5.0 (2016-05-10)
+
+
+#### Improvements
+
+* **SubCommand Aliases:**  adds feature to yaml configs too ([69592195](https://github.com/kbknapp/clap-rs/commit/695921954dde46dfd483399dcdef482c9dd7f34a))
+
+#### Features
+
+* **SubCommands:**  adds support for subcommand aliases ([66b4dea6](https://github.com/kbknapp/clap-rs/commit/66b4dea65c44d8f77ff522238a9237aed1bcab6d), closes [#469](https://github.com/kbknapp/clap-rs/issues/469))
+
+
+<a name="v2.4.3"></a>
+### v2.4.3 (2016-05-10)
+
+
+#### Bug Fixes
+
+* **Usage Strings:**
+  *  now properly dedups args that are also in groups ([3ca0947c](https://github.com/kbknapp/clap-rs/commit/3ca0947c166b4f8525752255e3a4fa6565eb9689), closes [#498](https://github.com/kbknapp/clap-rs/issues/498))
+  *  removes duplicate groups from usage strings ([f574fb8a](https://github.com/kbknapp/clap-rs/commit/f574fb8a7cde4d4a2fa4c4481d59be2d0f135427))
+
+#### Improvements
+
+* **Groups:**  formats positional args in groups in a better way ([fef11154](https://github.com/kbknapp/clap-rs/commit/fef11154fb7430d1cbf04a672aabb366e456a368))
+* **Help:**
+  *  moves positionals to standard <> formatting ([03dfe5ce](https://github.com/kbknapp/clap-rs/commit/03dfe5ceff1d63f172788ff688567ddad9fe119b))
+  *  default help subcommand string has been shortened ([5b7fe8e4](https://github.com/kbknapp/clap-rs/commit/5b7fe8e4161e43ab19e2e5fcf55fbe46791134e9), closes [#494](https://github.com/kbknapp/clap-rs/issues/494))
+
+<a name="v2.4.2"></a>
+### v2.4.3 (2016-05-10)
+
+* Ghost Release
+
+<a name="v2.4.1"></a>
+### v2.4.3 (2016-05-10)
+
+* Ghost Release
+
+<a name="v2.4.0"></a>
+## v2.4.0 (2016-05-02)
+
+
+#### Features
+
+* **Help:**  adds support for displaying info before help message ([29fbfa3b](https://github.com/kbknapp/clap-rs/commit/29fbfa3b963f2f3ca7704bf5d3e1201531baa373))
+* **Required:**  adds allowing args that are required unless certain args are present ([af1f7916](https://github.com/kbknapp/clap-rs/commit/af1f79168390ea7da4074d0d9777de458ea64971))
+
+#### Documentation
+
+*   hides formatting from docs ([cb708093](https://github.com/kbknapp/clap-rs/commit/cb708093a7cd057f08c98b7bd1ed54c2db86ae7e))
+* **required_unless:**  adds docs and examples for required_unless ([ca727b52](https://github.com/kbknapp/clap-rs/commit/ca727b52423b9883acd88b2f227b2711bc144573))
+
+#### Bug Fixes
+
+* **Required Args:**  fixes issue where missing required args are sometimes duplicatd in error messages ([3beebd81](https://github.com/kbknapp/clap-rs/commit/3beebd81e7bc2faa4115ac109cf570e512c5477f), closes [#492](https://github.com/kbknapp/clap-rs/issues/492))
+
+
+<a name="v2.3.0"></a>
+## v2.3.0 (2016-04-18)
+
+
+#### Improvements
+
+* **macros.rs:**  Added write_nspaces macro (a new version of write_spaces) ([9d757e86](https://github.com/kbknapp/clap-rs/commit/9d757e8678e334e5a740ac750c76a9ed4e785cba))
+* **parser.rs:**
+  *  Provide a way to create a usage string without the USAGE: title ([a91d378b](https://github.com/kbknapp/clap-rs/commit/a91d378ba0c91b5796457f8c6e881b13226ab735))
+  *  Make Parser's create_usage public allowing to have function outside the parser to generate the help ([d51945f8](https://github.com/kbknapp/clap-rs/commit/d51945f8b82ebb0963f4f40b384a9e8335783091))
+  *  Expose Parser's flags, opts and positionals argument as iterators ([9b23e7ee](https://github.com/kbknapp/clap-rs/commit/9b23e7ee40e51f7a823644c4496be955dc6c9d3a))
+* **src/args:**  Exposes argument display order by introducing a new Trait ([1321630e](https://github.com/kbknapp/clap-rs/commit/1321630ef56955f152c73376d4d85cceb0bb4a12))
+* **srs/args:**  Added longest_filter to AnyArg trait ([65b3f667](https://github.com/kbknapp/clap-rs/commit/65b3f667532685f854c699ddd264d326599cf7e5))
+
+#### Features
+
+* **Authors Macro:**  adds a crate_authors macro ([38fb59ab](https://github.com/kbknapp/clap-rs/commit/38fb59abf480eb2b6feca269097412f8b00b5b54), closes [#447](https://github.com/kbknapp/clap-rs/issues/447))
+* **HELP:**
+  *  implements optional colored help messages ([abc8f669](https://github.com/kbknapp/clap-rs/commit/abc8f669c3c8193ffc3a3b0ac6c3ac2198794d4f), closes [#483](https://github.com/kbknapp/clap-rs/issues/483))
+  *  Add a Templated Help system. ([81e121ed](https://github.com/kbknapp/clap-rs/commit/81e121edd616f7285593f11120c63bcccae0d23e))
+
+#### Bug Fixes
+
+* **HELP:**  Adjust Help to semantic changes introduced in 6933b84 ([8d23806b](https://github.com/kbknapp/clap-rs/commit/8d23806bd67530ad412c34a1dcdcb1435555573d))
+
+<a name="v2.2.6"></a>
+### v2.2.6 (2016-04-11)
+
+#### Bug Fixes
+
+* **Arg Groups**: fixes bug where arg name isn't printed properly ([3019a685](https://github.com/kbknapp/clap-rs/commit/3019a685eee747ccbe6be09ad5dddce0b1d1d4db), closes [#476](https://github.com/kbknapp/clap-rs/issues/476))
+
+
+<a name="v2.2.5"></a>
+### v2.2.5 (2016-04-03)
+
+
+#### Bug Fixes
+
+* **Empty Values:**  fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470))
+* **Help Message:**  fixes bug where arg name is printed twice ([71acf1d5](https://github.com/kbknapp/clap-rs/commit/71acf1d576946658b8bbdb5ae79e6716c43a030f), closes [#472](https://github.com/kbknapp/clap-rs/issues/472))
+
+
+<a name="v2.2.4"></a>
+### v2.2.4 (2016-03-30)
+
+
+#### Bug Fixes
+
+*   fixes compiling with debug cargo feature ([d4b55450](https://github.com/kbknapp/clap-rs/commit/d4b554509928031ac0808076178075bb21f8c1da))
+* **Empty Values:**  fixes bug where empty values weren't stored ([885d166f](https://github.com/kbknapp/clap-rs/commit/885d166f04eb3fb581898ae5818c6c8032e5a686), closes [#470](https://github.com/kbknapp/clap-rs/issues/470))
+
+
+
+<a name="v2.2.3"></a>
+### v2.2.3 (2016-03-28)
+
+
+#### Bug Fixes
+
+* **Help Subcommand:**  fixes issue where help and version flags weren't properly displayed ([205b07bf](https://github.com/kbknapp/clap-rs/commit/205b07bf2e6547851f1290f8cd6b169145e144f1), closes [#466](https://github.com/kbknapp/clap-rs/issues/466))
+
+<a name="v2.2.2"></a>
+### v2.2.2 (2016-03-27)
+
+
+#### Bug Fixes
+
+* **Help Message:**  fixes bug with wrapping in the middle of a unicode sequence ([05365ddc](https://github.com/kbknapp/clap-rs/commit/05365ddcc252e4b49e7a75e199d6001a430bd84d), closes [#456](https://github.com/kbknapp/clap-rs/issues/456))
+* **Usage Strings:**  fixes small bug where -- would appear needlessly in usage strings ([6933b849](https://github.com/kbknapp/clap-rs/commit/6933b8491c2a7e28cdb61b47dcf10caf33c2f78a), closes [#461](https://github.com/kbknapp/clap-rs/issues/461))
+
+
+<a name="2.2.1"></a>
+### 2.2.1 (2016-03-16)
+
+
+#### Features
+
+* **Help Message:**  wraps and aligns the help message of subcommands ([813d75d0](https://github.com/kbknapp/clap-rs/commit/813d75d06fbf077c65762608c0fa5e941cfc393c), closes [#452](https://github.com/kbknapp/clap-rs/issues/452))
+
+#### Bug Fixes
+
+* **Help Message:**  fixes a bug where small terminal sizes causing a loop ([1d73b035](https://github.com/kbknapp/clap-rs/commit/1d73b0355236923aeaf6799abc759762ded7e1d0), closes [#453](https://github.com/kbknapp/clap-rs/issues/453))
+
+
+<a name="v2.2.0"></a>
+## v2.2.0 (2016-03-15)
+
+
+#### Features
+
+* **Help Message:**  can auto wrap and aligning help text to term width ([e36af026](https://github.com/kbknapp/clap-rs/commit/e36af0266635f23e85e951b9088d561e9a5d1bf6), closes [#428](https://github.com/kbknapp/clap-rs/issues/428))
+* **Help Subcommand:**  adds support passing additional subcommands to help subcommand ([2c12757b](https://github.com/kbknapp/clap-rs/commit/2c12757bbdf34ce481f3446c074e24c09c2e60fd), closes [#416](https://github.com/kbknapp/clap-rs/issues/416))
+* **Opts and Flags:**  adds support for custom ordering in help messages ([9803b51e](https://github.com/kbknapp/clap-rs/commit/9803b51e799904c0befaac457418ee766ccc1ab9))
+* **Settings:**  adds support for automatically deriving custom display order of args ([ad86e433](https://github.com/kbknapp/clap-rs/commit/ad86e43334c4f70e86909689a088fb87e26ff95a), closes [#444](https://github.com/kbknapp/clap-rs/issues/444))
+* **Subcommands:**  adds support for custom ordering in help messages ([7d2a2ed4](https://github.com/kbknapp/clap-rs/commit/7d2a2ed413f5517d45988eef0765cdcd663b6372), closes [#442](https://github.com/kbknapp/clap-rs/issues/442))
+
+#### Bug Fixes
+
+* **From Usage:**  fixes a bug where adding empty lines werent ignored ([c5c58c86](https://github.com/kbknapp/clap-rs/commit/c5c58c86b9c503d8de19da356a5a5cffb59fbe84))
+
+#### Documentation
+
+* **Groups:**  explains required ArgGroups better ([4ff0205b](https://github.com/kbknapp/clap-rs/commit/4ff0205b85a45151b59bbaf090a89df13438380f), closes [#439](https://github.com/kbknapp/clap-rs/issues/439))
+
+<a name="v2.1.2"></a>
+### v2.1.2 (2016-02-24)
+
+#### Bug Fixes
+
+* **Nightly:**  fixes failing nightly build ([d752c170](https://github.com/kbknapp/clap-rs/commit/d752c17029598b19037710f204b7943f0830ae75), closes [#434](https://github.com/kbknapp/clap-rs/issues/434))
+
+
+<a name="v2.1.1"></a>
+### v2.1.1 (2016-02-19)
+
+
+#### Documentation
+
+* **AppSettings:**  clarifies that AppSettings do not propagate ([3c8db0e9](https://github.com/kbknapp/clap-rs/commit/3c8db0e9be1d24edaad364359513cbb02abb4186), closes [#429](https://github.com/kbknapp/clap-rs/issues/429))
+* **Arg Examples:**  adds better examples ([1e79cccc](https://github.com/kbknapp/clap-rs/commit/1e79cccc12937bc0e7cd2aad8e404410798e9fff))
+
+#### Improvements
+
+* **Help:**  adds setting for next line help by arg ([066df748](https://github.com/kbknapp/clap-rs/commit/066df7486e684cf50a8479a356a12ba972c34ce1), closes [#427](https://github.com/kbknapp/clap-rs/issues/427))
+
+
+<a name="v2.1.0"></a>
+## v2.1.0 (2016-02-10)
+
+
+#### Features
+
+* **Defult Values:**  adds support for default values in args ([73211952](https://github.com/kbknapp/clap-rs/commit/73211952964a79d97b434dd567e6d7d34be7feb5), closes [#418](https://github.com/kbknapp/clap-rs/issues/418))
+
+#### Documentation
+
+* **Default Values:**  adds better examples and notes for default values ([9facd74f](https://github.com/kbknapp/clap-rs/commit/9facd74f843ef3807c5d35259558a344e6c25905))
+
+
+<a name="v2.0.6"></a>
+### v2.0.6 (2016-02-09)
+
+
+#### Improvements
+
+* **Positional Arguments:**  now displays value name if appropriate ([f0a99916](https://github.com/kbknapp/clap-rs/commit/f0a99916c59ce675515c6dcdfe9a40b130510908), closes [#420](https://github.com/kbknapp/clap-rs/issues/420))
+
+
+<a name="v2.0.5"></a>
+### v2.0.5 (2016-02-05)
+
+
+#### Bug Fixes
+
+* **Multiple Values:**  fixes bug where number_of_values wasnt respected ([72c387da](https://github.com/kbknapp/clap-rs/commit/72c387da0bb8a6f526f863770f08bb8ca0d3de03))
+
+
+<a name="v2.0.4"></a>
+### v2.0.4 (2016-02-04)
+
+
+#### Bug Fixes
+
+*   adds support for building ArgGroups from standalone YAML ([fcbc7e12](https://github.com/kbknapp/clap-rs/commit/fcbc7e12f5d7b023b8f30cba8cad28a01cf6cd26))
+*   Stop lonely hyphens from causing panic ([85b11468](https://github.com/kbknapp/clap-rs/commit/85b11468b0189d5cc15f1cfac5db40d17a0077dc), closes [#410](https://github.com/kbknapp/clap-rs/issues/410))
+* **AppSettings:**  fixes bug where subcmds didn't receive parent ver ([a62e4527](https://github.com/kbknapp/clap-rs/commit/a62e452754b3b0e3ac9a15aa8b5330636229ead1))
+
+<a name="v2.0.3"></a>
+### v2.0.3 (2016-02-02)
+
+
+#### Improvements
+
+* **values:**  adds support for up to u64::max values per arg ([c7abf7d7](https://github.com/kbknapp/clap-rs/commit/c7abf7d7611e317b0d31d97632e3d2e13570947c))
+* **occurrences:**  Allow for more than 256 occurrences of an argument. ([3731ddb3](https://github.com/kbknapp/clap-rs/commit/3731ddb361163f3d6b86844362871e48c80fa530))
+
+#### Features
+
+* **AppSettings:**  adds HidePossibleValuesInHelp to skip writing those values ([cdee7a0e](https://github.com/kbknapp/clap-rs/commit/cdee7a0eb2beeec723cb98acfacf03bf629c1da3))
+
+#### Bug Fixes
+
+* **value_t_or_exit:**  fixes typo which causes value_t_or_exit to return a Result ([ee96baff](https://github.com/kbknapp/clap-rs/commit/ee96baffd306cb8d20ddc5575cf739bb1a6354e8))
+
+
+<a name="v2.0.2"></a>
+### v2.0.2 (2016-01-31)
+
+
+#### Improvements
+
+* **arg_enum:**  enum declared with arg_enum returns [&'static str; #] instead of Vec ([9c4b8a1a](https://github.com/kbknapp/clap-rs/commit/9c4b8a1a6b12949222f17d1074578ad7676b9c0d))
+
+#### Bug Fixes
+
+*   clap_app! should be gated by unstable, not nightly feature ([0c8b84af](https://github.com/kbknapp/clap-rs/commit/0c8b84af6161d5baf683688eafc00874846f83fa))
+* **SubCommands:**  fixed where subcmds weren't recognized after mult args ([c19c17a8](https://github.com/kbknapp/clap-rs/commit/c19c17a8850602990e24347aeb4427cf43316223), closes [#405](https://github.com/kbknapp/clap-rs/issues/405))
+* **Usage Parser:**  fixes a bug where literal single quotes weren't allowed in help strings ([0bcc7120](https://github.com/kbknapp/clap-rs/commit/0bcc71206478074769e311479b34a9f74fe80f5c), closes [#406](https://github.com/kbknapp/clap-rs/issues/406))
+
+
+<a name="v2.0.1"></a>
+### v2.0.1 (2016-01-30)
+
+
+#### Bug Fixes
+
+*   fixes cargo features to NOT require nightly with unstable features ([dcbcc60c](https://github.com/kbknapp/clap-rs/commit/dcbcc60c9ba17894be636472ea4b07a82d86a9db), closes [#402](https://github.com/kbknapp/clap-rs/issues/402))
+
+
+<a name="v2.0.0"></a>
+## v2.0.0 (2016-01-28)
+
+
+#### Improvements
+
+* **From Usage:**  vastly improves the usage parser ([fa3a2f86](https://github.com/kbknapp/clap-rs/commit/fa3a2f86bd674c5eb07128c95098fab7d1437247), closes [#350](https://github.com/kbknapp/clap-rs/issues/350))
+
+#### Features
+
+*   adds support for external subcommands ([177fe5cc](https://github.com/kbknapp/clap-rs/commit/177fe5cce745c2164a8e38c23be4c4460d2d7211), closes [#372](https://github.com/kbknapp/clap-rs/issues/372))
+*   adds support values with a leading hyphen ([e4d429b9](https://github.com/kbknapp/clap-rs/commit/e4d429b9d52e95197bd0b572d59efacecf305a59), closes [#385](https://github.com/kbknapp/clap-rs/issues/385))
+*   adds support for turning off the value delimiter ([508db850](https://github.com/kbknapp/clap-rs/commit/508db850a87c2e251cf6b6ddead9ad56b29f9e57), closes [#352](https://github.com/kbknapp/clap-rs/issues/352))
+*   adds support changing the value delimiter ([dafeae8a](https://github.com/kbknapp/clap-rs/commit/dafeae8a526162640f6a68da434370c64d190889), closes [#353](https://github.com/kbknapp/clap-rs/issues/353))
+*   adds support for comma separated values ([e69da6af](https://github.com/kbknapp/clap-rs/commit/e69da6afcd2fe48a3c458ca031db40997f860eda), closes [#348](https://github.com/kbknapp/clap-rs/issues/348))
+*   adds support with options with optional values ([4555736c](https://github.com/kbknapp/clap-rs/commit/4555736cad01441dcde4ea84a285227e0844c16e), closes [#367](https://github.com/kbknapp/clap-rs/issues/367))
+* **UTF-8:**  adds support for invalid utf8 in values ([c5c59dec](https://github.com/kbknapp/clap-rs/commit/c5c59dec0bc33b86b2e99d30741336f17ec84282), closes [#269](https://github.com/kbknapp/clap-rs/issues/269))
+* **v2:**  implementing the base of 2.x ([a3536054](https://github.com/kbknapp/clap-rs/commit/a3536054512ba833533dc56615ce3663d884381c))
+
+#### Bug Fixes
+
+*   fixes nightly build with new lints ([17599195](https://github.com/kbknapp/clap-rs/commit/175991956c37dc83ba9c49396e927a1cb65c5b11))
+*   fixes Windows build for 2x release ([674c9b48](https://github.com/kbknapp/clap-rs/commit/674c9b48c7c92079cb180cc650a9e39f34781c32), closes [#392](https://github.com/kbknapp/clap-rs/issues/392))
+*   fixes yaml build for 2x base ([adceae64](https://github.com/kbknapp/clap-rs/commit/adceae64c8556d00ab715677377b216f9f468ad7))
+
+#### Documentation
+
+*   updates examples for 2x release ([1303b360](https://github.com/kbknapp/clap-rs/commit/1303b3607468f362ab1b452d5614c1a064dc69b4), closes [#394](https://github.com/kbknapp/clap-rs/issues/394))
+*   updates examples for 2x release ([0a011f31](https://github.com/kbknapp/clap-rs/commit/0a011f3142aec338d388a6c8bfe22fa7036021bb), closes [#394](https://github.com/kbknapp/clap-rs/issues/394))
+*   updates documentation for v2 release ([8d51724e](https://github.com/kbknapp/clap-rs/commit/8d51724ef73dfde5bb94fb9466bc5463a1cc1502))
+*   updating docs for 2x release ([576d0e0e](https://github.com/kbknapp/clap-rs/commit/576d0e0e2c7b8f386589179bbf7419b93abacf1c))
+* **README.md:**
+  *  updates readme for v2 release ([acaba01a](https://github.com/kbknapp/clap-rs/commit/acaba01a353c12144b9cd9a3ce447400691849b0), closes [#393](https://github.com/kbknapp/clap-rs/issues/393))
+  *  fix typo and make documentation conspicuous ([07b9f614](https://github.com/kbknapp/clap-rs/commit/07b9f61495d927f69f7abe6c0d85253f0f4e6107))
+
+#### BREAKING CHANGES
+
+* **Fewer liftimes! Yay!**
+ * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>`
+ * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>`
+ * `ArgMatches<'a, 'b>` => `ArgMatches<'a>`
+* **Simply Renamed**
+ * `App::arg_group` => `App::group`
+ * `App::arg_groups` => `App::groups`
+ * `ArgGroup::add` => `ArgGroup::arg`
+ * `ArgGroup::add_all` => `ArgGroup::args`
+ * `ClapError` => `Error`
+  * struct field `ClapError::error_type` => `Error::kind`
+ * `ClapResult` => `Result`
+ * `ClapErrorType` => `ErrorKind`
+* **Removed Deprecated Functions and Methods**
+ * `App::subcommands_negate_reqs`
+ * `App::subcommand_required`
+ * `App::arg_required_else_help`
+ * `App::global_version(bool)`
+ * `App::versionless_subcommands`
+ * `App::unified_help_messages`
+ * `App::wait_on_error`
+ * `App::subcommand_required_else_help`
+ * `SubCommand::new`
+ * `App::error_on_no_subcommand`
+ * `Arg::new`
+ * `Arg::mutually_excludes`
+ * `Arg::mutually_excludes_all`
+ * `Arg::mutually_overrides_with`
+ * `simple_enum!`
+* **Renamed Error Variants**
+ * `InvalidUnicode` => `InvalidUtf8`
+ * `InvalidArgument` => `UnknownArgument`
+* **Usage Parser**
+ * Value names can now be specified inline, i.e. `-o, --option <FILE> <FILE2> 'some option which takes two files'`
+ * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code**
+* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code)
+* `crate_version!` returns `&'static str` instead of `String`
+* Using the `clap_app!` macro requires compiling with the `unstable` feature because the syntax could change slightly in the future
+
+
+<a name="v1.5.5"></a>
+### v1.5.5 (2016-01-04)
+
+
+#### Bug Fixes
+
+*   fixes an issue where invalid short args didn't cause an error ([c9bf7e44](https://github.com/kbknapp/clap-rs/commit/c9bf7e4440bd2f9b524ea955311d433c40a7d1e0))
+*   prints the name in version and help instead of binary name ([8f3817f6](https://github.com/kbknapp/clap-rs/commit/8f3817f665c0cab6726bc16c56a53b6a61e44448), closes [#368](https://github.com/kbknapp/clap-rs/issues/368))
+*   fixes an intentional panic issue discovered via clippy ([ea83a3d4](https://github.com/kbknapp/clap-rs/commit/ea83a3d421ea8856d4cac763942834d108b71406))
+
+
+<a name="v1.5.4"></a>
+### v1.5.4 (2015-12-18)
+
+
+#### Examples
+
+* **17_yaml:**  conditinonally compile 17_yaml example ([575de089](https://github.com/kbknapp/clap-rs/commit/575de089a3e240c398cb10e6cf5a5c6b68662c01))
+
+#### Improvements
+
+*   clippy improvements ([99cdebc2](https://github.com/kbknapp/clap-rs/commit/99cdebc23da3a45a165f14b27bebeb2ed828a2ce))
+
+#### Bug Fixes
+
+
+* **errors:**  return correct error type in WrongNumValues error builder ([5ba8ba9d](https://github.com/kbknapp/clap-rs/commit/5ba8ba9dcccdfa74dd1c44260e64b359bbb36be6))
+*   ArgRequiredElseHelp setting now takes precedence over missing required args ([faad83fb](https://github.com/kbknapp/clap-rs/commit/faad83fbef6752f3093b6e98fca09a9449b830f4), closes [#362](https://github.com/kbknapp/clap-rs/issues/362))
+
+
+<a name="v1.5.3"></a>
+### v1.5.3 (2015-11-20)
+
+
+#### Bug Fixes
+
+* **Errors:**  fixes some instances when errors are missing a final newline ([c4d2b171](https://github.com/kbknapp/clap-rs/commit/c4d2b1711994479ad64ee52b6b49d2ceccbf2118))
+
+
+
+
+<a name="v1.5.2"></a>
+### v1.5.2 (2015-11-14)
+
+
+#### Bug Fixes
+
+* **Errors:**  fixes a compiling bug when built on Windows or without the color feature ([a35f7634](https://github.com/kbknapp/clap-rs/commit/a35f76346fe6ecc88dda6a1eb13627186e7ce185))
+
+
+
+<a name="v1.5.1"></a>
+### v1.5.1 (2015-11-13)
+
+
+#### Bug Fixes
+
+* **Required Args:**  fixes a bug where required args are not correctly accounted for ([f03b88a9](https://github.com/kbknapp/clap-rs/commit/f03b88a9766b331a63879bcd747687f2e5a2661b), closes [#343](https://github.com/kbknapp/clap-rs/issues/343))
+
+
+
+<a name="v1.5.0"></a>
+## v1.5.0 (2015-11-13)
+
+
+#### Bug Fixes
+
+*   fixes a bug with required positional args in usage strings ([c6858f78](https://github.com/kbknapp/clap-rs/commit/c6858f78755f8e860204323c828c8355a066dc83))
+
+#### Documentation
+
+* **FAQ:**  updates readme with slight changes to FAQ ([a4ef0fab](https://github.com/kbknapp/clap-rs/commit/a4ef0fab73c8dc68f1b138965d1340459c113398))
+
+#### Improvements
+
+*   massive errors overhaul ([cdc29175](https://github.com/kbknapp/clap-rs/commit/cdc29175bc9c53e5b4aec86cbc04c1743154dae6))
+* **ArgMatcher:**  huge refactor and deduplication of code ([8988853f](https://github.com/kbknapp/clap-rs/commit/8988853fb8825e8f841fde349834cc12cdbad081))
+* **Errors:**  errors have been vastly improved ([e59bc0c1](https://github.com/kbknapp/clap-rs/commit/e59bc0c16046db156a88ba71a037db05028e995c))
+* **Traits:**  refactoring some configuration into traits ([5800cdec](https://github.com/kbknapp/clap-rs/commit/5800cdec6dce3def4242b9f7bd136308afb19685))
+
+#### Performance
+
+* **App:**
+  *  more BTreeMap->Vec, Opts and SubCmds ([bc4495b3](https://github.com/kbknapp/clap-rs/commit/bc4495b32ec752b6c4b29719e831c043ef2a26ce))
+  *  changes flags BTreeMap->Vec ([d357640f](https://github.com/kbknapp/clap-rs/commit/d357640fab55e5964fe83efc3c771e53aa3222fd))
+  *  removed unneeded BTreeMap ([78971fd6](https://github.com/kbknapp/clap-rs/commit/78971fd68d7dc5c8e6811b4520cdc54e4188f733))
+  *  changes BTreeMap to VecMap in some instances ([64b921d0](https://github.com/kbknapp/clap-rs/commit/64b921d087fdd03775c95ba0bcf65d3f5d36f812))
+  *  removed excess clones ([ec0089d4](https://github.com/kbknapp/clap-rs/commit/ec0089d42ed715d293fb668d3a90b0db0aa3ec39))
+
+
+
+<a name="v1.4.7"></a>
+### v1.4.7 (2015-11-03)
+
+
+#### Documentation
+
+*   Clarify behavior of Arg::multiple with options. ([434f497a](https://github.com/kbknapp/clap-rs/commit/434f497ab6d831f8145cf09278c97ca6ee6c6fe7))
+*   Fix typos and improve grammar. ([c1f66b5d](https://github.com/kbknapp/clap-rs/commit/c1f66b5de7b5269fbf8760a005ef8c645edd3229))
+
+#### Bug Fixes
+
+* **Error Status:**  fixes bug where --help and --version return non-zero exit code ([89b51fdf](https://github.com/kbknapp/clap-rs/commit/89b51fdf8b1ab67607567344e2317ff1a757cb12))
+
+
+
+<a name="v1.4.6"></a>
+### v1.4.6 (2015-10-29)
+
+
+#### Features
+
+*   allows parsing without a binary name for daemons and interactive CLIs ([aff89d57](https://github.com/kbknapp/clap-rs/commit/aff89d579b5b85c3dc81b64f16d5865299ec39a2), closes [#318](https://github.com/kbknapp/clap-rs/issues/318))
+
+#### Bug Fixes
+
+* **Errors:**  tones down quoting in some error messages ([34ce59ed](https://github.com/kbknapp/clap-rs/commit/34ce59ede53bfa2eef722c74881cdba7419fd9c7), closes [#309](https://github.com/kbknapp/clap-rs/issues/309))
+* **Help and Version:**  only builds help and version once ([e3be87cf](https://github.com/kbknapp/clap-rs/commit/e3be87cfc095fc41c9811adcdc6d2b079f237d5e))
+* **Option Args:**  fixes bug with args and multiple values ([c9a9548a](https://github.com/kbknapp/clap-rs/commit/c9a9548a8f96cef8a3dd9a980948325fbbc1b91b), closes [#323](https://github.com/kbknapp/clap-rs/issues/323))
+* **POSIX Overrides:**  fixes bug where required args are overridden ([40ed2b50](https://github.com/kbknapp/clap-rs/commit/40ed2b50c3a9fe88bfdbaa43cef9fd6493ecaa8e))
+* **Safe Matches:**  using 'safe' forms of the get_matches family no longer exit the process ([c47025dc](https://github.com/kbknapp/clap-rs/commit/c47025dca2b3305dea0a0acfdd741b09af0c0d05), closes [#256](https://github.com/kbknapp/clap-rs/issues/256))
+* **Versionless SubCommands:**  fixes a bug where the -V flag was needlessly built ([27df8b9d](https://github.com/kbknapp/clap-rs/commit/27df8b9d98d13709dad3929a009f40ebff089a1a), closes [#329](https://github.com/kbknapp/clap-rs/issues/329))
+
+#### Documentation
+
+*   adds comparison in readme ([1a8bf31e](https://github.com/kbknapp/clap-rs/commit/1a8bf31e7a6b87ce48a66af2cde1645b2dd5bc95), closes [#325](https://github.com/kbknapp/clap-rs/issues/325))
+
+
+
+<a name="v1.4.5"></a>
+### v1.4.5 (2015-10-06)
+
+
+#### Bug Fixes
+
+*   fixes crash on invalid arg error ([c78ce128](https://github.com/kbknapp/clap-rs/commit/c78ce128ebbe7b8f730815f8176c29d76f4ade8c))
+
+
+
+<a name="v1.4.4"></a>
+### v1.4.4 (2015-10-06)
+
+
+#### Documentation
+
+*   clean up some formatting ([b7df92d7](https://github.com/kbknapp/clap-rs/commit/b7df92d7ea25835701dd22ddff984b9749f48a00))
+*   move the crate-level docs to top of the lib.rs file ([d7233bf1](https://github.com/kbknapp/clap-rs/commit/d7233bf122dbf80ba8fc79e5641be2df8af10e7a))
+*   changes doc comments to rustdoc comments ([34b601be](https://github.com/kbknapp/clap-rs/commit/34b601be5fdde76c1a0859385b359b96d66b8732))
+*   fixes panic in 14_groups example ([945b00a0](https://github.com/kbknapp/clap-rs/commit/945b00a0c27714b63bdca48d003fe205fcfdc578), closes [#295](https://github.com/kbknapp/clap-rs/issues/295))
+*   avoid suggesting star dependencies. ([d33228f4](https://github.com/kbknapp/clap-rs/commit/d33228f40b5fefb84cf3dd51546bfb340dcd9f5a))
+* **Rustdoc:**  adds portions of the readme to main rustdoc page ([6f9ee181](https://github.com/kbknapp/clap-rs/commit/6f9ee181e69d90bd4206290e59d6f3f1e8f0cbb2), closes [#293](https://github.com/kbknapp/clap-rs/issues/293))
+
+#### Bug Fixes
+
+*   grammar error in some conflicting option errors ([e73b07e1](https://github.com/kbknapp/clap-rs/commit/e73b07e19474323ad2260da66abbf6a6d4ecbd4f))
+* **Unified Help:**  sorts both flags and options as a unified category ([2a223dad](https://github.com/kbknapp/clap-rs/commit/2a223dad82901fa2e74baad3bfc4c7b94509300f))
+* **Usage:**  fixes a bug where required args aren't filtered properly ([72b453dc](https://github.com/kbknapp/clap-rs/commit/72b453dc170af3050bb123d35364f6da77fc06d7), closes [#277](https://github.com/kbknapp/clap-rs/issues/277))
+* **Usage Strings:**  fixes a bug ordering of elements in usage strings ([aaf0d6fe](https://github.com/kbknapp/clap-rs/commit/aaf0d6fe7aa2403e76096c16204d254a9ee61ee2), closes [#298](https://github.com/kbknapp/clap-rs/issues/298))
+
+#### Features
+
+*   supports -aValue style options ([0e3733e4](https://github.com/kbknapp/clap-rs/commit/0e3733e4fec2015c2d566a51432dcd92cb69cad3))
+* **Trailing VarArg:**  adds opt-in setting for final arg being vararg ([27018b18](https://github.com/kbknapp/clap-rs/commit/27018b1821a4bcd5235cfe92abe71b3c99efc24d), closes [#278](https://github.com/kbknapp/clap-rs/issues/278))
+
+
+
+<a name="v1.4.3"></a>
+### v1.4.3 (2015-09-30)
+
+
+#### Features
+
+*   allows accessing arg values by group name ([c92a4b9e](https://github.com/kbknapp/clap-rs/commit/c92a4b9eff2d679957f61c0c41ff404b40d38a91))
+
+#### Documentation
+
+*   use links to examples instead of plain text ([bb4fe237](https://github.com/kbknapp/clap-rs/commit/bb4fe237858535627271465147add537e4556b43))
+
+#### Bug Fixes
+
+* **Help Message:**  required args no longer double list in usage ([1412e639](https://github.com/kbknapp/clap-rs/commit/1412e639e0a79df84936d1101a837f90077d1c83), closes [#277](https://github.com/kbknapp/clap-rs/issues/277))
+* **Possible Values:**  possible value validation is restored ([f121ae74](https://github.com/kbknapp/clap-rs/commit/f121ae749f8f4bfe754ef2e8a6dfc286504b5b75), closes [#287](https://github.com/kbknapp/clap-rs/issues/287))
+
+
+
+<a name="v1.4.2"></a>
+### v1.4.2 (2015-09-23)
+
+
+#### Bug Fixes
+
+* **Conflicts:**  fixes bug with conflicts not removing required args ([e17fcec5](https://github.com/kbknapp/clap-rs/commit/e17fcec53b3216ad047a13dddc6f740473fad1a1), closes [#271](https://github.com/kbknapp/clap-rs/issues/271))
+
+
+
+<a name="v1.4.1"></a>
+### v1.4.1 (2015-09-22)
+
+
+#### Examples
+
+*   add clap_app quick example ([4ba6249c](https://github.com/kbknapp/clap-rs/commit/4ba6249c3cf4d2e083370d1fe4dcc7025282c28a))
+
+#### Features
+
+* **Unicode:**  allows non-panicing on invalid unicode characters ([c5bf7ddc](https://github.com/kbknapp/clap-rs/commit/c5bf7ddc8cfb876ec928a5aaf5591232bbb32e5d))
+
+#### Documentation
+
+*   properly names Examples section for rustdoc ([87ba5445](https://github.com/kbknapp/clap-rs/commit/87ba54451d7ec7b1c9b9ef134f90bbe39e6fac69))
+*   fixes various typos and spelling ([f85640f9](https://github.com/kbknapp/clap-rs/commit/f85640f9f6d8fd3821a40e9b8b7a34fabb789d02))
+* **Arg:**  unhides fields of the Arg struct ([931aea88](https://github.com/kbknapp/clap-rs/commit/931aea88427edf43a3da90d5a500c1ff2b2c3614))
+
+#### Bug Fixes
+
+*   flush the buffer in App::print_version() ([cbc42a37](https://github.com/kbknapp/clap-rs/commit/cbc42a37d212d84d22b1777d08e584ff191934e7))
+*   Macro benchmarks ([13712da1](https://github.com/kbknapp/clap-rs/commit/13712da1d36dc7614eec3a10ad488257ba615751))
+
+
+
+<a name="v1.4.0"></a>
+## v1.4.0 (2015-09-09)
+
+
+#### Features
+
+*   allows printing help message by library consumers ([56b95f32](https://github.com/kbknapp/clap-rs/commit/56b95f320875c62dda82cb91b29059671e120ed1))
+*   allows defining hidden args and subcmds ([2cab4d03](https://github.com/kbknapp/clap-rs/commit/2cab4d0334ea3c2439a1d4bfca5bf9905c7ea9ac), closes [#231](https://github.com/kbknapp/clap-rs/issues/231))
+*   Builder macro to assist with App/Arg/Group/SubCommand building ([443841b0](https://github.com/kbknapp/clap-rs/commit/443841b012a8d795cd5c2bd69ae6e23ef9b16477))
+* **Errors:**  allows consumers to write to stderr and exit on error ([1e6403b6](https://github.com/kbknapp/clap-rs/commit/1e6403b6a863574fa3cb6946b1fb58f034e8664c))
+
+
+
+<a name="v1.3.2"></a>
+### v1.3.2 (2015-09-08)
+
+
+#### Documentation
+
+*   fixed ErrorKind docs ([dd057843](https://github.com/kbknapp/clap-rs/commit/dd05784327fa070eb6ce5ce89a8507e011d8db94))
+* **ErrorKind:**  changed examples content ([b9ca2616](https://github.com/kbknapp/clap-rs/commit/b9ca261634b89613bbf3d98fd74d55cefbb31a8c))
+
+#### Bug Fixes
+
+*   fixes a bug where the help subcommand wasn't overridable ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745))
+
+#### Features
+
+*   adds abiltiy not consume self when parsing matches and/or exit on help ([94003db4](https://github.com/kbknapp/clap-rs/commit/94003db4b5eebe552ca337521c1c001295822745))
+* **App:**  Added ability for users to handle errors themselves ([934e6fbb](https://github.com/kbknapp/clap-rs/commit/934e6fbb643b2385efc23444fe6fce31494dc288))
+
+
+
+<a name="v1.3.1"></a>
+### v1.3.1 (2015-09-04)
+
+
+#### Examples
+
+* **17_yaml:**  fixed example ([9b848622](https://github.com/kbknapp/clap-rs/commit/9b848622296c8c5c7b9a39b93ddd41f51df790b5))
+
+#### Performance
+
+*   changes ArgGroup HashSets to Vec ([3cb4a48e](https://github.com/kbknapp/clap-rs/commit/3cb4a48ebd15c20692f4f3a2a924284dc7fd5e10))
+*   changes BTreeSet for Vec in some instances ([baab2e3f](https://github.com/kbknapp/clap-rs/commit/baab2e3f4060e811abee14b1654cbcd5cf3b5fea))
+
+
+
+<a name="v1.3.0"></a>
+## v1.3.0 (2015-09-01)
+
+
+#### Features
+
+* **YAML:**  allows building a CLI from YAML files ([86cf4c45](https://github.com/kbknapp/clap-rs/commit/86cf4c45626a36b8115446952f9069f73c1debc3))
+* **ArgGroups:**  adds support for building ArgGroups from yaml ([ecf88665](https://github.com/kbknapp/clap-rs/commit/ecf88665cbff367018b29161a1b75d44a212707d))
+* **Subcommands:**  adds support for subcommands from yaml ([e415cf78](https://github.com/kbknapp/clap-rs/commit/e415cf78ba916052d118a8648deba2b9c16b1530))
+
+#### Documentation
+
+* **YAML:**  adds examples for using YAML to build a CLI ([ab41d7f3](https://github.com/kbknapp/clap-rs/commit/ab41d7f38219544750e6e1426076dc498073191b))
+* **Args from YAML:**  fixes doc examples ([19b348a1](https://github.com/kbknapp/clap-rs/commit/19b348a10050404cd93888dbbbe4f396681b67d0))
+* **Examples:**  adds better usage examples instead of having unused variables ([8cbacd88](https://github.com/kbknapp/clap-rs/commit/8cbacd8883004fe71a8ea036ec4391c7dd8efe94))
+
+#### Examples
+
+*   Add AppSettings example ([12705079](https://github.com/kbknapp/clap-rs/commit/12705079ca96a709b4dd94f7ddd20a833b26838c))
+
+#### Bug Fixes
+
+* **Unified Help Messages:**  fixes a crash from this setting and no opts ([169ffec1](https://github.com/kbknapp/clap-rs/commit/169ffec1003d58d105d7ef2585b3425e57980000), closes [#210](https://github.com/kbknapp/clap-rs/issues/210))
+
+
+
+<a name="v1.2.5"></a>
+### v1.2.5 (2015-08-27)
+
+
+#### Examples
+
+*   add custom validator example ([b9997d1f](https://github.com/kbknapp/clap-rs/commit/b9997d1fca74d4d8f93971f2a01bdf9798f913d5))
+*   fix indentation ([d4f1b740](https://github.com/kbknapp/clap-rs/commit/d4f1b740ede410fd2528b9ecd89592c2fd8b1e20))
+
+#### Features
+
+* **Args:**  allows opts and args to define a name for help and usage msgs ([ad962ec4](https://github.com/kbknapp/clap-rs/commit/ad962ec478da999c7dba0afdb84c266f4d09b1bd))
+
+
+
+<a name="v1.2.4"></a>
+### v1.2.4 (2015-08-26)
+
+
+#### Bug Fixes
+
+* **Possible Values:**  fixes a bug where suggestions arent made when using --long=value format ([3d5e9a6c](https://github.com/kbknapp/clap-rs/commit/3d5e9a6cedb26668839b481c9978e2fbbab8be6f), closes [#192](https://github.com/kbknapp/clap-rs/issues/192))
+
+
+
+<a name="v1.2.3"></a>
+### v1.2.3 (2015-08-24)
+
+
+#### Bug Fixes
+
+* **App, Args:**  fixed subcommand reqs negation ([b41afa8c](https://github.com/kbknapp/clap-rs/commit/b41afa8c3ded3d1be12f7a2f8ea06cc44afc9458), closes [#188](https://github.com/kbknapp/clap-rs/issues/188))
+
+
+
+<a name="v1.2.2"></a>
+### v1.2.2 (2015-08-23)
+
+
+#### Bug Fixes
+
+*   fixed confusing error message, also added test for it ([fc7a31a7](https://github.com/kbknapp/clap-rs/commit/fc7a31a745efbf1768ee2c62cd3bb72bfe30c708))
+* **App:**  fixed requirmets overriding ([9c135eb7](https://github.com/kbknapp/clap-rs/commit/9c135eb790fa16183e5bdb2009ddc3cf9e25f99f))
+
+
+
+<a name="v1.2.1"></a>
+### v1.2.1 (2015-08-20)
+
+
+#### Documentation
+
+* **README.md:**  updates for new features ([16cf9245](https://github.com/kbknapp/clap-rs/commit/16cf9245fb5fc4cf6face898e358368bf9961cbb))
+
+#### Features
+
+*   implements posix compatible conflicts for long args ([8c2d48ac](https://github.com/kbknapp/clap-rs/commit/8c2d48acf5473feebd721a9049a9c9b7051e70f9))
+*   added overrides to support conflicts in POSIX compatible manner ([0b916a00](https://github.com/kbknapp/clap-rs/commit/0b916a00de26f6941538f6bc5f3365fa302083c1))
+* **Args:**  allows defining POSIX compatible argument conflicts ([d715646e](https://github.com/kbknapp/clap-rs/commit/d715646e69759ccd95e01f49b04f489827ecf502))
+
+#### Bug Fixes
+
+*   fixed links in cargo and license buttons ([6d9837ad](https://github.com/kbknapp/clap-rs/commit/6d9837ad9a9e006117cd7372fdc60f9a3889c7e2))
+
+#### Performance
+
+* **Args and Apps:**  changes HashSet->Vec in some instances for increased performance ([d0c3b379](https://github.com/kbknapp/clap-rs/commit/d0c3b379700757e0a9b0c40af709f8af1f5b4949))
+
+
+
+<a name="v1.2.0"></a>
+### v1.2.0 (2015-08-15)
+
+
+#### Bug Fixes
+
+*   fixed misspell and enum name ([7df170d7](https://github.com/kbknapp/clap-rs/commit/7df170d7f4ecff06608317655d1e0c4298f62076))
+*   fixed use for clap crate ([dc3ada73](https://github.com/kbknapp/clap-rs/commit/dc3ada738667d4b689678f79d14251ee82004ece))
+
+#### Documentation
+
+*   updates docs for new features ([03496547](https://github.com/kbknapp/clap-rs/commit/034965471782d872ca495045b58d34b31807c5b1))
+*   fixed docs for previous changes ([ade36778](https://github.com/kbknapp/clap-rs/commit/ade367780c366425de462506d256e0f554ed3b9c))
+
+#### Improvements
+
+* **AppSettings:**  adds ability to add multiple settings at once ([4a00e251](https://github.com/kbknapp/clap-rs/commit/4a00e2510d0ca8d095d5257d51691ba3b61c1374))
+
+#### Features
+
+*   Replace application level settings with enum variants ([618dc4e2](https://github.com/kbknapp/clap-rs/commit/618dc4e2c205bf26bc43146164e65eb1f6b920ed))
+* **Args:**  allows for custom argument value validations to be defined ([84ae2ddb](https://github.com/kbknapp/clap-rs/commit/84ae2ddbceda34b5cbda98a6959edaa52fde2e1a), closes [#170](https://github.com/kbknapp/clap-rs/issues/170))
+
+
+
+<a name="v1.1.6"></a>
+### v1.1.6 (2015-08-01)
+
+
+#### Bug Fixes
+
+*   fixes two bugs in App when printing newlines in help and subcommands required error ([d63c0136](https://github.com/kbknapp/clap-rs/commit/d63c0136310db9dd2b1c7b4745938311601d8938))
+
+
+
+<a name="v1.1.5"></a>
+### v1.1.5 (2015-07-29)
+
+#### Performance
+
+*   removes some unneeded allocations ([93e915df](https://github.com/kbknapp/clap-rs/commit/93e915dfe300f7b7d6209ca93323c6a46f89a8c1))
+
+<a name="v1.1.4"></a>
+### v1.1.4 (2015-07-20)
+
+
+#### Improvements
+
+* **Usage Strings**  displays a [--] when it may be helpful ([86c3be85](https://github.com/kbknapp/clap-rs/commit/86c3be85fb6f77f83b5a6d2df40ae60937486984))
+
+#### Bug Fixes
+
+* **Macros**  fixes a typo in a macro generated error message ([c9195c5f](https://github.com/kbknapp/clap-rs/commit/c9195c5f92abb8cd6a37b4f4fbb2f1fee2a8e368))
+* **Type Errors**  fixes formatting of error output when failed type parsing ([fe5d95c6](https://github.com/kbknapp/clap-rs/commit/fe5d95c64f3296e6eddcbec0cb8b86659800145f))
+
+
+
+<a name="v1.1.3"></a>
+### v1.1.3 (2015-07-18)
+
+
+#### Documentation
+
+*   updates README.md to include lack of color support on Windows ([52f81e17](https://github.com/kbknapp/clap-rs/commit/52f81e17377b18d2bd0f34693b642b7f358998ee))
+
+#### Bug Fixes
+
+*   fixes formatting bug which prevented compiling on windows ([9cb5dceb](https://github.com/kbknapp/clap-rs/commit/9cb5dceb3e5fe5e0e7b24619ff77e5040672b723), closes [#163](https://github.com/kbknapp/clap-rs/issues/163))
+
+
+
+<a name="v1.1.2"></a>
+### v1.1.2 (2015-07-17)
+
+
+#### Bug Fixes
+
+*   fixes a bug when parsing multiple {n} newlines inside help strings ([6d214b54](https://github.com/kbknapp/clap-rs/commit/6d214b549a9b7e189a94e5fa2b7c92cc333ca637))
+
+
+
+<a name="v1.1.1"></a>
+## v1.1.1 (2015-07-17)
+
+
+#### Bug Fixes
+
+*   fixes a logic bug and allows setting Arg::number_of_values() < 2 ([42b6d1fc](https://github.com/kbknapp/clap-rs/commit/42b6d1fc3c519c92dfb3af15276e7d3b635e6cfe), closes [#161](https://github.com/kbknapp/clap-rs/issues/161))
+
+
+
+<a name="v1.1.0"></a>
+## v1.1.0 (2015-07-16)
+
+
+#### Features
+
+*   allows creating unified help messages, a la docopt or getopts ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1), closes [#158](https://github.com/kbknapp/clap-rs/issues/158))
+*   allows stating all subcommands should *not* have --version flags ([336c476f](https://github.com/kbknapp/clap-rs/commit/336c476f631d512b54ac56fdca6f29ebdc2c00c5), closes [#156](https://github.com/kbknapp/clap-rs/issues/156))
+*   allows setting version number to auto-propagate through subcommands ([bc66d3c6](https://github.com/kbknapp/clap-rs/commit/bc66d3c6deedeca62463fff95369ab1cfcdd366b), closes [#157](https://github.com/kbknapp/clap-rs/issues/157))
+
+#### Improvements
+
+* **Help Strings**  properly aligns and handles newlines in long help strings ([f9800a29](https://github.com/kbknapp/clap-rs/commit/f9800a29696dd2cc0b0284bf693b3011831e556f), closes [#145](https://github.com/kbknapp/clap-rs/issues/145))
+
+
+#### Performance
+
+* **Help Messages**  big performance improvements when printing help messages ([52bcd892](https://github.com/kbknapp/clap-rs/commit/52bcd892ea51564ce463bc5865acd64f8fe91cb1))
+
+#### Documentation
+
+*   updates readme with new features ([8232f7bb](https://github.com/kbknapp/clap-rs/commit/8232f7bb52e88862bc13c3d4f99ee4f56cfe4bc0))
+*   fix incorrect code example for `App::subcommand_required` ([8889689d](https://github.com/kbknapp/clap-rs/commit/8889689dc6336ccc45b2c9f2cf8e2e483a639e93))
+
+
+<a name="v1.0.3"></a>
+### v1.0.3 (2015-07-11)
+
+
+#### Improvements
+
+* **Errors**  writes errors to stderr ([cc76ab8c](https://github.com/kbknapp/clap-rs/commit/cc76ab8c2b77c67b42f4717ded530df7806142cf), closes [#154](https://github.com/kbknapp/clap-rs/issues/154))
+
+#### Documentation
+
+* **README.md**  updates example help message to new format ([0aca29bd](https://github.com/kbknapp/clap-rs/commit/0aca29bd5d6d1a4e9971bdc88d946ffa58606efa))
+
+
+
+<a name="v1.0.2"></a>
+### v1.0.2 (2015-07-09)
+
+
+#### Improvements
+
+* **Usage**  re-orders optional arguments and required to natural standard ([dc7e1fce](https://github.com/kbknapp/clap-rs/commit/dc7e1fcea5c85d317018fb201d2a9262249131b4), closes [#147](https://github.com/kbknapp/clap-rs/issues/147))
+
+
+
+<a name="v1.0.1"></a>
+### v1.0.1 (2015-07-08)
+
+
+#### Bug Fixes
+
+*   allows empty values when using --long='' syntax ([083f82d3](https://github.com/kbknapp/clap-rs/commit/083f82d333b69720a6ef30074875310921d964d1), closes [#151](https://github.com/kbknapp/clap-rs/issues/151))
+
+
+
+<a name="v1.0.0"></a>
+## v1.0.0 (2015-07-08)
+
+
+#### Documentation
+
+* **README.md**  adds new features to what's new list ([938f7f01](https://github.com/kbknapp/clap-rs/commit/938f7f01340f521969376cf4e2e3d9436bca21f7))
+* **README.md**  use with_name for subcommands ([28b7e316](https://github.com/kbknapp/clap-rs/commit/28b7e3161fb772e5309042648fe8c3a420645bac))
+
+#### Features
+
+*   args can now be parsed from arbitrary locations, not just std::env::args() ([75312528](https://github.com/kbknapp/clap-rs/commit/753125282b1b9bfff875f1557ce27610edcc59e1))
+
+
+
+<a name="v1.0.0"></a>
+## v1.0.0-beta (2015-06-30)
+
+
+#### Features
+
+*   allows waiting for user input on error ([d0da3bdd](https://github.com/kbknapp/clap-rs/commit/d0da3bdd9d1871541907ea9c645322a74d260e07), closes [#140](https://github.com/kbknapp/clap-rs/issues/140))
+* **Help**  allows one to fully override the auto-generated help message ([26d5ae3e](https://github.com/kbknapp/clap-rs/commit/26d5ae3e330d1e150811d5b60b2b01a8f8df854e), closes [#141](https://github.com/kbknapp/clap-rs/issues/141))
+
+#### Documentation
+
+*   adds "whats new" section to readme ([ff149a29](https://github.com/kbknapp/clap-rs/commit/ff149a29dd9e179865e6d577cd7dc87c54f8f95c))
+
+#### Improvements
+
+*   removes deprecated functions in prep for 1.0 ([274484df](https://github.com/kbknapp/clap-rs/commit/274484dfd08fff4859cefd7e9bef3b73d3a9cb5f))
+
+
+
+<a name="v0.11.0"></a>
+## v0.11.0 (2015-06-17) - BREAKING CHANGE
+
+
+#### Documentation
+
+*   updates docs to new version flag defaults ([ebf442eb](https://github.com/kbknapp/clap-rs/commit/ebf442ebebbcd2ec6bfe2c06566c9d362bccb112))
+
+#### Features
+
+* **Help and Version**  default short for version is now `-V` but can be overridden (only breaks manual documentation) (**BREAKING CHANGE** [eb1d9320](https://github.com/kbknapp/clap-rs/commit/eb1d9320c509c1e4e57d7c7959da82bcfe06ada0))
+
+
+
+<a name="v0.10.5"></a>
+### v0.10.5 (2015-06-06)
+
+
+#### Bug Fixes
+
+* **Global Args**  global arguments propogate fully now ([1f377960](https://github.com/kbknapp/clap-rs/commit/1f377960a48c82f54ca5f39eb56bcb393140b046), closes [#137](https://github.com/kbknapp/clap-rs/issues/137))
+
+
+
+<a name="v0.10.4"></a>
+### v0.10.4 (2015-06-06)
+
+
+#### Bug Fixes
+
+* **Global Args**  global arguments propogate fully now ([8f2c0160](https://github.com/kbknapp/clap-rs/commit/8f2c0160c8d844daef375a33dbaec7d89de00a00), closes [#137](https://github.com/kbknapp/clap-rs/issues/137))
+
+
+
+<a name="v0.10.3"></a>
+### v0.10.3 (2015-05-31)
+
+
+#### Bug Fixes
+
+* **Global Args**  fixes a bug where globals only transfer to one subcommand ([a37842ee](https://github.com/kbknapp/clap-rs/commit/a37842eec1ee3162b86fdbda23420b221cdb1e3b), closes [#135](https://github.com/kbknapp/clap-rs/issues/135))
+
+
+
+<a name="v0.10.2"></a>
+### v0.10.2 (2015-05-30)
+
+
+#### Improvements
+
+* **Binary Names**  allows users to override the system determined bin name ([2191fe94](https://github.com/kbknapp/clap-rs/commit/2191fe94bda35771383b52872fb7f5421b178be1), closes [#134](https://github.com/kbknapp/clap-rs/issues/134))
+
+#### Documentation
+
+*   adds contributing guidelines ([6f76bd0a](https://github.com/kbknapp/clap-rs/commit/6f76bd0a07e8b7419b391243ab2d6687cd8a9c5f))
+
+
+
+<a name="v0.10.1"></a>
+### v0.10.1 (2015-05-26)
+
+
+#### Features
+
+*   can now specify that an app or subcommand should display help on no args or subcommands ([29ca7b2f](https://github.com/kbknapp/clap-rs/commit/29ca7b2f74376ca0cdb9d8ee3bfa99f7640cc404), closes [#133](https://github.com/kbknapp/clap-rs/issues/133))
+
+
+
+<a name="v0.10.0"></a>
+## v0.10.0 (2015-05-23)
+
+
+#### Features
+
+* **Global Args**  allows args that propagate down to child commands ([2bcc6137](https://github.com/kbknapp/clap-rs/commit/2bcc6137a83cb07757771a0afea953e68e692f0b), closes [#131](https://github.com/kbknapp/clap-rs/issues/131))
+
+#### Improvements
+
+* **Colors**  implements more structured colored output ([d6c3ed54](https://github.com/kbknapp/clap-rs/commit/d6c3ed54d21cf7b40d9f130d4280ff5448522fc5), closes [#129](https://github.com/kbknapp/clap-rs/issues/129))
+
+#### Deprecations
+
+* **SubCommand/App**  several methods and functions for stable release ([28b73855](https://github.com/kbknapp/clap-rs/commit/28b73855523ad170544afdb20665db98702fbe70))
+
+#### Documentation
+
+*   updates for deprecations and new features ([743eefe8](https://github.com/kbknapp/clap-rs/commit/743eefe8dd40c1260065ce086d572e9e9358bc4c))
+
+
+
+<a name="v0.9.2"></a>
+## v0.9.2 (2015-05-20)
+
+
+#### Bug Fixes
+
+* **help**  allows parent requirements to be ignored with help and version ([52218cc1](https://github.com/kbknapp/clap-rs/commit/52218cc1fdb06a42456c964d98cc2c7ac3432412), closes [#124](https://github.com/kbknapp/clap-rs/issues/124))
+
+
+
+<a name="v0.9.1"></a>
+## v0.9.1 (2015-05-18)
+
+
+#### Bug Fixes
+
+* **help**  fixes a bug where requirements are included as program name in help and version ([08ba3f25](https://github.com/kbknapp/clap-rs/commit/08ba3f25cf38b149229ba8b9cb37a5804fe6b789))
+
+
+
+<a name="v0.9.0"></a>
+## v0.9.0 (2015-05-17)
+
+
+#### Improvements
+
+* **usage**  usage strings now include parent command requirements ([dd8f21c7](https://github.com/kbknapp/clap-rs/commit/dd8f21c7c15cde348fdcf44fa7c205f0e98d2e4a), closes [#125](https://github.com/kbknapp/clap-rs/issues/125))
+* **args**  allows consumer of clap to decide if empty values are allowed or not ([ab4ec609](https://github.com/kbknapp/clap-rs/commit/ab4ec609ccf692b9b72cccef5c9f74f5577e360d), closes [#122](https://github.com/kbknapp/clap-rs/issues/122))
+
+#### Features
+
+* **subcommands**
+  *  allows optionally specifying that no subcommand is an error ([7554f238](https://github.com/kbknapp/clap-rs/commit/7554f238fd3afdd60b7e4dcf00ff4a9eccf842c1), closes [#126](https://github.com/kbknapp/clap-rs/issues/126))
+  *  subcommands can optionally negate parent requirements ([4a4229f5](https://github.com/kbknapp/clap-rs/commit/4a4229f500e21c350e1ef78dd09ef27559653288), closes [#123](https://github.com/kbknapp/clap-rs/issues/123))
+
+
+
+<a name="v0.8.6"></a>
+## v0.8.6 (2015-05-17)
+
+
+#### Bug Fixes
+
+* **args**  `-` can now be parsed as a value for an argument ([bc12e78e](https://github.com/kbknapp/clap-rs/commit/bc12e78eadd7eaf9d008a8469fdd2dfd7990cb5d), closes [#121](https://github.com/kbknapp/clap-rs/issues/121))
+
+
+
+<a name="v0.8.5"></a>
+## v0.8.5 (2015-05-15)
+
+
+#### Bug Fixes
+
+* **macros**  makes macro errors consistent with others ([0c264a8c](https://github.com/kbknapp/clap-rs/commit/0c264a8ca57ec1cfdcb74dae79145d766cdc9b97), closes [#118](https://github.com/kbknapp/clap-rs/issues/118))
+
+#### Features
+
+* **macros**
+  *  arg_enum! and simple_enum! provide a Vec<&str> of variant names ([30fa87ba](https://github.com/kbknapp/clap-rs/commit/30fa87ba4e0f3189351d8f4f78b72e616a30d0bd), closes [#119](https://github.com/kbknapp/clap-rs/issues/119))
+  *  arg_enum! and simple_enum! auto-implement Display ([d1219f0d](https://github.com/kbknapp/clap-rs/commit/d1219f0d1371d872061bd0718057eca4ef47b739), closes [#120](https://github.com/kbknapp/clap-rs/issues/120))
+
+
+
+<a name="v0.8.4"></a>
+## v0.8.4 (2015-05-12)
+
+
+#### Bug Fixes
+
+* **suggestions**  --help and --version now get suggestions ([d2b3b1fa](https://github.com/kbknapp/clap-rs/commit/d2b3b1faa0bdc1c5d2350cc4635aba81e02e9d96), closes [#116](https://github.com/kbknapp/clap-rs/issues/116))
+
+
+
+<a name="v0.8.3"></a>
+## v0.8.3 (2015-05-10)
+
+
+#### Bug Fixes
+
+* **usage**  groups unfold their members in usage strings ([55d15582](https://github.com/kbknapp/clap-rs/commit/55d155827ea4a6b077a83669701e797ce1ad68f4), closes [#114](https://github.com/kbknapp/clap-rs/issues/114))
+
+#### Performance
+
+* **usage**  removes unneeded allocations ([fd53cd18](https://github.com/kbknapp/clap-rs/commit/fd53cd188555f5c3dc8bc341c5d7eb04b761a70f))
+
+
+
+<a name="v0.8.2"></a>
+## v0.8.2 (2015-05-08)
+
+
+#### Bug Fixes
+
+* **usage strings**  positional arguments are presented in index order ([eb0e374e](https://github.com/kbknapp/clap-rs/commit/eb0e374ecf952f1eefbc73113f21e0705936e40b), closes [#112](https://github.com/kbknapp/clap-rs/issues/112))
+
+
+
+<a name="v0.8.1"></a>
+## v0.8.1 (2015-05-06)
+
+
+#### Bug Fixes
+
+* **subcommands**  stops parsing multiple values when subcommands are found ([fc79017e](https://github.com/kbknapp/clap-rs/commit/fc79017eced04fd41cc1801331e5054df41fac17), closes [#109](https://github.com/kbknapp/clap-rs/issues/109))
+
+#### Improvements
+
+* **color**  reduces color in error messages ([aab44cca](https://github.com/kbknapp/clap-rs/commit/aab44cca6352f47e280c296e50c535f5d752dd46), closes [#110](https://github.com/kbknapp/clap-rs/issues/110))
+* **suggestions**  adds suggested arguments to usage strings ([99447414](https://github.com/kbknapp/clap-rs/commit/994474146e9fb8b701af773a52da71553d74d4b7))
+
+
+
+<a name="v0.8.0"></a>
+## v0.8.0 (2015-05-06)
+
+
+#### Bug Fixes
+
+* **did-you-mean**  for review ([0535cfb0](https://github.com/kbknapp/clap-rs/commit/0535cfb0c711331568b4de8080eeef80bd254b68))
+* **Positional**  positionals were ignored if they matched a subcmd, even after '--' ([90e7b081](https://github.com/kbknapp/clap-rs/commit/90e7b0818741668b47cbe3becd029bab588e3553))
+* **help**  fixes bug where space between arg and help is too long ([632fb115](https://github.com/kbknapp/clap-rs/commit/632fb11514c504999ea86bdce47cdd34f8ebf646))
+
+#### Features
+
+* **from_usage**  adds ability to add value names or num of vals in usage string ([3d581976](https://github.com/kbknapp/clap-rs/commit/3d58197674ed7886ca315efb76e411608a327501), closes [#98](https://github.com/kbknapp/clap-rs/issues/98))
+* **did-you-mean**
+  *  gate it behind 'suggestions' ([c0e38351](https://github.com/kbknapp/clap-rs/commit/c0e383515d01bdd5ca459af9c2f7e2cf49e2488b))
+  *  for possible values ([1cc2deb2](https://github.com/kbknapp/clap-rs/commit/1cc2deb29158e0e4e8b434e4ce26b3d819301a7d))
+  *  for long flags (i.e. --long) ([52a0b850](https://github.com/kbknapp/clap-rs/commit/52a0b8505c99354bdf5fd1cd256cf41197ac2d81))
+  *  for subcommands ([06e869b5](https://github.com/kbknapp/clap-rs/commit/06e869b5180258047ed3c60ba099de818dd25fff))
+* **Flags**  adds sugestions functionality ([8745071c](https://github.com/kbknapp/clap-rs/commit/8745071c3257dd327c497013516f12a823df9530))
+* **errors**  colorizes output red on error ([f8b26b13](https://github.com/kbknapp/clap-rs/commit/f8b26b13da82ba3ba9a932d3d1ab4ea45d1ab036))
+
+#### Improvements
+
+* **arg_enum**  allows ascii case insensitivity for enum variants ([b249f965](https://github.com/kbknapp/clap-rs/commit/b249f9657c6921c004764bd80d13ebca81585eec), closes [#104](https://github.com/kbknapp/clap-rs/issues/104))
+* **clap-test**  simplified `make test` invocation ([d17dcb29](https://github.com/kbknapp/clap-rs/commit/d17dcb2920637a1f58c61c596b7bd362fd53047c))
+
+#### Documentation
+
+* **README**  adds details about optional and new features ([960389de](https://github.com/kbknapp/clap-rs/commit/960389de02c9872aaee9adabe86987f71f986e39))
+* **clap**  fix typos caught by codespell ([8891d929](https://github.com/kbknapp/clap-rs/commit/8891d92917aa1a069cca67272be41b99e548356e))
+* **from_usage**  explains new usage strings with multiple values ([05476fc6](https://github.com/kbknapp/clap-rs/commit/05476fc61cd1e5f4a4e750d258c878732a3a9c64))
+
+
+
+<a name="v0.7.6"></a>
+## v0.7.6 (2015-05-05)
+
+
+#### Improvements
+
+* **Options**  adds number of values to options in help/usage ([c1c993c4](https://github.com/kbknapp/clap-rs/commit/c1c993c419d18e35c443785053d8de9a2ef88073))
+
+#### Features
+
+* **from_usage**  adds ability to add value names or num of vals in usage string ([ad55748c](https://github.com/kbknapp/clap-rs/commit/ad55748c265cf27935c7b210307d2040b6a09125), closes [#98](https://github.com/kbknapp/clap-rs/issues/98))
+
+#### Bug Fixes
+
+* **MultipleValues**  properly distinguishes between multiple values and multiple occurrences ([dd2a7564](https://github.com/kbknapp/clap-rs/commit/dd2a75640ca68a91b973faad15f04df891356cef), closes [#99](https://github.com/kbknapp/clap-rs/issues/99))
+* **help**  fixes tab alignment with multiple values ([847001ff](https://github.com/kbknapp/clap-rs/commit/847001ff6d8f4d9518e810fefb8edf746dd0f31e))
+
+#### Documentation
+
+* **from_usage**  explains new usage strings with multiple values ([5a3a42df](https://github.com/kbknapp/clap-rs/commit/5a3a42dfa3a783537f88dedc0fd5f0edcb8ea372))
+
+
+
+<a name="v0.7.5"></a>
+## v0.7.5 (2015-05-04)
+
+
+#### Bug Fixes
+
+* **Options**  fixes bug where options with no value don't error out ([a1fb94be](https://github.com/kbknapp/clap-rs/commit/a1fb94be53141572ffd97aad037295d4ffec82d0))
+
+
+
+<a name="v0.7.4"></a>
+## v0.7.4 (2015-05-03)
+
+
+#### Bug Fixes
+
+* **Options**  fixes a bug where option arguments in succession get their values skipped ([f66334d0](https://github.com/kbknapp/clap-rs/commit/f66334d0ce984e2b56e5c19abb1dd536fae9342a))
+
+
+
+<a name="v0.7.3"></a>
+## v0.7.3 (2015-05-03)
+
+
+#### Bug Fixes
+
+* **RequiredValues**  fixes a bug where missing values are parsed as missing arguments ([93c4a723](https://github.com/kbknapp/clap-rs/commit/93c4a7231ba1a08152648598f7aa4503ea82e4de))
+
+#### Improvements
+
+* **ErrorMessages**  improves error messages and corrections ([a29c3983](https://github.com/kbknapp/clap-rs/commit/a29c3983c4229906655a29146ec15a0e46dd942d))
+* **ArgGroups**  improves requirement and confliction support for groups ([c236dc5f](https://github.com/kbknapp/clap-rs/commit/c236dc5ff475110d2a1b80e62903f80296163ad3))
+
+
+
+<a name="v0.7.2"></a>
+## v0.7.2 (2015-05-03)
+
+
+#### Bug Fixes
+
+* **RequiredArgs**  fixes bug where required-by-default arguments are not listed in usage ([12aea961](https://github.com/kbknapp/clap-rs/commit/12aea9612d290845ba86515c240aeeb0a21198db), closes [#96](https://github.com/kbknapp/clap-rs/issues/96))
+
+
+
+<a name="v0.7.1"></a>
+## v0.7.1 (2015-05-01)
+
+
+#### Bug Fixes
+
+* **MultipleValues**  stops evaluating values if the max or exact number of values was reached ([86d92c9f](https://github.com/kbknapp/clap-rs/commit/86d92c9fdbf9f422442e9562977bbaf268dbbae1))
+
+
+
+<a name="v0.7.0"></a>
+## v0.7.0 (2015-04-30) - BREAKING CHANGE
+
+
+#### Bug Fixes
+
+* **from_usage**  removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83))
+
+#### Features
+
+* **MultipleValues**
+  *  add support for minimum and maximum number of values ([53f6b8c9](https://github.com/kbknapp/clap-rs/commit/53f6b8c9d8dc408b4fa9f833fc3a63683873c42f))
+  *  adds support limited number and named values ([ae09f05e](https://github.com/kbknapp/clap-rs/commit/ae09f05e92251c1b39a83d372736fcc7b504e432))
+  *  implement shorthand for options with multiple values ([6669f0a9](https://github.com/kbknapp/clap-rs/commit/6669f0a9687d4f668523145d7bd5c007d1eb59a8))
+* **arg**  allow other types besides Vec for multiple value settings (**BREAKING CHANGE** [0cc2f698](https://github.com/kbknapp/clap-rs/commit/0cc2f69839b9b1db5d06330771b494783049a88e), closes [#87](https://github.com/kbknapp/clap-rs/issues/87))
+* **usage**  implement smart usage strings on errors ([d77048ef](https://github.com/kbknapp/clap-rs/commit/d77048efb1e595ffe831f1a2bea2f2700db53b9f), closes [#88](https://github.com/kbknapp/clap-rs/issues/88))
+
+
+
+<a name="v0.6.9"></a>
+## v0.6.9 (2015-04-29)
+
+
+#### Bug Fixes
+
+* **from_usage**  removes bug where usage strings have no help text ([ad4e5451](https://github.com/kbknapp/clap-rs/commit/ad4e54510739aeabf75f0da3278fb0952db531b3), closes [#83](https://github.com/kbknapp/clap-rs/issues/83))
+
+
+
+<a name="0.6.8"></a>
+## 0.6.8 (2015-04-27)
+
+
+#### Bug Fixes
+
+* **help**  change long help --long=long -> --long <long> ([1e25abfc](https://github.com/kbknapp/clap-rs/commit/1e25abfc36679ab89eae71bf98ced4de81992d00))
+* **RequiredArgs**  required by default args should no longer be required when their exclusions are present ([4bb4c3cc](https://github.com/kbknapp/clap-rs/commit/4bb4c3cc076b49e86720e882bf8c489877199f2d))
+
+#### Features
+
+* **ArgGroups**  add ability to create arg groups ([09eb4d98](https://github.com/kbknapp/clap-rs/commit/09eb4d9893af40c347e50e2b717e1adef552357d))
+
+
+
+<a name="v0.6.7"></a>
+## v0.6.7 (2015-04-22)
+
+
+#### Bug Fixes
+
+* **from_usage**  fix bug causing args to not be required ([b76129e9](https://github.com/kbknapp/clap-rs/commit/b76129e9b71a63365d5c77a7f57b58dbd1e94d49))
+
+#### Features
+
+* **apps**  add ability to display additional help info after auto-gen'ed help msg ([65cc259e](https://github.com/kbknapp/clap-rs/commit/65cc259e4559cbe3653c865ec0c4b1e42a389b07))
+
+
+
+<a name="v0.6.6"></a>
+## v0.6.6 (2015-04-19)
+
+
+#### Bug Fixes
+
+* **from_usage**  tabs and spaces should be treated equally ([4fd44181](https://github.com/kbknapp/clap-rs/commit/4fd44181d55d8eb88caab1e625231cfa3129e347))
+
+#### Features
+
+* **macros.rs**  add macro to get version from Cargo.toml ([c630969a](https://github.com/kbknapp/clap-rs/commit/c630969aa3bbd386379219cae27ba1305b117f3e))
+
+
+
+<a name="v0.6.5"></a>
+## v0.6.5 (2015-04-19)
+
+
+#### Bug Fixes
+
+* **macros.rs**  fix use statements for trait impls ([86e4075e](https://github.com/kbknapp/clap-rs/commit/86e4075eb111937c8a7bdb344e866e350429f042))
+
+
+
+<a name="v0.6.4"></a>
+## v0.6.4 (2015-04-17)
+
+
+#### Features
+
+* **macros**  add ability to create enums pub or priv with derives ([2c499f80](https://github.com/kbknapp/clap-rs/commit/2c499f8015a199827cdf1fa3ec4f6f171722f8c7))
+
+
+
+<a name="v0.6.3"></a>
+## v0.6.3 (2015-04-16)
+
+
+#### Features
+
+* **macros**  add macro to create custom enums to use as types ([fb672aff](https://github.com/kbknapp/clap-rs/commit/fb672aff561c29db2e343d6c607138f141aca8b6))
+
+
+
+<a name="v0.6.2"></a>
+## v0.6.2 (2015-04-14)
+
+
+#### Features
+
+* **macros**
+  *  add ability to get multiple typed values or exit ([0b87251f](https://github.com/kbknapp/clap-rs/commit/0b87251fc088234bee51c323c2b652d7254f7a59))
+  *  add ability to get a typed multiple values ([e243fe38](https://github.com/kbknapp/clap-rs/commit/e243fe38ddbbf845a46c0b9baebaac3778c80927))
+  *  add convenience macro to get a typed value or exit ([4b7cd3ea](https://github.com/kbknapp/clap-rs/commit/4b7cd3ea4947780d9daa39f3e1ddab53ad4c7fef))
+  *  add convenience macro to get a typed value ([8752700f](https://github.com/kbknapp/clap-rs/commit/8752700fbb30e89ee68adbce24489ae9a24d33a9))
+
+
+
+<a name="v0.6.1"></a>
+## v0.6.1 (2015-04-13)
+
+
+#### Bug Fixes
+
+* **from_usage**  trim all whitespace before parsing ([91d29045](https://github.com/kbknapp/clap-rs/commit/91d2904599bd602deef2e515dfc65dc2863bdea0))
+
+
+
+<a name="v0.6.0"></a>
+## v0.6.0 (2015-04-13)
+
+
+#### Bug Fixes
+
+* **tests**  fix failing doc tests ([3710cd69](https://github.com/kbknapp/clap-rs/commit/3710cd69162f87221a62464f63437c1ce843ad3c))
+
+#### Features
+
+* **app**  add support for building args from usage strings ([d5d48bcf](https://github.com/kbknapp/clap-rs/commit/d5d48bcf463a4e494ef758836bd69a4c220bbbb5))
+* **args**  add ability to create basic arguments from a usage string ([ab409a8f](https://github.com/kbknapp/clap-rs/commit/ab409a8f1db9e37cc70200f6f4a84a162692e618))
+
+
+
+<a name="v0.5.14"></a>
+## v0.5.14 (2015-04-10)
+
+
+#### Bug Fixes
+
+* **usage**
+  *  remove unneeded space ([51372789](https://github.com/kbknapp/clap-rs/commit/5137278942121bc2593ce6e5dc224ec2682549e6))
+  *  remove warning about unused variables ([ba817b9d](https://github.com/kbknapp/clap-rs/commit/ba817b9d815e37320650973f1bea0e7af3030fd7))
+
+#### Features
+
+* **usage**  add ability to get usage string for subcommands too ([3636afc4](https://github.com/kbknapp/clap-rs/commit/3636afc401c2caa966efb5b1869ef4f1ed3384aa))
+
+
+
+<a name="v0.5.13"></a>
+## v0.5.13 (2015-04-09)
+
+
+#### Features
+
+* **SubCommands**  add method to get name and subcommand matches together ([64e53928](https://github.com/kbknapp/clap-rs/commit/64e539280e23e567cf5de393b346eb0ca20e7eb5))
+* **ArgMatches**  add method to get default usage string ([02462150](https://github.com/kbknapp/clap-rs/commit/02462150ca750bdc7012627d7e8d96379d494d7f))
+
+
+
+<a name="v0.5.12"></a>
+## v0.5.12 (2015-04-08)
+
+
+#### Features
+
+* **help**  sort arguments by name so as to not display a random order ([f4b2bf57](https://github.com/kbknapp/clap-rs/commit/f4b2bf5767386013069fb74862e6e938dacf44d2))
+
+
+
+<a name="v0.5.11"></a>
+## v0.5.11 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **flags**  fix bug not allowing users to specify -v or -h ([90e72cff](https://github.com/kbknapp/clap-rs/commit/90e72cffdee321b79eea7a2207119533540062b4))
+
+
+
+<a name="v0.5.10"></a>
+## v0.5.10 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **help**  fix spacing when option argument has not long version ([ca17fa49](https://github.com/kbknapp/clap-rs/commit/ca17fa494b68e92da83ee364bf64b0687006824b))
+
+
+
+<a name="v0.5.9"></a>
+## v0.5.9 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **positional args**  all previous positional args become required when a latter one is required ([c14c3f31](https://github.com/kbknapp/clap-rs/commit/c14c3f31fd557c165570b60911d8ee483d89d6eb), closes [#50](https://github.com/kbknapp/clap-rs/issues/50))
+* **clap**  remove unstable features for Rust 1.0 ([9abdb438](https://github.com/kbknapp/clap-rs/commit/9abdb438e36e364d41550e7f5d44ebcaa8ee6b10))
+* **args**  improve error messages for arguments with mutual exclusions ([18dbcf37](https://github.com/kbknapp/clap-rs/commit/18dbcf37024daf2b76ca099a6f118b53827aa339), closes [#51](https://github.com/kbknapp/clap-rs/issues/51))
+
+
+
+<a name="v0.5.8"></a>
+## v0.5.8 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **option args**  fix bug in getting the wrong number of occurrences for options ([82ad6ad7](https://github.com/kbknapp/clap-rs/commit/82ad6ad77539cf9f9a03b78db466f575ebd972cc))
+* **help**  fix formatting for option arguments with no long ([e8691004](https://github.com/kbknapp/clap-rs/commit/e869100423d93fa3acff03c4620cbcc0d0e790a1))
+* **flags**  add assertion to catch flags with specific value sets ([a0a2a40f](https://github.com/kbknapp/clap-rs/commit/a0a2a40fed57f7c5ad9d68970d090e9856306c7d), closes [#52](https://github.com/kbknapp/clap-rs/issues/52))
+* **args**  improve error messages for arguments with mutual exclusions ([bff945fc](https://github.com/kbknapp/clap-rs/commit/bff945fc5d03bba4266533340adcffb002508d1b), closes [#51](https://github.com/kbknapp/clap-rs/issues/51))
+* **tests**  add missing .takes_value(true) to option2 ([bdb0e88f](https://github.com/kbknapp/clap-rs/commit/bdb0e88f696c8595c3def3bfb0e52d538c7be085))
+* **positional args**  all previous positional args become required when a latter one is required ([343d47dc](https://github.com/kbknapp/clap-rs/commit/343d47dcbf83786a45c0d0f01b27fd9dd76725de), closes [#50](https://github.com/kbknapp/clap-rs/issues/50))
+
+
+
+<a name="v0.5.7"></a>
+## v0.5.7 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **args**  fix bug in arguments who are required and mutually exclusive ([6ceb88a5](https://github.com/kbknapp/clap-rs/commit/6ceb88a594caae825605abc1cdad95204996bf29))
+
+
+
+<a name="v0.5.6"></a>
+## v0.5.6 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **help**  fix formatting of help and usage ([28691b52](https://github.com/kbknapp/clap-rs/commit/28691b52f67e65c599e10e4ea2a0f6f9765a06b8))
+
+
+
+<a name="v0.5.5"></a>
+## v0.5.5 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **help**  fix formatting of help for flags and options ([6ec10115](https://github.com/kbknapp/clap-rs/commit/6ec1011563a746f0578a93b76d45e63878e0f9a8))
+
+
+
+<a name="v0.5.4"></a>
+## v0.5.4 (2015-04-08)
+
+
+#### Features
+
+* **help**  add '...' to indicate multiple values supported ([297ddba7](https://github.com/kbknapp/clap-rs/commit/297ddba77000e2228762ab0eca50b480f7467386))
+
+
+
+<a name="v0.5.3"></a>
+## v0.5.3 (2015-04-08)
+
+
+#### Features
+
+* **positionals**
+  *  add assertions for positional args with multiple vals ([b7fa72d4](https://github.com/kbknapp/clap-rs/commit/b7fa72d40f18806ec2042dd67a518401c2cf5681))
+  *  add support for multiple values ([80784009](https://github.com/kbknapp/clap-rs/commit/807840094109fbf90b348039ae22669ef27889ba))
+
+
+
+<a name="v0.5.2"></a>
+## v0.5.2 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **apps**  allow use of hyphens in application and subcommand names ([da549dcb](https://github.com/kbknapp/clap-rs/commit/da549dcb6c7e0d773044ab17829744483a8b0f7f))
+
+
+
+<a name="v0.5.1"></a>
+## v0.5.1 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **args**  determine if the only arguments allowed are also required ([0a09eb36](https://github.com/kbknapp/clap-rs/commit/0a09eb365ced9a03faf8ed24f083ef730acc90e8))
+
+
+
+<a name="v0.5.0"></a>
+## v0.5.0 (2015-04-08)
+
+
+#### Features
+
+* **args**  add support for a specific set of allowed values on options or positional arguments ([270eb889](https://github.com/kbknapp/clap-rs/commit/270eb88925b6dc2881bff1f31ee344f085d31809))
+
+
+
+<a name="v0.4.18"></a>
+## v0.4.18 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **usage**  display required args in usage, even if only required by others ([1b7316d4](https://github.com/kbknapp/clap-rs/commit/1b7316d4a8df70b0aa584ccbfd33f68966ad2a54))
+
+#### Features
+
+* **subcommands**  properly list subcommands in help and usage ([4ee02344](https://github.com/kbknapp/clap-rs/commit/4ee023442abc3dba54b68138006a52b714adf331))
+
+
+
+<a name="v0.4.17"></a>
+## v0.4.17 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **tests**  remove cargo test from claptests makefile ([1cf73817](https://github.com/kbknapp/clap-rs/commit/1cf73817d6fb1dccb5b6a23b46c2efa8b567ad62))
+
+
+
+<a name="v0.4.16"></a>
+## v0.4.16 (2015-04-08)
+
+
+#### Bug Fixes
+
+* **option**  fix bug with option occurrence values ([9af52e93](https://github.com/kbknapp/clap-rs/commit/9af52e93cef9e17ac9974963f132013d0b97b946))
+* **tests**  fix testing script bug and formatting ([d8f03a55](https://github.com/kbknapp/clap-rs/commit/d8f03a55c4f74d126710ee06aad5a667246a8001))
+
+#### Features
+
+* **arg**  allow lifetimes other than 'static in arguments ([9e8c1fb9](https://github.com/kbknapp/clap-rs/commit/9e8c1fb9406f8448873ca58bab07fe905f1551e5))
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/CONTRIBUTORS.md
@@ -0,0 +1,91 @@
+the following is a list of contributors:
+
+
+[<img alt="kbknapp" src="https://avatars1.githubusercontent.com/u/6942134?v=4&s=117" width="117">](https://github.com/kbknapp) |[<img alt="homu" src="https://avatars1.githubusercontent.com/u/10212162?v=4&s=117" width="117">](https://github.com/homu) |[<img alt="Vinatorul" src="https://avatars1.githubusercontent.com/u/6770624?v=4&s=117" width="117">](https://github.com/Vinatorul) |[<img alt="tormol" src="https://avatars3.githubusercontent.com/u/10460821?v=4&s=117" width="117">](https://github.com/tormol) |[<img alt="willmurphyscode" src="https://avatars3.githubusercontent.com/u/12529630?v=4&s=117" width="117">](https://github.com/willmurphyscode) |[<img alt="little-dude" src="https://avatars2.githubusercontent.com/u/6646324?v=4&s=117" width="117">](https://github.com/little-dude) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[kbknapp](https://github.com/kbknapp) |[homu](https://github.com/homu) |[Vinatorul](https://github.com/Vinatorul) |[tormol](https://github.com/tormol) |[willmurphyscode](https://github.com/willmurphyscode) |[little-dude](https://github.com/little-dude) |
+
+[<img alt="sru" src="https://avatars3.githubusercontent.com/u/2485892?v=4&s=117" width="117">](https://github.com/sru) |[<img alt="mgeisler" src="https://avatars0.githubusercontent.com/u/89623?v=4&s=117" width="117">](https://github.com/mgeisler) |[<img alt="nabijaczleweli" src="https://avatars3.githubusercontent.com/u/6709544?v=4&s=117" width="117">](https://github.com/nabijaczleweli) |[<img alt="Byron" src="https://avatars2.githubusercontent.com/u/63622?v=4&s=117" width="117">](https://github.com/Byron) |[<img alt="hgrecco" src="https://avatars0.githubusercontent.com/u/278566?v=4&s=117" width="117">](https://github.com/hgrecco) |[<img alt="bluejekyll" src="https://avatars3.githubusercontent.com/u/986845?v=4&s=117" width="117">](https://github.com/bluejekyll) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[sru](https://github.com/sru) |[mgeisler](https://github.com/mgeisler) |[nabijaczleweli](https://github.com/nabijaczleweli) |[Byron](https://github.com/Byron) |[hgrecco](https://github.com/hgrecco) |[bluejekyll](https://github.com/bluejekyll) |
+
+[<img alt="segevfiner" src="https://avatars0.githubusercontent.com/u/24731903?v=4&s=117" width="117">](https://github.com/segevfiner) |[<img alt="ignatenkobrain" src="https://avatars1.githubusercontent.com/u/2866862?v=4&s=117" width="117">](https://github.com/ignatenkobrain) |[<img alt="james-darkfox" src="https://avatars3.githubusercontent.com/u/637155?v=4&s=117" width="117">](https://github.com/james-darkfox) |[<img alt="H2CO3" src="https://avatars2.githubusercontent.com/u/742370?v=4&s=117" width="117">](https://github.com/H2CO3) |[<img alt="nateozem" src="https://avatars2.githubusercontent.com/u/22719441?v=4&s=117" width="117">](https://github.com/nateozem) |[<img alt="glowing-chemist" src="https://avatars0.githubusercontent.com/u/17074682?v=4&s=117" width="117">](https://github.com/glowing-chemist) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[segevfiner](https://github.com/segevfiner) |[ignatenkobrain](https://github.com/ignatenkobrain) |[james-darkfox](https://github.com/james-darkfox) |[H2CO3](https://github.com/H2CO3) |[nateozem](https://github.com/nateozem) |[glowing-chemist](https://github.com/glowing-chemist) |
+
+[<img alt="discosultan" src="https://avatars1.githubusercontent.com/u/2970736?v=4&s=117" width="117">](https://github.com/discosultan) |[<img alt="rtaycher" src="https://avatars0.githubusercontent.com/u/324733?v=4&s=117" width="117">](https://github.com/rtaycher) |[<img alt="Arnavion" src="https://avatars2.githubusercontent.com/u/1096010?v=4&s=117" width="117">](https://github.com/Arnavion) |[<img alt="japaric" src="https://avatars3.githubusercontent.com/u/5018213?v=4&s=117" width="117">](https://github.com/japaric) |[<img alt="untitaker" src="https://avatars0.githubusercontent.com/u/837573?v=4&s=117" width="117">](https://github.com/untitaker) |[<img alt="afiune" src="https://avatars0.githubusercontent.com/u/5712253?v=4&s=117" width="117">](https://github.com/afiune) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[discosultan](https://github.com/discosultan) |[rtaycher](https://github.com/rtaycher) |[Arnavion](https://github.com/Arnavion) |[japaric](https://github.com/japaric) |[untitaker](https://github.com/untitaker) |[afiune](https://github.com/afiune) |
+
+[<img alt="crazymerlyn" src="https://avatars1.githubusercontent.com/u/6919679?v=4&s=117" width="117">](https://github.com/crazymerlyn) |[<img alt="SuperFluffy" src="https://avatars0.githubusercontent.com/u/701177?v=4&s=117" width="117">](https://github.com/SuperFluffy) |[<img alt="matthiasbeyer" src="https://avatars0.githubusercontent.com/u/427866?v=4&s=117" width="117">](https://github.com/matthiasbeyer) |[<img alt="malbarbo" src="https://avatars3.githubusercontent.com/u/1678126?v=4&s=117" width="117">](https://github.com/malbarbo) |[<img alt="tshepang" src="https://avatars0.githubusercontent.com/u/588486?v=4&s=117" width="117">](https://github.com/tshepang) |[<img alt="golem131" src="https://avatars3.githubusercontent.com/u/2429587?v=4&s=117" width="117">](https://github.com/golem131) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[crazymerlyn](https://github.com/crazymerlyn) |[SuperFluffy](https://github.com/SuperFluffy) |[matthiasbeyer](https://github.com/matthiasbeyer) |[malbarbo](https://github.com/malbarbo) |[tshepang](https://github.com/tshepang) |[golem131](https://github.com/golem131) |
+
+[<img alt="jimmycuadra" src="https://avatars2.githubusercontent.com/u/122457?v=4&s=117" width="117">](https://github.com/jimmycuadra) |[<img alt="Nemo157" src="https://avatars1.githubusercontent.com/u/81079?v=4&s=117" width="117">](https://github.com/Nemo157) |[<img alt="severen" src="https://avatars1.githubusercontent.com/u/4061736?v=4&s=117" width="117">](https://github.com/severen) |[<img alt="Eijebong" src="https://avatars2.githubusercontent.com/u/3650385?v=4&s=117" width="117">](https://github.com/Eijebong) |[<img alt="cstorey" src="https://avatars3.githubusercontent.com/u/743059?v=4&s=117" width="117">](https://github.com/cstorey) |[<img alt="wdv4758h" src="https://avatars1.githubusercontent.com/u/2716047?v=4&s=117" width="117">](https://github.com/wdv4758h) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[jimmycuadra](https://github.com/jimmycuadra) |[Nemo157](https://github.com/Nemo157) |[severen](https://github.com/severen) |[Eijebong](https://github.com/Eijebong) |[cstorey](https://github.com/cstorey) |[wdv4758h](https://github.com/wdv4758h) |
+
+[<img alt="frewsxcv" src="https://avatars2.githubusercontent.com/u/416575?v=4&s=117" width="117">](https://github.com/frewsxcv) |[<img alt="hoodie" src="https://avatars1.githubusercontent.com/u/260370?v=4&s=117" width="117">](https://github.com/hoodie) |[<img alt="huonw" src="https://avatars1.githubusercontent.com/u/1203825?v=4&s=117" width="117">](https://github.com/huonw) |[<img alt="GrappigPanda" src="https://avatars0.githubusercontent.com/u/2055372?v=4&s=117" width="117">](https://github.com/GrappigPanda) |[<img alt="shepmaster" src="https://avatars0.githubusercontent.com/u/174509?v=4&s=117" width="117">](https://github.com/shepmaster) |[<img alt="starkat99" src="https://avatars1.githubusercontent.com/u/8295111?v=4&s=117" width="117">](https://github.com/starkat99) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[frewsxcv](https://github.com/frewsxcv) |[hoodie](https://github.com/hoodie) |[huonw](https://github.com/huonw) |[GrappigPanda](https://github.com/GrappigPanda) |[shepmaster](https://github.com/shepmaster) |[starkat99](https://github.com/starkat99) |
+
+[<img alt="porglezomp" src="https://avatars1.githubusercontent.com/u/1690225?v=4&s=117" width="117">](https://github.com/porglezomp) |[<img alt="kraai" src="https://avatars1.githubusercontent.com/u/552646?v=4&s=117" width="117">](https://github.com/kraai) |[<img alt="musoke" src="https://avatars0.githubusercontent.com/u/16665084?v=4&s=117" width="117">](https://github.com/musoke) |[<img alt="nelsonjchen" src="https://avatars1.githubusercontent.com/u/5363?v=4&s=117" width="117">](https://github.com/nelsonjchen) |[<img alt="pkgw" src="https://avatars0.githubusercontent.com/u/59598?v=4&s=117" width="117">](https://github.com/pkgw) |[<img alt="Deedasmi" src="https://avatars0.githubusercontent.com/u/5093293?v=4&s=117" width="117">](https://github.com/Deedasmi) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[porglezomp](https://github.com/porglezomp) |[kraai](https://github.com/kraai) |[musoke](https://github.com/musoke) |[nelsonjchen](https://github.com/nelsonjchen) |[pkgw](https://github.com/pkgw) |[Deedasmi](https://github.com/Deedasmi) |
+
+[<img alt="vmchale" src="https://avatars1.githubusercontent.com/u/13259982?v=4&s=117" width="117">](https://github.com/vmchale) |[<img alt="etopiei" src="https://avatars3.githubusercontent.com/u/17671663?v=4&s=117" width="117">](https://github.com/etopiei) |[<img alt="messense" src="https://avatars0.githubusercontent.com/u/1556054?v=4&s=117" width="117">](https://github.com/messense) |[<img alt="Keats" src="https://avatars2.githubusercontent.com/u/680355?v=4&s=117" width="117">](https://github.com/Keats) |[<img alt="kieraneglin" src="https://avatars0.githubusercontent.com/u/569917?v=4&s=117" width="117">](https://github.com/kieraneglin) |[<img alt="durka" src="https://avatars3.githubusercontent.com/u/47007?v=4&s=117" width="117">](https://github.com/durka) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[vmchale](https://github.com/vmchale) |[etopiei](https://github.com/etopiei) |[messense](https://github.com/messense) |[Keats](https://github.com/Keats) |[kieraneglin](https://github.com/kieraneglin) |[durka](https://github.com/durka) |
+
+[<img alt="alex-gulyas" src="https://avatars0.githubusercontent.com/u/8698329?v=4&s=117" width="117">](https://github.com/alex-gulyas) |[<img alt="cite-reader" src="https://avatars1.githubusercontent.com/u/4196987?v=4&s=117" width="117">](https://github.com/cite-reader) |[<img alt="alexbool" src="https://avatars3.githubusercontent.com/u/1283792?v=4&s=117" width="117">](https://github.com/alexbool) |[<img alt="AluisioASG" src="https://avatars2.githubusercontent.com/u/1904165?v=4&s=117" width="117">](https://github.com/AluisioASG) |[<img alt="BurntSushi" src="https://avatars3.githubusercontent.com/u/456674?v=4&s=117" width="117">](https://github.com/BurntSushi) |[<img alt="AndrewGaspar" src="https://avatars1.githubusercontent.com/u/2292643?v=4&s=117" width="117">](https://github.com/AndrewGaspar) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[alex-gulyas](https://github.com/alex-gulyas) |[cite-reader](https://github.com/cite-reader) |[alexbool](https://github.com/alexbool) |[AluisioASG](https://github.com/AluisioASG) |[BurntSushi](https://github.com/BurntSushi) |[AndrewGaspar](https://github.com/AndrewGaspar) |
+
+[<img alt="nox" src="https://avatars0.githubusercontent.com/u/123095?v=4&s=117" width="117">](https://github.com/nox) |[<img alt="mitsuhiko" src="https://avatars1.githubusercontent.com/u/7396?v=4&s=117" width="117">](https://github.com/mitsuhiko) |[<img alt="pixelistik" src="https://avatars1.githubusercontent.com/u/170929?v=4&s=117" width="117">](https://github.com/pixelistik) |[<img alt="ogham" src="https://avatars3.githubusercontent.com/u/503760?v=4&s=117" width="117">](https://github.com/ogham) |[<img alt="Bilalh" src="https://avatars0.githubusercontent.com/u/171602?v=4&s=117" width="117">](https://github.com/Bilalh) |[<img alt="dotdash" src="https://avatars1.githubusercontent.com/u/230962?v=4&s=117" width="117">](https://github.com/dotdash) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[nox](https://github.com/nox) |[mitsuhiko](https://github.com/mitsuhiko) |[pixelistik](https://github.com/pixelistik) |[ogham](https://github.com/ogham) |[Bilalh](https://github.com/Bilalh) |[dotdash](https://github.com/dotdash) |
+
+[<img alt="bradurani" src="https://avatars0.githubusercontent.com/u/4195952?v=4&s=117" width="117">](https://github.com/bradurani) |[<img alt="Seeker14491" src="https://avatars2.githubusercontent.com/u/6490497?v=4&s=117" width="117">](https://github.com/Seeker14491) |[<img alt="brianp" src="https://avatars1.githubusercontent.com/u/179134?v=4&s=117" width="117">](https://github.com/brianp) |[<img alt="cldershem" src="https://avatars3.githubusercontent.com/u/201608?v=4&s=117" width="117">](https://github.com/cldershem) |[<img alt="casey" src="https://avatars2.githubusercontent.com/u/1945?v=4&s=117" width="117">](https://github.com/casey) |[<img alt="volks73" src="https://avatars1.githubusercontent.com/u/1915469?v=4&s=117" width="117">](https://github.com/volks73) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[bradurani](https://github.com/bradurani) |[Seeker14491](https://github.com/Seeker14491) |[brianp](https://github.com/brianp) |[cldershem](https://github.com/cldershem) |[casey](https://github.com/casey) |[volks73](https://github.com/volks73) |
+
+[<img alt="daboross" src="https://avatars1.githubusercontent.com/u/1152146?v=4&s=117" width="117">](https://github.com/daboross) |[<img alt="da-x" src="https://avatars1.githubusercontent.com/u/321273?v=4&s=117" width="117">](https://github.com/da-x) |[<img alt="mernen" src="https://avatars0.githubusercontent.com/u/6412?v=4&s=117" width="117">](https://github.com/mernen) |[<img alt="dguo" src="https://avatars0.githubusercontent.com/u/2763135?v=4&s=117" width="117">](https://github.com/dguo) |[<img alt="davidszotten" src="https://avatars3.githubusercontent.com/u/412005?v=4&s=117" width="117">](https://github.com/davidszotten) |[<img alt="drusellers" src="https://avatars1.githubusercontent.com/u/63355?v=4&s=117" width="117">](https://github.com/drusellers) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[daboross](https://github.com/daboross) |[da-x](https://github.com/da-x) |[mernen](https://github.com/mernen) |[dguo](https://github.com/dguo) |[davidszotten](https://github.com/davidszotten) |[drusellers](https://github.com/drusellers) |
+
+[<img alt="eddyb" src="https://avatars2.githubusercontent.com/u/77424?v=4&s=117" width="117">](https://github.com/eddyb) |[<img alt="Enet4" src="https://avatars0.githubusercontent.com/u/4738426?v=4&s=117" width="117">](https://github.com/Enet4) |[<img alt="Fraser999" src="https://avatars3.githubusercontent.com/u/190532?v=4&s=117" width="117">](https://github.com/Fraser999) |[<img alt="birkenfeld" src="https://avatars0.githubusercontent.com/u/144359?v=4&s=117" width="117">](https://github.com/birkenfeld) |[<img alt="guanqun" src="https://avatars0.githubusercontent.com/u/53862?v=4&s=117" width="117">](https://github.com/guanqun) |[<img alt="tanakh" src="https://avatars2.githubusercontent.com/u/109069?v=4&s=117" width="117">](https://github.com/tanakh) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[eddyb](https://github.com/eddyb) |[Enet4](https://github.com/Enet4) |[Fraser999](https://github.com/Fraser999) |[birkenfeld](https://github.com/birkenfeld) |[guanqun](https://github.com/guanqun) |[tanakh](https://github.com/tanakh) |
+
+[<img alt="SirVer" src="https://avatars0.githubusercontent.com/u/140115?v=4&s=117" width="117">](https://github.com/SirVer) |[<img alt="idmit" src="https://avatars1.githubusercontent.com/u/2546728?v=4&s=117" width="117">](https://github.com/idmit) |[<img alt="archer884" src="https://avatars1.githubusercontent.com/u/679494?v=4&s=117" width="117">](https://github.com/archer884) |[<img alt="jacobmischka" src="https://avatars1.githubusercontent.com/u/3939997?v=4&s=117" width="117">](https://github.com/jacobmischka) |[<img alt="jespino" src="https://avatars0.githubusercontent.com/u/290303?v=4&s=117" width="117">](https://github.com/jespino) |[<img alt="jfrankenau" src="https://avatars3.githubusercontent.com/u/2736480?v=4&s=117" width="117">](https://github.com/jfrankenau) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[SirVer](https://github.com/SirVer) |[idmit](https://github.com/idmit) |[archer884](https://github.com/archer884) |[jacobmischka](https://github.com/jacobmischka) |[jespino](https://github.com/jespino) |[jfrankenau](https://github.com/jfrankenau) |
+
+[<img alt="jtdowney" src="https://avatars1.githubusercontent.com/u/44654?v=4&s=117" width="117">](https://github.com/jtdowney) |[<img alt="andete" src="https://avatars2.githubusercontent.com/u/689017?v=4&s=117" width="117">](https://github.com/andete) |[<img alt="joshtriplett" src="https://avatars2.githubusercontent.com/u/162737?v=4&s=117" width="117">](https://github.com/joshtriplett) |[<img alt="Kalwyn" src="https://avatars3.githubusercontent.com/u/22778640?v=4&s=117" width="117">](https://github.com/Kalwyn) |[<img alt="manuel-rhdt" src="https://avatars1.githubusercontent.com/u/3199013?v=4&s=117" width="117">](https://github.com/manuel-rhdt) |[<img alt="Marwes" src="https://avatars3.githubusercontent.com/u/957312?v=4&s=117" width="117">](https://github.com/Marwes) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[jtdowney](https://github.com/jtdowney) |[andete](https://github.com/andete) |[joshtriplett](https://github.com/joshtriplett) |[Kalwyn](https://github.com/Kalwyn) |[manuel-rhdt](https://github.com/manuel-rhdt) |[Marwes](https://github.com/Marwes) |
+
+[<img alt="mdaffin" src="https://avatars1.githubusercontent.com/u/171232?v=4&s=117" width="117">](https://github.com/mdaffin) |[<img alt="iliekturtles" src="https://avatars3.githubusercontent.com/u/5081378?v=4&s=117" width="117">](https://github.com/iliekturtles) |[<img alt="nicompte" src="https://avatars2.githubusercontent.com/u/439369?v=4&s=117" width="117">](https://github.com/nicompte) |[<img alt="NickeZ" src="https://avatars2.githubusercontent.com/u/492753?v=4&s=117" width="117">](https://github.com/NickeZ) |[<img alt="nvzqz" src="https://avatars0.githubusercontent.com/u/10367662?v=4&s=117" width="117">](https://github.com/nvzqz) |[<img alt="nuew" src="https://avatars2.githubusercontent.com/u/26099511?v=4&s=117" width="117">](https://github.com/nuew) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[mdaffin](https://github.com/mdaffin) |[iliekturtles](https://github.com/iliekturtles) |[nicompte](https://github.com/nicompte) |[NickeZ](https://github.com/NickeZ) |[nvzqz](https://github.com/nvzqz) |[nuew](https://github.com/nuew) |
+
+[<img alt="Geogi" src="https://avatars1.githubusercontent.com/u/1818316?v=4&s=117" width="117">](https://github.com/Geogi) |[<img alt="focusaurus" src="https://avatars1.githubusercontent.com/u/482377?v=4&s=117" width="117">](https://github.com/focusaurus) |[<img alt="flying-sheep" src="https://avatars0.githubusercontent.com/u/291575?v=4&s=117" width="117">](https://github.com/flying-sheep) |[<img alt="Phlosioneer" src="https://avatars2.githubusercontent.com/u/4657718?v=4&s=117" width="117">](https://github.com/Phlosioneer) |[<img alt="peppsac" src="https://avatars3.githubusercontent.com/u/2198295?v=4&s=117" width="117">](https://github.com/peppsac) |[<img alt="golddranks" src="https://avatars1.githubusercontent.com/u/2675542?v=4&s=117" width="117">](https://github.com/golddranks) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[Geogi](https://github.com/Geogi) |[focusaurus](https://github.com/focusaurus) |[flying-sheep](https://github.com/flying-sheep) |[Phlosioneer](https://github.com/Phlosioneer) |[peppsac](https://github.com/peppsac) |[golddranks](https://github.com/golddranks) |
+
+[<img alt="hexjelly" src="https://avatars0.githubusercontent.com/u/435283?v=4&s=117" width="117">](https://github.com/hexjelly) |[<img alt="rom1v" src="https://avatars1.githubusercontent.com/u/543275?v=4&s=117" width="117">](https://github.com/rom1v) |[<img alt="rnelson" src="https://avatars3.githubusercontent.com/u/118361?v=4&s=117" width="117">](https://github.com/rnelson) |[<img alt="swatteau" src="https://avatars3.githubusercontent.com/u/5521255?v=4&s=117" width="117">](https://github.com/swatteau) |[<img alt="tchajed" src="https://avatars3.githubusercontent.com/u/1255037?v=4&s=117" width="117">](https://github.com/tchajed) |[<img alt="tspiteri" src="https://avatars0.githubusercontent.com/u/18604588?v=4&s=117" width="117">](https://github.com/tspiteri) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[hexjelly](https://github.com/hexjelly) |[rom1v](https://github.com/rom1v) |[rnelson](https://github.com/rnelson) |[swatteau](https://github.com/swatteau) |[tchajed](https://github.com/tchajed) |[tspiteri](https://github.com/tspiteri) |
+
+[<img alt="siiptuo" src="https://avatars0.githubusercontent.com/u/10729330?v=4&s=117" width="117">](https://github.com/siiptuo) |[<img alt="vks" src="https://avatars2.githubusercontent.com/u/33460?v=4&s=117" width="117">](https://github.com/vks) |[<img alt="vsupalov" src="https://avatars2.githubusercontent.com/u/2801030?v=4&s=117" width="117">](https://github.com/vsupalov) |[<img alt="mineo" src="https://avatars1.githubusercontent.com/u/78236?v=4&s=117" width="117">](https://github.com/mineo) |[<img alt="wabain" src="https://avatars3.githubusercontent.com/u/7651435?v=4&s=117" width="117">](https://github.com/wabain) |[<img alt="grossws" src="https://avatars2.githubusercontent.com/u/171284?v=4&s=117" width="117">](https://github.com/grossws) |
+:---: |:---: |:---: |:---: |:---: |:---: |
+[siiptuo](https://github.com/siiptuo) |[vks](https://github.com/vks) |[vsupalov](https://github.com/vsupalov) |[mineo](https://github.com/mineo) |[wabain](https://github.com/wabain) |[grossws](https://github.com/grossws) |
+
+[<img alt="kennytm" src="https://avatars1.githubusercontent.com/u/103023?v=4&s=117" width="117">](https://github.com/kennytm) |[<img alt="king6cong" src="https://avatars3.githubusercontent.com/u/302560?v=4&s=117" width="117">](https://github.com/king6cong) |[<img alt="mvaude" src="https://avatars1.githubusercontent.com/u/9532611?v=4&s=117" width="117">](https://github.com/mvaude) |[<img alt="panicbit" src="https://avatars2.githubusercontent.com/u/628445?v=4&s=117" width="117">](https://github.com/panicbit) |[<img alt="brennie" src="https://avatars3.githubusercontent.com/u/156585?v=4&s=117" width="117">](https://github.com/brennie) |
+:---: |:---: |:---: |:---: |:---: |
+[kennytm](https://github.com/kennytm) |[king6cong](https://github.com/king6cong) |[mvaude](https://github.com/mvaude) |[panicbit](https://github.com/panicbit) |[brennie](https://github.com/brennie) |
+
+
+
+
+This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/Cargo.toml
@@ -0,0 +1,132 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "clap"
+version = "2.34.0"
+authors = ["Kevin K. <kbknapp@gmail.com>"]
+exclude = ["examples/*", "clap-test/*", "tests/*", "benches/*", "*.png", "clap-perf/*", "*.dot"]
+description = "A simple to use, efficient, and full-featured Command Line Argument Parser\n"
+homepage = "https://clap.rs/"
+documentation = "https://docs.rs/clap/"
+readme = "README.md"
+keywords = ["argument", "cli", "arg", "parser", "parse"]
+categories = ["command-line-interface"]
+license = "MIT"
+repository = "https://github.com/clap-rs/clap"
+[package.metadata.docs.rs]
+features = ["doc"]
+[profile.bench]
+opt-level = 3
+lto = true
+codegen-units = 1
+debug = false
+debug-assertions = false
+rpath = false
+
+[profile.dev]
+opt-level = 0
+lto = false
+codegen-units = 4
+debug = true
+debug-assertions = true
+rpath = false
+
+[profile.release]
+opt-level = 3
+lto = true
+codegen-units = 1
+debug = false
+debug-assertions = false
+rpath = false
+
+[profile.test]
+opt-level = 1
+lto = false
+codegen-units = 4
+debug = true
+debug-assertions = true
+rpath = false
+[dependencies.atty]
+version = "0.2.2"
+optional = true
+
+[dependencies.bitflags]
+version = "1.0"
+
+[dependencies.clippy]
+version = "~0.0.166"
+optional = true
+
+[dependencies.strsim]
+version = "0.8"
+optional = true
+
+[dependencies.term_size]
+version = "0.3.0"
+optional = true
+
+[dependencies.textwrap]
+version = "0.11.0"
+
+[dependencies.unicode-width]
+version = "0.1.4"
+
+[dependencies.vec_map]
+version = "0.8"
+optional = true
+
+[dependencies.yaml-rust]
+version = "0.3.5"
+optional = true
+[dev-dependencies.lazy_static]
+version = "1.3"
+
+[dev-dependencies.regex]
+version = "1"
+
+[dev-dependencies.version-sync]
+version = "0.8"
+
+[features]
+color = ["ansi_term", "atty"]
+debug = []
+default = ["suggestions", "color", "vec_map"]
+doc = ["yaml"]
+nightly = []
+no_cargo = []
+suggestions = ["strsim"]
+unstable = []
+wrap_help = ["term_size", "textwrap/term_size"]
+yaml = ["yaml-rust"]
+[target."cfg(not(windows))".dependencies.ansi_term]
+version = "0.12"
+optional = true
+[badges.appveyor]
+repository = "clap-rs/clap"
+
+[badges.coveralls]
+branch = "master"
+repository = "clap-rs/clap"
+
+[badges.is-it-maintained-issue-resolution]
+repository = "clap-rs/clap"
+
+[badges.is-it-maintained-open-issues]
+repository = "clap-rs/clap"
+
+[badges.maintenance]
+status = "actively-developed"
+
+[badges.travis-ci]
+repository = "clap-rs/clap"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/LICENSE-MIT
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-2016 Kevin B. Knapp
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/README.md
@@ -0,0 +1,542 @@
+clap
+====
+
+[![Crates.io](https://img.shields.io/crates/v/clap.svg)](https://crates.io/crates/clap) [![Crates.io](https://img.shields.io/crates/d/clap.svg)](https://crates.io/crates/clap) [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/clap-rs/clap/blob/master/LICENSE-MIT) [![Coverage Status](https://coveralls.io/repos/kbknapp/clap-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/kbknapp/clap-rs?branch=master) [![Join the chat at https://gitter.im/kbknapp/clap-rs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/kbknapp/clap-rs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+Linux: [![Build Status](https://travis-ci.org/clap-rs/clap.svg?branch=master)](https://travis-ci.org/clap-rs/clap)
+Windows: [![Build status](https://ci.appveyor.com/api/projects/status/ejg8c33dn31nhv36/branch/master?svg=true)](https://ci.appveyor.com/project/kbknapp/clap-rs/branch/master)
+
+Command Line Argument Parser for Rust
+
+It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcommands when writing console/terminal applications.
+
+* [documentation](https://docs.rs/clap/)
+* [website](https://clap.rs/)
+* [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U)
+
+Table of Contents
+=================
+
+* [About](#about)
+* [FAQ](#faq)
+* [Features](#features)
+* [Quick Example](#quick-example)
+* [Try it!](#try-it)
+  * [Pre-Built Test](#pre-built-test)
+  * [BYOB (Build Your Own Binary)](#byob-build-your-own-binary)
+* [Usage](#usage)
+  * [Optional Dependencies / Features](#optional-dependencies--features)
+  * [Dependencies Tree](#dependencies-tree)
+  * [More Information](#more-information)
+    * [Video Tutorials](#video-tutorials)
+* [How to Contribute](#how-to-contribute)
+  * [Compatibility Policy](#compatibility-policy)
+    * [Minimum Version of Rust](#minimum-version-of-rust)
+* [Related Crates](#related-crates)
+* [License](#license)
+* [Recent Breaking Changes](#recent-breaking-changes)
+  * [Deprecations](#deprecations)
+
+Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)
+
+## About
+
+`clap` is used to parse *and validate* the string of command line arguments provided by a user at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means you focus on your *applications* functionality, and less on the parsing and validating of arguments.
+
+`clap` provides many things 'for free' (with no configuration) including the traditional version and help switches (or flags) along with associated messages. If you are using subcommands, `clap` will also auto-generate a `help` subcommand and separate associated help messages.
+
+Once `clap` parses the user provided string of arguments, it returns the matches along with any applicable values. If the user made an error or typo, `clap` informs them with a friendly message and exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to exit). Because of this, you can make reasonable assumptions in your code about the validity of the arguments prior to your applications main execution.
+
+## FAQ
+
+For a full FAQ and more in depth details, see [the wiki page](https://github.com/clap-rs/clap/wiki/FAQ)
+
+### Comparisons
+
+First, let me say that these comparisons are highly subjective, and not meant in a critical or harsh manner. All the argument parsing libraries out there (to include `clap`) have their own strengths and weaknesses. Sometimes it just comes down to personal taste when all other factors are equal. When in doubt, try them all and pick one that you enjoy :) There's plenty of room in the Rust community for multiple implementations!
+
+#### How does `clap` compare to [getopts](https://github.com/rust-lang-nursery/getopts)?
+
+`getopts` is a very basic, fairly minimalist argument parsing library. This isn't a bad thing, sometimes you don't need tons of features, you just want to parse some simple arguments, and have some help text generated for you based on valid arguments you specify. The downside to this approach is that you must manually implement most of the common features (such as checking to display help messages, usage strings, etc.). If you want a highly custom argument parser, and don't mind writing the majority of the functionality yourself, `getopts` is an excellent base.
+
+`getopts` also doesn't allocate much, or at all. This gives it a very small performance boost. Although, as you start implementing additional features, that boost quickly disappears.
+
+Personally, I find many, many uses of `getopts` are manually implementing features that `clap` provides by default. Using `clap` simplifies your codebase allowing you to focus on your application, and not argument parsing.
+
+#### How does `clap` compare to [docopt.rs](https://github.com/docopt/docopt.rs)?
+
+I first want to say I'm a big a fan of BurntSushi's work, the creator of `Docopt.rs`. I aspire to produce the quality of libraries that this man does! When it comes to comparing these two libraries they are very different. `docopt` tasks you with writing a help message, and then it parsers that message for you to determine all valid arguments and their use. Some people LOVE this approach, others do not. If you're willing to write a detailed help message, it's nice that you can stick that in your program and have `docopt` do the rest. On the downside, it's far less flexible.
+
+`docopt` is also excellent at translating arguments into Rust types automatically. There is even a syntax extension which will do all this for you, if you're willing to use a nightly compiler (use of a stable compiler requires you to somewhat manually translate from arguments to Rust types). To use BurntSushi's words, `docopt` is also a sort of black box. You get what you get, and it's hard to tweak implementation or customize the experience for your use case.
+
+Because `docopt` is doing a ton of work to parse your help messages and determine what you were trying to communicate as valid arguments, it's also one of the more heavy weight parsers performance-wise. For most applications this isn't a concern and this isn't to say `docopt` is slow, in fact far from it. This is just something to keep in mind while comparing.
+
+#### All else being equal, what are some reasons to use `clap`? (The Pitch)
+
+`clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap` when just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex, and advanced requirements, without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs.
+
+#### All else being equal, what are some reasons *not* to use `clap`? (The Anti Pitch)
+
+Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many fine-tuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways which may be contrary to some users use-cases. Finally, `clap` is "stringly typed" when referring to arguments which can cause typos in code. This particular paper-cut is being actively worked on, and should be gone in v3.x.
+
+## Features
+
+Below are a few of the features which `clap` supports, full descriptions and usage can be found in the [documentation](https://docs.rs/clap/) and [examples/](examples) directory
+
+* **Auto-generated Help, Version, and Usage information**
+  - Can optionally be fully, or partially overridden if you want a custom help, version, or usage statements
+* **Auto-generated completion scripts at compile time (Bash, Zsh, Fish, and PowerShell)**
+  - Even works through many multiple levels of subcommands
+  - Works with options which only accept certain values
+  - Works with subcommand aliases
+* **Flags / Switches** (i.e. bool fields)
+  - Both short and long versions supported (i.e. `-f` and `--flag` respectively)
+  - Supports combining short versions (i.e. `-fBgoZ` is the same as `-f -B -g -o -Z`)
+  - Supports multiple occurrences (i.e. `-vvv` or `-v -v -v`)
+* **Positional Arguments** (i.e. those which are based off an index from the program name)
+  - Supports multiple values (i.e. `myprog <file>...` such as `myprog file1.txt file2.txt` being two values for the same "file" argument)
+  - Supports Specific Value Sets (See below)
+  - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
+  - Can set custom validations on values to extend the argument parsing capability to truly custom domains
+* **Option Arguments** (i.e. those that take values)
+  - Both short and long versions supported (i.e. `-o value`, `-ovalue`, `-o=value` and `--option value` or `--option=value` respectively)
+  - Supports multiple values (i.e. `-o <val1> -o <val2>` or `-o <val1> <val2>`)
+  - Supports delimited values (i.e. `-o=val1,val2,val3`, can also change the delimiter)
+  - Supports Specific Value Sets (See below)
+  - Supports named values so that the usage/help info appears as `-o <FILE> <INTERFACE>` etc. for when you require specific multiple values
+  - Can set value parameters (such as the minimum number of values, the maximum number of values, or the exact number of values)
+  - Can set custom validations on values to extend the argument parsing capability to truly custom domains
+* **Sub-Commands** (i.e. `git add <file>` where `add` is a sub-command of `git`)
+  - Support their own sub-arguments, and sub-sub-commands independent of the parent
+  - Get their own auto-generated Help, Version, and Usage independent of parent
+* **Support for building CLIs from YAML** - This keeps your Rust source nice and tidy and makes supporting localized translation very simple!
+* **Requirement Rules**: Arguments can define the following types of requirement rules
+  - Can be required by default
+  - Can be required only if certain arguments are present
+  - Can require other arguments to be present
+  - Can be required only if certain values of other arguments are used
+* **Confliction Rules**: Arguments can optionally define the following types of exclusion rules
+  - Can be disallowed when certain arguments are present
+  - Can disallow use of other arguments when present
+* **Groups**: Arguments can be made part of a group
+  - Fully compatible with other relational rules (requirements, conflicts, and overrides) which allows things like requiring the use of any arg in a group, or denying the use of an entire group conditionally
+* **Specific Value Sets**: Positional or Option Arguments can define a specific set of allowed values (i.e. imagine a `--mode` option which may *only* have one of two values `fast` or `slow` such as `--mode fast` or `--mode slow`)
+* **Default Values**
+  - Also supports conditional default values (i.e. a default which only applies if specific arguments are used, or specific values of those arguments)
+* **Automatic Version from Cargo.toml**: `clap` is fully compatible with Rust's `env!()` macro for automatically setting the version of your application to the version in your Cargo.toml. See [09_auto_version example](examples/09_auto_version.rs) for how to do this (Thanks to [jhelwig](https://github.com/jhelwig) for pointing this out)
+* **Typed Values**: You can use several convenience macros provided by `clap` to get typed values (i.e. `i32`, `u8`, etc.) from positional or option arguments so long as the type you request implements `std::str::FromStr` See the [12_typed_values example](examples/12_typed_values.rs). You can also use `clap`s `arg_enum!` macro to create an enum with variants that automatically implement `std::str::FromStr`. See [13a_enum_values_automatic example](examples/13a_enum_values_automatic.rs) for details
+* **Suggestions**: Suggests corrections when the user enters a typo. For example, if you defined a `--myoption` argument, and the user mistakenly typed `--moyption` (notice `y` and `o` transposed), they would receive a `Did you mean '--myoption'?` error and exit gracefully. This also works for subcommands and flags. (Thanks to [Byron](https://github.com/Byron) for the implementation) (This feature can optionally be disabled, see 'Optional Dependencies / Features')
+* **Colorized Errors (Non Windows OS only)**: Error message are printed in in colored text (this feature can optionally be disabled, see 'Optional Dependencies / Features').
+* **Global Arguments**: Arguments can optionally be defined once, and be available to all child subcommands. There values will also be propagated up/down throughout all subcommands.
+* **Custom Validations**: You can define a function to use as a validator of argument values. Imagine defining a function to validate IP addresses, or fail parsing upon error. This means your application logic can be solely focused on *using* values.
+* **POSIX Compatible Conflicts/Overrides** - In POSIX args can be conflicting, but not fail parsing because whichever arg comes *last* "wins" so to speak. This allows things such as aliases (i.e. `alias ls='ls -l'` but then using `ls -C` in your terminal which ends up passing `ls -l -C` as the final arguments. Since `-l` and `-C` aren't compatible, this effectively runs `ls -C` in `clap` if you choose...`clap` also supports hard conflicts that fail parsing). (Thanks to [Vinatorul](https://github.com/Vinatorul)!)
+* Supports the Unix `--` meaning, only positional arguments follow
+
+## Quick Example
+
+The following examples show a quick example of some of the very basic functionality of `clap`. For more advanced usage, such as requirements, conflicts, groups, multiple values and occurrences see the [documentation](https://docs.rs/clap/), [examples/](examples) directory of this repository or the [video tutorials](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U).
+
+ **NOTE:** All of these examples are functionally the same, but show different styles in which to use `clap`. These different styles are purely a matter of personal preference.
+
+The first example shows a method using the 'Builder Pattern' which allows more advanced configuration options (not shown in this small example), or even dynamically generating arguments when desired.
+
+```rust
+// (Full example with detailed comments in examples/01b_quick_example.rs)
+//
+// This example demonstrates clap's full 'builder pattern' style of creating arguments which is
+// more verbose, but allows easier editing, and at times more advanced options, or the possibility
+// to generate arguments dynamically.
+extern crate clap;
+use clap::{Arg, App, SubCommand};
+
+fn main() {
+    let matches = App::new("My Super Program")
+                          .version("1.0")
+                          .author("Kevin K. <kbknapp@gmail.com>")
+                          .about("Does awesome things")
+                          .arg(Arg::with_name("config")
+                               .short("c")
+                               .long("config")
+                               .value_name("FILE")
+                               .help("Sets a custom config file")
+                               .takes_value(true))
+                          .arg(Arg::with_name("INPUT")
+                               .help("Sets the input file to use")
+                               .required(true)
+                               .index(1))
+                          .arg(Arg::with_name("v")
+                               .short("v")
+                               .multiple(true)
+                               .help("Sets the level of verbosity"))
+                          .subcommand(SubCommand::with_name("test")
+                                      .about("controls testing features")
+                                      .version("1.3")
+                                      .author("Someone E. <someone_else@other.com>")
+                                      .arg(Arg::with_name("debug")
+                                          .short("d")
+                                          .help("print debug information verbosely")))
+                          .get_matches();
+
+    // Gets a value for config if supplied by user, or defaults to "default.conf"
+    let config = matches.value_of("config").unwrap_or("default.conf");
+    println!("Value for config: {}", config);
+
+    // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
+    // required we could have used an 'if let' to conditionally get the value)
+    println!("Using input file: {}", matches.value_of("INPUT").unwrap());
+
+    // Vary the output based on how many times the user used the "verbose" flag
+    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
+    match matches.occurrences_of("v") {
+        0 => println!("No verbose info"),
+        1 => println!("Some verbose info"),
+        2 => println!("Tons of verbose info"),
+        3 | _ => println!("Don't be crazy"),
+    }
+
+    // You can handle information about subcommands by requesting their matches by name
+    // (as below), requesting just the name used, or both at the same time
+    if let Some(matches) = matches.subcommand_matches("test") {
+        if matches.is_present("debug") {
+            println!("Printing debug info...");
+        } else {
+            println!("Printing normally...");
+        }
+    }
+
+    // more program logic goes here...
+}
+```
+
+One could also optionally declare their CLI in YAML format and keep your Rust source tidy
+or support multiple localized translations by having different YAML files for each localization.
+
+First, create the `cli.yml` file to hold your CLI options, but it could be called anything we like:
+
+```yaml
+name: myapp
+version: "1.0"
+author: Kevin K. <kbknapp@gmail.com>
+about: Does awesome things
+args:
+    - config:
+        short: c
+        long: config
+        value_name: FILE
+        help: Sets a custom config file
+        takes_value: true
+    - INPUT:
+        help: Sets the input file to use
+        required: true
+        index: 1
+    - verbose:
+        short: v
+        multiple: true
+        help: Sets the level of verbosity
+subcommands:
+    - test:
+        about: controls testing features
+        version: "1.3"
+        author: Someone E. <someone_else@other.com>
+        args:
+            - debug:
+                short: d
+                help: print debug information
+```
+
+Since this feature requires additional dependencies that not everyone may want, it is *not* compiled in by default and we need to enable a feature flag in Cargo.toml:
+
+Simply change your `clap = "2.34"` to `clap = {version = "2.34", features = ["yaml"]}`.
+
+Finally we create our `main.rs` file just like we would have with the previous two examples:
+
+```rust
+// (Full example with detailed comments in examples/17_yaml.rs)
+//
+// This example demonstrates clap's building from YAML style of creating arguments which is far
+// more clean, but takes a very small performance hit compared to the other two methods.
+#[macro_use]
+extern crate clap;
+use clap::App;
+
+fn main() {
+    // The YAML file is found relative to the current file, similar to how modules are found
+    let yaml = load_yaml!("cli.yml");
+    let matches = App::from_yaml(yaml).get_matches();
+
+    // Same as previous examples...
+}
+```
+
+If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or `help` subcommand, since we defined `test` as a subcommand) the following would be output
+
+```sh
+$ myprog --help
+My Super Program 1.0
+Kevin K. <kbknapp@gmail.com>
+Does awesome things
+
+USAGE:
+    MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
+
+FLAGS:
+    -h, --help       Prints help information
+    -v               Sets the level of verbosity
+    -V, --version    Prints version information
+
+OPTIONS:
+    -c, --config <FILE>    Sets a custom config file
+
+ARGS:
+    INPUT    The input file to use
+
+SUBCOMMANDS:
+    help    Prints this message or the help of the given subcommand(s)
+    test    Controls testing features
+```
+
+**NOTE:** You could also run `myapp test --help` or `myapp help test` to see the help message for the `test` subcommand.
+
+There are also two other methods to create CLIs. Which style you choose is largely a matter of personal preference. The two other methods are:
+
+* Using [usage strings (examples/01a_quick_example.rs)](examples/01a_quick_example.rs) similar to (but not exact) docopt style usage statements. This is far less verbose than the above methods, but incurs a slight runtime penalty.
+* Using [a macro (examples/01c_quick_example.rs)](examples/01c_quick_example.rs) which is like a hybrid of the builder and usage string style. It's less verbose, but doesn't incur the runtime penalty of the usage string style. The downside is that it's harder to debug, and more opaque.
+
+Examples of each method can be found in the [examples/](examples) directory of this repository.
+
+## Try it!
+
+### Pre-Built Test
+
+To try out the pre-built examples, use the following steps:
+
+* Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/`
+* Compile the example `$ cargo build --example <EXAMPLE>`
+* Run the help info `$ ./target/debug/examples/<EXAMPLE> --help`
+* Play with the arguments!
+* You can also do a onetime run via `$ cargo run --example <EXAMPLE> -- [args to example]`
+
+### BYOB (Build Your Own Binary)
+
+To test out `clap`'s default auto-generated help/version follow these steps:
+* Create a new cargo project `$ cargo new fake --bin && cd fake`
+* Add `clap` to your `Cargo.toml`
+
+```toml
+[dependencies]
+clap = "2"
+```
+
+* Add the following to your `src/main.rs`
+
+```rust
+extern crate clap;
+use clap::App;
+
+fn main() {
+  App::new("fake").version("v1.0-beta").get_matches();
+}
+```
+
+* Build your program `$ cargo build --release`
+* Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake --version`
+
+## Usage
+
+For full usage, add `clap` as a dependency in your `Cargo.toml` () to use from crates.io:
+
+```toml
+[dependencies]
+clap = "~2.34"
+```
+
+(**note**: If you are concerned with supporting a minimum version of Rust that is *older* than the current stable Rust minus 2 stable releases, it's recommended to use the `~major.minor.patch` style versions in your `Cargo.toml` which will only update the patch version automatically. For more information see the [Compatibility Policy](#compatibility-policy))
+
+Then add `extern crate clap;` to your crate root.
+
+Define a list of valid arguments for your program (see the [documentation](https://docs.rs/clap/) or [examples/](examples) directory of this repo)
+
+Then run `cargo build` or `cargo update && cargo build` for your project.
+
+### Optional Dependencies / Features
+
+#### Features enabled by default
+
+* **"suggestions"**: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`)
+* **"color"**: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` only on non-Windows targets)
+* **"vec_map"**: Use [`VecMap`](https://crates.io/crates/vec_map) internally instead of a [`BTreeMap`](https://doc.rust-lang.org/stable/std/collections/struct.BTreeMap.html). This feature provides a _slight_ performance improvement. (builds dependency `vec_map`)
+
+To disable these, add this to your `Cargo.toml`:
+
+```toml
+[dependencies.clap]
+version = "2.34"
+default-features = false
+```
+
+You can also selectively enable only the features you'd like to include, by adding:
+
+```toml
+[dependencies.clap]
+version = "2.34"
+default-features = false
+
+# Cherry-pick the features you'd like to use
+features = [ "suggestions", "color" ]
+```
+
+#### Opt-in features
+
+* **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`)
+* **"unstable"**: Enables unstable `clap` features that may change from release to release
+* **"wrap_help"**: Turns on the help text wrapping feature, based on the terminal size. (builds dependency `term-size`)
+
+### Dependencies Tree
+
+The following graphic depicts `clap`s dependency graph (generated using [cargo-graph](https://github.com/kbknapp/cargo-graph)).
+
+ * **Dashed** Line: Optional dependency
+ * **Red** Color: **NOT** included by default (must use cargo `features` to enable)
+ * **Blue** Color: Dev dependency, only used while developing.
+
+![clap dependencies](clap_dep_graph.png)
+
+### More Information
+
+You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project.
+
+You can also find usage examples in the [examples/](examples) directory of this repo.
+
+#### Video Tutorials
+
+There's also the video tutorial series [Argument Parsing with Rust v2](https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U).
+
+These videos slowly trickle out as I finish them and currently a work in progress.
+
+## How to Contribute
+
+Details on how to contribute can be found in the [CONTRIBUTING.md](.github/CONTRIBUTING.md) file.
+
+### Compatibility Policy
+
+Because `clap` takes SemVer and compatibility seriously, this is the official policy regarding breaking changes and minimum required versions of Rust.
+
+`clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version of `clap` will be bumped.
+
+In order to keep from being surprised of breaking changes, it is **highly** recommended to use the `~major.minor.patch` style in your `Cargo.toml` only if you wish to target a version of Rust that is *older* than current stable minus two releases:
+
+```toml
+[dependencies]
+clap = "~2.34"
+```
+
+This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore cannot break due to new features, or bumped minimum versions of Rust.
+
+#### Warning about '~' Dependencies
+
+Using `~` can cause issues in certain circumstances.
+
+From @alexcrichton:
+
+Right now Cargo's version resolution is pretty naive, it's just a brute-force search of the solution space, returning the first resolvable graph. This also means that it currently won't terminate until it proves there is not possible resolvable graph. This leads to situations where workspaces with multiple binaries, for example, have two different dependencies such as:
+
+```toml,no_sync
+
+# In one Cargo.toml
+[dependencies]
+clap = "~2.34.0"
+
+# In another Cargo.toml
+[dependencies]
+clap = "2.34.0"
+```
+
+This is inherently an unresolvable crate graph in Cargo right now. Cargo requires there's only one major version of a crate, and being in the same workspace these two crates must share a version. This is impossible in this location, though, as these version constraints cannot be met.
+
+#### Minimum Version of Rust
+
+`clap` will officially support current stable Rust, minus two releases, but may work with prior releases as well. For example, current stable Rust at the time of this writing is 1.41.0, meaning `clap` is guaranteed to compile with 1.39.0 and beyond.
+
+At the 1.42.0 stable release, `clap` will be guaranteed to compile with 1.40.0 and beyond, etc.
+
+Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be clearly annotated in the `CHANGELOG.md`
+
+#### Breaking Changes
+
+`clap` takes a similar policy to Rust and will bump the major version number upon breaking changes with only the following exceptions:
+
+ * The breaking change is to fix a security concern
+ * The breaking change is to be fixing a bug (i.e. relying on a bug as a feature)
+ * The breaking change is a feature isn't used in the wild, or all users of said feature have given approval *prior* to the change
+
+#### Compatibility with Wasm
+
+A best effort is made to ensure that `clap` will work on projects targeting `wasm32-unknown-unknown`. However there is no dedicated CI build
+covering this specific target.
+
+## License
+
+`clap` is licensed under the MIT license. Please read the [LICENSE-MIT](LICENSE-MIT) file in this repository for more information.
+
+## Related Crates
+
+There are several excellent crates which can be used with `clap`, I recommend checking them all out! If you've got a crate that would be a good fit to be used with `clap` open an issue and let me know, I'd love to add it!
+
+* [`structopt`](https://github.com/TeXitoi/structopt) - This crate allows you to define a struct, and build a CLI from it! No more "stringly typed" and it uses `clap` behind the scenes! (*Note*: There is work underway to pull this crate into mainline `clap`).
+* [`assert_cli`](https://github.com/assert-rs/assert_cli) - This crate allows you test your CLIs in a very intuitive and functional way!
+
+## Recent Breaking Changes
+
+`clap` follows semantic versioning, so breaking changes should only happen upon major version bumps. The only exception to this rule is breaking changes that happen due to implementation that was deemed to be a bug, security concerns, or it can be reasonably proved to affect no code. For the full details, see [CHANGELOG.md](./CHANGELOG.md).
+
+As of 2.27.0:
+
+* Argument values now take precedence over subcommand names. This only arises by using unrestrained multiple values and subcommands together where the subcommand name can coincide with one of the multiple values. Such as `$ prog <files>... <subcommand>`. The fix is to place restraints on number of values, or disallow the use of `$ prog <prog-args> <subcommand>` structure.
+
+As of 2.0.0 (From 1.x)
+
+* **Fewer lifetimes! Yay!**
+ * `App<'a, 'b, 'c, 'd, 'e, 'f>` => `App<'a, 'b>`
+ * `Arg<'a, 'b, 'c, 'd, 'e, 'f>` => `Arg<'a, 'b>`
+ * `ArgMatches<'a, 'b>` => `ArgMatches<'a>`
+* **Simply Renamed**
+ * `App::arg_group` => `App::group`
+ * `App::arg_groups` => `App::groups`
+ * `ArgGroup::add` => `ArgGroup::arg`
+ * `ArgGroup::add_all` => `ArgGroup::args`
+ * `ClapError` => `Error`
+  * struct field `ClapError::error_type` => `Error::kind`
+ * `ClapResult` => `Result`
+ * `ClapErrorType` => `ErrorKind`
+* **Removed Deprecated Functions and Methods**
+ * `App::subcommands_negate_reqs`
+ * `App::subcommand_required`
+ * `App::arg_required_else_help`
+ * `App::global_version(bool)`
+ * `App::versionless_subcommands`
+ * `App::unified_help_messages`
+ * `App::wait_on_error`
+ * `App::subcommand_required_else_help`
+ * `SubCommand::new`
+ * `App::error_on_no_subcommand`
+ * `Arg::new`
+ * `Arg::mutually_excludes`
+ * `Arg::mutually_excludes_all`
+ * `Arg::mutually_overrides_with`
+ * `simple_enum!`
+* **Renamed Error Variants**
+ * `InvalidUnicode` => `InvalidUtf8`
+ * `InvalidArgument` => `UnknownArgument`
+* **Usage Parser**
+ * Value names can now be specified inline, i.e. `-o, --option <FILE> <FILE2> 'some option which takes two files'`
+ * **There is now a priority of order to determine the name** - This is perhaps the biggest breaking change. See the documentation for full details. Prior to this change, the value name took precedence. **Ensure your args are using the proper names (i.e. typically the long or short and NOT the value name) throughout the code**
+* `ArgMatches::values_of` returns an `Values` now which implements `Iterator` (should not break any code)
+* `crate_version!` returns `&'static str` instead of `String`
+
+### Deprecations
+
+Old method names will be left around for several minor version bumps, or one major version bump.
+
+As of 2.27.0:
+
+* **AppSettings::PropagateGlobalValuesDown:**  this setting deprecated and is no longer required to propagate values down or up
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/SPONSORS.md
@@ -0,0 +1,17 @@
+Below is a list of sponsors for the clap-rs project
+
+If you are interested in becoming a sponsor for this project please our [sponsorship page](https://clap.rs/sponsorship/).
+
+## Recurring Sponsors:
+
+| [<img alt="Noelia Seva-Gonzalez" src="https://clap.rs/wp-content/uploads/2017/10/noelia_sm-1.png" width="117">](https://noeliasg.com/about/)  | [<img alt="messense" src="https://clap.rs/wp-content/uploads/2018/01/messense-400x400.png" width="117">](https://github.com/messense)  | [<img alt="Josh" src="https://clap.rs/wp-content/uploads/2018/11/josh_t.jpg" width="117">](https://joshtriplett.org)  | <img alt="Stephen Oats" src="https://clap.rs/wp-content/uploads/2019/03/stephenoats.png" width="117"> |
+|:-:|:-:|:-:|:-:|
+|Noelia Seva-Gonzalez | Messense | Josh Triplett | Stephen Oats |
+
+
+## Single-Donation and Former Sponsors:
+
+| [<img alt="Rob Tsuk" src="https://clap.rs/wp-content/uploads/2017/10/robtsuk_sm.png" width="117">](https://github.com/rtsuk)| | |
+|:-:|:-:|:-:|
+|Rob Tsuk| | |
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/clap-test.rs
@@ -0,0 +1,86 @@
+#[allow(unused_imports, dead_code)]
+mod test {
+    use std::str;
+    use std::io::{Cursor, Write};
+
+    use regex::Regex;
+
+    use clap::{App, Arg, SubCommand, ArgGroup};
+
+    fn compare<S, S2>(l: S, r: S2) -> bool
+        where S: AsRef<str>,
+              S2: AsRef<str>
+    {
+        let re = Regex::new("\x1b[^m]*m").unwrap();
+        // Strip out any mismatching \r character on windows that might sneak in on either side
+        let ls = l.as_ref().trim().replace("\r", "");
+        let rs = r.as_ref().trim().replace("\r", "");
+        let left = re.replace_all(&*ls, "");
+        let right = re.replace_all(&*rs, "");
+        let b = left == right;
+        if !b {
+            println!();
+            println!("--> left");
+            println!("{}", left);
+            println!("--> right");
+            println!("{}", right);
+            println!("--")
+        }
+        b
+    }
+
+    pub fn compare_output(l: App, args: &str, right: &str, stderr: bool) -> bool {
+        let mut buf = Cursor::new(Vec::with_capacity(50));
+        let res = l.get_matches_from_safe(args.split(' ').collect::<Vec<_>>());
+        let err = res.unwrap_err();
+        err.write_to(&mut buf).unwrap();
+        let content = buf.into_inner();
+        let left = String::from_utf8(content).unwrap();
+        assert_eq!(stderr, err.use_stderr());
+        compare(left, right)
+    }
+    pub fn compare_output2(l: App, args: &str, right1: &str, right2: &str, stderr: bool) -> bool {
+        let mut buf = Cursor::new(Vec::with_capacity(50));
+        let res = l.get_matches_from_safe(args.split(' ').collect::<Vec<_>>());
+        let err = res.unwrap_err();
+        err.write_to(&mut buf).unwrap();
+        let content = buf.into_inner();
+        let left = String::from_utf8(content).unwrap();
+        assert_eq!(stderr, err.use_stderr());
+        compare(&*left, right1) || compare(&*left, right2)
+    }
+
+    // Legacy tests from the Python script days
+
+    pub fn complex_app() -> App<'static, 'static> {
+        let args = "-o --option=[opt]... 'tests options'
+                    [positional] 'tests positionals'";
+        let opt3_vals = ["fast", "slow"];
+        let pos3_vals = ["vi", "emacs"];
+        App::new("clap-test")
+            .version("v1.4.8")
+            .about("tests clap library")
+            .author("Kevin K. <kbknapp@gmail.com>")
+            .args_from_usage(args)
+            .arg(Arg::from_usage("-f --flag... 'tests flags'")
+                .global(true))
+            .args(&[
+                Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("long-option-2"),
+                Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"),
+                Arg::from_usage("[positional2] 'tests positionals with exclusions'"),
+                Arg::from_usage("-O --Option [option3] 'specific vals'").possible_values(&opt3_vals),
+                Arg::from_usage("[positional3]... 'tests specific values'").possible_values(&pos3_vals),
+                Arg::from_usage("--multvals [one] [two] 'Tests multiple values, not mult occs'"),
+                Arg::from_usage("--multvalsmo... [one] [two] 'Tests multiple values, and mult occs'"),
+                Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2),
+                Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3)
+            ])
+            .subcommand(SubCommand::with_name("subcmd")
+                                    .about("tests subcommands")
+                                    .version("0.1")
+                                    .author("Kevin K. <kbknapp@gmail.com>")
+                                    .arg_from_usage("-o --option [scoption]... 'tests options'")
+                                    .arg_from_usage("-s --subcmdarg [subcmdarg] 'tests other args'")
+                                    .arg_from_usage("[scpositional] 'tests positionals'"))
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/justfile
@@ -0,0 +1,39 @@
+@update-contributors:
+	echo 'Removing old CONTRIBUTORS.md'
+	mv CONTRIBUTORS.md CONTRIBUTORS.md.bak
+	echo 'Downloading a list of new contributors'
+	echo "the following is a list of contributors:" > CONTRIBUTORS.md
+	echo "" >> CONTRIBUTORS.md
+	echo "" >> CONTRIBUTORS.md
+	githubcontrib --owner clap-rs --repo clap --sha master --cols 6 --format md --showlogin true --sortBy contributions --sortOrder desc >> CONTRIBUTORS.md
+	echo "" >> CONTRIBUTORS.md
+	echo "" >> CONTRIBUTORS.md
+	echo "This list was generated by [mgechev/github-contributors-list](https://github.com/mgechev/github-contributors-list)" >> CONTRIBUTORS.md
+	rm CONTRIBUTORS.md.bak
+
+run-test TEST:
+	cargo test --test {{TEST}}
+
+debug TEST:
+	cargo test --test {{TEST}} --features debug
+
+run-tests:
+	cargo test --features "yaml unstable"
+
+@bench: nightly
+	cargo bench && just remove-nightly
+
+nightly:
+	rustup override add nightly
+
+remove-nightly:
+	rustup override remove
+
+@lint: nightly
+	cargo build --features lints && just remove-nightly
+
+clean:
+	cargo clean
+	find . -type f -name "*.orig" -exec rm {} \;
+	find . -type f -name "*.bk" -exec rm {} \;
+	find . -type f -name ".*~" -exec rm {} \;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/help.rs
@@ -0,0 +1,1032 @@
+// Std
+use std::{
+    borrow::Cow,
+    cmp,
+    collections::BTreeMap,
+    fmt::Display,
+    io::{self, Cursor, Read, Write},
+    usize,
+};
+
+// Third Party
+#[cfg(feature = "wrap_help")]
+use term_size;
+#[cfg(feature = "wrap_help")]
+use textwrap;
+use unicode_width::UnicodeWidthStr;
+
+// Internal
+use crate::{
+    app::{parser::Parser, usage, App, AppSettings},
+    args::{AnyArg, ArgSettings, DispOrder},
+    errors::{Error, Result as ClapResult},
+    fmt::{Colorizer, ColorizerOption, Format},
+    map::VecMap,
+    INTERNAL_ERROR_MSG,
+};
+
+#[cfg(not(feature = "wrap_help"))]
+mod term_size {
+    pub fn dimensions() -> Option<(usize, usize)> {
+        None
+    }
+}
+
+fn str_width(s: &str) -> usize {
+    UnicodeWidthStr::width(s)
+}
+
+const TAB: &str = "    ";
+
+// These are just convenient traits to make the code easier to read.
+trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {}
+impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T where T: AnyArg<'b, 'c> + Display {}
+
+trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder {
+    fn as_base(&self) -> &ArgWithDisplay<'b, 'c>;
+}
+impl<'b, 'c, T> ArgWithOrder<'b, 'c> for T
+where
+    T: ArgWithDisplay<'b, 'c> + DispOrder,
+{
+    fn as_base(&self) -> &ArgWithDisplay<'b, 'c> {
+        self
+    }
+}
+
+fn as_arg_trait<'a, 'b, T: ArgWithOrder<'a, 'b>>(x: &T) -> &ArgWithOrder<'a, 'b> {
+    x
+}
+
+impl<'b, 'c> DispOrder for App<'b, 'c> {
+    fn disp_ord(&self) -> usize {
+        999
+    }
+}
+
+macro_rules! color {
+    ($_self:ident, $s:expr, $c:ident) => {
+        if $_self.color {
+            write!($_self.writer, "{}", $_self.cizer.$c($s))
+        } else {
+            write!($_self.writer, "{}", $s)
+        }
+    };
+    ($_self:ident, $fmt_s:expr, $v:expr, $c:ident) => {
+        if $_self.color {
+            write!($_self.writer, "{}", $_self.cizer.$c(format!($fmt_s, $v)))
+        } else {
+            write!($_self.writer, $fmt_s, $v)
+        }
+    };
+}
+
+/// `clap` Help Writer.
+///
+/// Wraps a writer stream providing different methods to generate help for `clap` objects.
+pub struct Help<'a> {
+    writer: &'a mut Write,
+    next_line_help: bool,
+    hide_pv: bool,
+    term_w: usize,
+    color: bool,
+    cizer: Colorizer,
+    longest: usize,
+    force_next_line: bool,
+    use_long: bool,
+}
+
+// Public Functions
+impl<'a> Help<'a> {
+    /// Create a new `Help` instance.
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::too_many_arguments))]
+    pub fn new(
+        w: &'a mut Write,
+        next_line_help: bool,
+        hide_pv: bool,
+        color: bool,
+        cizer: Colorizer,
+        term_w: Option<usize>,
+        max_w: Option<usize>,
+        use_long: bool,
+    ) -> Self {
+        debugln!("Help::new;");
+        Help {
+            writer: w,
+            next_line_help,
+            hide_pv,
+            term_w: match term_w {
+                Some(width) => {
+                    if width == 0 {
+                        usize::MAX
+                    } else {
+                        width
+                    }
+                }
+                None => cmp::min(
+                    term_size::dimensions().map_or(120, |(w, _)| w),
+                    match max_w {
+                        None | Some(0) => usize::MAX,
+                        Some(mw) => mw,
+                    },
+                ),
+            },
+            color,
+            cizer,
+            longest: 0,
+            force_next_line: false,
+            use_long,
+        }
+    }
+
+    /// Reads help settings from an App
+    /// and write its help to the wrapped stream.
+    pub fn write_app_help(w: &'a mut Write, app: &App, use_long: bool) -> ClapResult<()> {
+        debugln!("Help::write_app_help;");
+        Self::write_parser_help(w, &app.p, use_long)
+    }
+
+    /// Reads help settings from a Parser
+    /// and write its help to the wrapped stream.
+    pub fn write_parser_help(w: &'a mut Write, parser: &Parser, use_long: bool) -> ClapResult<()> {
+        debugln!("Help::write_parser_help;");
+        Self::_write_parser_help(w, parser, false, use_long)
+    }
+
+    /// Reads help settings from a Parser
+    /// and write its help to the wrapped stream which will be stderr. This method prevents
+    /// formatting when required.
+    pub fn write_parser_help_to_stderr(w: &'a mut Write, parser: &Parser) -> ClapResult<()> {
+        debugln!("Help::write_parser_help;");
+        Self::_write_parser_help(w, parser, true, false)
+    }
+
+    #[doc(hidden)]
+    pub fn _write_parser_help(
+        w: &'a mut Write,
+        parser: &Parser,
+        stderr: bool,
+        use_long: bool,
+    ) -> ClapResult<()> {
+        debugln!("Help::write_parser_help;");
+        let nlh = parser.is_set(AppSettings::NextLineHelp);
+        let hide_v = parser.is_set(AppSettings::HidePossibleValuesInHelp);
+        let color = parser.is_set(AppSettings::ColoredHelp);
+        let cizer = Colorizer::new(ColorizerOption {
+            use_stderr: stderr,
+            when: parser.color(),
+        });
+        Self::new(
+            w,
+            nlh,
+            hide_v,
+            color,
+            cizer,
+            parser.meta.term_w,
+            parser.meta.max_w,
+            use_long,
+        )
+        .write_help(parser)
+    }
+
+    /// Writes the parser help to the wrapped stream.
+    pub fn write_help(&mut self, parser: &Parser) -> ClapResult<()> {
+        debugln!("Help::write_help;");
+        if let Some(h) = parser.meta.help_str {
+            write!(self.writer, "{}", h).map_err(Error::from)?;
+        } else if let Some(tmpl) = parser.meta.template {
+            self.write_templated_help(parser, tmpl)?;
+        } else {
+            self.write_default_help(parser)?;
+        }
+        Ok(())
+    }
+}
+
+// Methods to write AnyArg help.
+impl<'a> Help<'a> {
+    /// Writes help for each argument in the order they were declared to the wrapped stream.
+    fn write_args_unsorted<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()>
+    where
+        I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>,
+    {
+        debugln!("Help::write_args_unsorted;");
+        // The shortest an arg can legally be is 2 (i.e. '-x')
+        self.longest = 2;
+        let mut arg_v = Vec::with_capacity(10);
+        let use_long = self.use_long;
+        for arg in args.filter(|arg| should_show_arg(use_long, *arg)) {
+            if arg.longest_filter() {
+                self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str()));
+            }
+            arg_v.push(arg)
+        }
+        let mut first = true;
+        for arg in arg_v {
+            if first {
+                first = false;
+            } else {
+                self.writer.write_all(b"\n")?;
+            }
+            self.write_arg(arg.as_base())?;
+        }
+        Ok(())
+    }
+
+    /// Sorts arguments by length and display order and write their help to the wrapped stream.
+    fn write_args<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()>
+    where
+        I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>,
+    {
+        debugln!("Help::write_args;");
+        // The shortest an arg can legally be is 2 (i.e. '-x')
+        self.longest = 2;
+        let mut ord_m = VecMap::new();
+        let use_long = self.use_long;
+        // Determine the longest
+        for arg in args.filter(|arg| {
+            // If it's NextLineHelp, but we don't care to compute how long because it may be
+            // NextLineHelp on purpose *because* it's so long and would throw off all other
+            // args alignment
+            should_show_arg(use_long, *arg)
+        }) {
+            if arg.longest_filter() {
+                debugln!("Help::write_args: Current Longest...{}", self.longest);
+                self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str()));
+                debugln!("Help::write_args: New Longest...{}", self.longest);
+            }
+            let btm = ord_m.entry(arg.disp_ord()).or_insert(BTreeMap::new());
+            btm.insert(arg.name(), arg);
+        }
+        let mut first = true;
+        for btm in ord_m.values() {
+            for arg in btm.values() {
+                if first {
+                    first = false;
+                } else {
+                    self.writer.write_all(b"\n")?;
+                }
+                self.write_arg(arg.as_base())?;
+            }
+        }
+        Ok(())
+    }
+
+    /// Writes help for an argument to the wrapped stream.
+    fn write_arg<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
+        debugln!("Help::write_arg;");
+        self.short(arg)?;
+        self.long(arg)?;
+        let spec_vals = self.val(arg)?;
+        self.help(arg, &*spec_vals)?;
+        Ok(())
+    }
+
+    /// Writes argument's short command to the wrapped stream.
+    fn short<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
+        debugln!("Help::short;");
+        write!(self.writer, "{}", TAB)?;
+        if let Some(s) = arg.short() {
+            color!(self, "-{}", s, good)
+        } else if arg.has_switch() {
+            write!(self.writer, "{}", TAB)
+        } else {
+            Ok(())
+        }
+    }
+
+    /// Writes argument's long command to the wrapped stream.
+    fn long<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> {
+        debugln!("Help::long;");
+        if !arg.has_switch() {
+            return Ok(());
+        }
+        if arg.takes_value() {
+            if let Some(l) = arg.long() {
+                if arg.short().is_some() {
+                    write!(self.writer, ", ")?;
+                }
+                color!(self, "--{}", l, good)?
+            }
+
+            let sep = if arg.is_set(ArgSettings::RequireEquals) {
+                "="
+            } else {
+                " "
+            };
+            write!(self.writer, "{}", sep)?;
+        } else if let Some(l) = arg.long() {
+            if arg.short().is_some() {
+                write!(self.writer, ", ")?;
+            }
+            color!(self, "--{}", l, good)?;
+        }
+        Ok(())
+    }
+
+    /// Writes argument's possible values to the wrapped stream.
+    fn val<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> Result<String, io::Error> {
+        debugln!("Help::val: arg={}", arg);
+        if arg.takes_value() {
+            let delim = if arg.is_set(ArgSettings::RequireDelimiter) {
+                arg.val_delim().expect(INTERNAL_ERROR_MSG)
+            } else {
+                ' '
+            };
+            if let Some(vec) = arg.val_names() {
+                let mut it = vec.iter().peekable();
+                while let Some((_, val)) = it.next() {
+                    color!(self, "<{}>", val, good)?;
+                    if it.peek().is_some() {
+                        write!(self.writer, "{}", delim)?;
+                    }
+                }
+                let num = vec.len();
+                if arg.is_set(ArgSettings::Multiple) && num == 1 {
+                    color!(self, "...", good)?;
+                }
+            } else if let Some(num) = arg.num_vals() {
+                let mut it = (0..num).peekable();
+                while let Some(_) = it.next() {
+                    color!(self, "<{}>", arg.name(), good)?;
+                    if it.peek().is_some() {
+                        write!(self.writer, "{}", delim)?;
+                    }
+                }
+                if arg.is_set(ArgSettings::Multiple) && num == 1 {
+                    color!(self, "...", good)?;
+                }
+            } else if arg.has_switch() {
+                color!(self, "<{}>", arg.name(), good)?;
+                if arg.is_set(ArgSettings::Multiple) {
+                    color!(self, "...", good)?;
+                }
+            } else {
+                color!(self, "{}", arg, good)?;
+            }
+        }
+
+        let spec_vals = self.spec_vals(arg);
+        let h = arg.help().unwrap_or("");
+        let h_w = str_width(h) + str_width(&*spec_vals);
+        let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp);
+        let taken = self.longest + 12;
+        self.force_next_line = !nlh
+            && self.term_w >= taken
+            && (taken as f32 / self.term_w as f32) > 0.40
+            && h_w > (self.term_w - taken);
+
+        debug!("Help::val: Has switch...");
+        if arg.has_switch() {
+            sdebugln!("Yes");
+            debugln!("Help::val: force_next_line...{:?}", self.force_next_line);
+            debugln!("Help::val: nlh...{:?}", nlh);
+            debugln!("Help::val: taken...{}", taken);
+            debugln!(
+                "Help::val: help_width > (width - taken)...{} > ({} - {})",
+                h_w,
+                self.term_w,
+                taken
+            );
+            debugln!("Help::val: longest...{}", self.longest);
+            debug!("Help::val: next_line...");
+            if !(nlh || self.force_next_line) {
+                sdebugln!("No");
+                let self_len = str_width(arg.to_string().as_str());
+                // subtract ourself
+                let mut spcs = self.longest - self_len;
+                // Since we're writing spaces from the tab point we first need to know if we
+                // had a long and short, or just short
+                if arg.long().is_some() {
+                    // Only account 4 after the val
+                    spcs += 4;
+                } else {
+                    // Only account for ', --' + 4 after the val
+                    spcs += 8;
+                }
+
+                write_nspaces!(self.writer, spcs);
+            } else {
+                sdebugln!("Yes");
+            }
+        } else if !(nlh || self.force_next_line) {
+            sdebugln!("No, and not next_line");
+            write_nspaces!(
+                self.writer,
+                self.longest + 4 - (str_width(arg.to_string().as_str()))
+            );
+        } else {
+            sdebugln!("No");
+        }
+        Ok(spec_vals)
+    }
+
+    fn write_before_after_help(&mut self, h: &str) -> io::Result<()> {
+        debugln!("Help::write_before_after_help;");
+        let mut help = String::from(h);
+        // determine if our help fits or needs to wrap
+        debugln!(
+            "Help::write_before_after_help: Term width...{}",
+            self.term_w
+        );
+        let too_long = str_width(h) >= self.term_w;
+
+        debug!("Help::write_before_after_help: Too long...");
+        if too_long || h.contains("{n}") {
+            sdebugln!("Yes");
+            debugln!("Help::write_before_after_help: help: {}", help);
+            debugln!(
+                "Help::write_before_after_help: help width: {}",
+                str_width(&*help)
+            );
+            // Determine how many newlines we need to insert
+            debugln!(
+                "Help::write_before_after_help: Usable space: {}",
+                self.term_w
+            );
+            help = wrap_help(&help.replace("{n}", "\n"), self.term_w);
+        } else {
+            sdebugln!("No");
+        }
+        write!(self.writer, "{}", help)?;
+        Ok(())
+    }
+
+    /// Writes argument's help to the wrapped stream.
+    fn help<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>, spec_vals: &str) -> io::Result<()> {
+        debugln!("Help::help;");
+        let h = if self.use_long && arg.name() != "" {
+            arg.long_help().unwrap_or_else(|| arg.help().unwrap_or(""))
+        } else {
+            arg.help().unwrap_or_else(|| arg.long_help().unwrap_or(""))
+        };
+        let mut help = String::from(h) + spec_vals;
+        let nlh = self.next_line_help
+            || arg.is_set(ArgSettings::NextLineHelp)
+            || (self.use_long && arg.name() != "");
+        debugln!("Help::help: Next Line...{:?}", nlh);
+
+        let spcs = if nlh || self.force_next_line {
+            12 // "tab" * 3
+        } else {
+            self.longest + 12
+        };
+
+        let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w;
+
+        // Is help on next line, if so then indent
+        if nlh || self.force_next_line {
+            write!(self.writer, "\n{}{}{}", TAB, TAB, TAB)?;
+        }
+
+        debug!("Help::help: Too long...");
+        if too_long && spcs <= self.term_w || h.contains("{n}") {
+            sdebugln!("Yes");
+            debugln!("Help::help: help...{}", help);
+            debugln!("Help::help: help width...{}", str_width(&*help));
+            // Determine how many newlines we need to insert
+            let avail_chars = self.term_w - spcs;
+            debugln!("Help::help: Usable space...{}", avail_chars);
+            help = wrap_help(&help.replace("{n}", "\n"), avail_chars);
+        } else {
+            sdebugln!("No");
+        }
+        if let Some(part) = help.lines().next() {
+            write!(self.writer, "{}", part)?;
+        }
+        for part in help.lines().skip(1) {
+            writeln!(self.writer)?;
+            if nlh || self.force_next_line {
+                write!(self.writer, "{}{}{}", TAB, TAB, TAB)?;
+            } else if arg.has_switch() {
+                write_nspaces!(self.writer, self.longest + 12);
+            } else {
+                write_nspaces!(self.writer, self.longest + 8);
+            }
+            write!(self.writer, "{}", part)?;
+        }
+        if !help.contains('\n') && (nlh || self.force_next_line) {
+            writeln!(self.writer)?;
+        }
+        Ok(())
+    }
+
+    fn spec_vals(&self, a: &ArgWithDisplay) -> String {
+        debugln!("Help::spec_vals: a={}", a);
+        let mut spec_vals = vec![];
+        if let Some(ref env) = a.env() {
+            debugln!(
+                "Help::spec_vals: Found environment variable...[{:?}:{:?}]",
+                env.0,
+                env.1
+            );
+            let env_val = if !a.is_set(ArgSettings::HideEnvValues) {
+                format!(
+                    "={}",
+                    env.1.map_or(Cow::Borrowed(""), |val| val.to_string_lossy())
+                )
+            } else {
+                String::new()
+            };
+            let env_info = format!(" [env: {}{}]", env.0.to_string_lossy(), env_val);
+            spec_vals.push(env_info);
+        }
+        if !a.is_set(ArgSettings::HideDefaultValue) {
+            if let Some(pv) = a.default_val() {
+                debugln!("Help::spec_vals: Found default value...[{:?}]", pv);
+                spec_vals.push(format!(
+                    " [default: {}]",
+                    if self.color {
+                        self.cizer.good(pv.to_string_lossy())
+                    } else {
+                        Format::None(pv.to_string_lossy())
+                    }
+                ));
+            }
+        }
+        if let Some(ref aliases) = a.aliases() {
+            debugln!("Help::spec_vals: Found aliases...{:?}", aliases);
+            spec_vals.push(format!(
+                " [aliases: {}]",
+                if self.color {
+                    aliases
+                        .iter()
+                        .map(|v| format!("{}", self.cizer.good(v)))
+                        .collect::<Vec<_>>()
+                        .join(", ")
+                } else {
+                    aliases.join(", ")
+                }
+            ));
+        }
+        if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) {
+            if let Some(pv) = a.possible_vals() {
+                debugln!("Help::spec_vals: Found possible vals...{:?}", pv);
+                spec_vals.push(if self.color {
+                    format!(
+                        " [possible values: {}]",
+                        pv.iter()
+                            .map(|v| format!("{}", self.cizer.good(v)))
+                            .collect::<Vec<_>>()
+                            .join(", ")
+                    )
+                } else {
+                    format!(" [possible values: {}]", pv.join(", "))
+                });
+            }
+        }
+        spec_vals.join(" ")
+    }
+}
+
+fn should_show_arg(use_long: bool, arg: &ArgWithOrder) -> bool {
+    if arg.is_set(ArgSettings::Hidden) {
+        return false;
+    }
+
+    (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long)
+        || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long)
+        || arg.is_set(ArgSettings::NextLineHelp)
+}
+
+// Methods to write Parser help.
+impl<'a> Help<'a> {
+    /// Writes help for all arguments (options, flags, args, subcommands)
+    /// including titles of a Parser Object to the wrapped stream.
+    pub fn write_all_args(&mut self, parser: &Parser) -> ClapResult<()> {
+        debugln!("Help::write_all_args;");
+        let flags = parser.has_flags();
+        let pos = parser
+            .positionals()
+            .filter(|arg| !arg.is_set(ArgSettings::Hidden))
+            .count()
+            > 0;
+        let opts = parser.has_opts();
+        let subcmds = parser.has_visible_subcommands();
+
+        let unified_help = parser.is_set(AppSettings::UnifiedHelpMessage);
+
+        let mut first = true;
+
+        if unified_help && (flags || opts) {
+            let opts_flags = parser
+                .flags()
+                .map(as_arg_trait)
+                .chain(parser.opts().map(as_arg_trait));
+            color!(self, "OPTIONS:\n", warning)?;
+            self.write_args(opts_flags)?;
+            first = false;
+        } else {
+            if flags {
+                color!(self, "FLAGS:\n", warning)?;
+                self.write_args(parser.flags().map(as_arg_trait))?;
+                first = false;
+            }
+            if opts {
+                if !first {
+                    self.writer.write_all(b"\n\n")?;
+                }
+                color!(self, "OPTIONS:\n", warning)?;
+                self.write_args(parser.opts().map(as_arg_trait))?;
+                first = false;
+            }
+        }
+
+        if pos {
+            if !first {
+                self.writer.write_all(b"\n\n")?;
+            }
+            color!(self, "ARGS:\n", warning)?;
+            self.write_args_unsorted(parser.positionals().map(as_arg_trait))?;
+            first = false;
+        }
+
+        if subcmds {
+            if !first {
+                self.writer.write_all(b"\n\n")?;
+            }
+            color!(self, "SUBCOMMANDS:\n", warning)?;
+            self.write_subcommands(parser)?;
+        }
+
+        Ok(())
+    }
+
+    /// Writes help for subcommands of a Parser Object to the wrapped stream.
+    fn write_subcommands(&mut self, parser: &Parser) -> io::Result<()> {
+        debugln!("Help::write_subcommands;");
+        // The shortest an arg can legally be is 2 (i.e. '-x')
+        self.longest = 2;
+        let mut ord_m = VecMap::new();
+        for sc in parser
+            .subcommands
+            .iter()
+            .filter(|s| !s.p.is_set(AppSettings::Hidden))
+        {
+            let btm = ord_m.entry(sc.p.meta.disp_ord).or_insert(BTreeMap::new());
+            self.longest = cmp::max(self.longest, str_width(sc.p.meta.name.as_str()));
+            //self.longest = cmp::max(self.longest, sc.p.meta.name.len());
+            btm.insert(sc.p.meta.name.clone(), sc.clone());
+        }
+
+        let mut first = true;
+        for btm in ord_m.values() {
+            for sc in btm.values() {
+                if first {
+                    first = false;
+                } else {
+                    self.writer.write_all(b"\n")?;
+                }
+                self.write_arg(sc)?;
+            }
+        }
+        Ok(())
+    }
+
+    /// Writes version of a Parser Object to the wrapped stream.
+    fn write_version(&mut self, parser: &Parser) -> io::Result<()> {
+        debugln!("Help::write_version;");
+        write!(self.writer, "{}", parser.meta.version.unwrap_or(""))?;
+        Ok(())
+    }
+
+    /// Writes binary name of a Parser Object to the wrapped stream.
+    fn write_bin_name(&mut self, parser: &Parser) -> io::Result<()> {
+        debugln!("Help::write_bin_name;");
+        macro_rules! write_name {
+            () => {{
+                let mut name = parser.meta.name.clone();
+                name = name.replace("{n}", "\n");
+                color!(self, wrap_help(&name, self.term_w), good)?;
+            }};
+        }
+        if let Some(bn) = parser.meta.bin_name.as_ref() {
+            if bn.contains(' ') {
+                // Incase we're dealing with subcommands i.e. git mv is translated to git-mv
+                color!(self, bn.replace(" ", "-"), good)?
+            } else {
+                write_name!();
+            }
+        } else {
+            write_name!();
+        }
+        Ok(())
+    }
+
+    /// Writes default help for a Parser Object to the wrapped stream.
+    pub fn write_default_help(&mut self, parser: &Parser) -> ClapResult<()> {
+        debugln!("Help::write_default_help;");
+        if let Some(h) = parser.meta.pre_help {
+            self.write_before_after_help(h)?;
+            self.writer.write_all(b"\n\n")?;
+        }
+
+        macro_rules! write_thing {
+            ($thing:expr) => {{
+                let mut owned_thing = $thing.to_owned();
+                owned_thing = owned_thing.replace("{n}", "\n");
+                write!(self.writer, "{}\n", wrap_help(&owned_thing, self.term_w))?
+            }};
+        }
+        // Print the version
+        self.write_bin_name(parser)?;
+        self.writer.write_all(b" ")?;
+        self.write_version(parser)?;
+        self.writer.write_all(b"\n")?;
+        if let Some(author) = parser.meta.author {
+            write_thing!(author)
+        }
+        // if self.use_long {
+        //     if let Some(about) = parser.meta.long_about {
+        //         debugln!("Help::write_default_help: writing long about");
+        //         write_thing!(about)
+        //     } else if let Some(about) = parser.meta.about {
+        //         debugln!("Help::write_default_help: writing about");
+        //         write_thing!(about)
+        //     }
+        // } else
+        if let Some(about) = parser.meta.long_about {
+            debugln!("Help::write_default_help: writing long about");
+            write_thing!(about)
+        } else if let Some(about) = parser.meta.about {
+            debugln!("Help::write_default_help: writing about");
+            write_thing!(about)
+        }
+
+        color!(self, "\nUSAGE:", warning)?;
+        write!(
+            self.writer,
+            "\n{}{}\n\n",
+            TAB,
+            usage::create_usage_no_title(parser, &[])
+        )?;
+
+        let flags = parser.has_flags();
+        let pos = parser.has_positionals();
+        let opts = parser.has_opts();
+        let subcmds = parser.has_subcommands();
+
+        if flags || opts || pos || subcmds {
+            self.write_all_args(parser)?;
+        }
+
+        if let Some(h) = parser.meta.more_help {
+            if flags || opts || pos || subcmds {
+                self.writer.write_all(b"\n\n")?;
+            }
+            self.write_before_after_help(h)?;
+        }
+
+        self.writer.flush().map_err(Error::from)
+    }
+}
+
+/// Possible results for a copying function that stops when a given
+/// byte was found.
+enum CopyUntilResult {
+    DelimiterFound(usize),
+    DelimiterNotFound(usize),
+    ReaderEmpty,
+    ReadError(io::Error),
+    WriteError(io::Error),
+}
+
+/// Copies the contents of a reader into a writer until a delimiter byte is found.
+/// On success, the total number of bytes that were
+/// copied from reader to writer is returned.
+fn copy_until<R: Read, W: Write>(r: &mut R, w: &mut W, delimiter_byte: u8) -> CopyUntilResult {
+    debugln!("copy_until;");
+
+    let mut count = 0;
+    for wb in r.bytes() {
+        match wb {
+            Ok(b) => {
+                if b == delimiter_byte {
+                    return CopyUntilResult::DelimiterFound(count);
+                }
+                match w.write(&[b]) {
+                    Ok(c) => count += c,
+                    Err(e) => return CopyUntilResult::WriteError(e),
+                }
+            }
+            Err(e) => return CopyUntilResult::ReadError(e),
+        }
+    }
+    if count > 0 {
+        CopyUntilResult::DelimiterNotFound(count)
+    } else {
+        CopyUntilResult::ReaderEmpty
+    }
+}
+
+/// Copies the contents of a reader into a writer until a {tag} is found,
+/// copying the tag content to a buffer and returning its size.
+/// In addition to errors, there are three possible outputs:
+///   - `None`: The reader was consumed.
+///   - `Some(Ok(0))`: No tag was captured but the reader still contains data.
+///   - `Some(Ok(length>0))`: a tag with `length` was captured to the `tag_buffer`.
+fn copy_and_capture<R: Read, W: Write>(
+    r: &mut R,
+    w: &mut W,
+    tag_buffer: &mut Cursor<Vec<u8>>,
+) -> Option<io::Result<usize>> {
+    use self::CopyUntilResult::*;
+    debugln!("copy_and_capture;");
+
+    // Find the opening byte.
+    match copy_until(r, w, b'{') {
+        // The end of the reader was reached without finding the opening tag.
+        // (either with or without having copied data to the writer)
+        // Return None indicating that we are done.
+        ReaderEmpty | DelimiterNotFound(_) => None,
+
+        // Something went wrong.
+        ReadError(e) | WriteError(e) => Some(Err(e)),
+
+        // The opening byte was found.
+        // (either with or without having copied data to the writer)
+        DelimiterFound(_) => {
+            // Lets reset the buffer first and find out how long it is.
+            tag_buffer.set_position(0);
+            let buffer_size = tag_buffer.get_ref().len();
+
+            // Find the closing byte,limiting the reader to the length of the buffer.
+            let mut rb = r.take(buffer_size as u64);
+            match copy_until(&mut rb, tag_buffer, b'}') {
+                // We were already at the end of the reader.
+                // Return None indicating that we are done.
+                ReaderEmpty => None,
+
+                // The closing tag was found.
+                // Return the tag_length.
+                DelimiterFound(tag_length) => Some(Ok(tag_length)),
+
+                // The end of the reader was found without finding the closing tag.
+                // Write the opening byte and captured text to the writer.
+                // Return 0 indicating that nothing was captured but the reader still contains data.
+                DelimiterNotFound(not_tag_length) => match w.write(b"{") {
+                    Err(e) => Some(Err(e)),
+                    _ => match w.write(&tag_buffer.get_ref()[0..not_tag_length]) {
+                        Err(e) => Some(Err(e)),
+                        _ => Some(Ok(0)),
+                    },
+                },
+
+                ReadError(e) | WriteError(e) => Some(Err(e)),
+            }
+        }
+    }
+}
+
+// Methods to write Parser help using templates.
+impl<'a> Help<'a> {
+    /// Write help to stream for the parser in the format defined by the template.
+    ///
+    /// Tags arg given inside curly brackets:
+    /// Valid tags are:
+    ///     * `{bin}`         - Binary name.
+    ///     * `{version}`     - Version number.
+    ///     * `{author}`      - Author information.
+    ///     * `{usage}`       - Automatically generated or given usage string.
+    ///     * `{all-args}`    - Help for all arguments (options, flags, positionals arguments,
+    ///                         and subcommands) including titles.
+    ///     * `{unified}`     - Unified help for options and flags.
+    ///     * `{flags}`       - Help for flags.
+    ///     * `{options}`     - Help for options.
+    ///     * `{positionals}` - Help for positionals arguments.
+    ///     * `{subcommands}` - Help for subcommands.
+    ///     * `{after-help}`  - Info to be displayed after the help message.
+    ///     * `{before-help}` - Info to be displayed before the help message.
+    ///
+    /// The template system is, on purpose, very simple. Therefore the tags have to written
+    /// in the lowercase and without spacing.
+    fn write_templated_help(&mut self, parser: &Parser, template: &str) -> ClapResult<()> {
+        debugln!("Help::write_templated_help;");
+        let mut tmplr = Cursor::new(&template);
+        let mut tag_buf = Cursor::new(vec![0u8; 15]);
+
+        // The strategy is to copy the template from the reader to wrapped stream
+        // until a tag is found. Depending on its value, the appropriate content is copied
+        // to the wrapped stream.
+        // The copy from template is then resumed, repeating this sequence until reading
+        // the complete template.
+
+        loop {
+            let tag_length = match copy_and_capture(&mut tmplr, &mut self.writer, &mut tag_buf) {
+                None => return Ok(()),
+                Some(Err(e)) => return Err(Error::from(e)),
+                Some(Ok(val)) if val > 0 => val,
+                _ => continue,
+            };
+
+            debugln!("Help::write_template_help:iter: tag_buf={};", unsafe {
+                String::from_utf8_unchecked(
+                    tag_buf.get_ref()[0..tag_length]
+                        .iter()
+                        .map(|&i| i)
+                        .collect::<Vec<_>>(),
+                )
+            });
+            match &tag_buf.get_ref()[0..tag_length] {
+                b"?" => {
+                    self.writer.write_all(b"Could not decode tag name")?;
+                }
+                b"bin" => {
+                    self.write_bin_name(parser)?;
+                }
+                b"version" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.version.unwrap_or("unknown version")
+                    )?;
+                }
+                b"author" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.author.unwrap_or("unknown author")
+                    )?;
+                }
+                b"about" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.about.unwrap_or("unknown about")
+                    )?;
+                }
+                b"long-about" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.long_about.unwrap_or("unknown about")
+                    )?;
+                }
+                b"usage" => {
+                    write!(self.writer, "{}", usage::create_usage_no_title(parser, &[]))?;
+                }
+                b"all-args" => {
+                    self.write_all_args(parser)?;
+                }
+                b"unified" => {
+                    let opts_flags = parser
+                        .flags()
+                        .map(as_arg_trait)
+                        .chain(parser.opts().map(as_arg_trait));
+                    self.write_args(opts_flags)?;
+                }
+                b"flags" => {
+                    self.write_args(parser.flags().map(as_arg_trait))?;
+                }
+                b"options" => {
+                    self.write_args(parser.opts().map(as_arg_trait))?;
+                }
+                b"positionals" => {
+                    self.write_args(parser.positionals().map(as_arg_trait))?;
+                }
+                b"subcommands" => {
+                    self.write_subcommands(parser)?;
+                }
+                b"after-help" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.more_help.unwrap_or("unknown after-help")
+                    )?;
+                }
+                b"before-help" => {
+                    write!(
+                        self.writer,
+                        "{}",
+                        parser.meta.pre_help.unwrap_or("unknown before-help")
+                    )?;
+                }
+                // Unknown tag, write it back.
+                r => {
+                    self.writer.write_all(b"{")?;
+                    self.writer.write_all(r)?;
+                    self.writer.write_all(b"}")?;
+                }
+            }
+        }
+    }
+}
+
+fn wrap_help(help: &str, avail_chars: usize) -> String {
+    let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false);
+    help.lines()
+        .map(|line| wrapper.fill(line))
+        .collect::<Vec<String>>()
+        .join("\n")
+}
+
+#[cfg(test)]
+mod test {
+    use super::wrap_help;
+
+    #[test]
+    fn wrap_help_last_word() {
+        let help = String::from("foo bar baz");
+        assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/meta.rs
@@ -0,0 +1,35 @@
+#[doc(hidden)]
+#[allow(missing_debug_implementations)]
+#[derive(Default, Clone)]
+pub struct AppMeta<'b> {
+    pub name: String,
+    pub bin_name: Option<String>,
+    pub author: Option<&'b str>,
+    pub version: Option<&'b str>,
+    pub long_version: Option<&'b str>,
+    pub about: Option<&'b str>,
+    pub long_about: Option<&'b str>,
+    pub more_help: Option<&'b str>,
+    pub pre_help: Option<&'b str>,
+    pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible)
+    pub usage_str: Option<&'b str>,
+    pub usage: Option<String>,
+    pub help_str: Option<&'b str>,
+    pub disp_ord: usize,
+    pub term_w: Option<usize>,
+    pub max_w: Option<usize>,
+    pub template: Option<&'b str>,
+}
+
+impl<'b> AppMeta<'b> {
+    pub fn new() -> Self {
+        Default::default()
+    }
+    pub fn with_name(s: String) -> Self {
+        AppMeta {
+            name: s,
+            disp_ord: 999,
+            ..Default::default()
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/mod.rs
@@ -0,0 +1,1909 @@
+mod help;
+mod meta;
+pub mod parser;
+mod settings;
+mod usage;
+mod validator;
+
+// Std
+use std::result::Result as StdResult;
+use std::{
+    env,
+    ffi::{OsStr, OsString},
+    fmt,
+    io::{self, BufRead, BufWriter, Write},
+    path::Path,
+    process,
+    rc::Rc,
+};
+
+// Third Party
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+// Internal
+use crate::errors::Result as ClapResult;
+use crate::{
+    app::{help::Help, parser::Parser},
+    args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings},
+    completions::Shell,
+    map::{self, VecMap},
+};
+pub use settings::AppSettings;
+
+/// Used to create a representation of a command line program and all possible command line
+/// arguments. Application settings are set using the "builder pattern" with the
+/// [`App::get_matches`] family of methods being the terminal methods that starts the
+/// runtime-parsing process. These methods then return information about the user supplied
+/// arguments (or lack there of).
+///
+/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
+/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
+/// called).
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{App, Arg};
+/// let m = App::new("My Program")
+///     .author("Me, me@mail.com")
+///     .version("1.0.2")
+///     .about("Explains in brief what the program does")
+///     .arg(
+///         Arg::with_name("in_file").index(1)
+///     )
+///     .after_help("Longer explanation to appear after the options when \
+///                  displaying the help information from --help or -h")
+///     .get_matches();
+///
+/// // Your program logic starts here...
+/// ```
+/// [`App::get_matches`]: ./struct.App.html#method.get_matches
+#[allow(missing_debug_implementations)]
+pub struct App<'a, 'b>
+where
+    'a: 'b,
+{
+    #[doc(hidden)]
+    pub p: Parser<'a, 'b>,
+}
+
+impl<'a, 'b> App<'a, 'b> {
+    /// Creates a new instance of an application requiring a name. The name may be, but doesn't
+    /// have to be same as the binary. The name will be displayed to the user when they request to
+    /// print version or help and usage information.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let prog = App::new("My Program")
+    /// # ;
+    /// ```
+    pub fn new<S: Into<String>>(n: S) -> Self {
+        App {
+            p: Parser::with_name(n.into()),
+        }
+    }
+
+    /// Get the name of the app
+    pub fn get_name(&self) -> &str {
+        &self.p.meta.name
+    }
+
+    /// Get the name of the binary
+    pub fn get_bin_name(&self) -> Option<&str> {
+        self.p.meta.bin_name.as_deref()
+    }
+
+    /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`]
+    /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let prog = App::with_defaults("My Program")
+    /// # ;
+    /// ```
+    /// [`crate_authors!`]: ./macro.crate_authors!.html
+    /// [`crate_version!`]: ./macro.crate_version!.html
+    /// [`App::author`]: ./struct.App.html#method.author
+    /// [`App::version`]: ./struct.App.html#method.author
+    #[deprecated(
+        since = "2.14.1",
+        note = "Can never work; use explicit App::author() and App::version() calls instead"
+    )]
+    pub fn with_defaults<S: Into<String>>(n: S) -> Self {
+        let mut a = App {
+            p: Parser::with_name(n.into()),
+        };
+        a.p.meta.author = Some("Kevin K. <kbknapp@gmail.com>");
+        a.p.meta.version = Some("2.19.2");
+        a
+    }
+
+    /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML
+    /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use
+    /// for using YAML is when supporting multiple languages and dialects, as each language could
+    /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your
+    /// `Cargo.toml`
+    ///
+    /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in
+    /// your settings for the `[dependencies.clap]` table of your `Cargo.toml`
+    ///
+    /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading
+    /// the YAML file at compile time (relative to the current file, like modules work). That YAML
+    /// object can then be passed to this function.
+    ///
+    /// # Panics
+    ///
+    /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to
+    /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
+    /// without error, you needn't worry because the YAML is properly formatted.
+    ///
+    /// # Examples
+    ///
+    /// The following example shows how to load a properly formatted YAML file to build an instance
+    /// of an [`App`] struct.
+    ///
+    /// ```ignore
+    /// # #[macro_use]
+    /// # extern crate clap;
+    /// # use clap::App;
+    /// # fn main() {
+    /// let yml = load_yaml!("app.yml");
+    /// let app = App::from_yaml(yml);
+    ///
+    /// // continued logic goes here, such as `app.get_matches()` etc.
+    /// # }
+    /// ```
+    /// [`App`]: ./struct.App.html
+    /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.rs
+    /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/v2.33.1/examples/17_yaml.yml
+    /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
+    #[cfg(feature = "yaml")]
+    pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> {
+        App::from(yaml)
+    }
+
+    /// Sets a string of author(s) that will be displayed to the user when they
+    /// request the help information with `--help` or `-h`.
+    ///
+    /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your
+    /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`]
+    /// directory for more information
+    ///
+    /// See the [`examples/`]
+    /// directory for more information
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///      .author("Me, me@mymain.com")
+    /// # ;
+    /// ```
+    /// [`crate_authors!`]: ./macro.crate_authors!.html
+    /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
+    pub fn author<S: Into<&'b str>>(mut self, author: S) -> Self {
+        self.p.meta.author = Some(author.into());
+        self
+    }
+
+    /// Overrides the system-determined binary name. This should only be used when absolutely
+    /// necessary, such as when the binary name for your application is misleading, or perhaps
+    /// *not* how the user should invoke your program.
+    ///
+    /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting
+    /// **should** be used!
+    ///
+    /// **NOTE:** This command **should not** be used for [`SubCommand`]s.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("My Program")
+    ///      .bin_name("my_binary")
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
+        self.p.meta.bin_name = Some(name.into());
+        self
+    }
+
+    /// Sets a string describing what the program does. This will be displayed when displaying help
+    /// information with `-h`.
+    ///
+    /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests
+    /// `--help` clap will still display the contents of `about` appropriately
+    ///
+    /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
+    /// concise
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .about("Does really amazing things to great people")
+    /// # ;
+    /// ```
+    /// [`App::long_about`]: ./struct.App.html#method.long_about
+    pub fn about<S: Into<&'b str>>(mut self, about: S) -> Self {
+        self.p.meta.about = Some(about.into());
+        self
+    }
+
+    /// Sets a string describing what the program does. This will be displayed when displaying help
+    /// information.
+    ///
+    /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests
+    /// `-h` clap will still display the contents of `long_about` appropriately
+    ///
+    /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
+    /// concise
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .long_about(
+    /// "Does really amazing things to great people. Now let's talk a little
+    ///  more in depth about how this subcommand really works. It may take about
+    ///  a few lines of text, but that's ok!")
+    /// # ;
+    /// ```
+    /// [`App::about`]: ./struct.App.html#method.about
+    pub fn long_about<S: Into<&'b str>>(mut self, about: S) -> Self {
+        self.p.meta.long_about = Some(about.into());
+        self
+    }
+
+    /// Sets the program's name. This will be displayed when displaying help information.
+    ///
+    /// **Pro-top:** This function is particularly useful when configuring a program via
+    /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's
+    /// name from its `Cargo.toml`.
+    ///
+    /// # Examples
+    /// ```ignore
+    /// # #[macro_use]
+    /// # extern crate clap;
+    /// # use clap::App;
+    /// # fn main() {
+    /// let yml = load_yaml!("app.yml");
+    /// let app = App::from_yaml(yml)
+    ///     .name(crate_name!());
+    ///
+    /// // continued logic goes here, such as `app.get_matches()` etc.
+    /// # }
+    /// ```
+    ///
+    /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml
+    /// [`crate_name!`]: ./macro.crate_name.html
+    pub fn name<S: Into<String>>(mut self, name: S) -> Self {
+        self.p.meta.name = name.into();
+        self
+    }
+
+    /// Adds additional help information to be displayed in addition to auto-generated help. This
+    /// information is displayed **after** the auto-generated help information. This is often used
+    /// to describe how to use the arguments, or caveats to be noted.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::App;
+    /// App::new("myprog")
+    ///     .after_help("Does really amazing things to great people...but be careful with -R")
+    /// # ;
+    /// ```
+    pub fn after_help<S: Into<&'b str>>(mut self, help: S) -> Self {
+        self.p.meta.more_help = Some(help.into());
+        self
+    }
+
+    /// Adds additional help information to be displayed in addition to auto-generated help. This
+    /// information is displayed **before** the auto-generated help information. This is often used
+    /// for header information.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::App;
+    /// App::new("myprog")
+    ///     .before_help("Some info I'd like to appear before the help info")
+    /// # ;
+    /// ```
+    pub fn before_help<S: Into<&'b str>>(mut self, help: S) -> Self {
+        self.p.meta.pre_help = Some(help.into());
+        self
+    }
+
+    /// Sets a string of the version number to be displayed when displaying version or help
+    /// information with `-V`.
+    ///
+    /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user
+    /// requests `--version` clap will still display the contents of `version` appropriately
+    ///
+    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
+    /// application's version to the same thing as your crate at compile time. See the [`examples/`]
+    /// directory for more information
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .version("v0.1.24")
+    /// # ;
+    /// ```
+    /// [`crate_version!`]: ./macro.crate_version!.html
+    /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
+    /// [`App::long_version`]: ./struct.App.html#method.long_version
+    pub fn version<S: Into<&'b str>>(mut self, ver: S) -> Self {
+        self.p.meta.version = Some(ver.into());
+        self
+    }
+
+    /// Sets a string of the version number to be displayed when displaying version or help
+    /// information with `--version`.
+    ///
+    /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user
+    /// requests `-V` clap will still display the contents of `long_version` appropriately
+    ///
+    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
+    /// application's version to the same thing as your crate at compile time. See the [`examples/`]
+    /// directory for more information
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .long_version(
+    /// "v0.1.24
+    ///  commit: abcdef89726d
+    ///  revision: 123
+    ///  release: 2
+    ///  binary: myprog")
+    /// # ;
+    /// ```
+    /// [`crate_version!`]: ./macro.crate_version!.html
+    /// [`examples/`]: https://github.com/clap-rs/clap/tree/v2.33.1/examples
+    /// [`App::version`]: ./struct.App.html#method.version
+    pub fn long_version<S: Into<&'b str>>(mut self, ver: S) -> Self {
+        self.p.meta.long_version = Some(ver.into());
+        self
+    }
+
+    /// Sets a custom usage string to override the auto-generated usage string.
+    ///
+    /// This will be displayed to the user when errors are found in argument parsing, or when you
+    /// call [`ArgMatches::usage`]
+    ///
+    /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this
+    /// setting is set, this will be the only usage string displayed to the user!
+    ///
+    /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will
+    /// still be applied by `clap`, you only need to specify the portion starting
+    /// with the binary name.
+    ///
+    /// **NOTE:** This will not replace the entire help message, *only* the portion
+    /// showing the usage.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .usage("myapp [-clDas] <some_file>")
+    /// # ;
+    /// ```
+    /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage
+    pub fn usage<S: Into<&'b str>>(mut self, usage: S) -> Self {
+        self.p.meta.usage_str = Some(usage.into());
+        self
+    }
+
+    /// Sets a custom help message and overrides the auto-generated one. This should only be used
+    /// when the auto-generated message does not suffice.
+    ///
+    /// This will be displayed to the user when they use `--help` or `-h`
+    ///
+    /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated.
+    ///
+    /// **NOTE:** This **only** replaces the help message for the current command, meaning if you
+    /// are using subcommands, those help messages will still be auto-generated unless you
+    /// specify a [`Arg::help`] for them as well.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myapp")
+    ///     .help("myapp v1.0\n\
+    ///            Does awesome things\n\
+    ///            (C) me@mail.com\n\n\
+    ///
+    ///            USAGE: myapp <opts> <command>\n\n\
+    ///
+    ///            Options:\n\
+    ///            -h, --help       Display this message\n\
+    ///            -V, --version    Display version info\n\
+    ///            -s <stuff>       Do something with stuff\n\
+    ///            -v               Be verbose\n\n\
+    ///
+    ///            Commmands:\n\
+    ///            help             Prints this message\n\
+    ///            work             Do some work")
+    /// # ;
+    /// ```
+    /// [`Arg::help`]: ./struct.Arg.html#method.help
+    pub fn help<S: Into<&'b str>>(mut self, help: S) -> Self {
+        self.p.meta.help_str = Some(help.into());
+        self
+    }
+
+    /// Sets the [`short`] for the auto-generated `help` argument.
+    ///
+    /// By default `clap` automatically assigns `h`, but this can be overridden if you have a
+    /// different argument which you'd prefer to use the `-h` short with. This can be done by
+    /// defining your own argument with a lowercase `h` as the [`short`].
+    ///
+    /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of
+    /// your own.
+    ///
+    /// **NOTE:** Any leading `-` characters will be stripped, and only the first
+    /// non `-` character will be used as the [`short`] version
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
+    /// # ;
+    /// ```
+    /// [`short`]: ./struct.Arg.html#method.short
+    pub fn help_short<S: AsRef<str> + 'b>(mut self, s: S) -> Self {
+        self.p.help_short(s.as_ref());
+        self
+    }
+
+    /// Sets the [`short`] for the auto-generated `version` argument.
+    ///
+    /// By default `clap` automatically assigns `V`, but this can be overridden if you have a
+    /// different argument which you'd prefer to use the `-V` short with. This can be done by
+    /// defining your own argument with an uppercase `V` as the [`short`].
+    ///
+    /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of
+    /// your own.
+    ///
+    /// **NOTE:** Any leading `-` characters will be stripped, and only the first
+    /// non `-` character will be used as the `short` version
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .version_short("v") // Using a lowercase `v` instead of the default capital `V`
+    /// # ;
+    /// ```
+    /// [`short`]: ./struct.Arg.html#method.short
+    pub fn version_short<S: AsRef<str>>(mut self, s: S) -> Self {
+        self.p.version_short(s.as_ref());
+        self
+    }
+
+    /// Sets the help text for the auto-generated `help` argument.
+    ///
+    /// By default `clap` sets this to `"Prints help information"`, but if you're using a
+    /// different convention for your help messages and would prefer a different phrasing you can
+    /// override it.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .help_message("Print help information") // Perhaps you want imperative help messages
+    ///
+    /// # ;
+    /// ```
+    pub fn help_message<S: Into<&'a str>>(mut self, s: S) -> Self {
+        self.p.help_message = Some(s.into());
+        self
+    }
+
+    /// Sets the help text for the auto-generated `version` argument.
+    ///
+    /// By default `clap` sets this to `"Prints version information"`, but if you're using a
+    /// different convention for your help messages and would prefer a different phrasing then you
+    /// can change it.
+    ///
+    /// # Examples
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .version_message("Print version information") // Perhaps you want imperative help messages
+    /// # ;
+    /// ```
+    pub fn version_message<S: Into<&'a str>>(mut self, s: S) -> Self {
+        self.p.version_message = Some(s.into());
+        self
+    }
+
+    /// Sets the help template to be used, overriding the default format.
+    ///
+    /// Tags arg given inside curly brackets.
+    ///
+    /// Valid tags are:
+    ///
+    ///   * `{bin}`         - Binary name.
+    ///   * `{version}`     - Version number.
+    ///   * `{author}`      - Author information.
+    ///   * `{about}`       - General description (from [`App::about`])
+    ///   * `{usage}`       - Automatically generated or given usage string.
+    ///   * `{all-args}`    - Help for all arguments (options, flags, positionals arguments,
+    ///                       and subcommands) including titles.
+    ///   * `{unified}`     - Unified help for options and flags. Note, you must *also* set
+    ///                       [`AppSettings::UnifiedHelpMessage`] to fully merge both options and
+    ///                       flags, otherwise the ordering is "best effort"
+    ///   * `{flags}`       - Help for flags.
+    ///   * `{options}`     - Help for options.
+    ///   * `{positionals}` - Help for positionals arguments.
+    ///   * `{subcommands}` - Help for subcommands.
+    ///   * `{after-help}`  - Help from [`App::after_help`]
+    ///   * `{before-help}`  - Help from [`App::before_help`]
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .version("1.0")
+    ///     .template("{bin} ({version}) - {usage}")
+    /// # ;
+    /// ```
+    /// **NOTE:** The template system is, on purpose, very simple. Therefore the tags have to be
+    /// written in lowercase and without spacing.
+    ///
+    /// [`App::about`]: ./struct.App.html#method.about
+    /// [`App::after_help`]: ./struct.App.html#method.after_help
+    /// [`App::before_help`]: ./struct.App.html#method.before_help
+    /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage
+    pub fn template<S: Into<&'b str>>(mut self, s: S) -> Self {
+        self.p.meta.template = Some(s.into());
+        self
+    }
+
+    /// Enables a single command, or [`SubCommand`], level settings.
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::SubcommandRequired)
+    ///     .setting(AppSettings::WaitOnError)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn setting(mut self, setting: AppSettings) -> Self {
+        self.p.set(setting);
+        self
+    }
+
+    /// Enables multiple command, or [`SubCommand`], level settings
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .settings(&[AppSettings::SubcommandRequired,
+    ///                  AppSettings::WaitOnError])
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn settings(mut self, settings: &[AppSettings]) -> Self {
+        for s in settings {
+            self.p.set(*s);
+        }
+        self
+    }
+
+    /// Enables a single setting that is propagated down through all child [`SubCommand`]s.
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .global_setting(AppSettings::SubcommandRequired)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn global_setting(mut self, setting: AppSettings) -> Self {
+        self.p.set(setting);
+        self.p.g_settings.set(setting);
+        self
+    }
+
+    /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s.
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .global_settings(&[AppSettings::SubcommandRequired,
+    ///                  AppSettings::ColoredHelp])
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn global_settings(mut self, settings: &[AppSettings]) -> Self {
+        for s in settings {
+            self.p.set(*s);
+            self.p.g_settings.set(*s)
+        }
+        self
+    }
+
+    /// Disables a single command, or [`SubCommand`], level setting.
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, AppSettings};
+    /// App::new("myprog")
+    ///     .unset_setting(AppSettings::ColorAuto)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn unset_setting(mut self, setting: AppSettings) -> Self {
+        self.p.unset(setting);
+        self
+    }
+
+    /// Disables multiple command, or [`SubCommand`], level settings.
+    ///
+    /// See [`AppSettings`] for a full list of possibilities and examples.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, AppSettings};
+    /// App::new("myprog")
+    ///     .unset_settings(&[AppSettings::ColorAuto,
+    ///                       AppSettings::AllowInvalidUtf8])
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings`]: ./enum.AppSettings.html
+    pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self {
+        for s in settings {
+            self.p.unset(*s);
+        }
+        self
+    }
+
+    /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will
+    /// ignore terminal widths and use source formatting.
+    ///
+    /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
+    /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width
+    /// cannot be determined, `clap` defaults to `120`.
+    ///
+    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+    ///
+    /// **NOTE:** This setting must be set **before** any subcommands are added!
+    ///
+    /// # Platform Specific
+    ///
+    /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width.
+    /// Even on those platforms, this setting is useful if for any reason the terminal width
+    /// cannot be determined.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::App;
+    /// App::new("myprog")
+    ///     .set_term_width(80)
+    /// # ;
+    /// ```
+    pub fn set_term_width(mut self, width: usize) -> Self {
+        self.p.meta.term_w = Some(width);
+        self
+    }
+
+    /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal
+    /// widths and use source formatting.
+    ///
+    /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows
+    /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to
+    /// limit the size (e.g. when the terminal is running fullscreen).
+    ///
+    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
+    ///
+    /// **NOTE:** This setting must be set **before** any subcommands are added!
+    ///
+    /// # Platform Specific
+    ///
+    /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::App;
+    /// App::new("myprog")
+    ///     .max_term_width(100)
+    /// # ;
+    /// ```
+    pub fn max_term_width(mut self, w: usize) -> Self {
+        self.p.meta.max_w = Some(w);
+        self
+    }
+
+    /// Adds an [argument] to the list of valid possibilities.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     // Adding a single "flag" argument with a short and help text, using Arg::with_name()
+    ///     .arg(
+    ///         Arg::with_name("debug")
+    ///            .short("d")
+    ///            .help("turns on debugging mode")
+    ///     )
+    ///     // Adding a single "option" argument with a short, a long, and help text using the less
+    ///     // verbose Arg::from_usage()
+    ///     .arg(
+    ///         Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'")
+    ///     )
+    /// # ;
+    /// ```
+    /// [argument]: ./struct.Arg.html
+    pub fn arg<A: Into<Arg<'a, 'b>>>(mut self, a: A) -> Self {
+        self.p.add_arg(a.into());
+        self
+    }
+
+    /// Adds multiple [arguments] to the list of valid possibilities
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .args(
+    ///         &[Arg::from_usage("[debug] -d 'turns on debugging info'"),
+    ///          Arg::with_name("input").index(1).help("the input file to use")]
+    ///     )
+    /// # ;
+    /// ```
+    /// [arguments]: ./struct.Arg.html
+    pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self {
+        for arg in args {
+            self.p.add_arg_ref(arg);
+        }
+        self
+    }
+
+    /// A convenience method for adding a single [argument] from a usage type string. The string
+    /// used follows the same rules and syntax as [`Arg::from_usage`]
+    ///
+    /// **NOTE:** The downside to using this method is that you can not set any additional
+    /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
+    /// # ;
+    /// ```
+    /// [argument]: ./struct.Arg.html
+    /// [`Arg`]: ./struct.Arg.html
+    /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
+    pub fn arg_from_usage(mut self, usage: &'a str) -> Self {
+        self.p.add_arg(Arg::from_usage(usage));
+        self
+    }
+
+    /// Adds multiple [arguments] at once from a usage string, one per line. See
+    /// [`Arg::from_usage`] for details on the syntax and rules supported.
+    ///
+    /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the
+    /// [`Arg`]s which [`Arg::from_usage`] supports.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// App::new("myprog")
+    ///     .args_from_usage(
+    ///         "-c --config=[FILE] 'Sets a configuration file to use'
+    ///          [debug]... -d 'Sets the debugging level'
+    ///          <FILE> 'The input file to use'"
+    ///     )
+    /// # ;
+    /// ```
+    /// [arguments]: ./struct.Arg.html
+    /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
+    /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage
+    /// [`Arg`]: ./struct.Arg.html
+    pub fn args_from_usage(mut self, usage: &'a str) -> Self {
+        for line in usage.lines() {
+            let l = line.trim();
+            if l.is_empty() {
+                continue;
+            }
+            self.p.add_arg(Arg::from_usage(l));
+        }
+        self
+    }
+
+    /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that
+    /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
+    /// than creating multiple hidden subcommands as one only needs to check for the existence of
+    /// this command, and not all variants.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    /// let m = App::new("myprog")
+    ///             .subcommand(SubCommand::with_name("test")
+    ///                 .alias("do-stuff"))
+    ///             .get_matches_from(vec!["myprog", "do-stuff"]);
+    /// assert_eq!(m.subcommand_name(), Some("test"));
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self {
+        if let Some(ref mut als) = self.p.meta.aliases {
+            als.push((name.into(), false));
+        } else {
+            self.p.meta.aliases = Some(vec![(name.into(), false)]);
+        }
+        self
+    }
+
+    /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that
+    /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
+    /// than creating multiple hidden subcommands as one only needs to check for the existence of
+    /// this command, and not all variants.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, SubCommand};
+    /// let m = App::new("myprog")
+    ///             .subcommand(SubCommand::with_name("test")
+    ///                 .aliases(&["do-stuff", "do-tests", "tests"]))
+    ///                 .arg(Arg::with_name("input")
+    ///                             .help("the file to add")
+    ///                             .index(1)
+    ///                             .required(false))
+    ///             .get_matches_from(vec!["myprog", "do-tests"]);
+    /// assert_eq!(m.subcommand_name(), Some("test"));
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    pub fn aliases(mut self, names: &[&'b str]) -> Self {
+        if let Some(ref mut als) = self.p.meta.aliases {
+            for n in names {
+                als.push((n, false));
+            }
+        } else {
+            self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
+        }
+        self
+    }
+
+    /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with
+    /// [`App::alias`], except that they are visible inside the help message.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    /// let m = App::new("myprog")
+    ///             .subcommand(SubCommand::with_name("test")
+    ///                 .visible_alias("do-stuff"))
+    ///             .get_matches_from(vec!["myprog", "do-stuff"]);
+    /// assert_eq!(m.subcommand_name(), Some("test"));
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`App::alias`]: ./struct.App.html#method.alias
+    pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self {
+        if let Some(ref mut als) = self.p.meta.aliases {
+            als.push((name.into(), true));
+        } else {
+            self.p.meta.aliases = Some(vec![(name.into(), true)]);
+        }
+        self
+    }
+
+    /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined
+    /// with [`App::aliases`], except that they are visible inside the help message.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    /// let m = App::new("myprog")
+    ///             .subcommand(SubCommand::with_name("test")
+    ///                 .visible_aliases(&["do-stuff", "tests"]))
+    ///             .get_matches_from(vec!["myprog", "do-stuff"]);
+    /// assert_eq!(m.subcommand_name(), Some("test"));
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`App::aliases`]: ./struct.App.html#method.aliases
+    pub fn visible_aliases(mut self, names: &[&'b str]) -> Self {
+        if let Some(ref mut als) = self.p.meta.aliases {
+            for n in names {
+                als.push((n, true));
+            }
+        } else {
+            self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
+        }
+        self
+    }
+
+    /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments.
+    /// By placing them in a logical group, you can build easier requirement and exclusion rules.
+    /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
+    /// one) argument from that group must be present at runtime.
+    ///
+    /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument.
+    /// Meaning any of the arguments that belong to that group will cause a failure if present with
+    /// the conflicting argument.
+    ///
+    /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead
+    /// of determining exactly which argument was used.
+    ///
+    /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
+    /// use
+    ///
+    /// # Examples
+    ///
+    /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
+    /// of the arguments from the specified group is present at runtime.
+    ///
+    /// ```no_run
+    /// # use clap::{App, ArgGroup};
+    /// App::new("app")
+    ///     .args_from_usage(
+    ///         "--set-ver [ver] 'set the version manually'
+    ///          --major         'auto increase major'
+    ///          --minor         'auto increase minor'
+    ///          --patch         'auto increase patch'")
+    ///     .group(ArgGroup::with_name("vers")
+    ///          .args(&["set-ver", "major", "minor","patch"])
+    ///          .required(true))
+    /// # ;
+    /// ```
+    /// [`ArgGroup`]: ./struct.ArgGroup.html
+    pub fn group(mut self, group: ArgGroup<'a>) -> Self {
+        self.p.add_group(group);
+        self
+    }
+
+    /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, ArgGroup};
+    /// App::new("app")
+    ///     .args_from_usage(
+    ///         "--set-ver [ver] 'set the version manually'
+    ///          --major         'auto increase major'
+    ///          --minor         'auto increase minor'
+    ///          --patch         'auto increase patch'
+    ///          -c [FILE]       'a config file'
+    ///          -i [IFACE]      'an interface'")
+    ///     .groups(&[
+    ///         ArgGroup::with_name("vers")
+    ///             .args(&["set-ver", "major", "minor","patch"])
+    ///             .required(true),
+    ///         ArgGroup::with_name("input")
+    ///             .args(&["c", "i"])
+    ///     ])
+    /// # ;
+    /// ```
+    /// [`ArgGroup`]: ./struct.ArgGroup.html
+    /// [`App`]: ./struct.App.html
+    pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self {
+        for g in groups {
+            self = self.group(g.into());
+        }
+        self
+    }
+
+    /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively
+    /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
+    /// etc. They also function just like [`App`]s, in that they get their own auto generated help,
+    /// version, and usage.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    /// App::new("myprog")
+    ///     .subcommand(SubCommand::with_name("config")
+    ///         .about("Controls configuration features")
+    ///         .arg_from_usage("<config> 'Required configuration file to use'"))
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    pub fn subcommand(mut self, subcmd: App<'a, 'b>) -> Self {
+        self.p.add_subcommand(subcmd);
+        self
+    }
+
+    /// Adds multiple subcommands to the list of valid possibilities by iterating over an
+    /// [`IntoIterator`] of [`SubCommand`]s
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, SubCommand};
+    /// # App::new("myprog")
+    /// .subcommands( vec![
+    ///        SubCommand::with_name("config").about("Controls configuration functionality")
+    ///                                 .arg(Arg::with_name("config_file").index(1)),
+    ///        SubCommand::with_name("debug").about("Controls debug functionality")])
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
+    pub fn subcommands<I>(mut self, subcmds: I) -> Self
+    where
+        I: IntoIterator<Item = App<'a, 'b>>,
+    {
+        for subcmd in subcmds {
+            self.p.add_subcommand(subcmd);
+        }
+        self
+    }
+
+    /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower
+    /// value will be displayed first in the help message. This is helpful when one would like to
+    /// emphasise frequently used subcommands, or prioritize those towards the top of the list.
+    /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
+    /// displayed in alphabetical order.
+    ///
+    /// **NOTE:** The default is 999 for all subcommands.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, SubCommand};
+    /// let m = App::new("cust-ord")
+    ///     .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped
+    ///                                                // alphabetically by name. Subcommands
+    ///                                                // without a display_order have a value of
+    ///                                                // 999 and are displayed alphabetically with
+    ///                                                // all other 999 subcommands
+    ///         .about("Some help and text"))
+    ///     .subcommand(SubCommand::with_name("beta")
+    ///         .display_order(1)   // In order to force this subcommand to appear *first*
+    ///                             // all we have to do is give it a value lower than 999.
+    ///                             // Any other subcommands with a value of 1 will be displayed
+    ///                             // alphabetically with this one...then 2 values, then 3, etc.
+    ///         .about("I should be first!"))
+    ///     .get_matches_from(vec![
+    ///         "cust-ord", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays the following help message
+    ///
+    /// ```text
+    /// cust-ord
+    ///
+    /// USAGE:
+    ///     cust-ord [FLAGS] [OPTIONS]
+    ///
+    /// FLAGS:
+    ///     -h, --help       Prints help information
+    ///     -V, --version    Prints version information
+    ///
+    /// SUBCOMMANDS:
+    ///     beta    I should be first!
+    ///     alpha   Some help and text
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    pub fn display_order(mut self, ord: usize) -> Self {
+        self.p.meta.disp_ord = ord;
+        self
+    }
+
+    /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
+    /// method as if someone ran `-h` to request the help message
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
+    /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// let mut app = App::new("myprog");
+    /// app.print_help();
+    /// ```
+    /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
+    /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
+    /// [`-h` (short)]: ./struct.Arg.html#method.help
+    /// [`--help` (long)]: ./struct.Arg.html#method.long_help
+    pub fn print_help(&mut self) -> ClapResult<()> {
+        // If there are global arguments, or settings we need to propagate them down to subcommands
+        // before parsing incase we run into a subcommand
+        self.p.propagate_globals();
+        self.p.propagate_settings();
+        self.p.derive_display_order();
+
+        self.p.create_help_and_version();
+        let out = io::stdout();
+        let mut buf_w = BufWriter::new(out.lock());
+        self.write_help(&mut buf_w)
+    }
+
+    /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
+    /// method as if someone ran `--help` to request the help message
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
+    /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// let mut app = App::new("myprog");
+    /// app.print_long_help();
+    /// ```
+    /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
+    /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
+    /// [`-h` (short)]: ./struct.Arg.html#method.help
+    /// [`--help` (long)]: ./struct.Arg.html#method.long_help
+    pub fn print_long_help(&mut self) -> ClapResult<()> {
+        let out = io::stdout();
+        let mut buf_w = BufWriter::new(out.lock());
+        self.write_long_help(&mut buf_w)
+    }
+
+    /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
+    /// the user ran `-h`
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
+    /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
+    ///
+    /// **NOTE:** There is a known bug where this method does not write propagated global arguments
+    /// or autogenerated arguments (i.e. the default help/version args). Prefer
+    /// [`App::write_long_help`] instead if possible!
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// use std::io;
+    /// let mut app = App::new("myprog");
+    /// let mut out = io::stdout();
+    /// app.write_help(&mut out).expect("failed to write to stdout");
+    /// ```
+    /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+    /// [`-h` (short)]: ./struct.Arg.html#method.help
+    /// [`--help` (long)]: ./struct.Arg.html#method.long_help
+    pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        // PENDING ISSUE: 808
+        //      https://github.com/clap-rs/clap/issues/808
+        // If there are global arguments, or settings we need to propagate them down to subcommands
+        // before parsing incase we run into a subcommand
+        // self.p.propagate_globals();
+        // self.p.propagate_settings();
+        // self.p.derive_display_order();
+        // self.p.create_help_and_version();
+
+        Help::write_app_help(w, self, false)
+    }
+
+    /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
+    /// the user ran `--help`
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
+    /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// use std::io;
+    /// let mut app = App::new("myprog");
+    /// let mut out = io::stdout();
+    /// app.write_long_help(&mut out).expect("failed to write to stdout");
+    /// ```
+    /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+    /// [`-h` (short)]: ./struct.Arg.html#method.help
+    /// [`--help` (long)]: ./struct.Arg.html#method.long_help
+    pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> ClapResult<()> {
+        // If there are global arguments, or settings we need to propagate them down to subcommands
+        // before parsing incase we run into a subcommand
+        self.p.propagate_globals();
+        self.p.propagate_settings();
+        self.p.derive_display_order();
+        self.p.create_help_and_version();
+
+        Help::write_app_help(w, self, true)
+    }
+
+    /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`.
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
+    /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// use std::io;
+    /// let mut app = App::new("myprog");
+    /// let mut out = io::stdout();
+    /// app.write_version(&mut out).expect("failed to write to stdout");
+    /// ```
+    /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+    /// [`-V` (short)]: ./struct.App.html#method.version
+    /// [`--version` (long)]: ./struct.App.html#method.long_version
+    pub fn write_version<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        self.p.write_version(w, false).map_err(From::from)
+    }
+
+    /// Writes the version message to the user to a [`io::Write`] object
+    ///
+    /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
+    /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::App;
+    /// use std::io;
+    /// let mut app = App::new("myprog");
+    /// let mut out = io::stdout();
+    /// app.write_long_version(&mut out).expect("failed to write to stdout");
+    /// ```
+    /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
+    /// [`-V` (short)]: ./struct.App.html#method.version
+    /// [`--version` (long)]: ./struct.App.html#method.long_version
+    pub fn write_long_version<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        self.p.write_version(w, true).map_err(From::from)
+    }
+
+    /// Generate a completions file for a specified shell at compile time.
+    ///
+    /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script"
+    ///
+    /// # Examples
+    ///
+    /// The following example generates a bash completion script via a `build.rs` script. In this
+    /// simple example, we'll demo a very small application with only a single subcommand and two
+    /// args. Real applications could be many multiple levels deep in subcommands, and have tens or
+    /// potentially hundreds of arguments.
+    ///
+    /// First, it helps if we separate out our `App` definition into a separate file. Whether you
+    /// do this as a function, or bare App definition is a matter of personal preference.
+    ///
+    /// ```
+    /// // src/cli.rs
+    ///
+    /// use clap::{App, Arg, SubCommand};
+    ///
+    /// pub fn build_cli() -> App<'static, 'static> {
+    ///     App::new("compl")
+    ///         .about("Tests completions")
+    ///         .arg(Arg::with_name("file")
+    ///             .help("some input file"))
+    ///         .subcommand(SubCommand::with_name("test")
+    ///             .about("tests things")
+    ///             .arg(Arg::with_name("case")
+    ///                 .long("case")
+    ///                 .takes_value(true)
+    ///                 .help("the case to test")))
+    /// }
+    /// ```
+    ///
+    /// In our regular code, we can simply call this `build_cli()` function, then call
+    /// `get_matches()`, or any of the other normal methods directly after. For example:
+    ///
+    /// ```ignore
+    /// // src/main.rs
+    ///
+    /// mod cli;
+    ///
+    /// fn main() {
+    ///     let m = cli::build_cli().get_matches();
+    ///
+    ///     // normal logic continues...
+    /// }
+    /// ```
+    ///
+    /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
+    ///
+    /// ```toml
+    /// # Cargo.toml
+    /// build = "build.rs"
+    ///
+    /// [build-dependencies]
+    /// clap = "2.23"
+    /// ```
+    ///
+    /// Next, we place a `build.rs` in our project root.
+    ///
+    /// ```ignore
+    /// extern crate clap;
+    ///
+    /// use clap::Shell;
+    ///
+    /// include!("src/cli.rs");
+    ///
+    /// fn main() {
+    ///     let outdir = match env::var_os("OUT_DIR") {
+    ///         None => return,
+    ///         Some(outdir) => outdir,
+    ///     };
+    ///     let mut app = build_cli();
+    ///     app.gen_completions("myapp",      // We need to specify the bin name manually
+    ///                         Shell::Bash,  // Then say which shell to build completions for
+    ///                         outdir);      // Then say where write the completions to
+    /// }
+    /// ```
+    /// Now, once we compile there will be a `{bin_name}.bash` file in the directory.
+    /// Assuming we compiled with debug mode, it would be somewhere similar to
+    /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash`.
+    ///
+    /// Fish shell completions will use the file format `{bin_name}.fish`
+    pub fn gen_completions<T: Into<OsString>, S: Into<String>>(
+        &mut self,
+        bin_name: S,
+        for_shell: Shell,
+        out_dir: T,
+    ) {
+        self.p.meta.bin_name = Some(bin_name.into());
+        self.p.gen_completions(for_shell, out_dir.into());
+    }
+
+    /// Generate a completions file for a specified shell at runtime.  Until `cargo install` can
+    /// install extra files like a completion script, this may be used e.g. in a command that
+    /// outputs the contents of the completion script, to be redirected into a file by the user.
+    ///
+    /// # Examples
+    ///
+    /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions),
+    /// we can let users generate a completion script using a command:
+    ///
+    /// ```ignore
+    /// // src/main.rs
+    ///
+    /// mod cli;
+    /// use std::io;
+    ///
+    /// fn main() {
+    ///     let matches = cli::build_cli().get_matches();
+    ///
+    ///     if matches.is_present("generate-bash-completions") {
+    ///         cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout());
+    ///     }
+    ///
+    ///     // normal logic continues...
+    /// }
+    ///
+    /// ```
+    ///
+    /// Usage:
+    ///
+    /// ```shell
+    /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
+    /// ```
+    pub fn gen_completions_to<W: Write, S: Into<String>>(
+        &mut self,
+        bin_name: S,
+        for_shell: Shell,
+        buf: &mut W,
+    ) {
+        self.p.meta.bin_name = Some(bin_name.into());
+        self.p.gen_completions_to(for_shell, buf);
+    }
+
+    /// Starts the parsing process, upon a failed parse an error will be displayed to the user and
+    /// the process will exit with the appropriate error code. By default this method gets all user
+    /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
+    /// which are legal on many platforms.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let matches = App::new("myprog")
+    ///     // Args and options go here...
+    ///     .get_matches();
+    /// ```
+    /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
+    pub fn get_matches(self) -> ArgMatches<'a> {
+        self.get_matches_from(&mut env::args_os())
+    }
+
+    /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
+    /// the process on failed parse. By default this method gets matches from [`env::args_os`]
+    ///
+    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+    /// used. It will return a [`clap::Error`], where the [`kind`] is a
+    /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call
+    /// [`Error::exit`] or perform a [`std::process::exit`].
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let matches = App::new("myprog")
+    ///     // Args and options go here...
+    ///     .get_matches_safe()
+    ///     .unwrap_or_else( |e| e.exit() );
+    /// ```
+    /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
+    /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
+    /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
+    /// [`Error::exit`]: ./struct.Error.html#method.exit
+    /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
+    /// [`clap::Result`]: ./type.Result.html
+    /// [`clap::Error`]: ./struct.Error.html
+    /// [`kind`]: ./struct.Error.html
+    pub fn get_matches_safe(self) -> ClapResult<ArgMatches<'a>> {
+        // Start the parsing
+        self.get_matches_from_safe(&mut env::args_os())
+    }
+
+    /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
+    /// and will automatically exit with an error message. This method, however, lets you specify
+    /// what iterator to use when performing matches, such as a [`Vec`] of your making.
+    ///
+    /// **NOTE:** The first argument will be parsed as the binary name unless
+    /// [`AppSettings::NoBinaryName`] is used
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+    ///
+    /// let matches = App::new("myprog")
+    ///     // Args and options go here...
+    ///     .get_matches_from(arg_vec);
+    /// ```
+    /// [`App::get_matches`]: ./struct.App.html#method.get_matches
+    /// [`clap::Result`]: ./type.Result.html
+    /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
+    /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
+    pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches<'a>
+    where
+        I: IntoIterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| {
+            // Otherwise, write to stderr and exit
+            if e.use_stderr() {
+                wlnerr!("{}", e.message);
+                if self.p.is_set(AppSettings::WaitOnError) {
+                    wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
+                    let mut s = String::new();
+                    let i = io::stdin();
+                    i.lock().read_line(&mut s).unwrap();
+                }
+                drop(self);
+                drop(e);
+                process::exit(1);
+            }
+
+            drop(self);
+            e.exit()
+        })
+    }
+
+    /// Starts the parsing process. A combination of [`App::get_matches_from`], and
+    /// [`App::get_matches_safe`]
+    ///
+    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
+    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`]
+    /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or
+    /// perform a [`std::process::exit`] yourself.
+    ///
+    /// **NOTE:** The first argument will be parsed as the binary name unless
+    /// [`AppSettings::NoBinaryName`] is used
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+    ///
+    /// let matches = App::new("myprog")
+    ///     // Args and options go here...
+    ///     .get_matches_from_safe(arg_vec)
+    ///     .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
+    /// ```
+    /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from
+    /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe
+    /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
+    /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
+    /// [`Error::exit`]: ./struct.Error.html#method.exit
+    /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
+    /// [`clap::Error`]: ./struct.Error.html
+    /// [`Error::exit`]: ./struct.Error.html#method.exit
+    /// [`kind`]: ./struct.Error.html
+    /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
+    pub fn get_matches_from_safe<I, T>(mut self, itr: I) -> ClapResult<ArgMatches<'a>>
+    where
+        I: IntoIterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        self.get_matches_from_safe_borrow(itr)
+    }
+
+    /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
+    /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does*
+    /// consume `self`.
+    ///
+    /// **NOTE:** The first argument will be parsed as the binary name unless
+    /// [`AppSettings::NoBinaryName`] is used
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg};
+    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
+    ///
+    /// let mut app = App::new("myprog");
+    ///     // Args and options go here...
+    /// let matches = app.get_matches_from_safe_borrow(arg_vec)
+    ///     .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
+    /// ```
+    /// [`App`]: ./struct.App.html
+    /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe
+    /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
+    pub fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches<'a>>
+    where
+        I: IntoIterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        // If there are global arguments, or settings we need to propagate them down to subcommands
+        // before parsing incase we run into a subcommand
+        if !self.p.is_set(AppSettings::Propagated) {
+            self.p.propagate_globals();
+            self.p.propagate_settings();
+            self.p.derive_display_order();
+            self.p.set(AppSettings::Propagated);
+        }
+
+        let mut matcher = ArgMatcher::new();
+
+        let mut it = itr.into_iter();
+        // Get the name of the program (argument 1 of env::args()) and determine the
+        // actual file
+        // that was used to execute the program. This is because a program called
+        // ./target/release/my_prog -a
+        // will have two arguments, './target/release/my_prog', '-a' but we don't want
+        // to display
+        // the full path when displaying help messages and such
+        if !self.p.is_set(AppSettings::NoBinaryName) {
+            if let Some(name) = it.next() {
+                let bn_os = name.into();
+                let p = Path::new(&*bn_os);
+                if let Some(f) = p.file_name() {
+                    if let Some(s) = f.to_os_string().to_str() {
+                        if self.p.meta.bin_name.is_none() {
+                            self.p.meta.bin_name = Some(s.to_owned());
+                        }
+                    }
+                }
+            }
+        }
+
+        // do the real parsing
+        if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) {
+            return Err(e);
+        }
+
+        let global_arg_vec: Vec<&str> = self.p.global_args.iter().map(|ga| ga.b.name).collect();
+        matcher.propagate_globals(&global_arg_vec);
+
+        Ok(matcher.into())
+    }
+}
+
+#[cfg(feature = "yaml")]
+impl<'a> From<&'a Yaml> for App<'a, 'a> {
+    fn from(mut yaml: &'a Yaml) -> Self {
+        use crate::args::SubCommand;
+        // We WANT this to panic on error...so expect() is good.
+        let mut is_sc = None;
+        let mut a = if let Some(name) = yaml["name"].as_str() {
+            App::new(name)
+        } else {
+            let yaml_hash = yaml.as_hash().unwrap();
+            let sc_key = yaml_hash.keys().nth(0).unwrap();
+            is_sc = Some(yaml_hash.get(sc_key).unwrap());
+            App::new(sc_key.as_str().unwrap())
+        };
+        yaml = if let Some(sc) = is_sc { sc } else { yaml };
+
+        macro_rules! yaml_str {
+            ($a:ident, $y:ident, $i:ident) => {
+                if let Some(v) = $y[stringify!($i)].as_str() {
+                    $a = $a.$i(v);
+                } else if $y[stringify!($i)] != Yaml::BadValue {
+                    panic!(
+                        "Failed to convert YAML value {:?} to a string",
+                        $y[stringify!($i)]
+                    );
+                }
+            };
+        }
+
+        yaml_str!(a, yaml, version);
+        yaml_str!(a, yaml, long_version);
+        yaml_str!(a, yaml, author);
+        yaml_str!(a, yaml, bin_name);
+        yaml_str!(a, yaml, about);
+        yaml_str!(a, yaml, long_about);
+        yaml_str!(a, yaml, before_help);
+        yaml_str!(a, yaml, after_help);
+        yaml_str!(a, yaml, template);
+        yaml_str!(a, yaml, usage);
+        yaml_str!(a, yaml, help);
+        yaml_str!(a, yaml, help_short);
+        yaml_str!(a, yaml, version_short);
+        yaml_str!(a, yaml, help_message);
+        yaml_str!(a, yaml, version_message);
+        yaml_str!(a, yaml, alias);
+        yaml_str!(a, yaml, visible_alias);
+
+        if let Some(v) = yaml["display_order"].as_i64() {
+            a = a.display_order(v as usize);
+        } else if yaml["display_order"] != Yaml::BadValue {
+            panic!(
+                "Failed to convert YAML value {:?} to a u64",
+                yaml["display_order"]
+            );
+        }
+        if let Some(v) = yaml["setting"].as_str() {
+            a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
+        } else if yaml["setting"] != Yaml::BadValue {
+            panic!(
+                "Failed to convert YAML value {:?} to an AppSetting",
+                yaml["setting"]
+            );
+        }
+        if let Some(v) = yaml["settings"].as_vec() {
+            for ys in v {
+                if let Some(s) = ys.as_str() {
+                    a = a.setting(s.parse().expect("unknown AppSetting found in YAML file"));
+                }
+            }
+        } else if let Some(v) = yaml["settings"].as_str() {
+            a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
+        } else if yaml["settings"] != Yaml::BadValue {
+            panic!(
+                "Failed to convert YAML value {:?} to a string",
+                yaml["settings"]
+            );
+        }
+        if let Some(v) = yaml["global_setting"].as_str() {
+            a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
+        } else if yaml["global_setting"] != Yaml::BadValue {
+            panic!(
+                "Failed to convert YAML value {:?} to an AppSetting",
+                yaml["setting"]
+            );
+        }
+        if let Some(v) = yaml["global_settings"].as_vec() {
+            for ys in v {
+                if let Some(s) = ys.as_str() {
+                    a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file"));
+                }
+            }
+        } else if let Some(v) = yaml["global_settings"].as_str() {
+            a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file"));
+        } else if yaml["global_settings"] != Yaml::BadValue {
+            panic!(
+                "Failed to convert YAML value {:?} to a string",
+                yaml["global_settings"]
+            );
+        }
+
+        macro_rules! vec_or_str {
+            ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{
+                let maybe_vec = $y[stringify!($as_vec)].as_vec();
+                if let Some(vec) = maybe_vec {
+                    for ys in vec {
+                        if let Some(s) = ys.as_str() {
+                            $a = $a.$as_single(s);
+                        } else {
+                            panic!("Failed to convert YAML value {:?} to a string", ys);
+                        }
+                    }
+                } else {
+                    if let Some(s) = $y[stringify!($as_vec)].as_str() {
+                        $a = $a.$as_single(s);
+                    } else if $y[stringify!($as_vec)] != Yaml::BadValue {
+                        panic!(
+                            "Failed to convert YAML value {:?} to either a vec or string",
+                            $y[stringify!($as_vec)]
+                        );
+                    }
+                }
+                $a
+            }};
+        }
+
+        a = vec_or_str!(a, yaml, aliases, alias);
+        a = vec_or_str!(a, yaml, visible_aliases, visible_alias);
+
+        if let Some(v) = yaml["args"].as_vec() {
+            for arg_yaml in v {
+                a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap()));
+            }
+        }
+        if let Some(v) = yaml["subcommands"].as_vec() {
+            for sc_yaml in v {
+                a = a.subcommand(SubCommand::from_yaml(sc_yaml));
+            }
+        }
+        if let Some(v) = yaml["groups"].as_vec() {
+            for ag_yaml in v {
+                a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap()));
+            }
+        }
+
+        a
+    }
+}
+
+impl<'a, 'b> Clone for App<'a, 'b> {
+    fn clone(&self) -> Self {
+        App { p: self.p.clone() }
+    }
+}
+
+impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> {
+    fn name(&self) -> &'n str {
+        ""
+    }
+    fn overrides(&self) -> Option<&[&'e str]> {
+        None
+    }
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
+        None
+    }
+    fn blacklist(&self) -> Option<&[&'e str]> {
+        None
+    }
+    fn required_unless(&self) -> Option<&[&'e str]> {
+        None
+    }
+    fn val_names(&self) -> Option<&VecMap<&'e str>> {
+        None
+    }
+    fn is_set(&self, _: ArgSettings) -> bool {
+        false
+    }
+    fn val_terminator(&self) -> Option<&'e str> {
+        None
+    }
+    fn set(&mut self, _: ArgSettings) {
+        unreachable!("App struct does not support AnyArg::set, this is a bug!")
+    }
+    fn has_switch(&self) -> bool {
+        false
+    }
+    fn max_vals(&self) -> Option<u64> {
+        None
+    }
+    fn num_vals(&self) -> Option<u64> {
+        None
+    }
+    fn possible_vals(&self) -> Option<&[&'e str]> {
+        None
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+        None
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+        None
+    }
+    fn min_vals(&self) -> Option<u64> {
+        None
+    }
+    fn short(&self) -> Option<char> {
+        None
+    }
+    fn long(&self) -> Option<&'e str> {
+        None
+    }
+    fn val_delim(&self) -> Option<char> {
+        None
+    }
+    fn takes_value(&self) -> bool {
+        true
+    }
+    fn help(&self) -> Option<&'e str> {
+        self.p.meta.about
+    }
+    fn long_help(&self) -> Option<&'e str> {
+        self.p.meta.long_about
+    }
+    fn default_val(&self) -> Option<&'e OsStr> {
+        None
+    }
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
+        None
+    }
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
+        None
+    }
+    fn longest_filter(&self) -> bool {
+        true
+    }
+    fn aliases(&self) -> Option<Vec<&'e str>> {
+        if let Some(ref aliases) = self.p.meta.aliases {
+            let vis_aliases: Vec<_> = aliases
+                .iter()
+                .filter_map(|&(n, v)| if v { Some(n) } else { None })
+                .collect();
+            if vis_aliases.is_empty() {
+                None
+            } else {
+                Some(vis_aliases)
+            }
+        } else {
+            None
+        }
+    }
+}
+
+impl<'n, 'e> fmt::Display for App<'n, 'e> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{}", self.p.meta.name)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/parser.rs
@@ -0,0 +1,2236 @@
+// Std
+#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
+use std::os::unix::ffi::OsStrExt;
+use std::{
+    cell::Cell,
+    ffi::{OsStr, OsString},
+    fmt::Display,
+    fs::File,
+    io::{self, BufWriter, Write},
+    iter::Peekable,
+    path::PathBuf,
+    slice::Iter,
+};
+
+// Internal
+#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))]
+use crate::osstringext::OsStrExt3;
+#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
+use crate::osstringext::OsStrExt3;
+use crate::{
+    app::{
+        help::Help, meta::AppMeta, settings::AppFlags, settings::AppSettings as AS, usage,
+        validator::Validator, App,
+    },
+    args::{
+        settings::ArgSettings, AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder,
+        PosBuilder, Switched,
+    },
+    completions::{ComplGen, Shell},
+    errors::Result as ClapResult,
+    errors::{Error, ErrorKind},
+    fmt::ColorWhen,
+    map::{self, VecMap},
+    osstringext::OsStrExt2,
+    suggestions, SubCommand, INTERNAL_ERROR_MSG, INVALID_UTF8,
+};
+
+#[derive(Debug, PartialEq, Copy, Clone)]
+#[doc(hidden)]
+pub enum ParseResult<'a> {
+    Flag,
+    Opt(&'a str),
+    Pos(&'a str),
+    MaybeHyphenValue,
+    MaybeNegNum,
+    NotFound,
+    ValuesDone,
+}
+
+#[allow(missing_debug_implementations)]
+#[doc(hidden)]
+#[derive(Clone, Default)]
+pub struct Parser<'a, 'b>
+where
+    'a: 'b,
+{
+    pub meta: AppMeta<'b>,
+    settings: AppFlags,
+    pub g_settings: AppFlags,
+    pub flags: Vec<FlagBuilder<'a, 'b>>,
+    pub opts: Vec<OptBuilder<'a, 'b>>,
+    pub positionals: VecMap<PosBuilder<'a, 'b>>,
+    pub subcommands: Vec<App<'a, 'b>>,
+    pub groups: Vec<ArgGroup<'a>>,
+    pub global_args: Vec<Arg<'a, 'b>>,
+    pub required: Vec<&'a str>,
+    pub r_ifs: Vec<(&'a str, &'b str, &'a str)>,
+    pub overrides: Vec<(&'b str, &'a str)>,
+    help_short: Option<char>,
+    version_short: Option<char>,
+    cache: Option<&'a str>,
+    pub help_message: Option<&'a str>,
+    pub version_message: Option<&'a str>,
+    cur_idx: Cell<usize>,
+}
+
+impl<'a, 'b> Parser<'a, 'b>
+where
+    'a: 'b,
+{
+    pub fn with_name(n: String) -> Self {
+        Parser {
+            meta: AppMeta::with_name(n),
+            g_settings: AppFlags::zeroed(),
+            cur_idx: Cell::new(0),
+            ..Default::default()
+        }
+    }
+
+    pub fn help_short(&mut self, s: &str) {
+        let c = s
+            .trim_left_matches(|c| c == '-')
+            .chars()
+            .next()
+            .unwrap_or('h');
+        self.help_short = Some(c);
+    }
+
+    pub fn version_short(&mut self, s: &str) {
+        let c = s
+            .trim_left_matches(|c| c == '-')
+            .chars()
+            .next()
+            .unwrap_or('V');
+        self.version_short = Some(c);
+    }
+
+    pub fn gen_completions_to<W: Write>(&mut self, for_shell: Shell, buf: &mut W) {
+        if !self.is_set(AS::Propagated) {
+            self.propagate_help_version();
+            self.build_bin_names();
+            self.propagate_globals();
+            self.propagate_settings();
+            self.set(AS::Propagated);
+        }
+
+        ComplGen::new(self).generate(for_shell, buf)
+    }
+
+    pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) {
+        use std::error::Error;
+
+        let out_dir = PathBuf::from(od);
+        let name = &*self.meta.bin_name.as_ref().unwrap().clone();
+        let file_name = match for_shell {
+            Shell::Bash => format!("{}.bash", name),
+            Shell::Fish => format!("{}.fish", name),
+            Shell::Zsh => format!("_{}", name),
+            Shell::PowerShell => format!("_{}.ps1", name),
+            Shell::Elvish => format!("{}.elv", name),
+        };
+
+        let mut file = match File::create(out_dir.join(file_name)) {
+            Err(why) => panic!("couldn't create completion file: {}", why.description()),
+            Ok(file) => file,
+        };
+        self.gen_completions_to(for_shell, &mut file)
+    }
+
+    #[inline]
+    fn app_debug_asserts(&self) -> bool {
+        assert!(self.verify_positionals());
+        let should_err = self.groups.iter().all(|g| {
+            g.args.iter().all(|arg| {
+                self.flags.iter().any(|f| &f.b.name == arg)
+                    || self.opts.iter().any(|o| &o.b.name == arg)
+                    || self.positionals.values().any(|p| &p.b.name == arg)
+                    || self.groups.iter().any(|g| &g.name == arg)
+            })
+        });
+        let g = self.groups.iter().find(|g| {
+            g.args.iter().any(|arg| {
+                !(self.flags.iter().any(|f| &f.b.name == arg)
+                    || self.opts.iter().any(|o| &o.b.name == arg)
+                    || self.positionals.values().any(|p| &p.b.name == arg)
+                    || self.groups.iter().any(|g| &g.name == arg))
+            })
+        });
+        assert!(
+            should_err,
+            "The group '{}' contains the arg '{}' that doesn't actually exist.",
+            g.unwrap().name,
+            g.unwrap()
+                .args
+                .iter()
+                .find(|arg| !(self.flags.iter().any(|f| &&f.b.name == arg)
+                    || self.opts.iter().any(|o| &&o.b.name == arg)
+                    || self.positionals.values().any(|p| &&p.b.name == arg)
+                    || self.groups.iter().any(|g| &&g.name == arg)))
+                .unwrap()
+        );
+        true
+    }
+
+    #[inline]
+    fn debug_asserts(&self, a: &Arg) -> bool {
+        assert!(
+            !arg_names!(self).any(|name| name == a.b.name),
+            "Non-unique argument name: {} is already in use",
+            a.b.name
+        );
+        if let Some(l) = a.s.long {
+            assert!(
+                !self.contains_long(l),
+                "Argument long must be unique\n\n\t--{} is already in use",
+                l
+            );
+        }
+        if let Some(s) = a.s.short {
+            assert!(
+                !self.contains_short(s),
+                "Argument short must be unique\n\n\t-{} is already in use",
+                s
+            );
+        }
+        let i = if a.index.is_none() {
+            self.positionals.len() + 1
+        } else {
+            a.index.unwrap() as usize
+        };
+        assert!(
+            !self.positionals.contains_key(i),
+            "Argument \"{}\" has the same index as another positional \
+             argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \
+             to take multiple values",
+            a.b.name
+        );
+        assert!(
+            !(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)),
+            "Global arguments cannot be required.\n\n\t'{}' is marked as \
+             global and required",
+            a.b.name
+        );
+        if a.b.is_set(ArgSettings::Last) {
+            assert!(
+                !self
+                    .positionals
+                    .values()
+                    .any(|p| p.b.is_set(ArgSettings::Last)),
+                "Only one positional argument may have last(true) set. Found two."
+            );
+            assert!(a.s.long.is_none(),
+                    "Flags or Options may not have last(true) set. {} has both a long and last(true) set.",
+                    a.b.name);
+            assert!(a.s.short.is_none(),
+                    "Flags or Options may not have last(true) set. {} has both a short and last(true) set.",
+                    a.b.name);
+        }
+        true
+    }
+
+    #[inline]
+    fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) {
+        if let Some(ref r_ifs) = a.r_ifs {
+            for &(arg, val) in r_ifs {
+                self.r_ifs.push((arg, val, a.b.name));
+            }
+        }
+    }
+
+    #[inline]
+    fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) {
+        if let Some(ref grps) = a.b.groups {
+            for g in grps {
+                let mut found = false;
+                if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) {
+                    ag.args.push(a.b.name);
+                    found = true;
+                }
+                if !found {
+                    let mut ag = ArgGroup::with_name(g);
+                    ag.args.push(a.b.name);
+                    self.groups.push(ag);
+                }
+            }
+        }
+    }
+
+    #[inline]
+    fn add_reqs(&mut self, a: &Arg<'a, 'b>) {
+        if a.is_set(ArgSettings::Required) {
+            // If the arg is required, add all it's requirements to master required list
+            self.required.push(a.b.name);
+            if let Some(ref areqs) = a.b.requires {
+                for name in areqs
+                    .iter()
+                    .filter(|&&(val, _)| val.is_none())
+                    .map(|&(_, name)| name)
+                {
+                    self.required.push(name);
+                }
+            }
+        }
+    }
+
+    #[inline]
+    fn implied_settings(&mut self, a: &Arg<'a, 'b>) {
+        if a.is_set(ArgSettings::Last) {
+            // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
+            // in the usage string don't get confused or left out.
+            self.set(AS::DontCollapseArgsInUsage);
+            self.set(AS::ContainsLast);
+        }
+        if let Some(l) = a.s.long {
+            if l == "version" {
+                self.unset(AS::NeedsLongVersion);
+            } else if l == "help" {
+                self.unset(AS::NeedsLongHelp);
+            }
+        }
+    }
+
+    // actually adds the arguments
+    pub fn add_arg(&mut self, a: Arg<'a, 'b>) {
+        // if it's global we have to clone anyways
+        if a.is_set(ArgSettings::Global) {
+            return self.add_arg_ref(&a);
+        }
+        debug_assert!(self.debug_asserts(&a));
+        self.add_conditional_reqs(&a);
+        self.add_arg_groups(&a);
+        self.add_reqs(&a);
+        self.implied_settings(&a);
+        if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
+            let i = if a.index.is_none() {
+                self.positionals.len() + 1
+            } else {
+                a.index.unwrap() as usize
+            };
+            self.positionals
+                .insert(i, PosBuilder::from_arg(a, i as u64));
+        } else if a.is_set(ArgSettings::TakesValue) {
+            let mut ob = OptBuilder::from(a);
+            ob.s.unified_ord = self.flags.len() + self.opts.len();
+            self.opts.push(ob);
+        } else {
+            let mut fb = FlagBuilder::from(a);
+            fb.s.unified_ord = self.flags.len() + self.opts.len();
+            self.flags.push(fb);
+        }
+    }
+    // actually adds the arguments but from a borrow (which means we have to do some cloning)
+    pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) {
+        debug_assert!(self.debug_asserts(a));
+        self.add_conditional_reqs(a);
+        self.add_arg_groups(a);
+        self.add_reqs(a);
+        self.implied_settings(a);
+        if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) {
+            let i = if a.index.is_none() {
+                self.positionals.len() + 1
+            } else {
+                a.index.unwrap() as usize
+            };
+            let pb = PosBuilder::from_arg_ref(a, i as u64);
+            self.positionals.insert(i, pb);
+        } else if a.is_set(ArgSettings::TakesValue) {
+            let mut ob = OptBuilder::from(a);
+            ob.s.unified_ord = self.flags.len() + self.opts.len();
+            self.opts.push(ob);
+        } else {
+            let mut fb = FlagBuilder::from(a);
+            fb.s.unified_ord = self.flags.len() + self.opts.len();
+            self.flags.push(fb);
+        }
+        if a.is_set(ArgSettings::Global) {
+            self.global_args.push(a.into());
+        }
+    }
+
+    pub fn add_group(&mut self, group: ArgGroup<'a>) {
+        if group.required {
+            self.required.push(group.name);
+            if let Some(ref reqs) = group.requires {
+                self.required.extend_from_slice(reqs);
+            }
+            //            if let Some(ref bl) = group.conflicts {
+            //                self.blacklist.extend_from_slice(bl);
+            //            }
+        }
+        if self.groups.iter().any(|g| g.name == group.name) {
+            let grp = self
+                .groups
+                .iter_mut()
+                .find(|g| g.name == group.name)
+                .expect(INTERNAL_ERROR_MSG);
+            grp.args.extend_from_slice(&group.args);
+            grp.requires = group.requires.clone();
+            grp.conflicts = group.conflicts.clone();
+            grp.required = group.required;
+        } else {
+            self.groups.push(group);
+        }
+    }
+
+    pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) {
+        debugln!(
+            "Parser::add_subcommand: term_w={:?}, name={}",
+            self.meta.term_w,
+            subcmd.p.meta.name
+        );
+        subcmd.p.meta.term_w = self.meta.term_w;
+        if subcmd.p.meta.name == "help" {
+            self.unset(AS::NeedsSubcommandHelp);
+        }
+
+        self.subcommands.push(subcmd);
+    }
+
+    pub fn propagate_settings(&mut self) {
+        debugln!(
+            "Parser::propagate_settings: self={}, g_settings={:#?}",
+            self.meta.name,
+            self.g_settings
+        );
+        for sc in &mut self.subcommands {
+            debugln!(
+                "Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}",
+                sc.p.meta.name,
+                sc.p.settings,
+                sc.p.g_settings
+            );
+            // We have to create a new scope in order to tell rustc the borrow of `sc` is
+            // done and to recursively call this method
+            {
+                let vsc = self.settings.is_set(AS::VersionlessSubcommands);
+                let gv = self.settings.is_set(AS::GlobalVersion);
+
+                if vsc {
+                    sc.p.set(AS::DisableVersion);
+                }
+                if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() {
+                    sc.p.set(AS::GlobalVersion);
+                    sc.p.meta.version = Some(self.meta.version.unwrap());
+                }
+                sc.p.settings = sc.p.settings | self.g_settings;
+                sc.p.g_settings = sc.p.g_settings | self.g_settings;
+                sc.p.meta.term_w = self.meta.term_w;
+                sc.p.meta.max_w = self.meta.max_w;
+            }
+            sc.p.propagate_settings();
+        }
+    }
+
+    pub fn derive_display_order(&mut self) {
+        if self.is_set(AS::DeriveDisplayOrder) {
+            let unified = self.is_set(AS::UnifiedHelpMessage);
+            for (i, o) in self
+                .opts
+                .iter_mut()
+                .enumerate()
+                .filter(|&(_, ref o)| o.s.disp_ord == 999)
+            {
+                o.s.disp_ord = if unified { o.s.unified_ord } else { i };
+            }
+            for (i, f) in self
+                .flags
+                .iter_mut()
+                .enumerate()
+                .filter(|&(_, ref f)| f.s.disp_ord == 999)
+            {
+                f.s.disp_ord = if unified { f.s.unified_ord } else { i };
+            }
+            for (i, sc) in &mut self
+                .subcommands
+                .iter_mut()
+                .enumerate()
+                .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999)
+            {
+                sc.p.meta.disp_ord = i;
+            }
+        }
+        for sc in &mut self.subcommands {
+            sc.p.derive_display_order();
+        }
+    }
+
+    pub fn required(&self) -> Iter<&str> {
+        self.required.iter()
+    }
+
+    #[inline]
+    pub fn has_args(&self) -> bool {
+        !(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty())
+    }
+
+    #[inline]
+    pub fn has_opts(&self) -> bool {
+        !self.opts.is_empty()
+    }
+
+    #[inline]
+    pub fn has_flags(&self) -> bool {
+        !self.flags.is_empty()
+    }
+
+    #[inline]
+    pub fn has_positionals(&self) -> bool {
+        !self.positionals.is_empty()
+    }
+
+    #[inline]
+    pub fn has_subcommands(&self) -> bool {
+        !self.subcommands.is_empty()
+    }
+
+    #[inline]
+    pub fn has_visible_opts(&self) -> bool {
+        if self.opts.is_empty() {
+            return false;
+        }
+        self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden))
+    }
+
+    #[inline]
+    pub fn has_visible_flags(&self) -> bool {
+        if self.flags.is_empty() {
+            return false;
+        }
+        self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden))
+    }
+
+    #[inline]
+    pub fn has_visible_positionals(&self) -> bool {
+        if self.positionals.is_empty() {
+            return false;
+        }
+        self.positionals
+            .values()
+            .any(|p| !p.is_set(ArgSettings::Hidden))
+    }
+
+    #[inline]
+    pub fn has_visible_subcommands(&self) -> bool {
+        self.has_subcommands()
+            && self
+                .subcommands
+                .iter()
+                .filter(|sc| sc.p.meta.name != "help")
+                .any(|sc| !sc.p.is_set(AS::Hidden))
+    }
+
+    #[inline]
+    pub fn is_set(&self, s: AS) -> bool {
+        self.settings.is_set(s)
+    }
+
+    #[inline]
+    pub fn set(&mut self, s: AS) {
+        self.settings.set(s)
+    }
+
+    #[inline]
+    pub fn unset(&mut self, s: AS) {
+        self.settings.unset(s)
+    }
+
+    pub fn verify_positionals(&self) -> bool {
+        // Because you must wait until all arguments have been supplied, this is the first chance
+        // to make assertions on positional argument indexes
+        //
+        // First we verify that the index highest supplied index, is equal to the number of
+        // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
+        // but no 2)
+        if let Some((idx, p)) = self.positionals.iter().rev().next() {
+            assert!(
+                !(idx != self.positionals.len()),
+                "Found positional argument \"{}\" whose index is {} but there \
+                 are only {} positional arguments defined",
+                p.b.name,
+                idx,
+                self.positionals.len()
+            );
+        }
+
+        // Next we verify that only the highest index has a .multiple(true) (if any)
+        if self.positionals.values().any(|a| {
+            a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len())
+        }) {
+            let mut it = self.positionals.values().rev();
+            let last = it.next().unwrap();
+            let second_to_last = it.next().unwrap();
+            // Either the final positional is required
+            // Or the second to last has a terminator or .last(true) set
+            let ok = last.is_set(ArgSettings::Required)
+                || (second_to_last.v.terminator.is_some()
+                    || second_to_last.b.is_set(ArgSettings::Last))
+                || last.is_set(ArgSettings::Last);
+            assert!(
+                ok,
+                "When using a positional argument with .multiple(true) that is *not the \
+                 last* positional argument, the last positional argument (i.e the one \
+                 with the highest index) *must* have .required(true) or .last(true) set."
+            );
+            let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last);
+            assert!(
+                ok,
+                "Only the last positional argument, or second to last positional \
+                 argument may be set to .multiple(true)"
+            );
+
+            let count = self
+                .positionals
+                .values()
+                .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none())
+                .count();
+            let ok = count <= 1
+                || (last.is_set(ArgSettings::Last)
+                    && last.is_set(ArgSettings::Multiple)
+                    && second_to_last.is_set(ArgSettings::Multiple)
+                    && count == 2);
+            assert!(
+                ok,
+                "Only one positional argument with .multiple(true) set is allowed per \
+                 command, unless the second one also has .last(true) set"
+            );
+        }
+
+        let mut found = false;
+        if self.is_set(AS::AllowMissingPositional) {
+            // Check that if a required positional argument is found, all positions with a lower
+            // index are also required.
+            let mut foundx2 = false;
+            for p in self.positionals.values().rev() {
+                if foundx2 && !p.b.settings.is_set(ArgSettings::Required) {
+                    assert!(
+                        p.b.is_set(ArgSettings::Required),
+                        "Found positional argument which is not required with a lower \
+                         index than a required positional argument by two or more: {:?} \
+                         index {}",
+                        p.b.name,
+                        p.index
+                    );
+                } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
+                    // Args that .last(true) don't count since they can be required and have
+                    // positionals with a lower index that aren't required
+                    // Imagine: prog <req1> [opt1] -- <req2>
+                    // Both of these are valid invocations:
+                    //      $ prog r1 -- r2
+                    //      $ prog r1 o1 -- r2
+                    if found {
+                        foundx2 = true;
+                        continue;
+                    }
+                    found = true;
+                    continue;
+                } else {
+                    found = false;
+                }
+            }
+        } else {
+            // Check that if a required positional argument is found, all positions with a lower
+            // index are also required
+            for p in self.positionals.values().rev() {
+                if found {
+                    assert!(
+                        p.b.is_set(ArgSettings::Required),
+                        "Found positional argument which is not required with a lower \
+                         index than a required positional argument: {:?} index {}",
+                        p.b.name,
+                        p.index
+                    );
+                } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) {
+                    // Args that .last(true) don't count since they can be required and have
+                    // positionals with a lower index that aren't required
+                    // Imagine: prog <req1> [opt1] -- <req2>
+                    // Both of these are valid invocations:
+                    //      $ prog r1 -- r2
+                    //      $ prog r1 o1 -- r2
+                    found = true;
+                    continue;
+                }
+            }
+        }
+        if self
+            .positionals
+            .values()
+            .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required))
+            && self.has_subcommands()
+            && !self.is_set(AS::SubcommandsNegateReqs)
+        {
+            panic!(
+                "Having a required positional argument with .last(true) set *and* child \
+                 subcommands without setting SubcommandsNegateReqs isn't compatible."
+            );
+        }
+
+        true
+    }
+
+    pub fn propagate_globals(&mut self) {
+        for sc in &mut self.subcommands {
+            // We have to create a new scope in order to tell rustc the borrow of `sc` is
+            // done and to recursively call this method
+            {
+                for a in &self.global_args {
+                    sc.p.add_arg_ref(a);
+                }
+            }
+            sc.p.propagate_globals();
+        }
+    }
+
+    // Checks if the arg matches a subcommand name, or any of it's aliases (if defined)
+    fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) {
+        debugln!("Parser::possible_subcommand: arg={:?}", arg_os);
+        fn starts(h: &str, n: &OsStr) -> bool {
+            let n_bytes = n.as_bytes();
+            let h_bytes = OsStr::new(h).as_bytes();
+
+            h_bytes.starts_with(n_bytes)
+        }
+
+        if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) {
+            return (false, None);
+        }
+        if !self.is_set(AS::InferSubcommands) {
+            if let Some(sc) = find_subcmd!(self, arg_os) {
+                return (true, Some(&sc.p.meta.name));
+            }
+        } else {
+            let v = self
+                .subcommands
+                .iter()
+                .filter(|s| {
+                    starts(&s.p.meta.name[..], &*arg_os)
+                        || (s.p.meta.aliases.is_some()
+                            && s.p
+                                .meta
+                                .aliases
+                                .as_ref()
+                                .unwrap()
+                                .iter()
+                                .filter(|&&(a, _)| starts(a, &*arg_os))
+                                .count()
+                                == 1)
+                })
+                .map(|sc| &sc.p.meta.name)
+                .collect::<Vec<_>>();
+
+            for sc in &v {
+                if OsStr::new(sc) == arg_os {
+                    return (true, Some(sc));
+                }
+            }
+
+            if v.len() == 1 {
+                return (true, Some(v[0]));
+            }
+        }
+        (false, None)
+    }
+
+    fn parse_help_subcommand<I, T>(&self, it: &mut I) -> ClapResult<ParseResult<'a>>
+    where
+        I: Iterator<Item = T>,
+        T: Into<OsString>,
+    {
+        debugln!("Parser::parse_help_subcommand;");
+        let cmds: Vec<OsString> = it.map(|c| c.into()).collect();
+        let mut help_help = false;
+        let mut bin_name = self
+            .meta
+            .bin_name
+            .as_ref()
+            .unwrap_or(&self.meta.name)
+            .clone();
+        let mut sc = {
+            let mut sc: &Parser = self;
+            for (i, cmd) in cmds.iter().enumerate() {
+                if &*cmd.to_string_lossy() == "help" {
+                    // cmd help help
+                    help_help = true;
+                }
+                if let Some(c) = sc
+                    .subcommands
+                    .iter()
+                    .find(|s| &*s.p.meta.name == cmd)
+                    .map(|sc| &sc.p)
+                {
+                    sc = c;
+                    if i == cmds.len() - 1 {
+                        break;
+                    }
+                } else if let Some(c) = sc
+                    .subcommands
+                    .iter()
+                    .find(|s| {
+                        if let Some(ref als) = s.p.meta.aliases {
+                            als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy())
+                        } else {
+                            false
+                        }
+                    })
+                    .map(|sc| &sc.p)
+                {
+                    sc = c;
+                    if i == cmds.len() - 1 {
+                        break;
+                    }
+                } else {
+                    return Err(Error::unrecognized_subcommand(
+                        cmd.to_string_lossy().into_owned(),
+                        self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
+                        self.color(),
+                    ));
+                }
+                bin_name = format!("{} {}", bin_name, &*sc.meta.name);
+            }
+            sc.clone()
+        };
+        if help_help {
+            let mut pb = PosBuilder::new("subcommand", 1);
+            pb.b.help = Some("The subcommand whose help message to display");
+            pb.set(ArgSettings::Multiple);
+            sc.positionals.insert(1, pb);
+            sc.settings = sc.settings | self.g_settings;
+        } else {
+            sc.create_help_and_version();
+        }
+        if sc.meta.bin_name != self.meta.bin_name {
+            sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name));
+        }
+        Err(sc._help(false))
+    }
+
+    // allow wrong self convention due to self.valid_neg_num = true and it's a private method
+    #[cfg_attr(feature = "lints", allow(wrong_self_convention))]
+    fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult) -> bool {
+        debugln!("Parser::is_new_arg:{:?}:{:?}", arg_os, needs_val_of);
+        let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) {
+            true
+        } else if self.is_set(AS::AllowNegativeNumbers) {
+            let a = arg_os.to_string_lossy();
+            if a.parse::<i64>().is_ok() || a.parse::<f64>().is_ok() {
+                self.set(AS::ValidNegNumFound);
+                true
+            } else {
+                false
+            }
+        } else {
+            false
+        };
+        let arg_allows_tac = match needs_val_of {
+            ParseResult::Opt(name) => {
+                let o = self
+                    .opts
+                    .iter()
+                    .find(|o| o.b.name == name)
+                    .expect(INTERNAL_ERROR_MSG);
+                o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings
+            }
+            ParseResult::Pos(name) => {
+                let p = self
+                    .positionals
+                    .values()
+                    .find(|p| p.b.name == name)
+                    .expect(INTERNAL_ERROR_MSG);
+                p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings
+            }
+            ParseResult::ValuesDone => return true,
+            _ => false,
+        };
+        debugln!("Parser::is_new_arg: arg_allows_tac={:?}", arg_allows_tac);
+
+        // Is this a new argument, or values from a previous option?
+        let mut ret = if arg_os.starts_with(b"--") {
+            debugln!("Parser::is_new_arg: -- found");
+            if arg_os.len() == 2 && !arg_allows_tac {
+                return true; // We have to return true so override everything else
+            } else if arg_allows_tac {
+                return false;
+            }
+            true
+        } else if arg_os.starts_with(b"-") {
+            debugln!("Parser::is_new_arg: - found");
+            // a singe '-' by itself is a value and typically means "stdin" on unix systems
+            arg_os.len() != 1
+        } else {
+            debugln!("Parser::is_new_arg: probably value");
+            false
+        };
+
+        ret = ret && !arg_allows_tac;
+
+        debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret);
+        ret
+    }
+
+    // The actual parsing function
+    #[cfg_attr(
+        feature = "cargo-clippy",
+        allow(clippy::while_let_on_iterator, clippy::nonminimal_bool)
+    )]
+    pub fn get_matches_with<I, T>(
+        &mut self,
+        matcher: &mut ArgMatcher<'a>,
+        it: &mut Peekable<I>,
+    ) -> ClapResult<()>
+    where
+        I: Iterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        debugln!("Parser::get_matches_with;");
+        // Verify all positional assertions pass
+        debug_assert!(self.app_debug_asserts());
+        if self.positionals.values().any(|a| {
+            a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len())
+        }) && self
+            .positionals
+            .values()
+            .last()
+            .map_or(false, |p| !p.is_set(ArgSettings::Last))
+        {
+            self.settings.set(AS::LowIndexMultiplePositional);
+        }
+        let has_args = self.has_args();
+
+        // Next we create the `--help` and `--version` arguments and add them if
+        // necessary
+        self.create_help_and_version();
+
+        let mut subcmd_name: Option<String> = None;
+        let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound;
+        let mut pos_counter = 1;
+        let mut sc_is_external = false;
+        while let Some(arg) = it.next() {
+            let arg_os = arg.into();
+            debugln!(
+                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
+                arg_os,
+                &*arg_os.as_bytes()
+            );
+
+            self.unset(AS::ValidNegNumFound);
+            // Is this a new argument, or values from a previous option?
+            let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of);
+            if !self.is_set(AS::TrailingValues)
+                && arg_os.starts_with(b"--")
+                && arg_os.len() == 2
+                && starts_new_arg
+            {
+                debugln!("Parser::get_matches_with: setting TrailingVals=true");
+                self.set(AS::TrailingValues);
+                continue;
+            }
+
+            // Has the user already passed '--'? Meaning only positional args follow
+            if !self.is_set(AS::TrailingValues) {
+                // Does the arg match a subcommand name, or any of it's aliases (if defined)
+                {
+                    match needs_val_of {
+                        ParseResult::Opt(_) | ParseResult::Pos(_) => (),
+                        _ => {
+                            let (is_match, sc_name) = self.possible_subcommand(&arg_os);
+                            debugln!(
+                                "Parser::get_matches_with: possible_sc={:?}, sc={:?}",
+                                is_match,
+                                sc_name
+                            );
+                            if is_match {
+                                let sc_name = sc_name.expect(INTERNAL_ERROR_MSG);
+                                if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) {
+                                    self.parse_help_subcommand(it)?;
+                                }
+                                subcmd_name = Some(sc_name.to_owned());
+                                break;
+                            }
+                        }
+                    }
+                }
+
+                if starts_new_arg {
+                    let check_all = self.is_set(AS::AllArgsOverrideSelf);
+                    {
+                        let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
+                        matcher.process_arg_overrides(
+                            any_arg,
+                            &mut self.overrides,
+                            &mut self.required,
+                            check_all,
+                        );
+                    }
+
+                    if arg_os.starts_with(b"--") {
+                        needs_val_of = self.parse_long_arg(matcher, &arg_os, it)?;
+                        debugln!(
+                            "Parser:get_matches_with: After parse_long_arg {:?}",
+                            needs_val_of
+                        );
+                        match needs_val_of {
+                            ParseResult::Flag | ParseResult::Opt(..) | ParseResult::ValuesDone => {
+                                continue
+                            }
+                            _ => (),
+                        }
+                    } else if arg_os.starts_with(b"-") && arg_os.len() != 1 {
+                        // Try to parse short args like normal, if AllowLeadingHyphen or
+                        // AllowNegativeNumbers is set, parse_short_arg will *not* throw
+                        // an error, and instead return Ok(None)
+                        needs_val_of = self.parse_short_arg(matcher, &arg_os)?;
+                        // If it's None, we then check if one of those two AppSettings was set
+                        debugln!(
+                            "Parser:get_matches_with: After parse_short_arg {:?}",
+                            needs_val_of
+                        );
+                        match needs_val_of {
+                            ParseResult::MaybeNegNum => {
+                                if !(arg_os.to_string_lossy().parse::<i64>().is_ok()
+                                    || arg_os.to_string_lossy().parse::<f64>().is_ok())
+                                {
+                                    return Err(Error::unknown_argument(
+                                        &*arg_os.to_string_lossy(),
+                                        "",
+                                        &*usage::create_error_usage(self, matcher, None),
+                                        self.color(),
+                                    ));
+                                }
+                            }
+                            ParseResult::Opt(..) | ParseResult::Flag | ParseResult::ValuesDone => {
+                                continue
+                            }
+                            _ => (),
+                        }
+                    }
+                } else if let ParseResult::Opt(name) = needs_val_of {
+                    // Check to see if parsing a value from a previous arg
+                    let arg = self
+                        .opts
+                        .iter()
+                        .find(|o| o.b.name == name)
+                        .expect(INTERNAL_ERROR_MSG);
+                    // get the OptBuilder so we can check the settings
+                    needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?;
+                    // get the next value from the iterator
+                    continue;
+                }
+            }
+
+            if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound))
+                && !self.is_set(AS::InferSubcommands)
+                && !self.is_set(AS::AllowExternalSubcommands)
+            {
+                if let Some(cdate) =
+                    suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self))
+                {
+                    return Err(Error::invalid_subcommand(
+                        arg_os.to_string_lossy().into_owned(),
+                        cdate,
+                        self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
+                        &*usage::create_error_usage(self, matcher, None),
+                        self.color(),
+                    ));
+                }
+            }
+
+            let low_index_mults = self.is_set(AS::LowIndexMultiplePositional)
+                && pos_counter == (self.positionals.len() - 1);
+            let missing_pos = self.is_set(AS::AllowMissingPositional)
+                && (pos_counter == (self.positionals.len() - 1)
+                    && !self.is_set(AS::TrailingValues));
+            debugln!(
+                "Parser::get_matches_with: Positional counter...{}",
+                pos_counter
+            );
+            debugln!(
+                "Parser::get_matches_with: Low index multiples...{:?}",
+                low_index_mults
+            );
+            if low_index_mults || missing_pos {
+                if let Some(na) = it.peek() {
+                    let n = (*na).clone().into();
+                    needs_val_of = if needs_val_of != ParseResult::ValuesDone {
+                        if let Some(p) = self.positionals.get(pos_counter) {
+                            ParseResult::Pos(p.b.name)
+                        } else {
+                            ParseResult::ValuesDone
+                        }
+                    } else {
+                        ParseResult::ValuesDone
+                    };
+                    let sc_match = { self.possible_subcommand(&n).0 };
+                    if self.is_new_arg(&n, needs_val_of)
+                        || sc_match
+                        || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self))
+                            .is_some()
+                    {
+                        debugln!("Parser::get_matches_with: Bumping the positional counter...");
+                        pos_counter += 1;
+                    }
+                } else {
+                    debugln!("Parser::get_matches_with: Bumping the positional counter...");
+                    pos_counter += 1;
+                }
+            } else if (self.is_set(AS::AllowMissingPositional) && self.is_set(AS::TrailingValues))
+                || (self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues))
+            {
+                // Came to -- and one postional has .last(true) set, so we go immediately
+                // to the last (highest index) positional
+                debugln!("Parser::get_matches_with: .last(true) and --, setting last pos");
+                pos_counter = self.positionals.len();
+            }
+            if let Some(p) = self.positionals.get(pos_counter) {
+                if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) {
+                    return Err(Error::unknown_argument(
+                        &*arg_os.to_string_lossy(),
+                        "",
+                        &*usage::create_error_usage(self, matcher, None),
+                        self.color(),
+                    ));
+                }
+                if !self.is_set(AS::TrailingValues)
+                    && (self.is_set(AS::TrailingVarArg) && pos_counter == self.positionals.len())
+                {
+                    self.settings.set(AS::TrailingValues);
+                }
+                if self.cache.map_or(true, |name| name != p.b.name) {
+                    let check_all = self.is_set(AS::AllArgsOverrideSelf);
+                    {
+                        let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
+                        matcher.process_arg_overrides(
+                            any_arg,
+                            &mut self.overrides,
+                            &mut self.required,
+                            check_all,
+                        );
+                    }
+                    self.cache = Some(p.b.name);
+                }
+                let _ = self.add_val_to_arg(p, &arg_os, matcher)?;
+
+                matcher.inc_occurrence_of(p.b.name);
+                let _ = self
+                    .groups_for_arg(p.b.name)
+                    .map(|vec| matcher.inc_occurrences_of(&*vec));
+
+                self.settings.set(AS::ValidArgFound);
+                // Only increment the positional counter if it doesn't allow multiples
+                if !p.b.settings.is_set(ArgSettings::Multiple) {
+                    pos_counter += 1;
+                }
+                self.settings.set(AS::ValidArgFound);
+            } else if self.is_set(AS::AllowExternalSubcommands) {
+                // Get external subcommand name
+                let sc_name = match arg_os.to_str() {
+                    Some(s) => s.to_string(),
+                    None => {
+                        if !self.is_set(AS::StrictUtf8) {
+                            return Err(Error::invalid_utf8(
+                                &*usage::create_error_usage(self, matcher, None),
+                                self.color(),
+                            ));
+                        }
+                        arg_os.to_string_lossy().into_owned()
+                    }
+                };
+
+                // Collect the external subcommand args
+                let mut sc_m = ArgMatcher::new();
+                // Due to borrow rules, this has to be a while let...
+                #[cfg_attr(feature = "cargo-clippy", allow(clippy::while_let_on_iterator))]
+                while let Some(v) = it.next() {
+                    let a = v.into();
+                    if a.to_str().is_none() && !self.is_set(AS::StrictUtf8) {
+                        return Err(Error::invalid_utf8(
+                            &*usage::create_error_usage(self, matcher, None),
+                            self.color(),
+                        ));
+                    }
+                    sc_m.add_val_to("", &a);
+                }
+
+                matcher.subcommand(SubCommand {
+                    name: sc_name,
+                    matches: sc_m.into(),
+                });
+                sc_is_external = true;
+            } else if !((self.is_set(AS::AllowLeadingHyphen)
+                || self.is_set(AS::AllowNegativeNumbers))
+                && arg_os.starts_with(b"-"))
+                && !self.is_set(AS::InferSubcommands)
+            {
+                return Err(Error::unknown_argument(
+                    &*arg_os.to_string_lossy(),
+                    "",
+                    &*usage::create_error_usage(self, matcher, None),
+                    self.color(),
+                ));
+            } else if !has_args || self.is_set(AS::InferSubcommands) && self.has_subcommands() {
+                if let Some(cdate) =
+                    suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self))
+                {
+                    return Err(Error::invalid_subcommand(
+                        arg_os.to_string_lossy().into_owned(),
+                        cdate,
+                        self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
+                        &*usage::create_error_usage(self, matcher, None),
+                        self.color(),
+                    ));
+                } else {
+                    return Err(Error::unrecognized_subcommand(
+                        arg_os.to_string_lossy().into_owned(),
+                        self.meta.bin_name.as_ref().unwrap_or(&self.meta.name),
+                        self.color(),
+                    ));
+                }
+            } else {
+                return Err(Error::unknown_argument(
+                    &*arg_os.to_string_lossy(),
+                    "",
+                    &*usage::create_error_usage(self, matcher, None),
+                    self.color(),
+                ));
+            }
+        }
+
+        if !sc_is_external {
+            if let Some(ref pos_sc_name) = subcmd_name {
+                let sc_name = {
+                    find_subcmd!(self, pos_sc_name)
+                        .expect(INTERNAL_ERROR_MSG)
+                        .p
+                        .meta
+                        .name
+                        .clone()
+                };
+                self.parse_subcommand(&*sc_name, matcher, it)?;
+            } else if self.is_set(AS::SubcommandRequired) {
+                let bn = self.meta.bin_name.as_ref().unwrap_or(&self.meta.name);
+                return Err(Error::missing_subcommand(
+                    bn,
+                    &usage::create_error_usage(self, matcher, None),
+                    self.color(),
+                ));
+            } else if self.is_set(AS::SubcommandRequiredElseHelp) {
+                debugln!("Parser::get_matches_with: SubcommandRequiredElseHelp=true");
+                let mut out = vec![];
+                self.write_help_err(&mut out)?;
+                return Err(Error {
+                    message: String::from_utf8_lossy(&*out).into_owned(),
+                    kind: ErrorKind::MissingArgumentOrSubcommand,
+                    info: None,
+                });
+            }
+        }
+
+        // In case the last arg was new, we  need to process it's overrides
+        let check_all = self.is_set(AS::AllArgsOverrideSelf);
+        {
+            let any_arg = find_any_by_name!(self, self.cache.unwrap_or(""));
+            matcher.process_arg_overrides(
+                any_arg,
+                &mut self.overrides,
+                &mut self.required,
+                check_all,
+            );
+        }
+
+        self.remove_overrides(matcher);
+
+        Validator::new(self).validate(needs_val_of, subcmd_name, matcher)
+    }
+
+    fn remove_overrides(&mut self, matcher: &mut ArgMatcher) {
+        debugln!("Parser::remove_overrides:{:?};", self.overrides);
+        for &(overr, name) in &self.overrides {
+            debugln!("Parser::remove_overrides:iter:({},{});", overr, name);
+            if matcher.is_present(overr) {
+                debugln!(
+                    "Parser::remove_overrides:iter:({},{}): removing {};",
+                    overr,
+                    name,
+                    name
+                );
+                matcher.remove(name);
+                for i in (0..self.required.len()).rev() {
+                    debugln!(
+                        "Parser::remove_overrides:iter:({},{}): removing required {};",
+                        overr,
+                        name,
+                        name
+                    );
+                    if self.required[i] == name {
+                        self.required.swap_remove(i);
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    fn propagate_help_version(&mut self) {
+        debugln!("Parser::propagate_help_version;");
+        self.create_help_and_version();
+        for sc in &mut self.subcommands {
+            sc.p.propagate_help_version();
+        }
+    }
+
+    fn build_bin_names(&mut self) {
+        debugln!("Parser::build_bin_names;");
+        for sc in &mut self.subcommands {
+            debug!("Parser::build_bin_names:iter: bin_name set...");
+            if sc.p.meta.bin_name.is_none() {
+                sdebugln!("No");
+                let bin_name = format!(
+                    "{}{}{}",
+                    self.meta
+                        .bin_name
+                        .as_ref()
+                        .unwrap_or(&self.meta.name.clone()),
+                    if self.meta.bin_name.is_some() {
+                        " "
+                    } else {
+                        ""
+                    },
+                    &*sc.p.meta.name
+                );
+                debugln!(
+                    "Parser::build_bin_names:iter: Setting bin_name of {} to {}",
+                    self.meta.name,
+                    bin_name
+                );
+                sc.p.meta.bin_name = Some(bin_name);
+            } else {
+                sdebugln!("yes ({:?})", sc.p.meta.bin_name);
+            }
+            debugln!(
+                "Parser::build_bin_names:iter: Calling build_bin_names from...{}",
+                sc.p.meta.name
+            );
+            sc.p.build_bin_names();
+        }
+    }
+
+    fn parse_subcommand<I, T>(
+        &mut self,
+        sc_name: &str,
+        matcher: &mut ArgMatcher<'a>,
+        it: &mut Peekable<I>,
+    ) -> ClapResult<()>
+    where
+        I: Iterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        use std::fmt::Write;
+        debugln!("Parser::parse_subcommand;");
+        let mut mid_string = String::new();
+        if !self.is_set(AS::SubcommandsNegateReqs) {
+            let mut hs: Vec<&str> = self.required.iter().map(|n| &**n).collect();
+            for k in matcher.arg_names() {
+                hs.push(k);
+            }
+            let reqs = usage::get_required_usage_from(self, &hs, Some(matcher), None, false);
+
+            for s in &reqs {
+                write!(&mut mid_string, " {}", s).expect(INTERNAL_ERROR_MSG);
+            }
+        }
+        mid_string.push(' ');
+        if let Some(ref mut sc) = self
+            .subcommands
+            .iter_mut()
+            .find(|s| s.p.meta.name == sc_name)
+        {
+            let mut sc_matcher = ArgMatcher::new();
+            // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
+            // a space
+            sc.p.meta.usage = Some(format!(
+                "{}{}{}",
+                self.meta.bin_name.as_ref().unwrap_or(&String::new()),
+                if self.meta.bin_name.is_some() {
+                    &*mid_string
+                } else {
+                    ""
+                },
+                &*sc.p.meta.name
+            ));
+            sc.p.meta.bin_name = Some(format!(
+                "{}{}{}",
+                self.meta.bin_name.as_ref().unwrap_or(&String::new()),
+                if self.meta.bin_name.is_some() {
+                    " "
+                } else {
+                    ""
+                },
+                &*sc.p.meta.name
+            ));
+            debugln!(
+                "Parser::parse_subcommand: About to parse sc={}",
+                sc.p.meta.name
+            );
+            debugln!("Parser::parse_subcommand: sc settings={:#?}", sc.p.settings);
+            sc.p.get_matches_with(&mut sc_matcher, it)?;
+            matcher.subcommand(SubCommand {
+                name: sc.p.meta.name.clone(),
+                matches: sc_matcher.into(),
+            });
+        }
+        Ok(())
+    }
+
+    pub fn groups_for_arg(&self, name: &str) -> Option<Vec<&'a str>> {
+        debugln!("Parser::groups_for_arg: name={}", name);
+
+        if self.groups.is_empty() {
+            debugln!("Parser::groups_for_arg: No groups defined");
+            return None;
+        }
+        let mut res = vec![];
+        debugln!("Parser::groups_for_arg: Searching through groups...");
+        for grp in &self.groups {
+            for a in &grp.args {
+                if a == &name {
+                    sdebugln!("\tFound '{}'", grp.name);
+                    res.push(&*grp.name);
+                }
+            }
+        }
+        if res.is_empty() {
+            return None;
+        }
+
+        Some(res)
+    }
+
+    pub fn args_in_group(&self, group: &str) -> Vec<String> {
+        debug_assert!(self.app_debug_asserts());
+
+        let mut g_vec = vec![];
+        let mut args = vec![];
+
+        for n in &self
+            .groups
+            .iter()
+            .find(|g| g.name == group)
+            .expect(INTERNAL_ERROR_MSG)
+            .args
+        {
+            if let Some(f) = self.flags.iter().find(|f| &f.b.name == n) {
+                args.push(f.to_string());
+            } else if let Some(f) = self.opts.iter().find(|o| &o.b.name == n) {
+                args.push(f.to_string());
+            } else if let Some(p) = self.positionals.values().find(|p| &p.b.name == n) {
+                args.push(p.b.name.to_owned());
+            } else {
+                g_vec.push(*n);
+            }
+        }
+
+        for av in g_vec.iter().map(|g| self.args_in_group(g)) {
+            args.extend(av);
+        }
+        args.dedup();
+        args.iter().map(ToOwned::to_owned).collect()
+    }
+
+    pub fn arg_names_in_group(&self, group: &str) -> Vec<&'a str> {
+        let mut g_vec = vec![];
+        let mut args = vec![];
+
+        for n in &self
+            .groups
+            .iter()
+            .find(|g| g.name == group)
+            .expect(INTERNAL_ERROR_MSG)
+            .args
+        {
+            if self.groups.iter().any(|g| g.name == *n) {
+                args.extend(self.arg_names_in_group(n));
+                g_vec.push(*n);
+            } else if !args.contains(n) {
+                args.push(*n);
+            }
+        }
+
+        args.iter().copied().collect()
+    }
+
+    pub fn create_help_and_version(&mut self) {
+        debugln!("Parser::create_help_and_version;");
+        // name is "hclap_help" because flags are sorted by name
+        if !self.is_set(AS::DisableHelpFlags) && !self.contains_long("help") {
+            debugln!("Parser::create_help_and_version: Building --help");
+            if self.help_short.is_none() && !self.contains_short('h') {
+                self.help_short = Some('h');
+            }
+            let arg = FlagBuilder {
+                b: Base {
+                    name: "hclap_help",
+                    help: self.help_message.or(Some("Prints help information")),
+                    ..Default::default()
+                },
+                s: Switched {
+                    short: self.help_short,
+                    long: Some("help"),
+                    ..Default::default()
+                },
+            };
+            self.flags.push(arg);
+        }
+        if !self.is_set(AS::DisableVersion) && !self.contains_long("version") {
+            debugln!("Parser::create_help_and_version: Building --version");
+            if self.version_short.is_none() && !self.contains_short('V') {
+                self.version_short = Some('V');
+            }
+            // name is "vclap_version" because flags are sorted by name
+            let arg = FlagBuilder {
+                b: Base {
+                    name: "vclap_version",
+                    help: self.version_message.or(Some("Prints version information")),
+                    ..Default::default()
+                },
+                s: Switched {
+                    short: self.version_short,
+                    long: Some("version"),
+                    ..Default::default()
+                },
+            };
+            self.flags.push(arg);
+        }
+        if !self.subcommands.is_empty()
+            && !self.is_set(AS::DisableHelpSubcommand)
+            && self.is_set(AS::NeedsSubcommandHelp)
+        {
+            debugln!("Parser::create_help_and_version: Building help");
+            self.subcommands.push(
+                App::new("help")
+                    .about("Prints this message or the help of the given subcommand(s)"),
+            );
+        }
+    }
+
+    // Retrieves the names of all args the user has supplied thus far, except required ones
+    // because those will be listed in self.required
+    fn check_for_help_and_version_str(&self, arg: &OsStr) -> ClapResult<()> {
+        debugln!("Parser::check_for_help_and_version_str;");
+        debug!(
+            "Parser::check_for_help_and_version_str: Checking if --{} is help or version...",
+            arg.to_str().unwrap()
+        );
+        if arg == "help" && self.is_set(AS::NeedsLongHelp) {
+            sdebugln!("Help");
+            return Err(self._help(true));
+        }
+        if arg == "version" && self.is_set(AS::NeedsLongVersion) {
+            sdebugln!("Version");
+            return Err(self._version(true));
+        }
+        sdebugln!("Neither");
+
+        Ok(())
+    }
+
+    fn check_for_help_and_version_char(&self, arg: char) -> ClapResult<()> {
+        debugln!("Parser::check_for_help_and_version_char;");
+        debug!(
+            "Parser::check_for_help_and_version_char: Checking if -{} is help or version...",
+            arg
+        );
+        if let Some(h) = self.help_short {
+            if arg == h && self.is_set(AS::NeedsLongHelp) {
+                sdebugln!("Help");
+                return Err(self._help(false));
+            }
+        }
+        if let Some(v) = self.version_short {
+            if arg == v && self.is_set(AS::NeedsLongVersion) {
+                sdebugln!("Version");
+                return Err(self._version(false));
+            }
+        }
+        sdebugln!("Neither");
+        Ok(())
+    }
+
+    fn use_long_help(&self) -> bool {
+        // In this case, both must be checked. This allows the retention of
+        // original formatting, but also ensures that the actual -h or --help
+        // specified by the user is sent through. If HiddenShortHelp is not included,
+        // then items specified with hidden_short_help will also be hidden.
+        let should_long = |v: &Base| {
+            v.long_help.is_some()
+                || v.is_set(ArgSettings::HiddenLongHelp)
+                || v.is_set(ArgSettings::HiddenShortHelp)
+        };
+
+        self.meta.long_about.is_some()
+            || self.flags.iter().any(|f| should_long(&f.b))
+            || self.opts.iter().any(|o| should_long(&o.b))
+            || self.positionals.values().any(|p| should_long(&p.b))
+            || self
+                .subcommands
+                .iter()
+                .any(|s| s.p.meta.long_about.is_some())
+    }
+
+    fn _help(&self, mut use_long: bool) -> Error {
+        debugln!("Parser::_help: use_long={:?}", use_long);
+        use_long = use_long && self.use_long_help();
+        let mut buf = vec![];
+        match Help::write_parser_help(&mut buf, self, use_long) {
+            Err(e) => e,
+            _ => Error {
+                message: String::from_utf8(buf).unwrap_or_default(),
+                kind: ErrorKind::HelpDisplayed,
+                info: None,
+            },
+        }
+    }
+
+    fn _version(&self, use_long: bool) -> Error {
+        debugln!("Parser::_version: ");
+        let out = io::stdout();
+        let mut buf_w = BufWriter::new(out.lock());
+        match self.print_version(&mut buf_w, use_long) {
+            Err(e) => e,
+            _ => Error {
+                message: String::new(),
+                kind: ErrorKind::VersionDisplayed,
+                info: None,
+            },
+        }
+    }
+
+    fn parse_long_arg<I, T>(
+        &mut self,
+        matcher: &mut ArgMatcher<'a>,
+        full_arg: &OsStr,
+        it: &mut Peekable<I>,
+    ) -> ClapResult<ParseResult<'a>>
+    where
+        I: Iterator<Item = T>,
+        T: Into<OsString> + Clone,
+    {
+        // maybe here lifetime should be 'a
+        debugln!("Parser::parse_long_arg;");
+
+        // Update the current index
+        self.cur_idx.set(self.cur_idx.get() + 1);
+
+        let mut val = None;
+        debug!("Parser::parse_long_arg: Does it contain '='...");
+        let arg = if full_arg.contains_byte(b'=') {
+            let (p0, p1) = full_arg.trim_left_matches(b'-').split_at_byte(b'=');
+            sdebugln!("Yes '{:?}'", p1);
+            val = Some(p1);
+            p0
+        } else {
+            sdebugln!("No");
+            full_arg.trim_left_matches(b'-')
+        };
+
+        if let Some(opt) = find_opt_by_long!(@os self, arg) {
+            debugln!(
+                "Parser::parse_long_arg: Found valid opt '{}'",
+                opt.to_string()
+            );
+            self.settings.set(AS::ValidArgFound);
+            let ret = self.parse_opt(val, opt, val.is_some(), matcher)?;
+            if self.cache.map_or(true, |name| name != opt.b.name) {
+                self.cache = Some(opt.b.name);
+            }
+
+            return Ok(ret);
+        } else if let Some(flag) = find_flag_by_long!(@os self, arg) {
+            debugln!(
+                "Parser::parse_long_arg: Found valid flag '{}'",
+                flag.to_string()
+            );
+            self.settings.set(AS::ValidArgFound);
+            // Only flags could be help or version, and we need to check the raw long
+            // so this is the first point to check
+            self.check_for_help_and_version_str(arg)?;
+
+            self.parse_flag(flag, matcher)?;
+
+            // Handle conflicts, requirements, etc.
+            if self.cache.map_or(true, |name| name != flag.b.name) {
+                self.cache = Some(flag.b.name);
+            }
+
+            return Ok(ParseResult::Flag);
+        } else if self.is_set(AS::AllowLeadingHyphen) {
+            return Ok(ParseResult::MaybeHyphenValue);
+        } else if self.is_set(AS::ValidNegNumFound) {
+            return Ok(ParseResult::MaybeNegNum);
+        }
+
+        debugln!("Parser::parse_long_arg: Didn't match anything");
+
+        let args_rest: Vec<_> = it.map(|x| x.into()).collect();
+        let args_rest2: Vec<_> = args_rest
+            .iter()
+            .map(|x| x.to_str().expect(INVALID_UTF8))
+            .collect();
+        self.did_you_mean_error(arg.to_str().expect(INVALID_UTF8), matcher, &args_rest2[..])
+            .map(|_| ParseResult::NotFound)
+    }
+
+    fn parse_short_arg(
+        &mut self,
+        matcher: &mut ArgMatcher<'a>,
+        full_arg: &OsStr,
+    ) -> ClapResult<ParseResult<'a>> {
+        debugln!("Parser::parse_short_arg: full_arg={:?}", full_arg);
+        let arg_os = full_arg.trim_left_matches(b'-');
+        let arg = arg_os.to_string_lossy();
+
+        // If AllowLeadingHyphen is set, we want to ensure `-val` gets parsed as `-val` and not
+        // `-v` `-a` `-l` assuming `v` `a` and `l` are all, or mostly, valid shorts.
+        if self.is_set(AS::AllowLeadingHyphen) {
+            if arg.chars().any(|c| !self.contains_short(c)) {
+                debugln!(
+                    "Parser::parse_short_arg: LeadingHyphenAllowed yet -{} isn't valid",
+                    arg
+                );
+                return Ok(ParseResult::MaybeHyphenValue);
+            }
+        } else if self.is_set(AS::ValidNegNumFound) {
+            // TODO: Add docs about having AllowNegativeNumbers and `-2` as a valid short
+            // May be better to move this to *after* not finding a valid flag/opt?
+            debugln!("Parser::parse_short_arg: Valid negative num...");
+            return Ok(ParseResult::MaybeNegNum);
+        }
+
+        let mut ret = ParseResult::NotFound;
+        for c in arg.chars() {
+            debugln!("Parser::parse_short_arg:iter:{}", c);
+
+            // update each index because `-abcd` is four indices to clap
+            self.cur_idx.set(self.cur_idx.get() + 1);
+
+            // Check for matching short options, and return the name if there is no trailing
+            // concatenated value: -oval
+            // Option: -o
+            // Value: val
+            if let Some(opt) = find_opt_by_short!(self, c) {
+                debugln!("Parser::parse_short_arg:iter:{}: Found valid opt", c);
+                self.settings.set(AS::ValidArgFound);
+                // Check for trailing concatenated value
+                let p: Vec<_> = arg.splitn(2, c).collect();
+                debugln!(
+                    "Parser::parse_short_arg:iter:{}: p[0]={:?}, p[1]={:?}",
+                    c,
+                    p[0].as_bytes(),
+                    p[1].as_bytes()
+                );
+                let i = p[0].as_bytes().len() + 1;
+                let val = if !p[1].as_bytes().is_empty() {
+                    debugln!(
+                        "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii)",
+                        c,
+                        arg_os.split_at(i).1.as_bytes(),
+                        arg_os.split_at(i).1
+                    );
+                    Some(arg_os.split_at(i).1)
+                } else {
+                    None
+                };
+
+                // Default to "we're expecting a value later"
+                let ret = self.parse_opt(val, opt, false, matcher)?;
+
+                if self.cache.map_or(true, |name| name != opt.b.name) {
+                    self.cache = Some(opt.b.name);
+                }
+
+                return Ok(ret);
+            } else if let Some(flag) = find_flag_by_short!(self, c) {
+                debugln!("Parser::parse_short_arg:iter:{}: Found valid flag", c);
+                self.settings.set(AS::ValidArgFound);
+                // Only flags can be help or version
+                self.check_for_help_and_version_char(c)?;
+                ret = self.parse_flag(flag, matcher)?;
+
+                // Handle conflicts, requirements, overrides, etc.
+                // Must be called here due to mutabililty
+                if self.cache.map_or(true, |name| name != flag.b.name) {
+                    self.cache = Some(flag.b.name);
+                }
+            } else {
+                let arg = format!("-{}", c);
+                return Err(Error::unknown_argument(
+                    &*arg,
+                    "",
+                    &*usage::create_error_usage(self, matcher, None),
+                    self.color(),
+                ));
+            }
+        }
+        Ok(ret)
+    }
+
+    fn parse_opt(
+        &self,
+        val: Option<&OsStr>,
+        opt: &OptBuilder<'a, 'b>,
+        had_eq: bool,
+        matcher: &mut ArgMatcher<'a>,
+    ) -> ClapResult<ParseResult<'a>> {
+        debugln!("Parser::parse_opt; opt={}, val={:?}", opt.b.name, val);
+        debugln!("Parser::parse_opt; opt.settings={:?}", opt.b.settings);
+        let mut has_eq = false;
+        let no_val = val.is_none();
+        let empty_vals = opt.is_set(ArgSettings::EmptyValues);
+        let min_vals_zero = opt.v.min_vals.unwrap_or(1) == 0;
+        let needs_eq = opt.is_set(ArgSettings::RequireEquals);
+
+        debug!("Parser::parse_opt; Checking for val...");
+        if let Some(fv) = val {
+            has_eq = fv.starts_with(&[b'=']) || had_eq;
+            let v = fv.trim_left_matches(b'=');
+            if !empty_vals && (v.is_empty() || (needs_eq && !has_eq)) {
+                sdebugln!("Found Empty - Error");
+                return Err(Error::empty_value(
+                    opt,
+                    &*usage::create_error_usage(self, matcher, None),
+                    self.color(),
+                ));
+            }
+            sdebugln!("Found - {:?}, len: {}", v, v.len());
+            debugln!(
+                "Parser::parse_opt: {:?} contains '='...{:?}",
+                fv,
+                fv.starts_with(&[b'='])
+            );
+            self.add_val_to_arg(opt, v, matcher)?;
+        } else if needs_eq && !(empty_vals || min_vals_zero) {
+            sdebugln!("None, but requires equals...Error");
+            return Err(Error::empty_value(
+                opt,
+                &*usage::create_error_usage(self, matcher, None),
+                self.color(),
+            ));
+        } else {
+            sdebugln!("None");
+        }
+
+        matcher.inc_occurrence_of(opt.b.name);
+        // Increment or create the group "args"
+        if let Some(vec) = self.groups_for_arg(opt.b.name) {
+            matcher.inc_occurrences_of(&*vec);
+        }
+
+        let needs_delim = opt.is_set(ArgSettings::RequireDelimiter);
+        let mult = opt.is_set(ArgSettings::Multiple);
+        if no_val && min_vals_zero && !has_eq && needs_eq {
+            debugln!("Parser::parse_opt: More arg vals not required...");
+            return Ok(ParseResult::ValuesDone);
+        } else if no_val || (mult && !needs_delim) && !has_eq && matcher.needs_more_vals(opt) {
+            debugln!("Parser::parse_opt: More arg vals required...");
+            return Ok(ParseResult::Opt(opt.b.name));
+        }
+        debugln!("Parser::parse_opt: More arg vals not required...");
+        Ok(ParseResult::ValuesDone)
+    }
+
+    fn add_val_to_arg<A>(
+        &self,
+        arg: &A,
+        val: &OsStr,
+        matcher: &mut ArgMatcher<'a>,
+    ) -> ClapResult<ParseResult<'a>>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name(), val);
+        debugln!(
+            "Parser::add_val_to_arg; trailing_vals={:?}, DontDelimTrailingVals={:?}",
+            self.is_set(AS::TrailingValues),
+            self.is_set(AS::DontDelimitTrailingValues)
+        );
+        if !(self.is_set(AS::TrailingValues) && self.is_set(AS::DontDelimitTrailingValues)) {
+            if let Some(delim) = arg.val_delim() {
+                if val.is_empty() {
+                    Ok(self.add_single_val_to_arg(arg, val, matcher)?)
+                } else {
+                    let mut iret = ParseResult::ValuesDone;
+                    for v in val.split(delim as u32 as u8) {
+                        iret = self.add_single_val_to_arg(arg, v, matcher)?;
+                    }
+                    // If there was a delimiter used, we're not looking for more values
+                    if val.contains_byte(delim as u32 as u8)
+                        || arg.is_set(ArgSettings::RequireDelimiter)
+                    {
+                        iret = ParseResult::ValuesDone;
+                    }
+                    Ok(iret)
+                }
+            } else {
+                self.add_single_val_to_arg(arg, val, matcher)
+            }
+        } else {
+            self.add_single_val_to_arg(arg, val, matcher)
+        }
+    }
+
+    fn add_single_val_to_arg<A>(
+        &self,
+        arg: &A,
+        v: &OsStr,
+        matcher: &mut ArgMatcher<'a>,
+    ) -> ClapResult<ParseResult<'a>>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Parser::add_single_val_to_arg;");
+        debugln!("Parser::add_single_val_to_arg: adding val...{:?}", v);
+
+        // update the current index because each value is a distinct index to clap
+        self.cur_idx.set(self.cur_idx.get() + 1);
+
+        // @TODO @docs @p4: docs for indices should probably note that a terminator isn't a value
+        // and therefore not reported in indices
+        if let Some(t) = arg.val_terminator() {
+            if t == v {
+                return Ok(ParseResult::ValuesDone);
+            }
+        }
+
+        matcher.add_val_to(arg.name(), v);
+        matcher.add_index_to(arg.name(), self.cur_idx.get());
+
+        // Increment or create the group "args"
+        if let Some(grps) = self.groups_for_arg(arg.name()) {
+            for grp in grps {
+                matcher.add_val_to(&*grp, v);
+            }
+        }
+
+        if matcher.needs_more_vals(arg) {
+            return Ok(ParseResult::Opt(arg.name()));
+        }
+        Ok(ParseResult::ValuesDone)
+    }
+
+    fn parse_flag(
+        &self,
+        flag: &FlagBuilder<'a, 'b>,
+        matcher: &mut ArgMatcher<'a>,
+    ) -> ClapResult<ParseResult<'a>> {
+        debugln!("Parser::parse_flag;");
+
+        matcher.inc_occurrence_of(flag.b.name);
+        matcher.add_index_to(flag.b.name, self.cur_idx.get());
+
+        // Increment or create the group "args"
+        if let Some(vec) = self.groups_for_arg(flag.b.name) {
+            matcher.inc_occurrences_of(&*vec);
+        }
+
+        Ok(ParseResult::Flag)
+    }
+
+    fn did_you_mean_error(
+        &self,
+        arg: &str,
+        matcher: &mut ArgMatcher<'a>,
+        args_rest: &[&str],
+    ) -> ClapResult<()> {
+        // Didn't match a flag or option
+        let suffix =
+            suggestions::did_you_mean_flag_suffix(arg, args_rest, longs!(self), &self.subcommands);
+
+        // Add the arg to the matches to build a proper usage string
+        if let Some(name) = suffix.1 {
+            if let Some(opt) = find_opt_by_long!(self, name) {
+                if let Some(grps) = self.groups_for_arg(&*opt.b.name) {
+                    matcher.inc_occurrences_of(&*grps);
+                }
+                matcher.insert(&*opt.b.name);
+            } else if let Some(flg) = find_flag_by_long!(self, name) {
+                if let Some(grps) = self.groups_for_arg(&*flg.b.name) {
+                    matcher.inc_occurrences_of(&*grps);
+                }
+                matcher.insert(&*flg.b.name);
+            }
+        }
+
+        let used_arg = format!("--{}", arg);
+        Err(Error::unknown_argument(
+            &*used_arg,
+            &*suffix.0,
+            &*usage::create_error_usage(self, matcher, None),
+            self.color(),
+        ))
+    }
+
+    // Prints the version to the user and exits if quit=true
+    fn print_version<W: Write>(&self, w: &mut W, use_long: bool) -> ClapResult<()> {
+        self.write_version(w, use_long)?;
+        w.flush().map_err(Error::from)
+    }
+
+    pub fn write_version<W: Write>(&self, w: &mut W, use_long: bool) -> io::Result<()> {
+        let ver = if use_long {
+            self.meta
+                .long_version
+                .unwrap_or_else(|| self.meta.version.unwrap_or(""))
+        } else {
+            self.meta
+                .version
+                .unwrap_or_else(|| self.meta.long_version.unwrap_or(""))
+        };
+        if let Some(bn) = self.meta.bin_name.as_ref() {
+            if bn.contains(' ') {
+                // Incase we're dealing with subcommands i.e. git mv is translated to git-mv
+                write!(w, "{} {}", bn.replace(" ", "-"), ver)
+            } else {
+                write!(w, "{} {}", &self.meta.name[..], ver)
+            }
+        } else {
+            write!(w, "{} {}", &self.meta.name[..], ver)
+        }
+    }
+
+    pub fn print_help(&self) -> ClapResult<()> {
+        let out = io::stdout();
+        let mut buf_w = BufWriter::new(out.lock());
+        self.write_help(&mut buf_w)
+    }
+
+    pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        Help::write_parser_help(w, self, false)
+    }
+
+    pub fn write_long_help<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        Help::write_parser_help(w, self, true)
+    }
+
+    pub fn write_help_err<W: Write>(&self, w: &mut W) -> ClapResult<()> {
+        Help::write_parser_help_to_stderr(w, self)
+    }
+
+    pub fn add_defaults(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
+        debugln!("Parser::add_defaults;");
+        macro_rules! add_val {
+            (@default $_self:ident, $a:ident, $m:ident) => {
+                if let Some(ref val) = $a.v.default_val {
+                    debugln!("Parser::add_defaults:iter:{}: has default vals", $a.b.name);
+                    if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) {
+                        debugln!("Parser::add_defaults:iter:{}: has no user defined vals", $a.b.name);
+                        $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
+
+                        if $_self.cache.map_or(true, |name| name != $a.name()) {
+                            $_self.cache = Some($a.name());
+                        }
+                    } else if $m.get($a.b.name).is_some() {
+                        debugln!("Parser::add_defaults:iter:{}: has user defined vals", $a.b.name);
+                    } else {
+                        debugln!("Parser::add_defaults:iter:{}: wasn't used", $a.b.name);
+
+                        $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
+
+                        if $_self.cache.map_or(true, |name| name != $a.name()) {
+                            $_self.cache = Some($a.name());
+                        }
+                    }
+                } else {
+                    debugln!("Parser::add_defaults:iter:{}: doesn't have default vals", $a.b.name);
+                }
+            };
+            ($_self:ident, $a:ident, $m:ident) => {
+                if let Some(ref vm) = $a.v.default_vals_ifs {
+                    sdebugln!(" has conditional defaults");
+                    let mut done = false;
+                    if $m.get($a.b.name).is_none() {
+                        for &(arg, val, default) in vm.values() {
+                            let add = if let Some(a) = $m.get(arg) {
+                                if let Some(v) = val {
+                                    a.vals.iter().any(|value| v == value)
+                                } else {
+                                    true
+                                }
+                            } else {
+                                false
+                            };
+                            if add {
+                                $_self.add_val_to_arg($a, OsStr::new(default), $m)?;
+                                if $_self.cache.map_or(true, |name| name != $a.name()) {
+                                    $_self.cache = Some($a.name());
+                                }
+                                done = true;
+                                break;
+                            }
+                        }
+                    }
+
+                    if done {
+                        continue; // outer loop (outside macro)
+                    }
+                } else {
+                    sdebugln!(" doesn't have conditional defaults");
+                }
+                add_val!(@default $_self, $a, $m)
+            };
+        }
+
+        for o in &self.opts {
+            debug!("Parser::add_defaults:iter:{}:", o.b.name);
+            add_val!(self, o, matcher);
+        }
+        for p in self.positionals.values() {
+            debug!("Parser::add_defaults:iter:{}:", p.b.name);
+            add_val!(self, p, matcher);
+        }
+        Ok(())
+    }
+
+    pub fn add_env(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
+        macro_rules! add_val {
+            ($_self:ident, $a:ident, $m:ident) => {
+                if let Some(ref val) = $a.v.env {
+                    if $m
+                        .get($a.b.name)
+                        .map(|ma| ma.vals.len())
+                        .map(|len| len == 0)
+                        .unwrap_or(false)
+                    {
+                        if let Some(ref val) = val.1 {
+                            $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
+
+                            if $_self.cache.map_or(true, |name| name != $a.name()) {
+                                $_self.cache = Some($a.name());
+                            }
+                        }
+                    } else {
+                        if let Some(ref val) = val.1 {
+                            $_self.add_val_to_arg($a, OsStr::new(val), $m)?;
+
+                            if $_self.cache.map_or(true, |name| name != $a.name()) {
+                                $_self.cache = Some($a.name());
+                            }
+                        }
+                    }
+                }
+            };
+        }
+
+        for o in &self.opts {
+            add_val!(self, o, matcher);
+        }
+        for p in self.positionals.values() {
+            add_val!(self, p, matcher);
+        }
+        Ok(())
+    }
+
+    pub fn flags(&self) -> Iter<FlagBuilder<'a, 'b>> {
+        self.flags.iter()
+    }
+
+    pub fn opts(&self) -> Iter<OptBuilder<'a, 'b>> {
+        self.opts.iter()
+    }
+
+    pub fn positionals(&self) -> map::Values<PosBuilder<'a, 'b>> {
+        self.positionals.values()
+    }
+
+    pub fn subcommands(&self) -> Iter<App> {
+        self.subcommands.iter()
+    }
+
+    // Should we color the output? None=determined by output location, true=yes, false=no
+    #[doc(hidden)]
+    pub fn color(&self) -> ColorWhen {
+        debugln!("Parser::color;");
+        debug!("Parser::color: Color setting...");
+        if self.is_set(AS::ColorNever) {
+            sdebugln!("Never");
+            ColorWhen::Never
+        } else if self.is_set(AS::ColorAlways) {
+            sdebugln!("Always");
+            ColorWhen::Always
+        } else {
+            sdebugln!("Auto");
+            ColorWhen::Auto
+        }
+    }
+
+    pub fn find_any_arg(&self, name: &str) -> Option<&AnyArg<'a, 'b>> {
+        if let Some(f) = find_by_name!(self, name, flags, iter) {
+            return Some(f);
+        }
+        if let Some(o) = find_by_name!(self, name, opts, iter) {
+            return Some(o);
+        }
+        if let Some(p) = find_by_name!(self, name, positionals, values) {
+            return Some(p);
+        }
+        None
+    }
+
+    /// Check is a given string matches the binary name for this parser
+    fn is_bin_name(&self, value: &str) -> bool {
+        self.meta
+            .bin_name
+            .as_ref()
+            .map(|name| value == name)
+            .unwrap_or(false)
+    }
+
+    /// Check is a given string is an alias for this parser
+    fn is_alias(&self, value: &str) -> bool {
+        self.meta
+            .aliases
+            .as_ref()
+            .map(|aliases| {
+                for alias in aliases {
+                    if alias.0 == value {
+                        return true;
+                    }
+                }
+                false
+            })
+            .unwrap_or(false)
+    }
+
+    // Only used for completion scripts due to bin_name messiness
+    #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))]
+    pub fn find_subcommand(&'b self, sc: &str) -> Option<&'b App<'a, 'b>> {
+        debugln!("Parser::find_subcommand: sc={}", sc);
+        debugln!(
+            "Parser::find_subcommand: Currently in Parser...{}",
+            self.meta.bin_name.as_ref().unwrap()
+        );
+        for s in &self.subcommands {
+            if s.p.is_bin_name(sc) {
+                return Some(s);
+            }
+            // XXX: why do we split here?
+            // isn't `sc` supposed to be single word already?
+            let last = sc.split(' ').rev().next().expect(INTERNAL_ERROR_MSG);
+            if s.p.is_alias(last) {
+                return Some(s);
+            }
+
+            if let Some(app) = s.p.find_subcommand(sc) {
+                return Some(app);
+            }
+        }
+        None
+    }
+
+    #[inline]
+    fn contains_long(&self, l: &str) -> bool {
+        longs!(self).any(|al| al == &l)
+    }
+
+    #[inline]
+    fn contains_short(&self, s: char) -> bool {
+        shorts!(self).any(|arg_s| arg_s == &s)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/settings.rs
@@ -0,0 +1,1192 @@
+// Std
+#[allow(deprecated, unused_imports)]
+use std::ascii::AsciiExt;
+use std::ops::BitOr;
+use std::str::FromStr;
+
+bitflags! {
+    struct Flags: u64 {
+        const SC_NEGATE_REQS       = 1;
+        const SC_REQUIRED          = 1 << 1;
+        const A_REQUIRED_ELSE_HELP = 1 << 2;
+        const GLOBAL_VERSION       = 1 << 3;
+        const VERSIONLESS_SC       = 1 << 4;
+        const UNIFIED_HELP         = 1 << 5;
+        const WAIT_ON_ERROR        = 1 << 6;
+        const SC_REQUIRED_ELSE_HELP= 1 << 7;
+        const NEEDS_LONG_HELP      = 1 << 8;
+        const NEEDS_LONG_VERSION   = 1 << 9;
+        const NEEDS_SC_HELP        = 1 << 10;
+        const DISABLE_VERSION      = 1 << 11;
+        const HIDDEN               = 1 << 12;
+        const TRAILING_VARARG      = 1 << 13;
+        const NO_BIN_NAME          = 1 << 14;
+        const ALLOW_UNK_SC         = 1 << 15;
+        const UTF8_STRICT          = 1 << 16;
+        const UTF8_NONE            = 1 << 17;
+        const LEADING_HYPHEN       = 1 << 18;
+        const NO_POS_VALUES        = 1 << 19;
+        const NEXT_LINE_HELP       = 1 << 20;
+        const DERIVE_DISP_ORDER    = 1 << 21;
+        const COLORED_HELP         = 1 << 22;
+        const COLOR_ALWAYS         = 1 << 23;
+        const COLOR_AUTO           = 1 << 24;
+        const COLOR_NEVER          = 1 << 25;
+        const DONT_DELIM_TRAIL     = 1 << 26;
+        const ALLOW_NEG_NUMS       = 1 << 27;
+        const LOW_INDEX_MUL_POS    = 1 << 28;
+        const DISABLE_HELP_SC      = 1 << 29;
+        const DONT_COLLAPSE_ARGS   = 1 << 30;
+        const ARGS_NEGATE_SCS      = 1 << 31;
+        const PROPAGATE_VALS_DOWN  = 1 << 32;
+        const ALLOW_MISSING_POS    = 1 << 33;
+        const TRAILING_VALUES      = 1 << 34;
+        const VALID_NEG_NUM_FOUND  = 1 << 35;
+        const PROPAGATED           = 1 << 36;
+        const VALID_ARG_FOUND      = 1 << 37;
+        const INFER_SUBCOMMANDS    = 1 << 38;
+        const CONTAINS_LAST        = 1 << 39;
+        const ARGS_OVERRIDE_SELF   = 1 << 40;
+        const DISABLE_HELP_FLAGS   = 1 << 41;
+    }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub struct AppFlags(Flags);
+
+impl BitOr for AppFlags {
+    type Output = Self;
+    fn bitor(self, rhs: Self) -> Self {
+        AppFlags(self.0 | rhs.0)
+    }
+}
+
+impl Default for AppFlags {
+    fn default() -> Self {
+        AppFlags(
+            Flags::NEEDS_LONG_VERSION
+                | Flags::NEEDS_LONG_HELP
+                | Flags::NEEDS_SC_HELP
+                | Flags::UTF8_NONE
+                | Flags::COLOR_AUTO,
+        )
+    }
+}
+
+#[allow(deprecated)]
+impl AppFlags {
+    pub fn new() -> Self {
+        AppFlags::default()
+    }
+    pub fn zeroed() -> Self {
+        AppFlags(Flags::empty())
+    }
+
+    impl_settings! { AppSettings,
+        ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP,
+        ArgsNegateSubcommands => Flags::ARGS_NEGATE_SCS,
+        AllArgsOverrideSelf => Flags::ARGS_OVERRIDE_SELF,
+        AllowExternalSubcommands => Flags::ALLOW_UNK_SC,
+        AllowInvalidUtf8 => Flags::UTF8_NONE,
+        AllowLeadingHyphen => Flags::LEADING_HYPHEN,
+        AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS,
+        AllowMissingPositional => Flags::ALLOW_MISSING_POS,
+        ColoredHelp => Flags::COLORED_HELP,
+        ColorAlways => Flags::COLOR_ALWAYS,
+        ColorAuto => Flags::COLOR_AUTO,
+        ColorNever => Flags::COLOR_NEVER,
+        DontDelimitTrailingValues => Flags::DONT_DELIM_TRAIL,
+        DontCollapseArgsInUsage => Flags::DONT_COLLAPSE_ARGS,
+        DeriveDisplayOrder => Flags::DERIVE_DISP_ORDER,
+        DisableHelpFlags => Flags::DISABLE_HELP_FLAGS,
+        DisableHelpSubcommand => Flags::DISABLE_HELP_SC,
+        DisableVersion => Flags::DISABLE_VERSION,
+        GlobalVersion => Flags::GLOBAL_VERSION,
+        HidePossibleValuesInHelp => Flags::NO_POS_VALUES,
+        Hidden => Flags::HIDDEN,
+        LowIndexMultiplePositional => Flags::LOW_INDEX_MUL_POS,
+        NeedsLongHelp => Flags::NEEDS_LONG_HELP,
+        NeedsLongVersion => Flags::NEEDS_LONG_VERSION,
+        NeedsSubcommandHelp => Flags::NEEDS_SC_HELP,
+        NoBinaryName => Flags::NO_BIN_NAME,
+        PropagateGlobalValuesDown=> Flags::PROPAGATE_VALS_DOWN,
+        StrictUtf8 => Flags::UTF8_STRICT,
+        SubcommandsNegateReqs => Flags::SC_NEGATE_REQS,
+        SubcommandRequired => Flags::SC_REQUIRED,
+        SubcommandRequiredElseHelp => Flags::SC_REQUIRED_ELSE_HELP,
+        TrailingVarArg => Flags::TRAILING_VARARG,
+        UnifiedHelpMessage => Flags::UNIFIED_HELP,
+        NextLineHelp => Flags::NEXT_LINE_HELP,
+        VersionlessSubcommands => Flags::VERSIONLESS_SC,
+        WaitOnError => Flags::WAIT_ON_ERROR,
+        TrailingValues => Flags::TRAILING_VALUES,
+        ValidNegNumFound => Flags::VALID_NEG_NUM_FOUND,
+        Propagated => Flags::PROPAGATED,
+        ValidArgFound => Flags::VALID_ARG_FOUND,
+        InferSubcommands => Flags::INFER_SUBCOMMANDS,
+        ContainsLast => Flags::CONTAINS_LAST
+    }
+}
+
+/// Application level settings, which affect how [`App`] operates
+///
+/// **NOTE:** When these settings are used, they apply only to current command, and are *not*
+/// propagated down or up through child or parent subcommands
+///
+/// [`App`]: ./struct.App.html
+#[derive(Debug, PartialEq, Copy, Clone)]
+pub enum AppSettings {
+    /// Specifies that any invalid UTF-8 code points should *not* be treated as an error.
+    /// This is the default behavior of `clap`.
+    ///
+    /// **NOTE:** Using argument values with invalid UTF-8 code points requires using
+    /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`],
+    /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid
+    /// UTF-8 values
+    ///
+    /// **NOTE:** This rule only applies to  argument values, as flags, options, and
+    /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
+    ///
+    /// # Platform Specific
+    ///
+    /// Non Windows systems only
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, AppSettings};
+    /// use std::ffi::OsString;
+    /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+    ///
+    /// let r = App::new("myprog")
+    ///   //.setting(AppSettings::AllowInvalidUtf8)
+    ///     .arg_from_usage("<arg> 'some positional arg'")
+    ///     .get_matches_from_safe(
+    ///         vec![
+    ///             OsString::from("myprog"),
+    ///             OsString::from_vec(vec![0xe9])]);
+    ///
+    /// assert!(r.is_ok());
+    /// let m = r.unwrap();
+    /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]);
+    /// ```
+    /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of
+    /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of
+    /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of
+    /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    AllowInvalidUtf8,
+
+    /// Essentially sets [`Arg::overrides_with("itself")`] for all arguments.
+    ///
+    /// **WARNING:** Positional arguments cannot override themselves (or we would never be able
+    /// to advance to the next positional). This setting ignores positional arguments.
+    /// [`Arg::overrides_with("itself")`]: ./struct.Arg.html#method.overrides_with
+    AllArgsOverrideSelf,
+
+    /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers
+    /// like `-10`. (which would otherwise be parsed as another flag or option)
+    ///
+    /// **NOTE:** Use this setting with caution as it silences certain circumstances which would
+    /// otherwise be an error (such as accidentally forgetting to specify a value for leading
+    /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{Arg, App, AppSettings};
+    /// // Imagine you needed to represent negative numbers as well, such as -10
+    /// let m = App::new("nums")
+    ///     .setting(AppSettings::AllowLeadingHyphen)
+    ///     .arg(Arg::with_name("neg").index(1))
+    ///     .get_matches_from(vec![
+    ///         "nums", "-20"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("neg"), Some("-20"));
+    /// # ;
+    /// ```
+    /// [`Arg::allow_hyphen_values`]: ./struct.Arg.html#method.allow_hyphen_values
+    AllowLeadingHyphen,
+
+    /// Allows negative numbers to pass as values. This is similar to
+    /// `AllowLeadingHyphen` except that it only allows numbers, all
+    /// other undefined leading hyphens will fail to parse.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// let res = App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::AllowNegativeNumbers)
+    ///     .arg(Arg::with_name("num"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "-20"
+    ///     ]);
+    /// assert!(res.is_ok());
+    /// let m = res.unwrap();
+    /// assert_eq!(m.value_of("num").unwrap(), "-20");
+    /// ```
+    /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen
+    AllowNegativeNumbers,
+
+    /// Allows one to implement two styles of CLIs where positionals can be used out of order.
+    ///
+    /// The first example is a CLI where the second to last positional argument is optional, but
+    /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
+    /// of the two following usages is allowed:
+    ///
+    /// * `$ prog [optional] <required>`
+    /// * `$ prog <required>`
+    ///
+    /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
+    ///
+    /// **Note:** when using this style of "missing positionals" the final positional *must* be
+    /// [required] if `--` will not be used to skip to the final positional argument.
+    ///
+    /// **Note:** This style also only allows a single positional argument to be "skipped" without
+    /// the use of `--`. To skip more than one, see the second example.
+    ///
+    /// The second example is when one wants to skip multiple optional positional arguments, and use
+    /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
+    ///
+    /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
+    /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
+    ///
+    /// With this setting the following invocations are possible:
+    ///
+    /// * `$ prog foo bar baz1 baz2 baz3`
+    /// * `$ prog foo -- baz1 baz2 baz3`
+    /// * `$ prog -- baz1 baz2 baz3`
+    ///
+    /// # Examples
+    ///
+    /// Style number one from above:
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::AllowMissingPositional)
+    ///     .arg(Arg::with_name("arg1"))
+    ///     .arg(Arg::with_name("arg2")
+    ///         .required(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "other"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("arg1"), None);
+    /// assert_eq!(m.value_of("arg2"), Some("other"));
+    /// ```
+    ///
+    /// Now the same example, but using a default value for the first optional positional argument
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::AllowMissingPositional)
+    ///     .arg(Arg::with_name("arg1")
+    ///         .default_value("something"))
+    ///     .arg(Arg::with_name("arg2")
+    ///         .required(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "other"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("arg1"), Some("something"));
+    /// assert_eq!(m.value_of("arg2"), Some("other"));
+    /// ```
+    /// Style number two from above:
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::AllowMissingPositional)
+    ///     .arg(Arg::with_name("foo"))
+    ///     .arg(Arg::with_name("bar"))
+    ///     .arg(Arg::with_name("baz").multiple(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "foo", "bar", "baz1", "baz2", "baz3"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("foo"), Some("foo"));
+    /// assert_eq!(m.value_of("bar"), Some("bar"));
+    /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+    /// ```
+    ///
+    /// Now notice if we don't specify `foo` or `baz` but use the `--` operator.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::AllowMissingPositional)
+    ///     .arg(Arg::with_name("foo"))
+    ///     .arg(Arg::with_name("bar"))
+    ///     .arg(Arg::with_name("baz").multiple(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--", "baz1", "baz2", "baz3"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("foo"), None);
+    /// assert_eq!(m.value_of("bar"), None);
+    /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
+    /// ```
+    /// [required]: ./struct.Arg.html#method.required
+    AllowMissingPositional,
+
+    /// Specifies that an unexpected positional argument,
+    /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error,
+    /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct.
+    ///
+    /// **NOTE:** Use this setting with caution,
+    /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
+    /// will **not** cause an error and instead be treated as a potential subcommand.
+    /// One should check for such cases manually and inform the user appropriately.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::AllowExternalSubcommands)
+    ///     .get_matches_from(vec![
+    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+    ///     ]);
+    ///
+    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+    /// // string argument name
+    /// match m.subcommand() {
+    ///     (external, Some(ext_m)) => {
+    ///          let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
+    ///          assert_eq!(external, "subcmd");
+    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+    ///     },
+    ///     _ => {},
+    /// }
+    /// ```
+    /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    AllowExternalSubcommands,
+
+    /// Specifies that use of a valid [argument] negates [subcommands] being used after. By default
+    /// `clap` allows arguments between subcommands such as
+    /// `<cmd> [cmd_args] <cmd2> [cmd2_args] <cmd3> [cmd3_args]`. This setting disables that
+    /// functionality and says that arguments can only follow the *final* subcommand. For instance
+    /// using this setting makes only the following invocations possible:
+    ///
+    /// * `<cmd> <cmd2> <cmd3> [cmd3_args]`
+    /// * `<cmd> <cmd2> [cmd2_args]`
+    /// * `<cmd> [cmd_args]`
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ArgsNegateSubcommands)
+    /// # ;
+    /// ```
+    /// [subcommands]: ./struct.SubCommand.html
+    /// [argument]: ./struct.Arg.html
+    ArgsNegateSubcommands,
+
+    /// Specifies that the help text should be displayed (and then exit gracefully),
+    /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`.
+    ///
+    /// **NOTE:** [`SubCommand`]s count as arguments
+    ///
+    /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will
+    /// ensure that some argument is always present.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ArgRequiredElseHelp)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
+    ArgRequiredElseHelp,
+
+    /// Uses colorized help messages.
+    ///
+    /// **NOTE:** Must be compiled with the `color` cargo feature
+    ///
+    /// # Platform Specific
+    ///
+    /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ColoredHelp)
+    ///     .get_matches();
+    /// ```
+    ColoredHelp,
+
+    /// Enables colored output only when the output is going to a terminal or TTY.
+    ///
+    /// **NOTE:** This is the default behavior of `clap`.
+    ///
+    /// **NOTE:** Must be compiled with the `color` cargo feature.
+    ///
+    /// # Platform Specific
+    ///
+    /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ColorAuto)
+    ///     .get_matches();
+    /// ```
+    ColorAuto,
+
+    /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
+    ///
+    /// **NOTE:** Must be compiled with the `color` cargo feature.
+    ///
+    /// # Platform Specific
+    ///
+    /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms).
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ColorAlways)
+    ///     .get_matches();
+    /// ```
+    ColorAlways,
+
+    /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
+    ///
+    /// **NOTE:** Must be compiled with the `color` cargo feature
+    ///
+    /// # Platform Specific
+    ///
+    /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms)
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::ColorNever)
+    ///     .get_matches();
+    /// ```
+    ColorNever,
+
+    /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::DontCollapseArgsInUsage)
+    ///     .get_matches();
+    /// ```
+    DontCollapseArgsInUsage,
+
+    /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`]
+    /// was used.
+    ///
+    /// **NOTE:** The same thing can be done manually by setting the final positional argument to
+    /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate
+    /// when making changes.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::DontDelimitTrailingValues)
+    ///     .get_matches();
+    /// ```
+    /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
+    /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
+    DontDelimitTrailingValues,
+
+    /// Disables `-h` and `--help` [`App`] without affecting any of the [`SubCommand`]s
+    /// (Defaults to `false`; application *does* have help flags)
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings, ErrorKind};
+    /// let res = App::new("myprog")
+    ///     .setting(AppSettings::DisableHelpFlags)
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "-h"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
+    /// let res = App::new("myprog")
+    ///     .setting(AppSettings::DisableHelpFlags)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "test", "-h"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    DisableHelpFlags,
+
+    /// Disables the `help` subcommand
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings, ErrorKind, SubCommand};
+    /// let res = App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::DisableHelpSubcommand)
+    ///     // Normally, creating a subcommand causes a `help` subcommand to automatically
+    ///     // be generated as well
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "help"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    DisableHelpSubcommand,
+
+    /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s
+    /// (Defaults to `false`; application *does* have a version flag)
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings, ErrorKind};
+    /// let res = App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::DisableVersion)
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "-V"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
+    /// let res = App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::DisableVersion)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "test", "-V"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    DisableVersion,
+
+    /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were
+    /// declared in, and not alphabetically which is the default.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::DeriveDisplayOrder)
+    ///     .get_matches();
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    DeriveDisplayOrder,
+
+    /// Specifies to use the version of the current command for all child [`SubCommand`]s.
+    /// (Defaults to `false`; subcommands have independent version strings from their parents.)
+    ///
+    /// **NOTE:** The version for the current command **and** this setting must be set **prior** to
+    /// adding any child subcommands
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::GlobalVersion)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches();
+    /// // running `$ myprog test --version` will display
+    /// // "myprog-test v1.1"
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    GlobalVersion,
+
+    /// Specifies that this [`SubCommand`] should be hidden from help messages
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, SubCommand};
+    /// App::new("myprog")
+    ///     .subcommand(SubCommand::with_name("test")
+    ///     .setting(AppSettings::Hidden))
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    Hidden,
+
+    /// Tells `clap` *not* to print possible values when displaying help information.
+    /// This can be useful if there are many values, or they are explained elsewhere.
+    HidePossibleValuesInHelp,
+
+    /// Tries to match unknown args to partial [`subcommands`] or their [aliases]. For example to
+    /// match a subcommand named `test`, one could use `t`, `te`, `tes`, and `test`.
+    ///
+    /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
+    /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
+    ///
+    /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
+    /// designing CLIs which allow inferred subcommands and have potential positional/free
+    /// arguments whose values could start with the same characters as subcommands. If this is the
+    /// case, it's recommended to use settings such as [`AppSeettings::ArgsNegateSubcommands`] in
+    /// conjunction with this setting.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// let m = App::new("prog")
+    ///     .setting(AppSettings::InferSubcommands)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "te"
+    ///     ]);
+    /// assert_eq!(m.subcommand_name(), Some("test"));
+    /// ```
+    /// [`subcommands`]: ./struct.SubCommand.html
+    /// [positional/free arguments]: ./struct.Arg.html#method.index
+    /// [aliases]: ./struct.App.html#method.alias
+    /// [`AppSeettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands
+    InferSubcommands,
+
+    /// Specifies that the parser should not assume the first argument passed is the binary name.
+    /// This is normally the case when using a "daemon" style mode, or an interactive CLI where one
+    /// one would not normally type the binary or program name for each command.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::NoBinaryName)
+    ///     .arg(Arg::from_usage("<cmd>... 'commands to run'"))
+    ///     .get_matches_from(vec!["command", "set"]);
+    ///
+    /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
+    /// assert_eq!(cmds, ["command", "set"]);
+    /// ```
+    NoBinaryName,
+
+    /// Places the help string for all arguments on the line after the argument.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::NextLineHelp)
+    ///     .get_matches();
+    /// ```
+    NextLineHelp,
+
+    /// **DEPRECATED**: This setting is no longer required in order to propagate values up or down
+    ///
+    /// Specifies that the parser should propagate global arg's values down or up through any *used*
+    /// child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to
+    /// said subcommand.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, SubCommand};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::from_usage("[cmd] 'command to run'")
+    ///         .global(true))
+    ///     .subcommand(SubCommand::with_name("foo"))
+    ///     .get_matches_from(vec!["myprog", "set", "foo"]);
+    ///
+    /// assert_eq!(m.value_of("cmd"), Some("set"));
+    ///
+    /// let sub_m = m.subcommand_matches("foo").unwrap();
+    /// assert_eq!(sub_m.value_of("cmd"), Some("set"));
+    /// ```
+    /// Now doing the same thing, but *not* using any subcommands will result in the value not being
+    /// propagated down.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, SubCommand};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::from_usage("[cmd] 'command to run'")
+    ///         .global(true))
+    ///     .subcommand(SubCommand::with_name("foo"))
+    ///     .get_matches_from(vec!["myprog", "set"]);
+    ///
+    /// assert_eq!(m.value_of("cmd"), Some("set"));
+    ///
+    /// assert!(m.subcommand_matches("foo").is_none());
+    /// ```
+    #[deprecated(since = "2.27.0", note = "No longer required to propagate values")]
+    PropagateGlobalValuesDown,
+
+    /// Allows [`SubCommand`]s to override all requirements of the parent command.
+    /// For example if you had a subcommand or top level application with a required argument
+    /// that is only required as long as there is no subcommand present,
+    /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
+    /// and yet receive no error so long as the user uses a valid subcommand instead.
+    ///
+    /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
+    ///
+    /// # Examples
+    ///
+    /// This first example shows that it is an error to not use a required argument
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
+    /// let err = App::new("myprog")
+    ///     .setting(AppSettings::SubcommandsNegateReqs)
+    ///     .arg(Arg::with_name("opt").required(true))
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog"
+    ///     ]);
+    /// assert!(err.is_err());
+    /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// # ;
+    /// ```
+    ///
+    /// This next example shows that it is no longer error to not use a required argument if a
+    /// valid subcommand is used.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
+    /// let noerr = App::new("myprog")
+    ///     .setting(AppSettings::SubcommandsNegateReqs)
+    ///     .arg(Arg::with_name("opt").required(true))
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "test"
+    ///     ]);
+    /// assert!(noerr.is_ok());
+    /// # ;
+    /// ```
+    /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    SubcommandsNegateReqs,
+
+    /// Specifies that the help text should be displayed (before exiting gracefully) if no
+    /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`).
+    ///
+    /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do
+    /// nearly same thing; this prints the help text, and the other prints an error.
+    ///
+    /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will
+    /// still be displayed and exit. If this is *not* the desired result, consider using
+    /// [`AppSettings::ArgRequiredElseHelp`] instead.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::SubcommandRequiredElseHelp)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired
+    /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp
+    SubcommandRequiredElseHelp,
+
+    /// Specifies that any invalid UTF-8 code points should be treated as an error and fail
+    /// with a [`ErrorKind::InvalidUtf8`] error.
+    ///
+    /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and
+    /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
+    ///
+    /// # Platform Specific
+    ///
+    /// Non Windows systems only
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, AppSettings, ErrorKind};
+    /// use std::ffi::OsString;
+    /// use std::os::unix::ffi::OsStringExt;
+    ///
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::StrictUtf8)
+    ///     .arg_from_usage("<arg> 'some positional arg'")
+    ///     .get_matches_from_safe(
+    ///         vec![
+    ///             OsString::from("myprog"),
+    ///             OsString::from_vec(vec![0xe9])]);
+    ///
+    /// assert!(m.is_err());
+    /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8
+    StrictUtf8,
+
+    /// Allows specifying that if no [`SubCommand`] is present at runtime,
+    /// error and exit gracefully.
+    ///
+    /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present)
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings, SubCommand, ErrorKind};
+    /// let err = App::new("myprog")
+    ///     .setting(AppSettings::SubcommandRequired)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog",
+    ///     ]);
+    /// assert!(err.is_err());
+    /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    SubcommandRequired,
+
+    /// Specifies that the final positional argument is a "VarArg" and that `clap` should not
+    /// attempt to parse any further args.
+    ///
+    /// The values of the trailing positional argument will contain all args from itself on.
+    ///
+    /// **NOTE:** The final positional argument **must** have [`Arg::multiple(true)`] or the usage
+    /// string equivalent.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// let m = App::new("myprog")
+    ///     .setting(AppSettings::TrailingVarArg)
+    ///     .arg(Arg::from_usage("<cmd>... 'commands to run'"))
+    ///     .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
+    ///
+    /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
+    /// assert_eq!(trail, ["arg1", "-r", "val1"]);
+    /// ```
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    TrailingVarArg,
+
+    /// Groups flags and options together, presenting a more unified help message
+    /// (a la `getopts` or `docopt` style).
+    ///
+    /// The default is that the auto-generated help message will group flags, and options
+    /// separately.
+    ///
+    /// **NOTE:** This setting is cosmetic only and does not affect any functionality.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::UnifiedHelpMessage)
+    ///     .get_matches();
+    /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message
+    /// ```
+    UnifiedHelpMessage,
+
+    /// Disables `-V` and `--version` for all [`SubCommand`]s
+    /// (Defaults to `false`; subcommands *do* have version flags.)
+    ///
+    /// **NOTE:** This setting must be set **prior** to adding any subcommands.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
+    /// let res = App::new("myprog")
+    ///     .version("v1.1")
+    ///     .setting(AppSettings::VersionlessSubcommands)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog", "test", "-V"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    VersionlessSubcommands,
+
+    /// Will display a message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before
+    /// exiting
+    ///
+    /// This is most useful when writing an application which is run from a GUI shortcut, or on
+    /// Windows where a user tries to open the binary by double-clicking instead of using the
+    /// command line.
+    ///
+    /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this
+    /// behavior for all subcommands, you must set this on each command (needing this is extremely
+    /// rare)
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings};
+    /// App::new("myprog")
+    ///     .setting(AppSettings::WaitOnError)
+    /// # ;
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    WaitOnError,
+
+    #[doc(hidden)]
+    NeedsLongVersion,
+
+    #[doc(hidden)]
+    NeedsLongHelp,
+
+    #[doc(hidden)]
+    NeedsSubcommandHelp,
+
+    #[doc(hidden)]
+    LowIndexMultiplePositional,
+
+    #[doc(hidden)]
+    TrailingValues,
+
+    #[doc(hidden)]
+    ValidNegNumFound,
+
+    #[doc(hidden)]
+    Propagated,
+
+    #[doc(hidden)]
+    ValidArgFound,
+
+    #[doc(hidden)]
+    ContainsLast,
+}
+
+impl FromStr for AppSettings {
+    type Err = String;
+    fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
+        match &*s.to_ascii_lowercase() {
+            "disablehelpflags" => Ok(AppSettings::DisableHelpFlags),
+            "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp),
+            "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands),
+            "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8),
+            "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen),
+            "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands),
+            "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers),
+            "colorauto" => Ok(AppSettings::ColorAuto),
+            "coloralways" => Ok(AppSettings::ColorAlways),
+            "colornever" => Ok(AppSettings::ColorNever),
+            "coloredhelp" => Ok(AppSettings::ColoredHelp),
+            "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder),
+            "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage),
+            "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues),
+            "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand),
+            "disableversion" => Ok(AppSettings::DisableVersion),
+            "globalversion" => Ok(AppSettings::GlobalVersion),
+            "hidden" => Ok(AppSettings::Hidden),
+            "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp),
+            "infersubcommands" => Ok(AppSettings::InferSubcommands),
+            "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional),
+            "nobinaryname" => Ok(AppSettings::NoBinaryName),
+            "nextlinehelp" => Ok(AppSettings::NextLineHelp),
+            "strictutf8" => Ok(AppSettings::StrictUtf8),
+            "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs),
+            "subcommandrequired" => Ok(AppSettings::SubcommandRequired),
+            "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp),
+            "trailingvararg" => Ok(AppSettings::TrailingVarArg),
+            "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage),
+            "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands),
+            "waitonerror" => Ok(AppSettings::WaitOnError),
+            "validnegnumfound" => Ok(AppSettings::ValidNegNumFound),
+            "validargfound" => Ok(AppSettings::ValidArgFound),
+            "propagated" => Ok(AppSettings::Propagated),
+            "trailingvalues" => Ok(AppSettings::TrailingValues),
+            _ => Err("unknown AppSetting, cannot convert from str".to_owned()),
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::AppSettings;
+
+    #[test]
+    fn app_settings_fromstr() {
+        assert_eq!(
+            "disablehelpflags".parse::<AppSettings>().unwrap(),
+            AppSettings::DisableHelpFlags
+        );
+        assert_eq!(
+            "argsnegatesubcommands".parse::<AppSettings>().unwrap(),
+            AppSettings::ArgsNegateSubcommands
+        );
+        assert_eq!(
+            "argrequiredelsehelp".parse::<AppSettings>().unwrap(),
+            AppSettings::ArgRequiredElseHelp
+        );
+        assert_eq!(
+            "allowexternalsubcommands".parse::<AppSettings>().unwrap(),
+            AppSettings::AllowExternalSubcommands
+        );
+        assert_eq!(
+            "allowinvalidutf8".parse::<AppSettings>().unwrap(),
+            AppSettings::AllowInvalidUtf8
+        );
+        assert_eq!(
+            "allowleadinghyphen".parse::<AppSettings>().unwrap(),
+            AppSettings::AllowLeadingHyphen
+        );
+        assert_eq!(
+            "allownegativenumbers".parse::<AppSettings>().unwrap(),
+            AppSettings::AllowNegativeNumbers
+        );
+        assert_eq!(
+            "coloredhelp".parse::<AppSettings>().unwrap(),
+            AppSettings::ColoredHelp
+        );
+        assert_eq!(
+            "colorauto".parse::<AppSettings>().unwrap(),
+            AppSettings::ColorAuto
+        );
+        assert_eq!(
+            "coloralways".parse::<AppSettings>().unwrap(),
+            AppSettings::ColorAlways
+        );
+        assert_eq!(
+            "colornever".parse::<AppSettings>().unwrap(),
+            AppSettings::ColorNever
+        );
+        assert_eq!(
+            "disablehelpsubcommand".parse::<AppSettings>().unwrap(),
+            AppSettings::DisableHelpSubcommand
+        );
+        assert_eq!(
+            "disableversion".parse::<AppSettings>().unwrap(),
+            AppSettings::DisableVersion
+        );
+        assert_eq!(
+            "dontcollapseargsinusage".parse::<AppSettings>().unwrap(),
+            AppSettings::DontCollapseArgsInUsage
+        );
+        assert_eq!(
+            "dontdelimittrailingvalues".parse::<AppSettings>().unwrap(),
+            AppSettings::DontDelimitTrailingValues
+        );
+        assert_eq!(
+            "derivedisplayorder".parse::<AppSettings>().unwrap(),
+            AppSettings::DeriveDisplayOrder
+        );
+        assert_eq!(
+            "globalversion".parse::<AppSettings>().unwrap(),
+            AppSettings::GlobalVersion
+        );
+        assert_eq!(
+            "hidden".parse::<AppSettings>().unwrap(),
+            AppSettings::Hidden
+        );
+        assert_eq!(
+            "hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(),
+            AppSettings::HidePossibleValuesInHelp
+        );
+        assert_eq!(
+            "lowindexmultiplePositional".parse::<AppSettings>().unwrap(),
+            AppSettings::LowIndexMultiplePositional
+        );
+        assert_eq!(
+            "nobinaryname".parse::<AppSettings>().unwrap(),
+            AppSettings::NoBinaryName
+        );
+        assert_eq!(
+            "nextlinehelp".parse::<AppSettings>().unwrap(),
+            AppSettings::NextLineHelp
+        );
+        assert_eq!(
+            "subcommandsnegatereqs".parse::<AppSettings>().unwrap(),
+            AppSettings::SubcommandsNegateReqs
+        );
+        assert_eq!(
+            "subcommandrequired".parse::<AppSettings>().unwrap(),
+            AppSettings::SubcommandRequired
+        );
+        assert_eq!(
+            "subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(),
+            AppSettings::SubcommandRequiredElseHelp
+        );
+        assert_eq!(
+            "strictutf8".parse::<AppSettings>().unwrap(),
+            AppSettings::StrictUtf8
+        );
+        assert_eq!(
+            "trailingvararg".parse::<AppSettings>().unwrap(),
+            AppSettings::TrailingVarArg
+        );
+        assert_eq!(
+            "unifiedhelpmessage".parse::<AppSettings>().unwrap(),
+            AppSettings::UnifiedHelpMessage
+        );
+        assert_eq!(
+            "versionlesssubcommands".parse::<AppSettings>().unwrap(),
+            AppSettings::VersionlessSubcommands
+        );
+        assert_eq!(
+            "waitonerror".parse::<AppSettings>().unwrap(),
+            AppSettings::WaitOnError
+        );
+        assert_eq!(
+            "validnegnumfound".parse::<AppSettings>().unwrap(),
+            AppSettings::ValidNegNumFound
+        );
+        assert_eq!(
+            "validargfound".parse::<AppSettings>().unwrap(),
+            AppSettings::ValidArgFound
+        );
+        assert_eq!(
+            "propagated".parse::<AppSettings>().unwrap(),
+            AppSettings::Propagated
+        );
+        assert_eq!(
+            "trailingvalues".parse::<AppSettings>().unwrap(),
+            AppSettings::TrailingValues
+        );
+        assert_eq!(
+            "infersubcommands".parse::<AppSettings>().unwrap(),
+            AppSettings::InferSubcommands
+        );
+        assert!("hahahaha".parse::<AppSettings>().is_err());
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/usage.rs
@@ -0,0 +1,493 @@
+// std
+use std::collections::{BTreeMap, VecDeque};
+
+// Internal
+use crate::{
+    app::{parser::Parser, settings::AppSettings as AS},
+    args::{settings::ArgSettings, AnyArg, ArgMatcher, PosBuilder},
+    INTERNAL_ERROR_MSG,
+};
+
+// Creates a usage string for display. This happens just after all arguments were parsed, but before
+// any subcommands have been parsed (so as to give subcommands their own usage recursively)
+pub fn create_usage_with_title(p: &Parser, used: &[&str]) -> String {
+    debugln!("usage::create_usage_with_title;");
+    let mut usage = String::with_capacity(75);
+    usage.push_str("USAGE:\n    ");
+    usage.push_str(&*create_usage_no_title(p, used));
+    usage
+}
+
+// Creates a usage string to be used in error message (i.e. one with currently used args)
+pub fn create_error_usage<'a, 'b>(
+    p: &Parser<'a, 'b>,
+    matcher: &'b ArgMatcher<'a>,
+    extra: Option<&str>,
+) -> String {
+    let mut args: Vec<_> = matcher
+        .arg_names()
+        .iter()
+        .filter(|n| {
+            if let Some(o) = find_by_name!(p, **n, opts, iter) {
+                !o.b.is_set(ArgSettings::Required) && !o.b.is_set(ArgSettings::Hidden)
+            } else if let Some(p) = find_by_name!(p, **n, positionals, values) {
+                !p.b.is_set(ArgSettings::Required) && p.b.is_set(ArgSettings::Hidden)
+            } else {
+                true // flags can't be required, so they're always true
+            }
+        })
+        .copied()
+        .collect();
+    if let Some(r) = extra {
+        args.push(r);
+    }
+    create_usage_with_title(p, &*args)
+}
+
+// Creates a usage string (*without title*) if one was not provided by the user manually.
+pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String {
+    debugln!("usage::create_usage_no_title;");
+    if let Some(u) = p.meta.usage_str {
+        String::from(&*u)
+    } else if used.is_empty() {
+        create_help_usage(p, true)
+    } else {
+        create_smart_usage(p, used)
+    }
+}
+
+// Creates a usage string for display in help messages (i.e. not for errors)
+pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String {
+    let mut usage = String::with_capacity(75);
+    let name = p
+        .meta
+        .usage
+        .as_ref()
+        .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name));
+    usage.push_str(&*name);
+    let req_string = if incl_reqs {
+        let mut reqs: Vec<&str> = p.required().map(|r| &**r).collect();
+        reqs.sort_unstable();
+        reqs.dedup();
+        get_required_usage_from(p, &reqs, None, None, false)
+            .iter()
+            .fold(String::new(), |a, s| a + &format!(" {}", s)[..])
+    } else {
+        String::new()
+    };
+
+    let flags = needs_flags_tag(p);
+    if flags && !p.is_set(AS::UnifiedHelpMessage) {
+        usage.push_str(" [FLAGS]");
+    } else if flags {
+        usage.push_str(" [OPTIONS]");
+    }
+    if !p.is_set(AS::UnifiedHelpMessage)
+        && p.opts
+            .iter()
+            .any(|o| !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden))
+    {
+        usage.push_str(" [OPTIONS]");
+    }
+
+    usage.push_str(&req_string[..]);
+
+    let has_last = p.positionals.values().any(|p| p.is_set(ArgSettings::Last));
+    // places a '--' in the usage string if there are args and options
+    // supporting multiple values
+    if p.opts.iter().any(|o| o.is_set(ArgSettings::Multiple))
+        && p.positionals
+            .values()
+            .any(|p| !p.is_set(ArgSettings::Required))
+        && !(p.has_visible_subcommands() || p.is_set(AS::AllowExternalSubcommands))
+        && !has_last
+    {
+        usage.push_str(" [--]");
+    }
+    let not_req_or_hidden = |p: &PosBuilder| {
+        (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last))
+            && !p.is_set(ArgSettings::Hidden)
+    };
+    if p.has_positionals() && p.positionals.values().any(not_req_or_hidden) {
+        if let Some(args_tag) = get_args_tag(p, incl_reqs) {
+            usage.push_str(&*args_tag);
+        } else {
+            usage.push_str(" [ARGS]");
+        }
+        if has_last && incl_reqs {
+            let pos = p
+                .positionals
+                .values()
+                .find(|p| p.b.is_set(ArgSettings::Last))
+                .expect(INTERNAL_ERROR_MSG);
+            debugln!("usage::create_help_usage: '{}' has .last(true)", pos.name());
+            let req = pos.is_set(ArgSettings::Required);
+            if req
+                && p.positionals
+                    .values()
+                    .any(|p| !p.is_set(ArgSettings::Required))
+            {
+                usage.push_str(" -- <");
+            } else if req {
+                usage.push_str(" [--] <");
+            } else {
+                usage.push_str(" [-- <");
+            }
+            usage.push_str(&*pos.name_no_brackets());
+            usage.push('>');
+            usage.push_str(pos.multiple_str());
+            if !req {
+                usage.push(']');
+            }
+        }
+    }
+
+    // incl_reqs is only false when this function is called recursively
+    if p.has_visible_subcommands() && incl_reqs || p.is_set(AS::AllowExternalSubcommands) {
+        if p.is_set(AS::SubcommandsNegateReqs) || p.is_set(AS::ArgsNegateSubcommands) {
+            usage.push_str("\n    ");
+            if !p.is_set(AS::ArgsNegateSubcommands) {
+                usage.push_str(&*create_help_usage(p, false));
+            } else {
+                usage.push_str(&*name);
+            }
+            usage.push_str(" <SUBCOMMAND>");
+        } else if p.is_set(AS::SubcommandRequired) || p.is_set(AS::SubcommandRequiredElseHelp) {
+            usage.push_str(" <SUBCOMMAND>");
+        } else {
+            usage.push_str(" [SUBCOMMAND]");
+        }
+    }
+    usage.shrink_to_fit();
+    debugln!("usage::create_help_usage: usage={}", usage);
+    usage
+}
+
+// Creates a context aware usage string, or "smart usage" from currently used
+// args, and requirements
+fn create_smart_usage(p: &Parser, used: &[&str]) -> String {
+    debugln!("usage::smart_usage;");
+    let mut usage = String::with_capacity(75);
+    let mut hs: Vec<&str> = p.required().map(|s| &**s).collect();
+    hs.extend_from_slice(used);
+
+    let r_string = get_required_usage_from(p, &hs, None, None, false)
+        .iter()
+        .fold(String::new(), |acc, s| acc + &format!(" {}", s)[..]);
+
+    usage.push_str(
+        &p.meta
+            .usage
+            .as_ref()
+            .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name))[..],
+    );
+    usage.push_str(&*r_string);
+    if p.is_set(AS::SubcommandRequired) {
+        usage.push_str(" <SUBCOMMAND>");
+    }
+    usage.shrink_to_fit();
+    usage
+}
+
+// Gets the `[ARGS]` tag for the usage string
+fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option<String> {
+    debugln!("usage::get_args_tag;");
+    let mut count = 0;
+    'outer: for pos in p
+        .positionals
+        .values()
+        .filter(|pos| !pos.is_set(ArgSettings::Required))
+        .filter(|pos| !pos.is_set(ArgSettings::Hidden))
+        .filter(|pos| !pos.is_set(ArgSettings::Last))
+    {
+        debugln!("usage::get_args_tag:iter:{}:", pos.b.name);
+        if let Some(g_vec) = p.groups_for_arg(pos.b.name) {
+            for grp_s in &g_vec {
+                debugln!("usage::get_args_tag:iter:{}:iter:{};", pos.b.name, grp_s);
+                // if it's part of a required group we don't want to count it
+                if p.groups.iter().any(|g| g.required && (&g.name == grp_s)) {
+                    continue 'outer;
+                }
+            }
+        }
+        count += 1;
+        debugln!(
+            "usage::get_args_tag:iter: {} Args not required or hidden",
+            count
+        );
+    }
+    if !p.is_set(AS::DontCollapseArgsInUsage) && count > 1 {
+        debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]");
+        return None; // [ARGS]
+    } else if count == 1 && incl_reqs {
+        let pos = p
+            .positionals
+            .values()
+            .find(|pos| {
+                !pos.is_set(ArgSettings::Required)
+                    && !pos.is_set(ArgSettings::Hidden)
+                    && !pos.is_set(ArgSettings::Last)
+            })
+            .expect(INTERNAL_ERROR_MSG);
+        debugln!(
+            "usage::get_args_tag:iter: Exactly one, returning '{}'",
+            pos.name()
+        );
+        return Some(format!(
+            " [{}]{}",
+            pos.name_no_brackets(),
+            pos.multiple_str()
+        ));
+    } else if p.is_set(AS::DontCollapseArgsInUsage) && !p.positionals.is_empty() && incl_reqs {
+        debugln!("usage::get_args_tag:iter: Don't collapse returning all");
+        return Some(
+            p.positionals
+                .values()
+                .filter(|pos| !pos.is_set(ArgSettings::Required))
+                .filter(|pos| !pos.is_set(ArgSettings::Hidden))
+                .filter(|pos| !pos.is_set(ArgSettings::Last))
+                .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
+                .collect::<Vec<_>>()
+                .join(""),
+        );
+    } else if !incl_reqs {
+        debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string");
+        let highest_req_pos = p
+            .positionals
+            .iter()
+            .filter_map(|(idx, pos)| {
+                if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) {
+                    Some(idx)
+                } else {
+                    None
+                }
+            })
+            .max()
+            .unwrap_or_else(|| p.positionals.len());
+        return Some(
+            p.positionals
+                .iter()
+                .filter_map(|(idx, pos)| {
+                    if idx <= highest_req_pos {
+                        Some(pos)
+                    } else {
+                        None
+                    }
+                })
+                .filter(|pos| !pos.is_set(ArgSettings::Required))
+                .filter(|pos| !pos.is_set(ArgSettings::Hidden))
+                .filter(|pos| !pos.is_set(ArgSettings::Last))
+                .map(|pos| format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()))
+                .collect::<Vec<_>>()
+                .join(""),
+        );
+    }
+    Some("".into())
+}
+
+// Determines if we need the `[FLAGS]` tag in the usage string
+fn needs_flags_tag(p: &Parser) -> bool {
+    debugln!("usage::needs_flags_tag;");
+    'outer: for f in &p.flags {
+        debugln!("usage::needs_flags_tag:iter: f={};", f.b.name);
+        if let Some(l) = f.s.long {
+            if l == "help" || l == "version" {
+                // Don't print `[FLAGS]` just for help or version
+                continue;
+            }
+        }
+        if let Some(g_vec) = p.groups_for_arg(f.b.name) {
+            for grp_s in &g_vec {
+                debugln!("usage::needs_flags_tag:iter:iter: grp_s={};", grp_s);
+                if p.groups.iter().any(|g| &g.name == grp_s && g.required) {
+                    debugln!("usage::needs_flags_tag:iter:iter: Group is required");
+                    continue 'outer;
+                }
+            }
+        }
+        if f.is_set(ArgSettings::Hidden) {
+            continue;
+        }
+        debugln!("usage::needs_flags_tag:iter: [FLAGS] required");
+        return true;
+    }
+
+    debugln!("usage::needs_flags_tag: [FLAGS] not required");
+    false
+}
+
+// Returns the required args in usage string form by fully unrolling all groups
+pub fn get_required_usage_from<'a, 'b>(
+    p: &Parser<'a, 'b>,
+    reqs: &[&'a str],
+    matcher: Option<&ArgMatcher<'a>>,
+    extra: Option<&str>,
+    incl_last: bool,
+) -> VecDeque<String> {
+    debugln!(
+        "usage::get_required_usage_from: reqs={:?}, extra={:?}",
+        reqs,
+        extra
+    );
+    let mut desc_reqs: Vec<&str> = vec![];
+    desc_reqs.extend(extra);
+    let mut new_reqs: Vec<&str> = vec![];
+    macro_rules! get_requires {
+        (@group $a: ident, $v:ident, $p:ident) => {{
+            if let Some(rl) = p
+                .groups
+                .iter()
+                .filter(|g| g.requires.is_some())
+                .find(|g| &g.name == $a)
+                .map(|g| g.requires.as_ref().unwrap())
+            {
+                for r in rl {
+                    if !$p.contains(&r) {
+                        debugln!(
+                            "usage::get_required_usage_from:iter:{}: adding group req={:?}",
+                            $a,
+                            r
+                        );
+                        $v.push(r);
+                    }
+                }
+            }
+        }};
+        ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{
+            if let Some(rl) = p
+                .$what
+                .$how()
+                .filter(|a| a.b.requires.is_some())
+                .find(|arg| &arg.b.name == $a)
+                .map(|a| a.b.requires.as_ref().unwrap())
+            {
+                for &(_, r) in rl.iter() {
+                    if !$p.contains(&r) {
+                        debugln!(
+                            "usage::get_required_usage_from:iter:{}: adding arg req={:?}",
+                            $a,
+                            r
+                        );
+                        $v.push(r);
+                    }
+                }
+            }
+        }};
+    }
+    // initialize new_reqs
+    for a in reqs {
+        get_requires!(a, flags, iter, new_reqs, reqs);
+        get_requires!(a, opts, iter, new_reqs, reqs);
+        get_requires!(a, positionals, values, new_reqs, reqs);
+        get_requires!(@group a, new_reqs, reqs);
+    }
+    desc_reqs.extend_from_slice(&*new_reqs);
+    debugln!(
+        "usage::get_required_usage_from: after init desc_reqs={:?}",
+        desc_reqs
+    );
+    loop {
+        let mut tmp = vec![];
+        for a in &new_reqs {
+            get_requires!(a, flags, iter, tmp, desc_reqs);
+            get_requires!(a, opts, iter, tmp, desc_reqs);
+            get_requires!(a, positionals, values, tmp, desc_reqs);
+            get_requires!(@group a, tmp, desc_reqs);
+        }
+        if tmp.is_empty() {
+            debugln!("usage::get_required_usage_from: no more children");
+            break;
+        } else {
+            debugln!("usage::get_required_usage_from: after iter tmp={:?}", tmp);
+            debugln!(
+                "usage::get_required_usage_from: after iter new_reqs={:?}",
+                new_reqs
+            );
+            desc_reqs.extend_from_slice(&*new_reqs);
+            new_reqs.clear();
+            new_reqs.extend_from_slice(&*tmp);
+            debugln!(
+                "usage::get_required_usage_from: after iter desc_reqs={:?}",
+                desc_reqs
+            );
+        }
+    }
+    desc_reqs.extend_from_slice(reqs);
+    desc_reqs.sort_unstable();
+    desc_reqs.dedup();
+    debugln!(
+        "usage::get_required_usage_from: final desc_reqs={:?}",
+        desc_reqs
+    );
+    let mut ret_val = VecDeque::new();
+    let args_in_groups = p
+        .groups
+        .iter()
+        .filter(|gn| desc_reqs.contains(&gn.name))
+        .flat_map(|g| p.arg_names_in_group(g.name))
+        .collect::<Vec<_>>();
+
+    let pmap = if let Some(m) = matcher {
+        desc_reqs
+            .iter()
+            .filter(|a| p.positionals.values().any(|p| &&p.b.name == a))
+            .filter(|&pos| !m.contains(pos))
+            .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos))
+            .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last))
+            .filter(|pos| !args_in_groups.contains(&pos.b.name))
+            .map(|pos| (pos.index, pos))
+            .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index
+    } else {
+        desc_reqs
+            .iter()
+            .filter(|a| p.positionals.values().any(|pos| &&pos.b.name == a))
+            .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos))
+            .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last))
+            .filter(|pos| !args_in_groups.contains(&pos.b.name))
+            .map(|pos| (pos.index, pos))
+            .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index
+    };
+    debugln!(
+        "usage::get_required_usage_from: args_in_groups={:?}",
+        args_in_groups
+    );
+    for &p in pmap.values() {
+        let s = p.to_string();
+        if args_in_groups.is_empty() || !args_in_groups.contains(&&*s) {
+            ret_val.push_back(s);
+        }
+    }
+    for a in desc_reqs
+        .iter()
+        .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name))
+        .filter(|name| !p.groups.iter().any(|g| &&g.name == name))
+        .filter(|name| !args_in_groups.contains(name))
+        .filter(|name| !(matcher.is_some() && matcher.as_ref().unwrap().contains(name)))
+    {
+        debugln!("usage::get_required_usage_from:iter:{}:", a);
+        let arg = find_by_name!(p, *a, flags, iter)
+            .map(|f| f.to_string())
+            .unwrap_or_else(|| {
+                find_by_name!(p, *a, opts, iter)
+                    .map(|o| o.to_string())
+                    .expect(INTERNAL_ERROR_MSG)
+            });
+        ret_val.push_back(arg);
+    }
+    let mut g_vec: Vec<String> = vec![];
+    for g in desc_reqs
+        .iter()
+        .filter(|n| p.groups.iter().any(|g| &&g.name == n))
+    {
+        let g_string = p.args_in_group(g).join("|");
+        let elem = format!("<{}>", &g_string[..g_string.len()]);
+        if !g_vec.contains(&elem) {
+            g_vec.push(elem);
+        }
+    }
+    for g in g_vec {
+        ret_val.push_back(g);
+    }
+
+    ret_val
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/app/validator.rs
@@ -0,0 +1,584 @@
+// std
+#[allow(deprecated, unused_imports)]
+use std::{ascii::AsciiExt, fmt::Display};
+
+// Internal
+use crate::{
+    app::{
+        parser::{ParseResult, Parser},
+        settings::AppSettings as AS,
+        usage,
+    },
+    args::{settings::ArgSettings, AnyArg, ArgMatcher, MatchedArg},
+    errors::{Error, ErrorKind, Result as ClapResult},
+    fmt::{Colorizer, ColorizerOption},
+    INTERNAL_ERROR_MSG, INVALID_UTF8,
+};
+
+pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>)
+where
+    'a: 'b,
+    'b: 'z;
+
+impl<'a, 'b, 'z> Validator<'a, 'b, 'z> {
+    pub fn new(p: &'z mut Parser<'a, 'b>) -> Self {
+        Validator(p)
+    }
+
+    pub fn validate(
+        &mut self,
+        needs_val_of: ParseResult<'a>,
+        subcmd_name: Option<String>,
+        matcher: &mut ArgMatcher<'a>,
+    ) -> ClapResult<()> {
+        debugln!("Validator::validate;");
+        let mut reqs_validated = false;
+        self.0.add_env(matcher)?;
+        self.0.add_defaults(matcher)?;
+        if let ParseResult::Opt(a) = needs_val_of {
+            debugln!("Validator::validate: needs_val_of={:?}", a);
+            let o = {
+                self.0
+                    .opts
+                    .iter()
+                    .find(|o| o.b.name == a)
+                    .expect(INTERNAL_ERROR_MSG)
+                    .clone()
+            };
+            self.validate_required(matcher)?;
+            reqs_validated = true;
+            let should_err = if let Some(v) = matcher.0.args.get(&*o.b.name) {
+                v.vals.is_empty() && !(o.v.min_vals.is_some() && o.v.min_vals.unwrap() == 0)
+            } else {
+                true
+            };
+            if should_err {
+                return Err(Error::empty_value(
+                    &o,
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+        }
+
+        if matcher.is_empty()
+            && matcher.subcommand_name().is_none()
+            && self.0.is_set(AS::ArgRequiredElseHelp)
+        {
+            let mut out = vec![];
+            self.0.write_help_err(&mut out)?;
+            return Err(Error {
+                message: String::from_utf8_lossy(&*out).into_owned(),
+                kind: ErrorKind::MissingArgumentOrSubcommand,
+                info: None,
+            });
+        }
+        self.validate_blacklist(matcher)?;
+        if !(reqs_validated || self.0.is_set(AS::SubcommandsNegateReqs) && subcmd_name.is_some()) {
+            self.validate_required(matcher)?;
+        }
+        self.validate_matched_args(matcher)?;
+        matcher.usage(usage::create_usage_with_title(self.0, &[]));
+
+        Ok(())
+    }
+
+    fn validate_arg_values<A>(
+        &self,
+        arg: &A,
+        ma: &MatchedArg,
+        matcher: &ArgMatcher<'a>,
+    ) -> ClapResult<()>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Validator::validate_arg_values: arg={:?}", arg.name());
+        for val in &ma.vals {
+            if self.0.is_set(AS::StrictUtf8) && val.to_str().is_none() {
+                debugln!(
+                    "Validator::validate_arg_values: invalid UTF-8 found in val {:?}",
+                    val
+                );
+                return Err(Error::invalid_utf8(
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+            if let Some(p_vals) = arg.possible_vals() {
+                debugln!("Validator::validate_arg_values: possible_vals={:?}", p_vals);
+                let val_str = val.to_string_lossy();
+                let ok = if arg.is_set(ArgSettings::CaseInsensitive) {
+                    p_vals.iter().any(|pv| pv.eq_ignore_ascii_case(&*val_str))
+                } else {
+                    p_vals.contains(&&*val_str)
+                };
+                if !ok {
+                    return Err(Error::invalid_value(
+                        val_str,
+                        p_vals,
+                        arg,
+                        &*usage::create_error_usage(self.0, matcher, None),
+                        self.0.color(),
+                    ));
+                }
+            }
+            if !arg.is_set(ArgSettings::EmptyValues)
+                && val.is_empty()
+                && matcher.contains(&*arg.name())
+            {
+                debugln!("Validator::validate_arg_values: illegal empty val found");
+                return Err(Error::empty_value(
+                    arg,
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+            if let Some(vtor) = arg.validator() {
+                debug!("Validator::validate_arg_values: checking validator...");
+                if let Err(e) = vtor(val.to_string_lossy().into_owned()) {
+                    sdebugln!("error");
+                    return Err(Error::value_validation(Some(arg), e, self.0.color()));
+                } else {
+                    sdebugln!("good");
+                }
+            }
+            if let Some(vtor) = arg.validator_os() {
+                debug!("Validator::validate_arg_values: checking validator_os...");
+                if let Err(e) = vtor(val) {
+                    sdebugln!("error");
+                    return Err(Error::value_validation(
+                        Some(arg),
+                        (*e).to_string_lossy().to_string(),
+                        self.0.color(),
+                    ));
+                } else {
+                    sdebugln!("good");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> {
+        debugln!("build_err!: name={}", name);
+        let mut c_with = find_from!(self.0, &name, blacklist, matcher);
+        c_with = c_with.or_else(|| {
+            self.0
+                .find_any_arg(name)
+                .and_then(|aa| aa.blacklist())
+                .and_then(|bl| bl.iter().find(|arg| matcher.contains(arg)))
+                .and_then(|an| self.0.find_any_arg(an))
+                .map(|aa| format!("{}", aa))
+        });
+        debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name);
+        //        matcher.remove(&name);
+        let usg = usage::create_error_usage(self.0, matcher, None);
+        if let Some(f) = find_by_name!(self.0, name, flags, iter) {
+            debugln!("build_err!: It was a flag...");
+            Err(Error::argument_conflict(f, c_with, &*usg, self.0.color()))
+        } else if let Some(o) = find_by_name!(self.0, name, opts, iter) {
+            debugln!("build_err!: It was an option...");
+            Err(Error::argument_conflict(o, c_with, &*usg, self.0.color()))
+        } else {
+            match find_by_name!(self.0, name, positionals, values) {
+                Some(p) => {
+                    debugln!("build_err!: It was a positional...");
+                    Err(Error::argument_conflict(p, c_with, &*usg, self.0.color()))
+                }
+                None => panic!("{}", INTERNAL_ERROR_MSG),
+            }
+        }
+    }
+
+    fn validate_blacklist(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
+        debugln!("Validator::validate_blacklist;");
+        let mut conflicts: Vec<&str> = vec![];
+        for (&name, _) in matcher.iter() {
+            debugln!("Validator::validate_blacklist:iter:{};", name);
+            if let Some(grps) = self.0.groups_for_arg(name) {
+                for grp in &grps {
+                    if let Some(g) = self.0.groups.iter().find(|g| &g.name == grp) {
+                        if !g.multiple {
+                            for arg in &g.args {
+                                if arg == &name {
+                                    continue;
+                                }
+                                conflicts.push(arg);
+                            }
+                        }
+                        if let Some(ref gc) = g.conflicts {
+                            conflicts.extend(&*gc);
+                        }
+                    }
+                }
+            }
+            if let Some(arg) = find_any_by_name!(self.0, name) {
+                if let Some(bl) = arg.blacklist() {
+                    for conf in bl {
+                        if matcher.get(conf).is_some() {
+                            conflicts.push(conf);
+                        }
+                    }
+                }
+            } else {
+                debugln!("Validator::validate_blacklist:iter:{}:group;", name);
+                let args = self.0.arg_names_in_group(name);
+                for arg in &args {
+                    debugln!(
+                        "Validator::validate_blacklist:iter:{}:group:iter:{};",
+                        name,
+                        arg
+                    );
+                    if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() {
+                        for conf in bl {
+                            if matcher.get(conf).is_some() {
+                                conflicts.push(conf);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        for name in &conflicts {
+            debugln!(
+                "Validator::validate_blacklist:iter:{}: Checking blacklisted arg",
+                name
+            );
+            let mut should_err = false;
+            if self.0.groups.iter().any(|g| &g.name == name) {
+                debugln!(
+                    "Validator::validate_blacklist:iter:{}: groups contains it...",
+                    name
+                );
+                for n in self.0.arg_names_in_group(name) {
+                    debugln!(
+                        "Validator::validate_blacklist:iter:{}:iter:{}: looking in group...",
+                        name,
+                        n
+                    );
+                    if matcher.contains(n) {
+                        debugln!(
+                            "Validator::validate_blacklist:iter:{}:iter:{}: matcher contains it...",
+                            name,
+                            n
+                        );
+                        return self.build_err(n, matcher);
+                    }
+                }
+            } else if let Some(ma) = matcher.get(name) {
+                debugln!(
+                    "Validator::validate_blacklist:iter:{}: matcher contains it...",
+                    name
+                );
+                should_err = ma.occurs > 0;
+            }
+            if should_err {
+                return self.build_err(*name, matcher);
+            }
+        }
+        Ok(())
+    }
+
+    fn validate_matched_args(&self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> {
+        debugln!("Validator::validate_matched_args;");
+        for (name, ma) in matcher.iter() {
+            debugln!(
+                "Validator::validate_matched_args:iter:{}: vals={:#?}",
+                name,
+                ma.vals
+            );
+            if let Some(opt) = find_by_name!(self.0, *name, opts, iter) {
+                self.validate_arg_num_vals(opt, ma, matcher)?;
+                self.validate_arg_values(opt, ma, matcher)?;
+                self.validate_arg_requires(opt, ma, matcher)?;
+                self.validate_arg_num_occurs(opt, ma, matcher)?;
+            } else if let Some(flag) = find_by_name!(self.0, *name, flags, iter) {
+                self.validate_arg_requires(flag, ma, matcher)?;
+                self.validate_arg_num_occurs(flag, ma, matcher)?;
+            } else if let Some(pos) = find_by_name!(self.0, *name, positionals, values) {
+                self.validate_arg_num_vals(pos, ma, matcher)?;
+                self.validate_arg_num_occurs(pos, ma, matcher)?;
+                self.validate_arg_values(pos, ma, matcher)?;
+                self.validate_arg_requires(pos, ma, matcher)?;
+            } else {
+                let grp = self
+                    .0
+                    .groups
+                    .iter()
+                    .find(|g| &g.name == name)
+                    .expect(INTERNAL_ERROR_MSG);
+                if let Some(ref g_reqs) = grp.requires {
+                    if g_reqs.iter().any(|&n| !matcher.contains(n)) {
+                        return self.missing_required_error(matcher, None);
+                    }
+                }
+            }
+        }
+        Ok(())
+    }
+
+    fn validate_arg_num_occurs<A>(
+        &self,
+        a: &A,
+        ma: &MatchedArg,
+        matcher: &ArgMatcher,
+    ) -> ClapResult<()>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Validator::validate_arg_num_occurs: a={};", a.name());
+        if ma.occurs > 1 && !a.is_set(ArgSettings::Multiple) {
+            // Not the first time, and we don't allow multiples
+            return Err(Error::unexpected_multiple_usage(
+                a,
+                &*usage::create_error_usage(self.0, matcher, None),
+                self.0.color(),
+            ));
+        }
+        Ok(())
+    }
+
+    fn validate_arg_num_vals<A>(
+        &self,
+        a: &A,
+        ma: &MatchedArg,
+        matcher: &ArgMatcher,
+    ) -> ClapResult<()>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Validator::validate_arg_num_vals:{}", a.name());
+        if let Some(num) = a.num_vals() {
+            debugln!("Validator::validate_arg_num_vals: num_vals set...{}", num);
+            let should_err = if a.is_set(ArgSettings::Multiple) {
+                ((ma.vals.len() as u64) % num) != 0
+            } else {
+                num != (ma.vals.len() as u64)
+            };
+            if should_err {
+                debugln!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
+                return Err(Error::wrong_number_of_values(
+                    a,
+                    num,
+                    if a.is_set(ArgSettings::Multiple) {
+                        ma.vals.len() % num as usize
+                    } else {
+                        ma.vals.len()
+                    },
+                    if ma.vals.len() == 1
+                        || (a.is_set(ArgSettings::Multiple) && (ma.vals.len() % num as usize) == 1)
+                    {
+                        "as"
+                    } else {
+                        "ere"
+                    },
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+        }
+        if let Some(num) = a.max_vals() {
+            debugln!("Validator::validate_arg_num_vals: max_vals set...{}", num);
+            if (ma.vals.len() as u64) > num {
+                debugln!("Validator::validate_arg_num_vals: Sending error TooManyValues");
+                return Err(Error::too_many_values(
+                    ma.vals
+                        .iter()
+                        .last()
+                        .expect(INTERNAL_ERROR_MSG)
+                        .to_str()
+                        .expect(INVALID_UTF8),
+                    a,
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+        }
+        let min_vals_zero = if let Some(num) = a.min_vals() {
+            debugln!("Validator::validate_arg_num_vals: min_vals set: {}", num);
+            if (ma.vals.len() as u64) < num && num != 0 {
+                debugln!("Validator::validate_arg_num_vals: Sending error TooFewValues");
+                return Err(Error::too_few_values(
+                    a,
+                    num,
+                    ma.vals.len(),
+                    &*usage::create_error_usage(self.0, matcher, None),
+                    self.0.color(),
+                ));
+            }
+            num == 0
+        } else {
+            false
+        };
+        // Issue 665 (https://github.com/clap-rs/clap/issues/665)
+        // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
+        if a.takes_value() && !min_vals_zero && ma.vals.is_empty() {
+            return Err(Error::empty_value(
+                a,
+                &*usage::create_error_usage(self.0, matcher, None),
+                self.0.color(),
+            ));
+        }
+        Ok(())
+    }
+
+    fn validate_arg_requires<A>(
+        &self,
+        a: &A,
+        ma: &MatchedArg,
+        matcher: &ArgMatcher,
+    ) -> ClapResult<()>
+    where
+        A: AnyArg<'a, 'b> + Display,
+    {
+        debugln!("Validator::validate_arg_requires:{};", a.name());
+        if let Some(a_reqs) = a.requires() {
+            for &(val, name) in a_reqs.iter().filter(|&&(val, _)| val.is_some()) {
+                let missing_req =
+                    |v| v == val.expect(INTERNAL_ERROR_MSG) && !matcher.contains(name);
+                if ma.vals.iter().any(missing_req) {
+                    return self.missing_required_error(matcher, None);
+                }
+            }
+            for &(_, name) in a_reqs.iter().filter(|&&(val, _)| val.is_none()) {
+                if !matcher.contains(name) {
+                    return self.missing_required_error(matcher, Some(name));
+                }
+            }
+        }
+        Ok(())
+    }
+
+    fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> {
+        debugln!(
+            "Validator::validate_required: required={:?};",
+            self.0.required
+        );
+
+        let mut should_err = false;
+        let mut to_rem = Vec::new();
+        for name in &self.0.required {
+            debugln!("Validator::validate_required:iter:{}:", name);
+            if matcher.contains(name) {
+                continue;
+            }
+            if to_rem.contains(name) {
+                continue;
+            } else if let Some(a) = find_any_by_name!(self.0, *name) {
+                if self.is_missing_required_ok(a, matcher) {
+                    to_rem.push(a.name());
+                    if let Some(reqs) = a.requires() {
+                        for r in reqs
+                            .iter()
+                            .filter(|&&(val, _)| val.is_none())
+                            .map(|&(_, name)| name)
+                        {
+                            to_rem.push(r);
+                        }
+                    }
+                    continue;
+                }
+            }
+            should_err = true;
+            break;
+        }
+        if should_err {
+            for r in &to_rem {
+                'inner: for i in (0..self.0.required.len()).rev() {
+                    if &self.0.required[i] == r {
+                        self.0.required.swap_remove(i);
+                        break 'inner;
+                    }
+                }
+            }
+            return self.missing_required_error(matcher, None);
+        }
+
+        // Validate the conditionally required args
+        for &(a, v, r) in &self.0.r_ifs {
+            if let Some(ma) = matcher.get(a) {
+                if matcher.get(r).is_none() && ma.vals.iter().any(|val| val == v) {
+                    return self.missing_required_error(matcher, Some(r));
+                }
+            }
+        }
+        Ok(())
+    }
+
+    fn validate_arg_conflicts(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> {
+        debugln!("Validator::validate_arg_conflicts: a={:?};", a.name());
+        a.blacklist().map(|bl| {
+            bl.iter().any(|conf| {
+                matcher.contains(conf)
+                    || self
+                        .0
+                        .groups
+                        .iter()
+                        .find(|g| &g.name == conf)
+                        .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg)))
+            })
+        })
+    }
+
+    fn validate_required_unless(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> {
+        debugln!("Validator::validate_required_unless: a={:?};", a.name());
+        macro_rules! check {
+            ($how:ident, $_self:expr, $a:ident, $m:ident) => {{
+                $a.required_unless().map(|ru| {
+                    ru.iter().$how(|n| {
+                        $m.contains(n) || {
+                            if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) {
+                                grp.args.iter().any(|arg| $m.contains(arg))
+                            } else {
+                                false
+                            }
+                        }
+                    })
+                })
+            }};
+        }
+        if a.is_set(ArgSettings::RequiredUnlessAll) {
+            check!(all, self.0, a, matcher)
+        } else {
+            check!(any, self.0, a, matcher)
+        }
+    }
+
+    fn missing_required_error(&self, matcher: &ArgMatcher, extra: Option<&str>) -> ClapResult<()> {
+        debugln!("Validator::missing_required_error: extra={:?}", extra);
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: self.0.color(),
+        });
+        let mut reqs = self.0.required.iter().map(|&r| &*r).collect::<Vec<_>>();
+        if let Some(r) = extra {
+            reqs.push(r);
+        }
+        reqs.retain(|n| !matcher.contains(n));
+        reqs.dedup();
+        debugln!("Validator::missing_required_error: reqs={:#?}", reqs);
+        let req_args =
+            usage::get_required_usage_from(self.0, &reqs[..], Some(matcher), extra, true)
+                .iter()
+                .fold(String::new(), |acc, s| {
+                    acc + &format!("\n    {}", c.error(s))[..]
+                });
+        debugln!(
+            "Validator::missing_required_error: req_args={:#?}",
+            req_args
+        );
+        Err(Error::missing_required_argument(
+            &*req_args,
+            &*usage::create_error_usage(self.0, matcher, extra),
+            self.0.color(),
+        ))
+    }
+
+    #[inline]
+    fn is_missing_required_ok(&self, a: &AnyArg, matcher: &ArgMatcher) -> bool {
+        debugln!("Validator::is_missing_required_ok: a={}", a.name());
+        self.validate_arg_conflicts(a, matcher).unwrap_or(false)
+            || self.validate_required_unless(a, matcher).unwrap_or(false)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/any_arg.rs
@@ -0,0 +1,139 @@
+// Std
+use std::{
+    ffi::{OsStr, OsString},
+    fmt as std_fmt,
+    rc::Rc,
+};
+
+// Internal
+use crate::{
+    args::settings::ArgSettings,
+    map::{self, VecMap},
+    INTERNAL_ERROR_MSG,
+};
+
+#[doc(hidden)]
+pub trait AnyArg<'n, 'e>: std_fmt::Display {
+    fn name(&self) -> &'n str;
+    fn overrides(&self) -> Option<&[&'e str]>;
+    fn aliases(&self) -> Option<Vec<&'e str>>;
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]>;
+    fn blacklist(&self) -> Option<&[&'e str]>;
+    fn required_unless(&self) -> Option<&[&'e str]>;
+    fn is_set(&self, setting: ArgSettings) -> bool;
+    fn set(&mut self, setting: ArgSettings);
+    fn has_switch(&self) -> bool;
+    fn max_vals(&self) -> Option<u64>;
+    fn min_vals(&self) -> Option<u64>;
+    fn num_vals(&self) -> Option<u64>;
+    fn possible_vals(&self) -> Option<&[&'e str]>;
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>>;
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>>;
+    fn short(&self) -> Option<char>;
+    fn long(&self) -> Option<&'e str>;
+    fn val_delim(&self) -> Option<char>;
+    fn takes_value(&self) -> bool;
+    fn val_names(&self) -> Option<&VecMap<&'e str>>;
+    fn help(&self) -> Option<&'e str>;
+    fn long_help(&self) -> Option<&'e str>;
+    fn default_val(&self) -> Option<&'e OsStr>;
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>>;
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)>;
+    fn longest_filter(&self) -> bool;
+    fn val_terminator(&self) -> Option<&'e str>;
+}
+
+pub trait DispOrder {
+    fn disp_ord(&self) -> usize;
+}
+
+impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T
+where
+    T: AnyArg<'n, 'e> + 'z,
+{
+    fn name(&self) -> &'n str {
+        (*self).name()
+    }
+    fn overrides(&self) -> Option<&[&'e str]> {
+        (*self).overrides()
+    }
+    fn aliases(&self) -> Option<Vec<&'e str>> {
+        (*self).aliases()
+    }
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
+        (*self).requires()
+    }
+    fn blacklist(&self) -> Option<&[&'e str]> {
+        (*self).blacklist()
+    }
+    fn required_unless(&self) -> Option<&[&'e str]> {
+        (*self).required_unless()
+    }
+    fn is_set(&self, a: ArgSettings) -> bool {
+        (*self).is_set(a)
+    }
+    fn set(&mut self, _: ArgSettings) {
+        panic!("{}", INTERNAL_ERROR_MSG)
+    }
+    fn has_switch(&self) -> bool {
+        (*self).has_switch()
+    }
+    fn max_vals(&self) -> Option<u64> {
+        (*self).max_vals()
+    }
+    fn min_vals(&self) -> Option<u64> {
+        (*self).min_vals()
+    }
+    fn num_vals(&self) -> Option<u64> {
+        (*self).num_vals()
+    }
+    fn possible_vals(&self) -> Option<&[&'e str]> {
+        (*self).possible_vals()
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>> {
+        (*self).validator()
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>> {
+        (*self).validator_os()
+    }
+    fn short(&self) -> Option<char> {
+        (*self).short()
+    }
+    fn long(&self) -> Option<&'e str> {
+        (*self).long()
+    }
+    fn val_delim(&self) -> Option<char> {
+        (*self).val_delim()
+    }
+    fn takes_value(&self) -> bool {
+        (*self).takes_value()
+    }
+    fn val_names(&self) -> Option<&VecMap<&'e str>> {
+        (*self).val_names()
+    }
+    fn help(&self) -> Option<&'e str> {
+        (*self).help()
+    }
+    fn long_help(&self) -> Option<&'e str> {
+        (*self).long_help()
+    }
+    fn default_val(&self) -> Option<&'e OsStr> {
+        (*self).default_val()
+    }
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
+        (*self).default_vals_ifs()
+    }
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
+        (*self).env()
+    }
+    fn longest_filter(&self) -> bool {
+        (*self).longest_filter()
+    }
+    fn val_terminator(&self) -> Option<&'e str> {
+        (*self).val_terminator()
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg.rs
@@ -0,0 +1,3961 @@
+#[cfg(feature = "yaml")]
+use std::collections::BTreeMap;
+#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
+use std::os::unix::ffi::OsStrExt;
+use std::{
+    env,
+    ffi::{OsStr, OsString},
+    rc::Rc,
+};
+
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
+use crate::osstringext::OsStrExt3;
+use crate::{
+    args::{
+        arg_builder::{Base, Switched, Valued},
+        settings::ArgSettings,
+    },
+    map::VecMap,
+    usage_parser::UsageParser,
+};
+
+/// The abstract representation of a command line argument. Used to set all the options and
+/// relationships that define a valid argument for the program.
+///
+/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
+/// manually, or using a usage string which is far less verbose but has fewer options. You can also
+/// use a combination of the two methods to achieve the best of both worlds.
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::Arg;
+/// // Using the traditional builder pattern and setting each option manually
+/// let cfg = Arg::with_name("config")
+///       .short("c")
+///       .long("config")
+///       .takes_value(true)
+///       .value_name("FILE")
+///       .help("Provides a config file to myprog");
+/// // Using a usage string (setting a similar argument to the one above)
+/// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'");
+/// ```
+/// [`Arg`]: ./struct.Arg.html
+#[allow(missing_debug_implementations)]
+#[derive(Default, Clone)]
+pub struct Arg<'a, 'b>
+where
+    'a: 'b,
+{
+    #[doc(hidden)]
+    pub b: Base<'a, 'b>,
+    #[doc(hidden)]
+    pub s: Switched<'b>,
+    #[doc(hidden)]
+    pub v: Valued<'a, 'b>,
+    #[doc(hidden)]
+    pub index: Option<u64>,
+    #[doc(hidden)]
+    pub r_ifs: Option<Vec<(&'a str, &'b str)>>,
+}
+
+impl<'a, 'b> Arg<'a, 'b> {
+    /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get
+    /// information about whether or not the argument was used at runtime, get values, set
+    /// relationships with other args, etc..
+    ///
+    /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`])
+    /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
+    /// be displayed when the user prints the usage/help information of the program.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    /// # ;
+    /// ```
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`Arg`]: ./struct.Arg.html
+    pub fn with_name(n: &'a str) -> Self {
+        Arg {
+            b: Base::new(n),
+            ..Default::default()
+        }
+    }
+
+    /// Creates a new instance of [`Arg`] from a .yml (YAML) file.
+    ///
+    /// # Examples
+    ///
+    /// ```ignore
+    /// # #[macro_use]
+    /// # extern crate clap;
+    /// # use clap::Arg;
+    /// # fn main() {
+    /// let yml = load_yaml!("arg.yml");
+    /// let arg = Arg::from_yaml(yml);
+    /// # }
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    #[cfg(feature = "yaml")]
+    pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg {
+        // We WANT this to panic on error...so expect() is good.
+        let name_yml = y.keys().nth(0).unwrap();
+        let name_str = name_yml.as_str().unwrap();
+        let mut a = Arg::with_name(name_str);
+        let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap();
+
+        for (k, v) in arg_settings.iter() {
+            a = match k.as_str().unwrap() {
+                "short" => yaml_to_str!(a, v, short),
+                "long" => yaml_to_str!(a, v, long),
+                "aliases" => yaml_vec_or_str!(v, a, alias),
+                "help" => yaml_to_str!(a, v, help),
+                "long_help" => yaml_to_str!(a, v, long_help),
+                "required" => yaml_to_bool!(a, v, required),
+                "required_if" => yaml_tuple2!(a, v, required_if),
+                "required_ifs" => yaml_tuple2!(a, v, required_if),
+                "takes_value" => yaml_to_bool!(a, v, takes_value),
+                "index" => yaml_to_u64!(a, v, index),
+                "global" => yaml_to_bool!(a, v, global),
+                "multiple" => yaml_to_bool!(a, v, multiple),
+                "hidden" => yaml_to_bool!(a, v, hidden),
+                "next_line_help" => yaml_to_bool!(a, v, next_line_help),
+                "empty_values" => yaml_to_bool!(a, v, empty_values),
+                "group" => yaml_to_str!(a, v, group),
+                "number_of_values" => yaml_to_u64!(a, v, number_of_values),
+                "max_values" => yaml_to_u64!(a, v, max_values),
+                "min_values" => yaml_to_u64!(a, v, min_values),
+                "value_name" => yaml_to_str!(a, v, value_name),
+                "use_delimiter" => yaml_to_bool!(a, v, use_delimiter),
+                "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values),
+                "last" => yaml_to_bool!(a, v, last),
+                "require_delimiter" => yaml_to_bool!(a, v, require_delimiter),
+                "value_delimiter" => yaml_to_str!(a, v, value_delimiter),
+                "required_unless" => yaml_to_str!(a, v, required_unless),
+                "display_order" => yaml_to_usize!(a, v, display_order),
+                "default_value" => yaml_to_str!(a, v, default_value),
+                "default_value_if" => yaml_tuple3!(a, v, default_value_if),
+                "default_value_ifs" => yaml_tuple3!(a, v, default_value_if),
+                "env" => yaml_to_str!(a, v, env),
+                "value_names" => yaml_vec_or_str!(v, a, value_name),
+                "groups" => yaml_vec_or_str!(v, a, group),
+                "requires" => yaml_vec_or_str!(v, a, requires),
+                "requires_if" => yaml_tuple2!(a, v, requires_if),
+                "requires_ifs" => yaml_tuple2!(a, v, requires_if),
+                "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with),
+                "overrides_with" => yaml_vec_or_str!(v, a, overrides_with),
+                "possible_values" => yaml_vec_or_str!(v, a, possible_value),
+                "case_insensitive" => yaml_to_bool!(a, v, case_insensitive),
+                "required_unless_one" => yaml_vec_or_str!(v, a, required_unless),
+                "required_unless_all" => {
+                    a = yaml_vec_or_str!(v, a, required_unless);
+                    a.setb(ArgSettings::RequiredUnlessAll);
+                    a
+                }
+                s => panic!(
+                    "Unknown Arg setting '{}' in YAML file for arg '{}'",
+                    s, name_str
+                ),
+            }
+        }
+
+        a
+    }
+
+    /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings
+    /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow.
+    ///
+    /// **NOTE**: Not all settings may be set using the usage string method. Some properties are
+    /// only available via the builder pattern.
+    ///
+    /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some
+    /// UTF-8 codepoints may work just fine, but this is not guaranteed.
+    ///
+    /// # Syntax
+    ///
+    /// Usage strings typically following the form:
+    ///
+    /// ```notrust
+    /// [explicit name] [short] [long] [value names] [help string]
+    /// ```
+    ///
+    /// This is not a hard rule as the attributes can appear in other orders. There are also
+    /// several additional sigils which denote additional settings. Below are the details of each
+    /// portion of the string.
+    ///
+    /// ### Explicit Name
+    ///
+    /// This is an optional field, if it's omitted the argument will use one of the additional
+    /// fields as the name using the following priority order:
+    ///
+    ///  * Explicit Name (This always takes precedence when present)
+    ///  * Long
+    ///  * Short
+    ///  * Value Name
+    ///
+    /// `clap` determines explicit names as the first string of characters between either `[]` or
+    /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning
+    /// the argument is required.
+    ///
+    /// Explicit names may be followed by:
+    ///  * The multiple denotation `...`
+    ///
+    /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a
+    /// required argument):
+    ///
+    /// ```notrust
+    /// [ename] -s, --long 'some flag'
+    /// <rname> -r, --longer 'some other flag'
+    /// ```
+    ///
+    /// ### Short
+    ///
+    /// This is set by placing a single character after a leading `-`.
+    ///
+    /// Shorts may be followed by
+    ///  * The multiple denotation `...`
+    ///  * An optional comma `,` which is cosmetic only
+    ///  * Value notation
+    ///
+    /// Example shorts are as follows (`-s`, and `-r`):
+    ///
+    /// ```notrust
+    /// -s, --long 'some flag'
+    /// <rname> -r [val], --longer 'some option'
+    /// ```
+    ///
+    /// ### Long
+    ///
+    /// This is set by placing a word (no spaces) after a leading `--`.
+    ///
+    /// Shorts may be followed by
+    ///  * The multiple denotation `...`
+    ///  * Value notation
+    ///
+    /// Example longs are as follows (`--some`, and `--rapid`):
+    ///
+    /// ```notrust
+    /// -s, --some 'some flag'
+    /// --rapid=[FILE] 'some option'
+    /// ```
+    ///
+    /// ### Values (Value Notation)
+    ///
+    /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this
+    /// is cosmetic only and does not affect functionality). If an explicit name has **not** been
+    /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument
+    ///
+    /// Values may be followed by
+    ///  * The multiple denotation `...`
+    ///  * More Value notation
+    ///
+    /// More than one value will also implicitly set the arguments number of values, i.e. having
+    /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it
+    /// must receive exactly two values
+    ///
+    /// Example values are as follows (`FILE`, and `SPEED`):
+    ///
+    /// ```notrust
+    /// -s, --some [FILE] 'some option'
+    /// --rapid=<SPEED>... 'some required multiple option'
+    /// ```
+    ///
+    /// ### Help String
+    ///
+    /// The help string is denoted between a pair of single quotes `''` and may contain any
+    /// characters.
+    ///
+    /// Example help strings are as follows:
+    ///
+    /// ```notrust
+    /// -s, --some [FILE] 'some option'
+    /// --rapid=<SPEED>... 'some required multiple option'
+    /// ```
+    ///
+    /// ### Additional Sigils
+    ///
+    /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may
+    /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values.
+    /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is
+    /// multiple occurrences (and then you can obviously have instances of both as well)
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// App::new("prog")
+    ///     .args(&[
+    ///         Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"),
+    ///         Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"),
+    ///         Arg::from_usage("[input] 'an optional input file to use'")
+    /// ])
+    /// # ;
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
+    pub fn from_usage(u: &'a str) -> Self {
+        let parser = UsageParser::from_usage(u);
+        parser.parse()
+    }
+
+    /// Sets the short version of the argument without the preceding `-`.
+    ///
+    /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and
+    /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own
+    /// arguments, in which case `clap` simply will not assign those to the auto-generated
+    /// `version` or `help` arguments.
+    ///
+    /// **NOTE:** Any leading `-` characters will be stripped, and only the first
+    /// non `-` character will be used as the [`short`] version
+    ///
+    /// # Examples
+    ///
+    /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as
+    /// `-c`, the `-` will be stripped.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .short("c")
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c`
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("config")
+    ///         .short("c"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-c"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("config"));
+    /// ```
+    /// [`short`]: ./struct.Arg.html#method.short
+    pub fn short<S: AsRef<str>>(mut self, s: S) -> Self {
+        self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().next();
+        self
+    }
+
+    /// Sets the long version of the argument without the preceding `--`.
+    ///
+    /// By default `clap` automatically assigns `version` and `help` to the auto-generated
+    /// `version` and `help` arguments respectively. You may use the word `version` or `help` for
+    /// the long form of your own arguments, in which case `clap` simply will not assign those to
+    /// the auto-generated `version` or `help` arguments.
+    ///
+    /// **NOTE:** Any leading `-` characters will be stripped
+    ///
+    /// # Examples
+    ///
+    /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading
+    /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
+    /// will *not* be stripped (i.e. `config-file` is allowed)
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("cfg")
+    ///     .long("config")
+    /// # ;
+    /// ```
+    ///
+    /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--config"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("cfg"));
+    /// ```
+    pub fn long(mut self, l: &'b str) -> Self {
+        self.s.long = Some(l.trim_left_matches(|c| c == '-'));
+        self
+    }
+
+    /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that
+    /// automatically dispatch as if this argument was used. This is more efficient, and easier
+    /// than creating multiple hidden arguments as one only needs to check for the existence of
+    /// this command, and not all variants.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///             .arg(Arg::with_name("test")
+    ///             .long("test")
+    ///             .alias("alias")
+    ///             .takes_value(true))
+    ///        .get_matches_from(vec![
+    ///             "prog", "--alias", "cool"
+    ///         ]);
+    /// assert!(m.is_present("test"));
+    /// assert_eq!(m.value_of("test"), Some("cool"));
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self {
+        if let Some(ref mut als) = self.s.aliases {
+            als.push((name.into(), false));
+        } else {
+            self.s.aliases = Some(vec![(name.into(), false)]);
+        }
+        self
+    }
+
+    /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that
+    /// automatically dispatch as if this argument was used. This is more efficient, and easier
+    /// than creating multiple hidden subcommands as one only needs to check for the existence of
+    /// this command, and not all variants.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///             .arg(Arg::with_name("test")
+    ///                     .long("test")
+    ///                     .aliases(&["do-stuff", "do-tests", "tests"])
+    ///                     .help("the file to add")
+    ///                     .required(false))
+    ///             .get_matches_from(vec![
+    ///                 "prog", "--do-tests"
+    ///             ]);
+    /// assert!(m.is_present("test"));
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    pub fn aliases(mut self, names: &[&'b str]) -> Self {
+        if let Some(ref mut als) = self.s.aliases {
+            for n in names {
+                als.push((n, false));
+            }
+        } else {
+            self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
+        }
+        self
+    }
+
+    /// Allows adding a [`Arg`] alias that functions exactly like those defined with
+    /// [`Arg::alias`], except that they are visible inside the help message.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///             .arg(Arg::with_name("test")
+    ///                 .visible_alias("something-awesome")
+    ///                 .long("test")
+    ///                 .takes_value(true))
+    ///        .get_matches_from(vec![
+    ///             "prog", "--something-awesome", "coffee"
+    ///         ]);
+    /// assert!(m.is_present("test"));
+    /// assert_eq!(m.value_of("test"), Some("coffee"));
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    /// [`App::alias`]: ./struct.Arg.html#method.alias
+    pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self {
+        if let Some(ref mut als) = self.s.aliases {
+            als.push((name.into(), true));
+        } else {
+            self.s.aliases = Some(vec![(name.into(), true)]);
+        }
+        self
+    }
+
+    /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined
+    /// with [`Arg::aliases`], except that they are visible inside the help message.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///             .arg(Arg::with_name("test")
+    ///                 .long("test")
+    ///                 .visible_aliases(&["something", "awesome", "cool"]))
+    ///        .get_matches_from(vec![
+    ///             "prog", "--awesome"
+    ///         ]);
+    /// assert!(m.is_present("test"));
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    /// [`App::aliases`]: ./struct.Arg.html#method.aliases
+    pub fn visible_aliases(mut self, names: &[&'b str]) -> Self {
+        if let Some(ref mut als) = self.s.aliases {
+            for n in names {
+                als.push((n, true));
+            }
+        } else {
+            self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
+        }
+        self
+    }
+
+    /// Sets the short help text of the argument that will be displayed to the user when they print
+    /// the help information with `-h`. Typically, this is a short (one line) description of the
+    /// arg.
+    ///
+    /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests
+    /// `--help` clap will still display the contents of `help` appropriately
+    ///
+    /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
+    ///
+    /// # Examples
+    ///
+    /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+    /// include a newline in the help text and have the following text be properly aligned with all
+    /// the other help text.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .help("The config file used by the myprog")
+    /// # ;
+    /// ```
+    ///
+    /// Setting `help` displays a short message to the side of the argument when the user passes
+    /// `-h` or `--help` (by default).
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    ///     --config     Some help text describing the --config arg
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help
+    pub fn help(mut self, h: &'b str) -> Self {
+        self.b.help = Some(h);
+        self
+    }
+
+    /// Sets the long help text of the argument that will be displayed to the user when they print
+    /// the help information with `--help`. Typically this a more detailed (multi-line) message
+    /// that describes the arg.
+    ///
+    /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h`
+    /// clap will still display the contents of `long_help` appropriately
+    ///
+    /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
+    ///
+    /// # Examples
+    ///
+    /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
+    /// include a newline in the help text and have the following text be properly aligned with all
+    /// the other help text.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .long_help(
+    /// "The config file used by the myprog must be in JSON format
+    /// with only valid keys and may not contain other nonsense
+    /// that cannot be read by this program. Obviously I'm going on
+    /// and on, so I'll stop now.")
+    /// # ;
+    /// ```
+    ///
+    /// Setting `help` displays a short message to the side of the argument when the user passes
+    /// `-h` or `--help` (by default).
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .long_help(
+    /// "The config file used by the myprog must be in JSON format
+    /// with only valid keys and may not contain other nonsense
+    /// that cannot be read by this program. Obviously I'm going on
+    /// and on, so I'll stop now."))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    ///    --config
+    ///         The config file used by the myprog must be in JSON format
+    ///         with only valid keys and may not contain other nonsense
+    ///         that cannot be read by this program. Obviously I'm going on
+    ///         and on, so I'll stop now.
+    ///
+    /// -h, --help
+    ///         Prints help information
+    ///
+    /// -V, --version
+    ///         Prints version information
+    /// ```
+    /// [`Arg::help`]: ./struct.Arg.html#method.help
+    pub fn long_help(mut self, h: &'b str) -> Self {
+        self.b.long_help = Some(h);
+        self
+    }
+
+    /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest
+    /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
+    /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax
+    /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
+    /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
+    /// the `--` syntax is otherwise not possible.
+    ///
+    /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- <ARG>]` if
+    /// `ARG` is marked as `.last(true)`.
+    ///
+    /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing
+    /// to set this can make the usage string very confusing.
+    ///
+    /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS /
+    /// OPTIONS
+    ///
+    /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not
+    /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`]
+    /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also
+    /// marked [`.required(true)`])
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("args")
+    ///     .last(true)
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args
+    /// and requires that the `--` syntax be used to access it early.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("first"))
+    ///     .arg(Arg::with_name("second"))
+    ///     .arg(Arg::with_name("third").last(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "one", "--", "three"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// let m = res.unwrap();
+    /// assert_eq!(m.value_of("third"), Some("three"));
+    /// assert!(m.value_of("second").is_none());
+    /// ```
+    ///
+    /// Even if the positional argument marked `.last(true)` is the only argument left to parse,
+    /// failing to use the `--` syntax results in an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("first"))
+    ///     .arg(Arg::with_name("second"))
+    ///     .arg(Arg::with_name("third").last(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "one", "two", "three"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
+    /// [index]: ./struct.Arg.html#method.index
+    /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage
+    /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands
+    /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs
+    /// [`.required(true)`]: ./struct.Arg.html#method.required
+    /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
+    pub fn last(self, l: bool) -> Self {
+        if l {
+            self.set(ArgSettings::Last)
+        } else {
+            self.unset(ArgSettings::Last)
+        }
+    }
+
+    /// Sets whether or not the argument is required by default. Required by default means it is
+    /// required, when no other conflicting rules have been evaluated. Conflicting rules take
+    /// precedence over being required. **Default:** `false`
+    ///
+    /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by
+    /// default. This is simply because if a flag should be required, it should simply be implied
+    /// as no additional information is required from user. Flags by their very nature are simply
+    /// yes/no, or true/false.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required(true)
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required(true)`] requires that the argument be used at runtime.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required(true)
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "file.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// ```
+    ///
+    /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required(true)
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
+    pub fn required(self, r: bool) -> Self {
+        if r {
+            self.set(ArgSettings::Required)
+        } else {
+            self.unset(ArgSettings::Required)
+        }
+    }
+
+    /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and
+    /// associated value) **Default:** `false`
+    ///
+    /// **NOTE:** This setting also removes the default of allowing empty values and implies
+    /// [`Arg::empty_values(false)`].
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .long("config")
+    ///     .takes_value(true)
+    ///     .require_equals(true)
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between
+    /// it and the associated value.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .require_equals(true)
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config=file.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// ```
+    ///
+    /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error
+    /// unless [`Arg::empty_values(true)`] is set.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .require_equals(true)
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "file.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
+    /// ```
+    /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals
+    /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values
+    /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values
+    pub fn require_equals(mut self, r: bool) -> Self {
+        if r {
+            self.unsetb(ArgSettings::EmptyValues);
+            self.set(ArgSettings::RequireEquals)
+        } else {
+            self.unset(ArgSettings::RequireEquals)
+        }
+    }
+
+    /// Allows values which start with a leading hyphen (`-`)
+    ///
+    /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as
+    /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values
+    /// when the user may have thought the second `--` would constitute the normal, "Only
+    /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`]
+    ///
+    /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and
+    /// the user passing in a value that matches a valid short. For example `prog -opt -F` where
+    /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should
+    /// should be taken when designing these args. This is compounded by the ability to "stack"
+    /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid
+    /// shorts.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("pattern")
+    ///     .allow_hyphen_values(true)
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("pat")
+    ///         .allow_hyphen_values(true)
+    ///         .takes_value(true)
+    ///         .long("pattern"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--pattern", "-file"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("pat"), Some("-file"));
+    /// ```
+    ///
+    /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a
+    /// hyphen is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("pat")
+    ///         .takes_value(true)
+    ///         .long("pattern"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--pattern", "-file"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
+    pub fn allow_hyphen_values(self, a: bool) -> Self {
+        if a {
+            self.set(ArgSettings::AllowLeadingHyphen)
+        } else {
+            self.unset(ArgSettings::AllowLeadingHyphen)
+        }
+    }
+    /// Sets an arg that override this arg's required setting. (i.e. this arg will be required
+    /// unless this other argument is present).
+    ///
+    /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not
+    /// mandatory to also set.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required_unless("debug")
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime
+    /// *unless* `name` is present. In the following example, the required argument is *not*
+    /// provided, but it's not an error because the `unless` arg has been supplied.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless("dbg")
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--debug"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless("dbg")
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless
+    /// [`Arg::required`]: ./struct.Arg.html#method.required
+    /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless
+    pub fn required_unless(mut self, name: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.r_unless {
+            vec.push(name);
+        } else {
+            self.b.r_unless = Some(vec![name]);
+        }
+        self.required(true)
+    }
+
+    /// Sets args that override this arg's required setting. (i.e. this arg will be required unless
+    /// all these other arguments are present).
+    ///
+    /// **NOTE:** If you wish for this argument to only be required if *one of* these args are
+    /// present see [`Arg::required_unless_one`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required_unless_all(&["cfg", "dbg"])
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime
+    /// *unless* *all* the args in `names` are present. In the following example, the required
+    /// argument is *not* provided, but it's not an error because all the `unless` args have been
+    /// supplied.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless_all(&["dbg", "infile"])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .arg(Arg::with_name("infile")
+    ///         .short("i")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--debug", "-i", "file"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this
+    /// arg is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless_all(&["dbg", "infile"])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .arg(Arg::with_name("infile")
+    ///         .short("i")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one
+    /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all
+    pub fn required_unless_all(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.r_unless {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.b.r_unless = Some(names.iter().copied().collect());
+        }
+        self.setb(ArgSettings::RequiredUnlessAll);
+        self.required(true)
+    }
+
+    /// Sets args that override this arg's [required] setting. (i.e. this arg will be required
+    /// unless *at least one of* these other arguments are present).
+    ///
+    /// **NOTE:** If you wish for this argument to only be required if *all of* these args are
+    /// present see [`Arg::required_unless_all`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required_unless_all(&["cfg", "dbg"])
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime
+    /// *unless* *at least one of* the args in `names` are present. In the following example, the
+    /// required argument is *not* provided, but it's not an error because one the `unless` args
+    /// have been supplied.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless_one(&["dbg", "infile"])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .arg(Arg::with_name("infile")
+    ///         .short("i")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--debug"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// ```
+    ///
+    /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names`
+    /// or this arg is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_unless_one(&["dbg", "infile"])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("dbg")
+    ///         .long("debug"))
+    ///     .arg(Arg::with_name("infile")
+    ///         .short("i")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [required]: ./struct.Arg.html#method.required
+    /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one
+    /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all
+    pub fn required_unless_one(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.r_unless {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.b.r_unless = Some(names.iter().copied().collect());
+        }
+        self.required(true)
+    }
+
+    /// Sets a conflicting argument by name. I.e. when using this argument,
+    /// the following argument can't be present and vice versa.
+    ///
+    /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+    /// only need to be set for one of the two arguments, they do not need to be set for each.
+    ///
+    /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+    /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
+    /// need to also do B.conflicts_with(A))
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .conflicts_with("debug")
+    /// # ;
+    /// ```
+    ///
+    /// Setting conflicting argument, and having both arguments present at runtime is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .conflicts_with("debug")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--debug", "--config", "file.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
+    /// ```
+    pub fn conflicts_with(mut self, name: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.blacklist {
+            vec.push(name);
+        } else {
+            self.b.blacklist = Some(vec![name]);
+        }
+        self
+    }
+
+    /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per
+    /// argument.
+    ///
+    /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
+    /// only need to be set for one of the two arguments, they do not need to be set for each.
+    ///
+    /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
+    /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
+    /// need to also do B.conflicts_with(A))
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .conflicts_with_all(&["debug", "input"])
+    /// # ;
+    /// ```
+    ///
+    /// Setting conflicting argument, and having any of the arguments present at runtime with a
+    /// conflicting argument is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .conflicts_with_all(&["debug", "input"])
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug"))
+    ///     .arg(Arg::with_name("input")
+    ///         .index(1))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "file.conf", "file.txt"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
+    /// ```
+    /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
+    pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.blacklist {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.b.blacklist = Some(names.iter().copied().collect());
+        }
+        self
+    }
+
+    /// Sets a overridable argument by name. I.e. this argument and the following argument
+    /// will override each other in POSIX style (whichever argument was specified at runtime
+    /// **last** "wins")
+    ///
+    /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+    /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+    ///
+    /// **WARNING:** Positional arguments cannot override themselves (or we would never be able
+    /// to advance to the next positional). If a positional agument lists itself as an override,
+    /// it is simply ignored.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::from_usage("-f, --flag 'some flag'")
+    ///         .conflicts_with("debug"))
+    ///     .arg(Arg::from_usage("-d, --debug 'other flag'"))
+    ///     .arg(Arg::from_usage("-c, --color 'third flag'")
+    ///         .overrides_with("flag"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-f", "-d", "-c"]);
+    ///             //    ^~~~~~~~~~~~^~~~~ flag is overridden by color
+    ///
+    /// assert!(m.is_present("color"));
+    /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
+    ///                                 // was never used because it was overridden with color
+    /// assert!(!m.is_present("flag"));
+    /// ```
+    /// Care must be taken when using this setting, and having an arg override with itself. This
+    /// is common practice when supporting things like shell aliases, config files, etc.
+    /// However, when combined with multiple values, it can get dicy.
+    /// Here is how clap handles such situations:
+    ///
+    /// When a flag overrides itself, it's as if the flag was only ever used once (essentially
+    /// preventing a "Unexpected multiple usage" error):
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("posix")
+    ///             .arg(Arg::from_usage("--flag  'some flag'").overrides_with("flag"))
+    ///             .get_matches_from(vec!["posix", "--flag", "--flag"]);
+    /// assert!(m.is_present("flag"));
+    /// assert_eq!(m.occurrences_of("flag"), 1);
+    /// ```
+    /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore
+    /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences.
+    ///
+    /// ```
+    /// # use clap::{App, Arg};
+    /// let m = App::new("posix")
+    ///             .arg(Arg::from_usage("--flag...  'some flag'").overrides_with("flag"))
+    ///             .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
+    /// assert!(m.is_present("flag"));
+    /// assert_eq!(m.occurrences_of("flag"), 4);
+    /// ```
+    /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last
+    /// occurrence happened.
+    ///
+    /// ```
+    /// # use clap::{App, Arg};
+    /// let m = App::new("posix")
+    ///             .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt"))
+    ///             .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
+    /// assert!(m.is_present("opt"));
+    /// assert_eq!(m.occurrences_of("opt"), 1);
+    /// assert_eq!(m.value_of("opt"), Some("other"));
+    /// ```
+    ///
+    /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting.
+    ///
+    /// ```
+    /// # use clap::{App, Arg};
+    /// let m = App::new("posix")
+    ///             .arg(Arg::from_usage("--opt [val]... 'some option'")
+    ///                 .overrides_with("opt"))
+    ///             .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
+    /// assert!(m.is_present("opt"));
+    /// assert_eq!(m.occurrences_of("opt"), 2);
+    /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
+    /// ```
+    ///
+    /// A safe thing to do if you'd like to support an option which supports multiple values, but
+    /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use
+    /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`)
+    ///
+    /// ```
+    /// # use clap::{App, Arg};
+    /// let m = App::new("posix")
+    ///             .arg(Arg::from_usage("--opt [val] 'some option'")
+    ///                 .overrides_with("opt")
+    ///                 .use_delimiter(false))
+    ///             .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]);
+    /// assert!(m.is_present("opt"));
+    /// assert_eq!(m.occurrences_of("opt"), 1);
+    /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]);
+    /// ```
+    pub fn overrides_with(mut self, name: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.overrides {
+            vec.push(name);
+        } else {
+            self.b.overrides = Some(vec![name]);
+        }
+        self
+    }
+
+    /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following
+    /// argument will override each other in POSIX style (whichever argument was specified at
+    /// runtime **last** "wins")
+    ///
+    /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
+    /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::from_usage("-f, --flag 'some flag'")
+    ///         .conflicts_with("color"))
+    ///     .arg(Arg::from_usage("-d, --debug 'other flag'"))
+    ///     .arg(Arg::from_usage("-c, --color 'third flag'")
+    ///         .overrides_with_all(&["flag", "debug"]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-f", "-d", "-c"]);
+    ///             //    ^~~~~~^~~~~~~~~ flag and debug are overridden by color
+    ///
+    /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
+    ///                                 // and debug were never used because they were overridden
+    ///                                 // with color
+    /// assert!(!m.is_present("debug"));
+    /// assert!(!m.is_present("flag"));
+    /// ```
+    pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.overrides {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.b.overrides = Some(names.iter().copied().collect());
+        }
+        self
+    }
+
+    /// Sets an argument by name that is required when this one is present I.e. when
+    /// using this argument, the following argument *must* be present.
+    ///
+    /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .requires("input")
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
+    /// defining argument is used. If the defining argument isn't used, the other argument isn't
+    /// required
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires("input")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("input")
+    ///         .index(1))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
+    /// ```
+    ///
+    /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires("input")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("input")
+    ///         .index(1))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "file.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [override]: ./struct.Arg.html#method.overrides_with
+    pub fn requires(mut self, name: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.requires {
+            vec.push((None, name));
+        } else {
+            self.b.requires = Some(vec![(None, name)]);
+        }
+        self
+    }
+
+    /// Allows a conditional requirement. The requirement will only become valid if this arg's value
+    /// equals `val`.
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows
+    ///
+    /// ```yaml
+    /// requires_if:
+    ///     - [val, arg]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .requires_if("val", "arg")
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the
+    /// defining argument's value is equal to `val`. If the defining argument is anything other than
+    /// `val`, the other argument isn't required.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires_if("my.cfg", "other")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("other"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "some.cfg"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
+    /// ```
+    ///
+    /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying
+    /// `arg` is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires_if("my.cfg", "input")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("input"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "my.cfg"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [override]: ./struct.Arg.html#method.overrides_with
+    pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.requires {
+            vec.push((Some(val), arg));
+        } else {
+            self.b.requires = Some(vec![(Some(val), arg)]);
+        }
+        self
+    }
+
+    /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value
+    /// equals `val`.
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows
+    ///
+    /// ```yaml
+    /// requires_if:
+    ///     - [val, arg]
+    ///     - [val2, arg2]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .requires_ifs(&[
+    ///         ("val", "arg"),
+    ///         ("other_val", "arg2"),
+    ///     ])
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the
+    /// defining argument's value is equal to `val`. If the defining argument's value is anything other
+    /// than `val`, `arg` isn't required.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires_ifs(&[
+    ///             ("special.conf", "opt"),
+    ///             ("other.conf", "other"),
+    ///         ])
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("option")
+    ///         .takes_value(true))
+    ///     .arg(Arg::with_name("other"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "special.conf"
+    ///     ]);
+    ///
+    /// assert!(res.is_err()); // We  used --config=special.conf so --option <val> is required
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [override]: ./struct.Arg.html#method.overrides_with
+    pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self {
+        if let Some(ref mut vec) = self.b.requires {
+            for &(val, arg) in ifs {
+                vec.push((Some(val), arg));
+            }
+        } else {
+            let mut vec = vec![];
+            for &(val, arg) in ifs {
+                vec.push((Some(val), arg));
+            }
+            self.b.requires = Some(vec);
+        }
+        self
+    }
+
+    /// Allows specifying that an argument is [required] conditionally. The requirement will only
+    /// become valid if the specified `arg`'s value equals `val`.
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows
+    ///
+    /// ```yaml
+    /// required_if:
+    ///     - [arg, val]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required_if("other_arg", "value")
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at
+    /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`,
+    /// this argument isn't required.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .required_if("other", "special")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--other", "not-special"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
+    /// ```
+    ///
+    /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not*
+    /// using this arg is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .required_if("other", "special")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--other", "special"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [required]: ./struct.Arg.html#method.required
+    pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self {
+        if let Some(ref mut vec) = self.r_ifs {
+            vec.push((arg, val));
+        } else {
+            self.r_ifs = Some(vec![(arg, val)]);
+        }
+        self
+    }
+
+    /// Allows specifying that an argument is [required] based on multiple conditions. The
+    /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid
+    /// if one of the specified `arg`'s value equals it's corresponding `val`.
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows
+    ///
+    /// ```yaml
+    /// required_if:
+    ///     - [arg, val]
+    ///     - [arg2, val2]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .required_ifs(&[
+    ///         ("extra", "val"),
+    ///         ("option", "spec")
+    ///     ])
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s
+    /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
+    /// anything other than `val`, this argument isn't required.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_ifs(&[
+    ///             ("extra", "val"),
+    ///             ("option", "spec")
+    ///         ])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("extra")
+    ///         .takes_value(true)
+    ///         .long("extra"))
+    ///     .arg(Arg::with_name("option")
+    ///         .takes_value(true)
+    ///         .long("option"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--option", "other"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
+    /// ```
+    ///
+    /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's
+    /// value of `val` but *not* using this arg is an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .required_ifs(&[
+    ///             ("extra", "val"),
+    ///             ("option", "spec")
+    ///         ])
+    ///         .takes_value(true)
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("extra")
+    ///         .takes_value(true)
+    ///         .long("extra"))
+    ///     .arg(Arg::with_name("option")
+    ///         .takes_value(true)
+    ///         .long("option"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--option", "spec"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [required]: ./struct.Arg.html#method.required
+    pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self {
+        if let Some(ref mut vec) = self.r_ifs {
+            for r_if in ifs {
+                vec.push((r_if.0, r_if.1));
+            }
+        } else {
+            let mut vec = vec![];
+            for r_if in ifs {
+                vec.push((r_if.0, r_if.1));
+            }
+            self.r_ifs = Some(vec);
+        }
+        self
+    }
+
+    /// Sets multiple arguments by names that are required when this one is present I.e. when
+    /// using this argument, the following arguments *must* be present.
+    ///
+    /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
+    /// by default.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::Arg;
+    /// Arg::with_name("config")
+    ///     .requires_all(&["input", "output"])
+    /// # ;
+    /// ```
+    ///
+    /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at
+    /// runtime if the defining argument is used. If the defining argument isn't used, the other
+    /// argument isn't required
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires("input")
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("input")
+    ///         .index(1))
+    ///     .arg(Arg::with_name("output")
+    ///         .index(2))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
+    /// ```
+    ///
+    /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an
+    /// error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .takes_value(true)
+    ///         .requires_all(&["input", "output"])
+    ///         .long("config"))
+    ///     .arg(Arg::with_name("input")
+    ///         .index(1))
+    ///     .arg(Arg::with_name("output")
+    ///         .index(2))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config", "file.conf", "in.txt"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// // We didn't use output
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
+    /// [override]: ./struct.Arg.html#method.overrides_with
+    /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all
+    pub fn requires_all(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.requires {
+            for s in names {
+                vec.push((None, s));
+            }
+        } else {
+            let mut vec = vec![];
+            for s in names {
+                vec.push((None, *s));
+            }
+            self.b.requires = Some(vec);
+        }
+        self
+    }
+
+    /// Specifies that the argument takes a value at run time.
+    ///
+    /// **NOTE:** values for arguments may be specified in any of the following methods
+    ///
+    /// * Using a space such as `-o value` or `--option value`
+    /// * Using an equals and no space such as `-o=value` or `--option=value`
+    /// * Use a short and no space such as `-ovalue`
+    ///
+    /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning
+    /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to
+    /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`],
+    /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .takes_value(true)
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--mode", "fast"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("mode"));
+    /// assert_eq!(m.value_of("mode"), Some("fast"));
+    /// ```
+    /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter
+    /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
+    /// [multiple values]: ./struct.Arg.html#method.multiple
+    pub fn takes_value(self, tv: bool) -> Self {
+        if tv {
+            self.set(ArgSettings::TakesValue)
+        } else {
+            self.unset(ArgSettings::TakesValue)
+        }
+    }
+
+    /// Specifies if the possible values of an argument should be displayed in the help text or
+    /// not. Defaults to `false` (i.e. show possible values)
+    ///
+    /// This is useful for args with many values, or ones which are explained elsewhere in the
+    /// help text.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .hide_possible_values(true)
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .possible_values(&["fast", "slow"])
+    ///         .takes_value(true)
+    ///         .hide_possible_values(true));
+    ///
+    /// ```
+    ///
+    /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
+    /// the help text would be omitted.
+    pub fn hide_possible_values(self, hide: bool) -> Self {
+        if hide {
+            self.set(ArgSettings::HidePossibleValues)
+        } else {
+            self.unset(ArgSettings::HidePossibleValues)
+        }
+    }
+
+    /// Specifies if the default value of an argument should be displayed in the help text or
+    /// not. Defaults to `false` (i.e. show default value)
+    ///
+    /// This is useful when default behavior of an arg is explained elsewhere in the help text.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .hide_default_value(true)
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("connect")
+    ///     .arg(Arg::with_name("host")
+    ///         .long("host")
+    ///         .default_value("localhost")
+    ///         .hide_default_value(true));
+    ///
+    /// ```
+    ///
+    /// If we were to run the above program with `--help` the `[default: localhost]` portion of
+    /// the help text would be omitted.
+    pub fn hide_default_value(self, hide: bool) -> Self {
+        if hide {
+            self.set(ArgSettings::HideDefaultValue)
+        } else {
+            self.unset(ArgSettings::HideDefaultValue)
+        }
+    }
+
+    /// Specifies the index of a positional argument **starting at** 1.
+    ///
+    /// **NOTE:** The index refers to position according to **other positional argument**. It does
+    /// not define position in the argument list as a whole.
+    ///
+    /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally
+    /// leave off the `index` method, and the index will be assigned in order of evaluation.
+    /// Utilizing the `index` method allows for setting indexes out of order
+    ///
+    /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument
+    /// may be defined as multiple (i.e. with the highest index)
+    ///
+    /// # Panics
+    ///
+    /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such
+    /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is
+    /// defined as multiple and is not the highest index
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("config")
+    ///     .index(1)
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .index(1))
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--debug", "fast"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("mode"));
+    /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
+    ///                                               // *not* first argument
+    /// ```
+    /// [`Arg::short`]: ./struct.Arg.html#method.short
+    /// [`Arg::long`]: ./struct.Arg.html#method.long
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    /// [`App`]: ./struct.App.html
+    /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
+    pub fn index(mut self, idx: u64) -> Self {
+        self.index = Some(idx);
+        self
+    }
+
+    /// Specifies that the argument may appear more than once. For flags, this results
+    /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d`
+    /// would count as three occurrences. For options there is a distinct difference in multiple
+    /// occurrences vs multiple values.
+    ///
+    /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas
+    /// `--opt val1 --opt val2` is two occurrences.
+    ///
+    /// **WARNING:**
+    ///
+    /// Setting `multiple(true)` for an [option] with no other details, allows multiple values
+    /// **and** multiple occurrences because it isn't possible to have more occurrences than values
+    /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly
+    /// valid, be careful when designing a CLI where positional arguments are expected after a
+    /// option which accepts multiple values, as `clap` will continue parsing *values* until it
+    /// reaches the max or specific number of values defined, or another flag or option.
+    ///
+    /// **Pro Tip**:
+    ///
+    /// It's possible to define an option which allows multiple occurrences, but only one value per
+    /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with
+    /// [`Arg::multiple(true)`].
+    ///
+    /// **WARNING:**
+    ///
+    /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that
+    /// accept values) and [subcommands], one needs to consider the possibility of an argument value
+    /// being the same as a valid subcommand. By default `clap` will parse the argument in question
+    /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a
+    /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and
+    /// a possible value that coincides with a subcommand name, the subcommand cannot be called
+    /// unless another argument is passed first.
+    ///
+    /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
+    ///
+    /// The following would be parsed as values to `--ui-paths`.
+    ///
+    /// ```notrust
+    /// $ program --ui-paths path1 path2 signer
+    /// ```
+    ///
+    /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values
+    /// until another argument is reached and it knows `--ui-paths` is done.
+    ///
+    /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding
+    /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer`
+    /// is parsed as both a subcommand and a value in the second case.
+    ///
+    /// ```notrust
+    /// $ program --ui-paths path1 signer
+    /// $ program --ui-paths path1 --ui-paths signer signer
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .short("d")
+    ///     .multiple(true)
+    /// # ;
+    /// ```
+    /// An example with flags
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("verbose")
+    ///         .multiple(true)
+    ///         .short("v"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-v", "-v", "-v"    // note, -vvv would have same result
+    ///     ]);
+    ///
+    /// assert!(m.is_present("verbose"));
+    /// assert_eq!(m.occurrences_of("verbose"), 3);
+    /// ```
+    ///
+    /// An example with options
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .multiple(true)
+    ///         .takes_value(true)
+    ///         .short("F"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-F", "file1", "file2", "file3"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("file"));
+    /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3"]);
+    /// ```
+    /// This is functionally equivalent to the example above
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .multiple(true)
+    ///         .takes_value(true)
+    ///         .short("F"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-F", "file1", "-F", "file2", "-F", "file3"
+    ///     ]);
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3"]);
+    ///
+    /// assert!(m.is_present("file"));
+    /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3"]);
+    /// ```
+    ///
+    /// A common mistake is to define an option which allows multiples, and a positional argument
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .multiple(true)
+    ///         .takes_value(true)
+    ///         .short("F"))
+    ///     .arg(Arg::with_name("word")
+    ///         .index(1))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-F", "file1", "file2", "file3", "word"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("file"));
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
+    /// assert!(!m.is_present("word")); // but we clearly used word!
+    /// ```
+    /// The problem is clap doesn't know when to stop parsing values for "files". This is further
+    /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would
+    /// appear to only fail sometimes...not good!
+    ///
+    /// A solution for the example above is to specify that `-F` only accepts one value, but is
+    /// allowed to appear multiple times
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .multiple(true)
+    ///         .takes_value(true)
+    ///         .number_of_values(1)
+    ///         .short("F"))
+    ///     .arg(Arg::with_name("word")
+    ///         .index(1))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("file"));
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3"]);
+    /// assert!(m.is_present("word"));
+    /// assert_eq!(m.value_of("word"), Some("word"));
+    /// ```
+    /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the
+    /// problem example above, it would have been a runtime error with a pretty message to the
+    /// user :)
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .multiple(true)
+    ///         .takes_value(true)
+    ///         .number_of_values(1)
+    ///         .short("F"))
+    ///     .arg(Arg::with_name("word")
+    ///         .index(1))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1", "file2", "file3", "word"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// [option]: ./struct.Arg.html#method.takes_value
+    /// [options]: ./struct.Arg.html#method.takes_value
+    /// [subcommands]: ./struct.SubCommand.html
+    /// [positionals]: ./struct.Arg.html#method.index
+    /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    pub fn multiple(self, multi: bool) -> Self {
+        if multi {
+            self.set(ArgSettings::Multiple)
+        } else {
+            self.unset(ArgSettings::Multiple)
+        }
+    }
+
+    /// Specifies a value that *stops* parsing multiple values of a give argument. By default when
+    /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that
+    /// argument until it reaches another valid argument, or one of the other more specific settings
+    /// for multiple values is used (such as [`min_values`], [`max_values`] or
+    /// [`number_of_values`]).
+    ///
+    /// **NOTE:** This setting only applies to [options] and [positional arguments]
+    ///
+    /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
+    /// of the values
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("vals")
+    ///     .takes_value(true)
+    ///     .multiple(true)
+    ///     .value_terminator(";")
+    /// # ;
+    /// ```
+    /// The following example uses two arguments, a sequence of commands, and the location in which
+    /// to perform them
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cmds")
+    ///         .multiple(true)
+    ///         .allow_hyphen_values(true)
+    ///         .value_terminator(";"))
+    ///     .arg(Arg::with_name("location"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
+    ///     ]);
+    /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
+    /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
+    /// assert_eq!(m.value_of("location"), Some("/home/clap"));
+    /// ```
+    /// [options]: ./struct.Arg.html#method.takes_value
+    /// [positional arguments]: ./struct.Arg.html#method.index
+    /// [`multiple(true)`]: ./struct.Arg.html#method.multiple
+    /// [`min_values`]: ./struct.Arg.html#method.min_values
+    /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values
+    /// [`max_values`]: ./struct.Arg.html#method.max_values
+    pub fn value_terminator(mut self, term: &'b str) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        self.v.terminator = Some(term);
+        self
+    }
+
+    /// Specifies that an argument can be matched to all child [`SubCommand`]s.
+    ///
+    /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
+    /// their values once a user uses them will be propagated back up to parents. In effect, this
+    /// means one should *define* all global arguments at the top level, however it doesn't matter
+    /// where the user *uses* the global argument.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .short("d")
+    ///     .global(true)
+    /// # ;
+    /// ```
+    ///
+    /// For example, assume an application with two subcommands, and you'd like to define a
+    /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
+    /// want to clutter the source with three duplicate [`Arg`] definitions.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, SubCommand};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("verb")
+    ///         .long("verbose")
+    ///         .short("v")
+    ///         .global(true))
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .subcommand(SubCommand::with_name("do-stuff"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "do-stuff", "--verbose"
+    ///     ]);
+    ///
+    /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
+    /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
+    /// assert!(sub_m.is_present("verb"));
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [required]: ./struct.Arg.html#method.required
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present
+    /// [`Arg`]: ./struct.Arg.html
+    pub fn global(self, g: bool) -> Self {
+        if g {
+            self.set(ArgSettings::Global)
+        } else {
+            self.unset(ArgSettings::Global)
+        }
+    }
+
+    /// Allows an argument to accept explicitly empty values. An empty value must be specified at
+    /// the command line with an explicit `""`, or `''`
+    ///
+    /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed)
+    ///
+    /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false`
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("file")
+    ///     .long("file")
+    ///     .empty_values(false)
+    /// # ;
+    /// ```
+    /// The default is to allow empty values, such as `--option ""` would be an empty value. But
+    /// we can change to make empty values become an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .short("v")
+    ///         .empty_values(false))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--config="
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
+    /// ```
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    pub fn empty_values(mut self, ev: bool) -> Self {
+        if ev {
+            self.set(ArgSettings::EmptyValues)
+        } else {
+            self = self.set(ArgSettings::TakesValue);
+            self.unset(ArgSettings::EmptyValues)
+        }
+    }
+
+    /// Hides an argument from help message output.
+    ///
+    /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`]
+    /// when set to true
+    ///
+    /// **NOTE:** This does **not** hide the argument from usage strings on error
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .hidden(true)
+    /// # ;
+    /// ```
+    /// Setting `hidden(true)` will hide the argument when displaying help text
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .hidden(true)
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help
+    /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help
+    pub fn hidden(self, h: bool) -> Self {
+        if h {
+            self.set(ArgSettings::Hidden)
+        } else {
+            self.unset(ArgSettings::Hidden)
+        }
+    }
+
+    /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that
+    /// only one of the specified values was used, or fails with an error message.
+    ///
+    /// **NOTE:** This setting only applies to [options] and [positional arguments]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("mode")
+    ///     .takes_value(true)
+    ///     .possible_values(&["fast", "slow", "medium"])
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .takes_value(true)
+    ///         .possible_values(&["fast", "slow", "medium"]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--mode", "fast"
+    ///     ]);
+    /// assert!(m.is_present("mode"));
+    /// assert_eq!(m.value_of("mode"), Some("fast"));
+    /// ```
+    ///
+    /// The next example shows a failed parse from using a value which wasn't defined as one of the
+    /// possible values.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .takes_value(true)
+    ///         .possible_values(&["fast", "slow", "medium"]))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--mode", "wrong"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
+    /// ```
+    /// [options]: ./struct.Arg.html#method.takes_value
+    /// [positional arguments]: ./struct.Arg.html#method.index
+    pub fn possible_values(mut self, names: &[&'b str]) -> Self {
+        if let Some(ref mut vec) = self.v.possible_vals {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.v.possible_vals = Some(names.iter().copied().collect());
+        }
+        self
+    }
+
+    /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies
+    /// that only one of the specified values was used, or fails with error message.
+    ///
+    /// **NOTE:** This setting only applies to [options] and [positional arguments]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("mode")
+    ///     .takes_value(true)
+    ///     .possible_value("fast")
+    ///     .possible_value("slow")
+    ///     .possible_value("medium")
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .takes_value(true)
+    ///         .possible_value("fast")
+    ///         .possible_value("slow")
+    ///         .possible_value("medium"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--mode", "fast"
+    ///     ]);
+    /// assert!(m.is_present("mode"));
+    /// assert_eq!(m.value_of("mode"), Some("fast"));
+    /// ```
+    ///
+    /// The next example shows a failed parse from using a value which wasn't defined as one of the
+    /// possible values.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("mode")
+    ///         .long("mode")
+    ///         .takes_value(true)
+    ///         .possible_value("fast")
+    ///         .possible_value("slow")
+    ///         .possible_value("medium"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "--mode", "wrong"
+    ///     ]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
+    /// ```
+    /// [options]: ./struct.Arg.html#method.takes_value
+    /// [positional arguments]: ./struct.Arg.html#method.index
+    pub fn possible_value(mut self, name: &'b str) -> Self {
+        if let Some(ref mut vec) = self.v.possible_vals {
+            vec.push(name);
+        } else {
+            self.v.possible_vals = Some(vec![name]);
+        }
+        self
+    }
+
+    /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if
+    /// the case differs from that of the specified `possible_value`.
+    ///
+    /// **Pro Tip:** Use this setting with [`arg_enum!`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// # use std::ascii::AsciiExt;
+    /// let m = App::new("pv")
+    ///     .arg(Arg::with_name("option")
+    ///         .long("--option")
+    ///         .takes_value(true)
+    ///         .possible_value("test123")
+    ///         .case_insensitive(true))
+    ///     .get_matches_from(vec![
+    ///         "pv", "--option", "TeSt123",
+    ///     ]);
+    ///
+    /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
+    /// ```
+    ///
+    /// This setting also works when multiple values can be defined:
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("pv")
+    ///     .arg(Arg::with_name("option")
+    ///         .short("-o")
+    ///         .long("--option")
+    ///         .takes_value(true)
+    ///         .possible_value("test123")
+    ///         .possible_value("test321")
+    ///         .multiple(true)
+    ///         .case_insensitive(true))
+    ///     .get_matches_from(vec![
+    ///         "pv", "--option", "TeSt123", "teST123", "tESt321"
+    ///     ]);
+    ///
+    /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
+    /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
+    /// ```
+    /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values
+    /// [`arg_enum!`]: ./macro.arg_enum.html
+    pub fn case_insensitive(self, ci: bool) -> Self {
+        if ci {
+            self.set(ArgSettings::CaseInsensitive)
+        } else {
+            self.unset(ArgSettings::CaseInsensitive)
+        }
+    }
+
+    /// Specifies the name of the [`ArgGroup`] the argument belongs to.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .long("debug")
+    ///     .group("mode")
+    /// # ;
+    /// ```
+    ///
+    /// Multiple arguments can be a member of a single group and then the group checked as if it
+    /// was one of said arguments.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug")
+    ///         .group("mode"))
+    ///     .arg(Arg::with_name("verbose")
+    ///         .long("verbose")
+    ///         .group("mode"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--debug"
+    ///     ]);
+    /// assert!(m.is_present("mode"));
+    /// ```
+    /// [`ArgGroup`]: ./struct.ArgGroup.html
+    pub fn group(mut self, name: &'a str) -> Self {
+        if let Some(ref mut vec) = self.b.groups {
+            vec.push(name);
+        } else {
+            self.b.groups = Some(vec![name]);
+        }
+        self
+    }
+
+    /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .long("debug")
+    ///     .groups(&["mode", "verbosity"])
+    /// # ;
+    /// ```
+    ///
+    /// Arguments can be members of multiple groups and then the group checked as if it
+    /// was one of said arguments.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug")
+    ///         .groups(&["mode", "verbosity"]))
+    ///     .arg(Arg::with_name("verbose")
+    ///         .long("verbose")
+    ///         .groups(&["mode", "verbosity"]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--debug"
+    ///     ]);
+    /// assert!(m.is_present("mode"));
+    /// assert!(m.is_present("verbosity"));
+    /// ```
+    /// [`ArgGroup`]: ./struct.ArgGroup.html
+    pub fn groups(mut self, names: &[&'a str]) -> Self {
+        if let Some(ref mut vec) = self.b.groups {
+            for s in names {
+                vec.push(s);
+            }
+        } else {
+            self.b.groups = Some(names.iter().copied().collect());
+        }
+        self
+    }
+
+    /// Specifies how many values are required to satisfy this argument. For example, if you had a
+    /// `-f <file>` argument where you wanted exactly 3 'files' you would set
+    /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided
+    /// 3 and only 3 values.
+    ///
+    /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting
+    /// [`Arg::multiple(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where
+    /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("file")
+    ///     .short("f")
+    ///     .number_of_values(3)
+    /// # ;
+    /// ```
+    ///
+    /// Not supplying the correct number of values is an error
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .takes_value(true)
+    ///         .number_of_values(2)
+    ///         .short("F"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
+    /// ```
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    pub fn number_of_values(mut self, qty: u64) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        self.v.num_vals = Some(qty);
+        self
+    }
+
+    /// Allows one to perform a custom validation on the argument value. You provide a closure
+    /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a
+    /// message displayed to the user.
+    ///
+    /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the
+    /// message as all errors will appear as
+    /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual
+    /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error.
+    ///
+    /// **NOTE:** There is a small performance hit for using validators, as they are implemented
+    /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order
+    /// to to be passed to the closure. This performance hit is extremely minimal in the grand
+    /// scheme of things.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// fn has_at(v: String) -> Result<(), String> {
+    ///     if v.contains("@") { return Ok(()); }
+    ///     Err(String::from("The value did not contain the required @ sigil"))
+    /// }
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .index(1)
+    ///         .validator(has_at))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "some@file"
+    ///     ]);
+    /// assert!(res.is_ok());
+    /// assert_eq!(res.unwrap().value_of("file"), Some("some@file"));
+    /// ```
+    /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
+    /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
+    /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
+    /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
+    pub fn validator<F>(mut self, f: F) -> Self
+    where
+        F: Fn(String) -> Result<(), String> + 'static,
+    {
+        self.v.validator = Some(Rc::new(f));
+        self
+    }
+
+    /// Works identically to Validator but is intended to be used with values that could
+    /// contain non UTF-8 formatted strings.
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```rust")]
+    /// # use clap::{App, Arg};
+    /// # use std::ffi::{OsStr, OsString};
+    /// # use std::os::unix::ffi::OsStrExt;
+    /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> {
+    ///     if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); }
+    ///     Err(OsString::from("The value did not contain the required & sigil"))
+    /// }
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .index(1)
+    ///         .validator_os(has_ampersand))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "Fish & chips"
+    ///     ]);
+    /// assert!(res.is_ok());
+    /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips"));
+    /// ```
+    /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
+    /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
+    /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
+    /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
+    /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
+    /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
+    pub fn validator_os<F>(mut self, f: F) -> Self
+    where
+        F: Fn(&OsStr) -> Result<(), OsString> + 'static,
+    {
+        self.v.validator_os = Some(Rc::new(f));
+        self
+    }
+
+    /// Specifies the *maximum* number of values are for this argument. For example, if you had a
+    /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and
+    /// this argument would be satisfied if the user provided, 1, 2, or 3 values.
+    ///
+    /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because
+    /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
+    /// occurrence with multiple values. For positional arguments this **does** set
+    /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
+    /// occurrences and multiple values.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("file")
+    ///     .short("f")
+    ///     .max_values(3)
+    /// # ;
+    /// ```
+    ///
+    /// Supplying less than the maximum number of values is allowed
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .takes_value(true)
+    ///         .max_values(3)
+    ///         .short("F"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1", "file2"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// let m = res.unwrap();
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2"]);
+    /// ```
+    ///
+    /// Supplying more than the maximum number of values is an error
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .takes_value(true)
+    ///         .max_values(2)
+    ///         .short("F"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1", "file2", "file3"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues);
+    /// ```
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    pub fn max_values(mut self, qty: u64) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        self.v.max_vals = Some(qty);
+        self
+    }
+
+    /// Specifies the *minimum* number of values for this argument. For example, if you had a
+    /// `-f <file>` argument where you wanted at least 2 'files' you would set
+    /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more
+    /// values.
+    ///
+    /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because
+    /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
+    /// occurrence with multiple values. For positional arguments this **does** set
+    /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
+    /// occurrences and multiple values.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("file")
+    ///     .short("f")
+    ///     .min_values(3)
+    /// # ;
+    /// ```
+    ///
+    /// Supplying more than the minimum number of values is allowed
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .takes_value(true)
+    ///         .min_values(2)
+    ///         .short("F"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1", "file2", "file3"
+    ///     ]);
+    ///
+    /// assert!(res.is_ok());
+    /// let m = res.unwrap();
+    /// let files: Vec<_> = m.values_of("file").unwrap().collect();
+    /// assert_eq!(files, ["file1", "file2", "file3"]);
+    /// ```
+    ///
+    /// Supplying less than the minimum number of values is an error
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("file")
+    ///         .takes_value(true)
+    ///         .min_values(2)
+    ///         .short("F"))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-F", "file1"
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues);
+    /// ```
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    pub fn min_values(mut self, qty: u64) -> Self {
+        self.v.min_vals = Some(qty);
+        self.set(ArgSettings::TakesValue)
+    }
+
+    /// Specifies whether or not an argument should allow grouping of multiple values via a
+    /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
+    /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
+    /// value delimiter for all arguments that accept values (options and positional arguments)
+    ///
+    /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`]
+    /// is the comma `,`.
+    ///
+    /// # Examples
+    ///
+    /// The following example shows the default behavior.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let delims = App::new("prog")
+    ///     .arg(Arg::with_name("option")
+    ///         .long("option")
+    ///         .use_delimiter(true)
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--option=val1,val2,val3",
+    ///     ]);
+    ///
+    /// assert!(delims.is_present("option"));
+    /// assert_eq!(delims.occurrences_of("option"), 1);
+    /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+    /// ```
+    /// The next example shows the difference when turning delimiters off. This is the default
+    /// behavior
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let nodelims = App::new("prog")
+    ///     .arg(Arg::with_name("option")
+    ///         .long("option")
+    ///         .use_delimiter(false)
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--option=val1,val2,val3",
+    ///     ]);
+    ///
+    /// assert!(nodelims.is_present("option"));
+    /// assert_eq!(nodelims.occurrences_of("option"), 1);
+    /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
+    /// ```
+    /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter
+    pub fn use_delimiter(mut self, d: bool) -> Self {
+        if d {
+            if self.v.val_delim.is_none() {
+                self.v.val_delim = Some(',');
+            }
+            self.setb(ArgSettings::TakesValue);
+            self.setb(ArgSettings::UseValueDelimiter);
+        } else {
+            self.v.val_delim = None;
+            self.unsetb(ArgSettings::UseValueDelimiter);
+        }
+        self.unset(ArgSettings::ValueDelimiterNotSet)
+    }
+
+    /// Specifies that *multiple values* may only be set using the delimiter. This means if an
+    /// if an option is encountered, and no delimiter is found, it automatically assumed that no
+    /// additional values for that option follow. This is unlike the default, where it is generally
+    /// assumed that more values will follow regardless of whether or not a delimiter is used.
+    ///
+    /// **NOTE:** The default is `false`.
+    ///
+    /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`]
+    ///
+    /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either
+    /// through help text or other means.
+    ///
+    /// # Examples
+    ///
+    /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice
+    /// everything works in this first example, as we use a delimiter, as expected.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let delims = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true)
+    ///         .require_delimiter(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-o", "val1,val2,val3",
+    ///     ]);
+    ///
+    /// assert!(delims.is_present("opt"));
+    /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+    /// ```
+    /// In this next example, we will *not* use a delimiter. Notice it's now an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true)
+    ///         .require_delimiter(true))
+    ///     .get_matches_from_safe(vec![
+    ///         "prog", "-o", "val1", "val2", "val3",
+    ///     ]);
+    ///
+    /// assert!(res.is_err());
+    /// let err = res.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::UnknownArgument);
+    /// ```
+    /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none
+    /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no
+    /// positional arguments have been defined, it's an error of an unexpected argument.
+    ///
+    /// In this final example, we contrast the above with `clap`'s default behavior where the above
+    /// is *not* an error.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let delims = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-o", "val1", "val2", "val3",
+    ///     ]);
+    ///
+    /// assert!(delims.is_present("opt"));
+    /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
+    /// ```
+    /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
+    pub fn require_delimiter(mut self, d: bool) -> Self {
+        if d {
+            self = self.use_delimiter(true);
+            self.unsetb(ArgSettings::ValueDelimiterNotSet);
+            self.setb(ArgSettings::UseValueDelimiter);
+            self.set(ArgSettings::RequireDelimiter)
+        } else {
+            self = self.use_delimiter(false);
+            self.unsetb(ArgSettings::UseValueDelimiter);
+            self.unset(ArgSettings::RequireDelimiter)
+        }
+    }
+
+    /// Specifies the separator to use when values are clumped together, defaults to `,` (comma).
+    ///
+    /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`]
+    ///
+    /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("config")
+    ///         .short("c")
+    ///         .long("config")
+    ///         .value_delimiter(";"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--config=val1;val2;val3"
+    ///     ]);
+    ///
+    /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
+    /// ```
+    /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    pub fn value_delimiter(mut self, d: &str) -> Self {
+        self.unsetb(ArgSettings::ValueDelimiterNotSet);
+        self.setb(ArgSettings::TakesValue);
+        self.setb(ArgSettings::UseValueDelimiter);
+        self.v.val_delim = Some(
+            d.chars()
+                .next()
+                .expect("Failed to get value_delimiter from arg"),
+        );
+        self
+    }
+
+    /// Specify multiple names for values of option arguments. These names are cosmetic only, used
+    /// for help and usage strings only. The names are **not** used to access arguments. The values
+    /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and
+    /// `two` `one` will be the first matched value, `two` will be the second).
+    ///
+    /// This setting can be very helpful when describing the type of input the user should be
+    /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+    /// use all capital letters for the value name.
+    ///
+    /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
+    /// multiple value names in order to not throw off the help text alignment of all options.
+    ///
+    /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is
+    /// greater than one. I.e. be aware that the number of "names" you set for the values, will be
+    /// the *exact* number of values required to satisfy this argument
+    ///
+    /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
+    ///
+    /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`].
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("speed")
+    ///     .short("s")
+    ///     .value_names(&["fast", "slow"])
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("io")
+    ///         .long("io-files")
+    ///         .value_names(&["INFILE", "OUTFILE"]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    /// Running the above program produces the following output
+    ///
+    /// ```notrust
+    /// valnames
+    ///
+    /// USAGE:
+    ///    valnames [FLAGS] [OPTIONS]
+    ///
+    /// FLAGS:
+    ///     -h, --help       Prints help information
+    ///     -V, --version    Prints version information
+    ///
+    /// OPTIONS:
+    ///     --io-files <INFILE> <OUTFILE>    Some help text
+    /// ```
+    /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help
+    /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    pub fn value_names(mut self, names: &[&'b str]) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        if self.is_set(ArgSettings::ValueDelimiterNotSet) {
+            self.unsetb(ArgSettings::ValueDelimiterNotSet);
+            self.setb(ArgSettings::UseValueDelimiter);
+        }
+        if let Some(ref mut vals) = self.v.val_names {
+            let mut l = vals.len();
+            for s in names {
+                vals.insert(l, s);
+                l += 1;
+            }
+        } else {
+            let mut vm = VecMap::new();
+            for (i, n) in names.iter().enumerate() {
+                vm.insert(i, *n);
+            }
+            self.v.val_names = Some(vm);
+        }
+        self
+    }
+
+    /// Specifies the name for value of [option] or [positional] arguments inside of help
+    /// documentation. This name is cosmetic only, the name is **not** used to access arguments.
+    /// This setting can be very helpful when describing the type of input the user should be
+    /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
+    /// use all capital letters for the value name.
+    ///
+    /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("cfg")
+    ///     .long("config")
+    ///     .value_name("FILE")
+    /// # ;
+    /// ```
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("config")
+    ///         .long("config")
+    ///         .value_name("FILE"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    /// Running the above program produces the following output
+    ///
+    /// ```notrust
+    /// valnames
+    ///
+    /// USAGE:
+    ///    valnames [FLAGS] [OPTIONS]
+    ///
+    /// FLAGS:
+    ///     -h, --help       Prints help information
+    ///     -V, --version    Prints version information
+    ///
+    /// OPTIONS:
+    ///     --config <FILE>     Some help text
+    /// ```
+    /// [option]: ./struct.Arg.html#method.takes_value
+    /// [positional]: ./struct.Arg.html#method.index
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    pub fn value_name(mut self, name: &'b str) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        if let Some(ref mut vals) = self.v.val_names {
+            let l = vals.len();
+            vals.insert(l, name);
+        } else {
+            let mut vm = VecMap::new();
+            vm.insert(0, name);
+            self.v.val_names = Some(vm);
+        }
+        self
+    }
+
+    /// Specifies the value of the argument when *not* specified at runtime.
+    ///
+    /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
+    /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
+    ///
+    /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
+    /// still return `true`. If you wish to determine whether the argument was used at runtime or
+    /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not*
+    /// used at runtime.
+    ///
+    /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
+    /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
+    /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided
+    /// a value at runtime **and** these other conditions are met as well. If you have set
+    /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this
+    /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the
+    /// `Arg::default_value` will be applied.
+    ///
+    /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
+    ///
+    /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in
+    /// conjunction as it ensures that some argument will always be present.
+    ///
+    /// # Examples
+    ///
+    /// First we use the default value without providing any value at runtime.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("myopt")
+    ///         .default_value("myval"))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("opt"), Some("myval"));
+    /// assert!(m.is_present("opt"));
+    /// assert_eq!(m.occurrences_of("opt"), 0);
+    /// ```
+    ///
+    /// Next we provide a value at runtime to override the default.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("myopt")
+    ///         .default_value("myval"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--myopt=non_default"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("opt"), Some("non_default"));
+    /// assert!(m.is_present("opt"));
+    /// assert_eq!(m.occurrences_of("opt"), 1);
+    /// ```
+    /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
+    /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
+    /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
+    pub fn default_value(self, val: &'a str) -> Self {
+        self.default_value_os(OsStr::from_bytes(val.as_bytes()))
+    }
+
+    /// Provides a default value in the exact same manner as [`Arg::default_value`]
+    /// only using [`OsStr`]s instead.
+    /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
+    /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
+    pub fn default_value_os(mut self, val: &'a OsStr) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        self.v.default_val = Some(val);
+        self
+    }
+
+    /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to
+    /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be
+    /// present at runtime **and** have the value `val`.
+    ///
+    /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
+    /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
+    /// at runtime. This setting however only takes affect when the user has not provided a value at
+    /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
+    /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did
+    /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be
+    /// applied.
+    ///
+    /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented
+    /// as `null` in YAML)
+    ///
+    /// ```yaml
+    /// default_value_if:
+    ///     - [arg, val, default]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// First we use the default value only if another arg is present at runtime.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_if("flag", None, "default"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--flag"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), Some("default"));
+    /// ```
+    ///
+    /// Next we run the same test, but without providing `--flag`.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_if("flag", None, "default"))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), None);
+    /// ```
+    ///
+    /// Now lets only use the default value if `--opt` contains the value `special`.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .takes_value(true)
+    ///         .long("opt"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_if("opt", Some("special"), "default"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--opt", "special"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), Some("default"));
+    /// ```
+    ///
+    /// We can run the same test and provide any value *other than* `special` and we won't get a
+    /// default value.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .takes_value(true)
+    ///         .long("opt"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_if("opt", Some("special"), "default"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--opt", "hahaha"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), None);
+    /// ```
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
+    pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self {
+        self.default_value_if_os(
+            arg,
+            val.map(str::as_bytes).map(OsStr::from_bytes),
+            OsStr::from_bytes(default.as_bytes()),
+        )
+    }
+
+    /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
+    /// only using [`OsStr`]s instead.
+    /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
+    /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
+    pub fn default_value_if_os(
+        mut self,
+        arg: &'a str,
+        val: Option<&'b OsStr>,
+        default: &'b OsStr,
+    ) -> Self {
+        self.setb(ArgSettings::TakesValue);
+        if let Some(ref mut vm) = self.v.default_vals_ifs {
+            let l = vm.len();
+            vm.insert(l, (arg, val, default));
+        } else {
+            let mut vm = VecMap::new();
+            vm.insert(0, (arg, val, default));
+            self.v.default_vals_ifs = Some(vm);
+        }
+        self
+    }
+
+    /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
+    /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
+    ///
+    /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
+    /// if multiple conditions are true, the first one found will be applied and the ultimate value.
+    ///
+    /// **NOTE:** If using YAML the values should be laid out as follows
+    ///
+    /// ```yaml
+    /// default_value_if:
+    ///     - [arg, val, default]
+    ///     - [arg2, null, default2]
+    /// ```
+    ///
+    /// # Examples
+    ///
+    /// First we use the default value only if another arg is present at runtime.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag"))
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("opt")
+    ///         .takes_value(true))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_ifs(&[
+    ///             ("flag", None, "default"),
+    ///             ("opt", Some("channal"), "chan"),
+    ///         ]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--opt", "channal"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), Some("chan"));
+    /// ```
+    ///
+    /// Next we run the same test, but without providing `--flag`.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag"))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_ifs(&[
+    ///             ("flag", None, "default"),
+    ///             ("opt", Some("channal"), "chan"),
+    ///         ]))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), None);
+    /// ```
+    ///
+    /// We can also see that these values are applied in order, and if more than one condition is
+    /// true, only the first evaluated "wins"
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag"))
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("opt")
+    ///         .takes_value(true))
+    ///     .arg(Arg::with_name("other")
+    ///         .long("other")
+    ///         .default_value_ifs(&[
+    ///             ("flag", None, "default"),
+    ///             ("opt", Some("channal"), "chan"),
+    ///         ]))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--opt", "channal", "--flag"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("other"), Some("default"));
+    /// ```
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
+    pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self {
+        for &(arg, val, default) in ifs {
+            self = self.default_value_if_os(
+                arg,
+                val.map(str::as_bytes).map(OsStr::from_bytes),
+                OsStr::from_bytes(default.as_bytes()),
+            );
+        }
+        self
+    }
+
+    /// Provides multiple conditional default values in the exact same manner as
+    /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
+    /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs
+    /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
+    pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self {
+        for &(arg, val, default) in ifs {
+            self = self.default_value_if_os(arg, val, default);
+        }
+        self
+    }
+
+    /// Specifies that if the value is not passed in as an argument, that it should be retrieved
+    /// from the environment, if available. If it is not present in the environment, then default
+    /// rules will apply.
+    ///
+    /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
+    /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
+    ///
+    /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
+    /// return `true` if the variable is present in the environment . If you wish to determine whether
+    /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will
+    /// return `0` if the argument was *not* used at runtime.
+    ///
+    /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
+    ///
+    /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be
+    /// set. Otherwise, only a single argument will be returned from the environment variable. The
+    /// default delimiter is `,` and follows all the other delimiter rules.
+    ///
+    /// # Examples
+    ///
+    /// In this example, we show the variable coming from the environment:
+    ///
+    /// ```rust
+    /// # use std::env;
+    /// # use clap::{App, Arg};
+    ///
+    /// env::set_var("MY_FLAG", "env");
+    ///
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag")
+    ///         .env("MY_FLAG"))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("flag"), Some("env"));
+    /// ```
+    ///
+    /// In this example, we show the variable coming from an option on the CLI:
+    ///
+    /// ```rust
+    /// # use std::env;
+    /// # use clap::{App, Arg};
+    ///
+    /// env::set_var("MY_FLAG", "env");
+    ///
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag")
+    ///         .env("MY_FLAG"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--flag", "opt"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("flag"), Some("opt"));
+    /// ```
+    ///
+    /// In this example, we show the variable coming from the environment even with the
+    /// presence of a default:
+    ///
+    /// ```rust
+    /// # use std::env;
+    /// # use clap::{App, Arg};
+    ///
+    /// env::set_var("MY_FLAG", "env");
+    ///
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag")
+    ///         .env("MY_FLAG")
+    ///         .default_value("default"))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.value_of("flag"), Some("env"));
+    /// ```
+    ///
+    /// In this example, we show the use of multiple values in a single environment variable:
+    ///
+    /// ```rust
+    /// # use std::env;
+    /// # use clap::{App, Arg};
+    ///
+    /// env::set_var("MY_FLAG_MULTI", "env1,env2");
+    ///
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .long("flag")
+    ///         .env("MY_FLAG_MULTI")
+    ///         .multiple(true)
+    ///         .use_delimiter(true))
+    ///     .get_matches_from(vec![
+    ///         "prog"
+    ///     ]);
+    ///
+    /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
+    /// ```
+    /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
+    /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
+    /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
+    /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
+    pub fn env(self, name: &'a str) -> Self {
+        self.env_os(OsStr::new(name))
+    }
+
+    /// Specifies that if the value is not passed in as an argument, that it should be retrieved
+    /// from the environment if available in the exact same manner as [`Arg::env`] only using
+    /// [`OsStr`]s instead.
+    pub fn env_os(mut self, name: &'a OsStr) -> Self {
+        self.setb(ArgSettings::TakesValue);
+
+        self.v.env = Some((name, env::var_os(name)));
+        self
+    }
+
+    /// @TODO @p2 @docs @release: write docs
+    pub fn hide_env_values(self, hide: bool) -> Self {
+        if hide {
+            self.set(ArgSettings::HideEnvValues)
+        } else {
+            self.unset(ArgSettings::HideEnvValues)
+        }
+    }
+
+    /// When set to `true` the help string will be displayed on the line after the argument and
+    /// indented once. This can be helpful for arguments with very long or complex help messages.
+    /// This can also be helpful for arguments with very long flag names, or many/long value names.
+    ///
+    /// **NOTE:** To apply this setting to all arguments consider using
+    /// [`AppSettings::NextLineHelp`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("opt")
+    ///         .long("long-option-flag")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .value_names(&["value1", "value2"])
+    ///         .help("Some really long help and complex\n\
+    ///                help that makes more sense to be\n\
+    ///                on a line after the option")
+    ///         .next_line_help(true))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays the following help message
+    ///
+    /// ```notrust
+    /// nlh
+    ///
+    /// USAGE:
+    ///     nlh [FLAGS] [OPTIONS]
+    ///
+    /// FLAGS:
+    ///     -h, --help       Prints help information
+    ///     -V, --version    Prints version information
+    ///
+    /// OPTIONS:
+    ///     -o, --long-option-flag <value1> <value2>
+    ///         Some really long help and complex
+    ///         help that makes more sense to be
+    ///         on a line after the option
+    /// ```
+    /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp
+    pub fn next_line_help(mut self, nlh: bool) -> Self {
+        if nlh {
+            self.setb(ArgSettings::NextLineHelp);
+        } else {
+            self.unsetb(ArgSettings::NextLineHelp);
+        }
+        self
+    }
+
+    /// Allows custom ordering of args within the help message. Args with a lower value will be
+    /// displayed first in the help message. This is helpful when one would like to emphasise
+    /// frequently used args, or prioritize those towards the top of the list. Duplicate values
+    /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical
+    /// order.
+    ///
+    /// **NOTE:** The default is 999 for all arguments.
+    ///
+    /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
+    /// [index] order.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name.
+    ///                              // Args without a display_order have a value of 999 and are
+    ///                              // displayed alphabetically with all other 999 valued args.
+    ///         .long("long-option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .help("Some help and text"))
+    ///     .arg(Arg::with_name("b")
+    ///         .long("other-option")
+    ///         .short("O")
+    ///         .takes_value(true)
+    ///         .display_order(1)   // In order to force this arg to appear *first*
+    ///                             // all we have to do is give it a value lower than 999.
+    ///                             // Any other args with a value of 1 will be displayed
+    ///                             // alphabetically with this one...then 2 values, then 3, etc.
+    ///         .help("I should be first!"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays the following help message
+    ///
+    /// ```notrust
+    /// cust-ord
+    ///
+    /// USAGE:
+    ///     cust-ord [FLAGS] [OPTIONS]
+    ///
+    /// FLAGS:
+    ///     -h, --help       Prints help information
+    ///     -V, --version    Prints version information
+    ///
+    /// OPTIONS:
+    ///     -O, --other-option <b>    I should be first!
+    ///     -o, --long-option <a>     Some help and text
+    /// ```
+    /// [positional arguments]: ./struct.Arg.html#method.index
+    /// [index]: ./struct.Arg.html#method.index
+    pub fn display_order(mut self, ord: usize) -> Self {
+        self.s.disp_ord = ord;
+        self
+    }
+
+    /// Indicates that all parameters passed after this should not be parsed
+    /// individually, but rather passed in their entirety. It is worth noting
+    /// that setting this requires all values to come after a `--` to indicate they
+    /// should all be captured. For example:
+    ///
+    /// ```notrust
+    /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
+    /// ```
+    /// Will result in everything after `--` to be considered one raw argument. This behavior
+    /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`]
+    /// may be more appropriate.
+    ///
+    /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and
+    /// [`Arg::last(true)`] when set to `true`
+    ///
+    /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+    /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
+    /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
+    /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
+    pub fn raw(self, raw: bool) -> Self {
+        self.multiple(raw).allow_hyphen_values(raw).last(raw)
+    }
+
+    /// Hides an argument from short help message output.
+    ///
+    /// **NOTE:** This does **not** hide the argument from usage strings on error
+    ///
+    /// **NOTE:** Setting this option will cause next-line-help output style to be used
+    /// when long help (`--help`) is called.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .hidden_short_help(true)
+    /// # ;
+    /// ```
+    /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .hidden_short_help(true)
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-h"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    ///
+    /// However, when --help is called
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .hidden_short_help(true)
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// Then the following would be displayed
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    ///     --config     Some help text describing the --config arg
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    pub fn hidden_short_help(self, hide: bool) -> Self {
+        if hide {
+            self.set(ArgSettings::HiddenShortHelp)
+        } else {
+            self.unset(ArgSettings::HiddenShortHelp)
+        }
+    }
+
+    /// Hides an argument from long help message output.
+    ///
+    /// **NOTE:** This does **not** hide the argument from usage strings on error
+    ///
+    /// **NOTE:** Setting this option will cause next-line-help output style to be used
+    /// when long help (`--help`) is called.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// Arg::with_name("debug")
+    ///     .hidden_long_help(true)
+    /// # ;
+    /// ```
+    /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .hidden_long_help(true)
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "--help"
+    ///     ]);
+    /// ```
+    ///
+    /// The above example displays
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    ///
+    /// However, when -h is called
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("prog")
+    ///     .arg(Arg::with_name("cfg")
+    ///         .long("config")
+    ///         .hidden_long_help(true)
+    ///         .help("Some help text describing the --config arg"))
+    ///     .get_matches_from(vec![
+    ///         "prog", "-h"
+    ///     ]);
+    /// ```
+    ///
+    /// Then the following would be displayed
+    ///
+    /// ```notrust
+    /// helptest
+    ///
+    /// USAGE:
+    ///    helptest [FLAGS]
+    ///
+    /// FLAGS:
+    ///     --config     Some help text describing the --config arg
+    /// -h, --help       Prints help information
+    /// -V, --version    Prints version information
+    /// ```
+    pub fn hidden_long_help(self, hide: bool) -> Self {
+        if hide {
+            self.set(ArgSettings::HiddenLongHelp)
+        } else {
+            self.unset(ArgSettings::HiddenLongHelp)
+        }
+    }
+
+    /// Checks if one of the [`ArgSettings`] settings is set for the argument.
+    ///
+    /// [`ArgSettings`]: ./enum.ArgSettings.html
+    pub fn is_set(&self, s: ArgSettings) -> bool {
+        self.b.is_set(s)
+    }
+
+    /// Sets one of the [`ArgSettings`] settings for the argument.
+    ///
+    /// [`ArgSettings`]: ./enum.ArgSettings.html
+    pub fn set(mut self, s: ArgSettings) -> Self {
+        self.setb(s);
+        self
+    }
+
+    /// Unsets one of the [`ArgSettings`] settings for the argument.
+    ///
+    /// [`ArgSettings`]: ./enum.ArgSettings.html
+    pub fn unset(mut self, s: ArgSettings) -> Self {
+        self.unsetb(s);
+        self
+    }
+
+    #[doc(hidden)]
+    pub fn setb(&mut self, s: ArgSettings) {
+        self.b.set(s);
+    }
+
+    #[doc(hidden)]
+    pub fn unsetb(&mut self, s: ArgSettings) {
+        self.b.unset(s);
+    }
+}
+
+impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> {
+    fn from(a: &'z Arg<'a, 'b>) -> Self {
+        Arg {
+            b: a.b.clone(),
+            v: a.v.clone(),
+            s: a.s.clone(),
+            index: a.index,
+            r_ifs: a.r_ifs.clone(),
+        }
+    }
+}
+
+impl<'n, 'e> PartialEq for Arg<'n, 'e> {
+    fn eq(&self, other: &Arg<'n, 'e>) -> bool {
+        self.b == other.b
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/base.rs
@@ -0,0 +1,48 @@
+use crate::args::{Arg, ArgFlags, ArgSettings};
+
+#[derive(Debug, Clone, Default)]
+pub struct Base<'a, 'b>
+where
+    'a: 'b,
+{
+    pub name: &'a str,
+    pub help: Option<&'b str>,
+    pub long_help: Option<&'b str>,
+    pub blacklist: Option<Vec<&'a str>>,
+    pub settings: ArgFlags,
+    pub r_unless: Option<Vec<&'a str>>,
+    pub overrides: Option<Vec<&'a str>>,
+    pub groups: Option<Vec<&'a str>>,
+    pub requires: Option<Vec<(Option<&'b str>, &'a str)>>,
+}
+
+impl<'n, 'e> Base<'n, 'e> {
+    pub fn new(name: &'n str) -> Self {
+        Base {
+            name,
+            ..Default::default()
+        }
+    }
+
+    pub fn set(&mut self, s: ArgSettings) {
+        self.settings.set(s);
+    }
+    pub fn unset(&mut self, s: ArgSettings) {
+        self.settings.unset(s);
+    }
+    pub fn is_set(&self, s: ArgSettings) -> bool {
+        self.settings.is_set(s)
+    }
+}
+
+impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> {
+    fn from(a: &'z Arg<'n, 'e>) -> Self {
+        a.b.clone()
+    }
+}
+
+impl<'n, 'e> PartialEq for Base<'n, 'e> {
+    fn eq(&self, other: &Base<'n, 'e>) -> bool {
+        self.name == other.name
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/flag.rs
@@ -0,0 +1,216 @@
+// Std
+use std::{
+    convert::From,
+    ffi::{OsStr, OsString},
+    fmt::{Display, Formatter, Result},
+    mem,
+    rc::Rc,
+    result::Result as StdResult,
+};
+
+// Internal
+use crate::{
+    args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched},
+    map::{self, VecMap},
+};
+
+#[derive(Default, Clone, Debug)]
+#[doc(hidden)]
+pub struct FlagBuilder<'n, 'e>
+where
+    'n: 'e,
+{
+    pub b: Base<'n, 'e>,
+    pub s: Switched<'e>,
+}
+
+impl<'n, 'e> FlagBuilder<'n, 'e> {
+    pub fn new(name: &'n str) -> Self {
+        FlagBuilder {
+            b: Base::new(name),
+            ..Default::default()
+        }
+    }
+}
+
+impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> {
+    fn from(a: &'z Arg<'a, 'b>) -> Self {
+        FlagBuilder {
+            b: Base::from(a),
+            s: Switched::from(a),
+        }
+    }
+}
+
+impl<'a, 'b> From<Arg<'a, 'b>> for FlagBuilder<'a, 'b> {
+    fn from(mut a: Arg<'a, 'b>) -> Self {
+        FlagBuilder {
+            b: mem::take(&mut a.b),
+            s: mem::take(&mut a.s),
+        }
+    }
+}
+
+impl<'n, 'e> Display for FlagBuilder<'n, 'e> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        if let Some(l) = self.s.long {
+            write!(f, "--{}", l)?;
+        } else {
+            write!(f, "-{}", self.s.short.unwrap())?;
+        }
+
+        Ok(())
+    }
+}
+
+impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> {
+    fn name(&self) -> &'n str {
+        self.b.name
+    }
+    fn overrides(&self) -> Option<&[&'e str]> {
+        self.b.overrides.as_ref().map(|o| &o[..])
+    }
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
+        self.b.requires.as_ref().map(|o| &o[..])
+    }
+    fn blacklist(&self) -> Option<&[&'e str]> {
+        self.b.blacklist.as_ref().map(|o| &o[..])
+    }
+    fn required_unless(&self) -> Option<&[&'e str]> {
+        self.b.r_unless.as_ref().map(|o| &o[..])
+    }
+    fn is_set(&self, s: ArgSettings) -> bool {
+        self.b.settings.is_set(s)
+    }
+    fn has_switch(&self) -> bool {
+        true
+    }
+    fn takes_value(&self) -> bool {
+        false
+    }
+    fn set(&mut self, s: ArgSettings) {
+        self.b.settings.set(s)
+    }
+    fn max_vals(&self) -> Option<u64> {
+        None
+    }
+    fn val_names(&self) -> Option<&VecMap<&'e str>> {
+        None
+    }
+    fn num_vals(&self) -> Option<u64> {
+        None
+    }
+    fn possible_vals(&self) -> Option<&[&'e str]> {
+        None
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+        None
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+        None
+    }
+    fn min_vals(&self) -> Option<u64> {
+        None
+    }
+    fn short(&self) -> Option<char> {
+        self.s.short
+    }
+    fn long(&self) -> Option<&'e str> {
+        self.s.long
+    }
+    fn val_delim(&self) -> Option<char> {
+        None
+    }
+    fn help(&self) -> Option<&'e str> {
+        self.b.help
+    }
+    fn long_help(&self) -> Option<&'e str> {
+        self.b.long_help
+    }
+    fn val_terminator(&self) -> Option<&'e str> {
+        None
+    }
+    fn default_val(&self) -> Option<&'e OsStr> {
+        None
+    }
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
+        None
+    }
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
+        None
+    }
+    fn longest_filter(&self) -> bool {
+        self.s.long.is_some()
+    }
+    fn aliases(&self) -> Option<Vec<&'e str>> {
+        if let Some(ref aliases) = self.s.aliases {
+            let vis_aliases: Vec<_> = aliases
+                .iter()
+                .filter_map(|&(n, v)| if v { Some(n) } else { None })
+                .collect();
+            if vis_aliases.is_empty() {
+                None
+            } else {
+                Some(vis_aliases)
+            }
+        } else {
+            None
+        }
+    }
+}
+
+impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> {
+    fn disp_ord(&self) -> usize {
+        self.s.disp_ord
+    }
+}
+
+impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> {
+    fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool {
+        self.b == other.b
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::FlagBuilder;
+    use crate::args::settings::ArgSettings;
+
+    #[test]
+    fn flagbuilder_display() {
+        let mut f = FlagBuilder::new("flg");
+        f.b.settings.set(ArgSettings::Multiple);
+        f.s.long = Some("flag");
+
+        assert_eq!(&*format!("{}", f), "--flag");
+
+        let mut f2 = FlagBuilder::new("flg");
+        f2.s.short = Some('f');
+
+        assert_eq!(&*format!("{}", f2), "-f");
+    }
+
+    #[test]
+    fn flagbuilder_display_single_alias() {
+        let mut f = FlagBuilder::new("flg");
+        f.s.long = Some("flag");
+        f.s.aliases = Some(vec![("als", true)]);
+
+        assert_eq!(&*format!("{}", f), "--flag");
+    }
+
+    #[test]
+    fn flagbuilder_display_multiple_aliases() {
+        let mut f = FlagBuilder::new("flg");
+        f.s.short = Some('f');
+        f.s.aliases = Some(vec![
+            ("alias_not_visible", false),
+            ("f2", true),
+            ("f3", true),
+            ("f4", true),
+        ]);
+        assert_eq!(&*format!("{}", f), "-f");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/mod.rs
@@ -0,0 +1,13 @@
+pub use self::base::Base;
+pub use self::flag::FlagBuilder;
+pub use self::option::OptBuilder;
+pub use self::positional::PosBuilder;
+pub use self::switched::Switched;
+pub use self::valued::Valued;
+
+mod base;
+mod flag;
+mod option;
+mod positional;
+mod switched;
+mod valued;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/option.rs
@@ -0,0 +1,295 @@
+// Std
+use std::{
+    ffi::{OsStr, OsString},
+    fmt::{Display, Formatter, Result},
+    mem,
+    rc::Rc,
+    result::Result as StdResult,
+};
+
+// Internal
+use crate::{
+    args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued},
+    map::{self, VecMap},
+    INTERNAL_ERROR_MSG,
+};
+
+#[allow(missing_debug_implementations)]
+#[doc(hidden)]
+#[derive(Default, Clone)]
+pub struct OptBuilder<'n, 'e>
+where
+    'n: 'e,
+{
+    pub b: Base<'n, 'e>,
+    pub s: Switched<'e>,
+    pub v: Valued<'n, 'e>,
+}
+
+impl<'n, 'e> OptBuilder<'n, 'e> {
+    pub fn new(name: &'n str) -> Self {
+        OptBuilder {
+            b: Base::new(name),
+            ..Default::default()
+        }
+    }
+}
+
+impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for OptBuilder<'n, 'e> {
+    fn from(a: &'z Arg<'n, 'e>) -> Self {
+        OptBuilder {
+            b: Base::from(a),
+            s: Switched::from(a),
+            v: Valued::from(a),
+        }
+    }
+}
+
+impl<'n, 'e> From<Arg<'n, 'e>> for OptBuilder<'n, 'e> {
+    fn from(mut a: Arg<'n, 'e>) -> Self {
+        a.v.fill_in();
+        OptBuilder {
+            b: mem::take(&mut a.b),
+            s: mem::take(&mut a.s),
+            v: mem::take(&mut a.v),
+        }
+    }
+}
+
+impl<'n, 'e> Display for OptBuilder<'n, 'e> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        debugln!("OptBuilder::fmt:{}", self.b.name);
+        let sep = if self.b.is_set(ArgSettings::RequireEquals) {
+            "="
+        } else {
+            " "
+        };
+        // Write the name such --long or -l
+        if let Some(l) = self.s.long {
+            write!(f, "--{}{}", l, sep)?;
+        } else {
+            write!(f, "-{}{}", self.s.short.unwrap(), sep)?;
+        }
+        let delim = if self.is_set(ArgSettings::RequireDelimiter) {
+            self.v.val_delim.expect(INTERNAL_ERROR_MSG)
+        } else {
+            ' '
+        };
+
+        // Write the values such as <name1> <name2>
+        if let Some(ref vec) = self.v.val_names {
+            let mut it = vec.iter().peekable();
+            while let Some((_, val)) = it.next() {
+                write!(f, "<{}>", val)?;
+                if it.peek().is_some() {
+                    write!(f, "{}", delim)?;
+                }
+            }
+            let num = vec.len();
+            if self.is_set(ArgSettings::Multiple) && num == 1 {
+                write!(f, "...")?;
+            }
+        } else if let Some(num) = self.v.num_vals {
+            let mut it = (0..num).peekable();
+            while let Some(_) = it.next() {
+                write!(f, "<{}>", self.b.name)?;
+                if it.peek().is_some() {
+                    write!(f, "{}", delim)?;
+                }
+            }
+            if self.is_set(ArgSettings::Multiple) && num == 1 {
+                write!(f, "...")?;
+            }
+        } else {
+            write!(
+                f,
+                "<{}>{}",
+                self.b.name,
+                if self.is_set(ArgSettings::Multiple) {
+                    "..."
+                } else {
+                    ""
+                }
+            )?;
+        }
+
+        Ok(())
+    }
+}
+
+impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> {
+    fn name(&self) -> &'n str {
+        self.b.name
+    }
+    fn overrides(&self) -> Option<&[&'e str]> {
+        self.b.overrides.as_ref().map(|o| &o[..])
+    }
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
+        self.b.requires.as_ref().map(|o| &o[..])
+    }
+    fn blacklist(&self) -> Option<&[&'e str]> {
+        self.b.blacklist.as_ref().map(|o| &o[..])
+    }
+    fn required_unless(&self) -> Option<&[&'e str]> {
+        self.b.r_unless.as_ref().map(|o| &o[..])
+    }
+    fn val_names(&self) -> Option<&VecMap<&'e str>> {
+        self.v.val_names.as_ref()
+    }
+    fn is_set(&self, s: ArgSettings) -> bool {
+        self.b.settings.is_set(s)
+    }
+    fn has_switch(&self) -> bool {
+        true
+    }
+    fn set(&mut self, s: ArgSettings) {
+        self.b.settings.set(s)
+    }
+    fn max_vals(&self) -> Option<u64> {
+        self.v.max_vals
+    }
+    fn val_terminator(&self) -> Option<&'e str> {
+        self.v.terminator
+    }
+    fn num_vals(&self) -> Option<u64> {
+        self.v.num_vals
+    }
+    fn possible_vals(&self) -> Option<&[&'e str]> {
+        self.v.possible_vals.as_ref().map(|o| &o[..])
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+        self.v.validator.as_ref()
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+        self.v.validator_os.as_ref()
+    }
+    fn min_vals(&self) -> Option<u64> {
+        self.v.min_vals
+    }
+    fn short(&self) -> Option<char> {
+        self.s.short
+    }
+    fn long(&self) -> Option<&'e str> {
+        self.s.long
+    }
+    fn val_delim(&self) -> Option<char> {
+        self.v.val_delim
+    }
+    fn takes_value(&self) -> bool {
+        true
+    }
+    fn help(&self) -> Option<&'e str> {
+        self.b.help
+    }
+    fn long_help(&self) -> Option<&'e str> {
+        self.b.long_help
+    }
+    fn default_val(&self) -> Option<&'e OsStr> {
+        self.v.default_val
+    }
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
+        self.v.default_vals_ifs.as_ref().map(|vm| vm.values())
+    }
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
+        self.v
+            .env
+            .as_ref()
+            .map(|&(key, ref value)| (key, value.as_ref()))
+    }
+    fn longest_filter(&self) -> bool {
+        true
+    }
+    fn aliases(&self) -> Option<Vec<&'e str>> {
+        if let Some(ref aliases) = self.s.aliases {
+            let vis_aliases: Vec<_> = aliases
+                .iter()
+                .filter_map(|&(n, v)| if v { Some(n) } else { None })
+                .collect();
+            if vis_aliases.is_empty() {
+                None
+            } else {
+                Some(vis_aliases)
+            }
+        } else {
+            None
+        }
+    }
+}
+
+impl<'n, 'e> DispOrder for OptBuilder<'n, 'e> {
+    fn disp_ord(&self) -> usize {
+        self.s.disp_ord
+    }
+}
+
+impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> {
+    fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool {
+        self.b == other.b
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::OptBuilder;
+    use crate::{args::settings::ArgSettings, map::VecMap};
+
+    #[test]
+    fn optbuilder_display1() {
+        let mut o = OptBuilder::new("opt");
+        o.s.long = Some("option");
+        o.b.settings.set(ArgSettings::Multiple);
+
+        assert_eq!(&*format!("{}", o), "--option <opt>...");
+    }
+
+    #[test]
+    fn optbuilder_display2() {
+        let mut v_names = VecMap::new();
+        v_names.insert(0, "file");
+        v_names.insert(1, "name");
+
+        let mut o2 = OptBuilder::new("opt");
+        o2.s.short = Some('o');
+        o2.v.val_names = Some(v_names);
+
+        assert_eq!(&*format!("{}", o2), "-o <file> <name>");
+    }
+
+    #[test]
+    fn optbuilder_display3() {
+        let mut v_names = VecMap::new();
+        v_names.insert(0, "file");
+        v_names.insert(1, "name");
+
+        let mut o2 = OptBuilder::new("opt");
+        o2.s.short = Some('o');
+        o2.v.val_names = Some(v_names);
+        o2.b.settings.set(ArgSettings::Multiple);
+
+        assert_eq!(&*format!("{}", o2), "-o <file> <name>");
+    }
+
+    #[test]
+    fn optbuilder_display_single_alias() {
+        let mut o = OptBuilder::new("opt");
+        o.s.long = Some("option");
+        o.s.aliases = Some(vec![("als", true)]);
+
+        assert_eq!(&*format!("{}", o), "--option <opt>");
+    }
+
+    #[test]
+    fn optbuilder_display_multiple_aliases() {
+        let mut o = OptBuilder::new("opt");
+        o.s.long = Some("option");
+        o.s.aliases = Some(vec![
+            ("als_not_visible", false),
+            ("als2", true),
+            ("als3", true),
+            ("als4", true),
+        ]);
+        assert_eq!(&*format!("{}", o), "--option <opt>");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/positional.rs
@@ -0,0 +1,284 @@
+// Std
+use std::{
+    borrow::Cow,
+    ffi::{OsStr, OsString},
+    fmt::{Display, Formatter, Result},
+    mem,
+    rc::Rc,
+    result::Result as StdResult,
+};
+
+// Internal
+use crate::{
+    args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Valued},
+    map::{self, VecMap},
+    INTERNAL_ERROR_MSG,
+};
+
+#[allow(missing_debug_implementations)]
+#[doc(hidden)]
+#[derive(Clone, Default)]
+pub struct PosBuilder<'n, 'e>
+where
+    'n: 'e,
+{
+    pub b: Base<'n, 'e>,
+    pub v: Valued<'n, 'e>,
+    pub index: u64,
+}
+
+impl<'n, 'e> PosBuilder<'n, 'e> {
+    pub fn new(name: &'n str, idx: u64) -> Self {
+        PosBuilder {
+            b: Base::new(name),
+            index: idx,
+            ..Default::default()
+        }
+    }
+
+    pub fn from_arg_ref(a: &Arg<'n, 'e>, idx: u64) -> Self {
+        let mut pb = PosBuilder {
+            b: Base::from(a),
+            v: Valued::from(a),
+            index: idx,
+        };
+        if a.v.max_vals.is_some()
+            || a.v.min_vals.is_some()
+            || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1)
+        {
+            pb.b.settings.set(ArgSettings::Multiple);
+        }
+        pb
+    }
+
+    pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self {
+        if a.v.max_vals.is_some()
+            || a.v.min_vals.is_some()
+            || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1)
+        {
+            a.b.settings.set(ArgSettings::Multiple);
+        }
+        PosBuilder {
+            b: mem::take(&mut a.b),
+            v: mem::take(&mut a.v),
+            index: idx,
+        }
+    }
+
+    pub fn multiple_str(&self) -> &str {
+        let mult_vals = self
+            .v
+            .val_names
+            .as_ref()
+            .map_or(true, |names| names.len() < 2);
+        if self.is_set(ArgSettings::Multiple) && mult_vals {
+            "..."
+        } else {
+            ""
+        }
+    }
+
+    pub fn name_no_brackets(&self) -> Cow<str> {
+        debugln!("PosBuilder::name_no_brackets;");
+        let mut delim = String::new();
+        delim.push(if self.is_set(ArgSettings::RequireDelimiter) {
+            self.v.val_delim.expect(INTERNAL_ERROR_MSG)
+        } else {
+            ' '
+        });
+        if let Some(ref names) = self.v.val_names {
+            debugln!("PosBuilder:name_no_brackets: val_names={:#?}", names);
+            if names.len() > 1 {
+                Cow::Owned(
+                    names
+                        .values()
+                        .map(|n| format!("<{}>", n))
+                        .collect::<Vec<_>>()
+                        .join(&*delim),
+                )
+            } else {
+                Cow::Borrowed(names.values().next().expect(INTERNAL_ERROR_MSG))
+            }
+        } else {
+            debugln!("PosBuilder:name_no_brackets: just name");
+            Cow::Borrowed(self.b.name)
+        }
+    }
+}
+
+impl<'n, 'e> Display for PosBuilder<'n, 'e> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        let mut delim = String::new();
+        delim.push(if self.is_set(ArgSettings::RequireDelimiter) {
+            self.v.val_delim.expect(INTERNAL_ERROR_MSG)
+        } else {
+            ' '
+        });
+        if let Some(ref names) = self.v.val_names {
+            write!(
+                f,
+                "{}",
+                names
+                    .values()
+                    .map(|n| format!("<{}>", n))
+                    .collect::<Vec<_>>()
+                    .join(&*delim)
+            )?;
+        } else {
+            write!(f, "<{}>", self.b.name)?;
+        }
+        if self.b.settings.is_set(ArgSettings::Multiple)
+            && (self.v.val_names.is_none() || self.v.val_names.as_ref().unwrap().len() == 1)
+        {
+            write!(f, "...")?;
+        }
+
+        Ok(())
+    }
+}
+
+impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> {
+    fn name(&self) -> &'n str {
+        self.b.name
+    }
+    fn overrides(&self) -> Option<&[&'e str]> {
+        self.b.overrides.as_ref().map(|o| &o[..])
+    }
+    fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> {
+        self.b.requires.as_ref().map(|o| &o[..])
+    }
+    fn blacklist(&self) -> Option<&[&'e str]> {
+        self.b.blacklist.as_ref().map(|o| &o[..])
+    }
+    fn required_unless(&self) -> Option<&[&'e str]> {
+        self.b.r_unless.as_ref().map(|o| &o[..])
+    }
+    fn val_names(&self) -> Option<&VecMap<&'e str>> {
+        self.v.val_names.as_ref()
+    }
+    fn is_set(&self, s: ArgSettings) -> bool {
+        self.b.settings.is_set(s)
+    }
+    fn set(&mut self, s: ArgSettings) {
+        self.b.settings.set(s)
+    }
+    fn has_switch(&self) -> bool {
+        false
+    }
+    fn max_vals(&self) -> Option<u64> {
+        self.v.max_vals
+    }
+    fn val_terminator(&self) -> Option<&'e str> {
+        self.v.terminator
+    }
+    fn num_vals(&self) -> Option<u64> {
+        self.v.num_vals
+    }
+    fn possible_vals(&self) -> Option<&[&'e str]> {
+        self.v.possible_vals.as_ref().map(|o| &o[..])
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> {
+        self.v.validator.as_ref()
+    }
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> {
+        self.v.validator_os.as_ref()
+    }
+    fn min_vals(&self) -> Option<u64> {
+        self.v.min_vals
+    }
+    fn short(&self) -> Option<char> {
+        None
+    }
+    fn long(&self) -> Option<&'e str> {
+        None
+    }
+    fn val_delim(&self) -> Option<char> {
+        self.v.val_delim
+    }
+    fn takes_value(&self) -> bool {
+        true
+    }
+    fn help(&self) -> Option<&'e str> {
+        self.b.help
+    }
+    fn long_help(&self) -> Option<&'e str> {
+        self.b.long_help
+    }
+    fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> {
+        self.v.default_vals_ifs.as_ref().map(|vm| vm.values())
+    }
+    fn default_val(&self) -> Option<&'e OsStr> {
+        self.v.default_val
+    }
+    fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> {
+        self.v
+            .env
+            .as_ref()
+            .map(|&(key, ref value)| (key, value.as_ref()))
+    }
+    fn longest_filter(&self) -> bool {
+        true
+    }
+    fn aliases(&self) -> Option<Vec<&'e str>> {
+        None
+    }
+}
+
+impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> {
+    fn disp_ord(&self) -> usize {
+        self.index as usize
+    }
+}
+
+impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> {
+    fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool {
+        self.b == other.b
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::PosBuilder;
+    use crate::{args::settings::ArgSettings, map::VecMap};
+
+    #[test]
+    fn display_mult() {
+        let mut p = PosBuilder::new("pos", 1);
+        p.b.settings.set(ArgSettings::Multiple);
+
+        assert_eq!(&*format!("{}", p), "<pos>...");
+    }
+
+    #[test]
+    fn display_required() {
+        let mut p2 = PosBuilder::new("pos", 1);
+        p2.b.settings.set(ArgSettings::Required);
+
+        assert_eq!(&*format!("{}", p2), "<pos>");
+    }
+
+    #[test]
+    fn display_val_names() {
+        let mut p2 = PosBuilder::new("pos", 1);
+        let mut vm = VecMap::new();
+        vm.insert(0, "file1");
+        vm.insert(1, "file2");
+        p2.v.val_names = Some(vm);
+
+        assert_eq!(&*format!("{}", p2), "<file1> <file2>");
+    }
+
+    #[test]
+    fn display_val_names_req() {
+        let mut p2 = PosBuilder::new("pos", 1);
+        p2.b.settings.set(ArgSettings::Required);
+        let mut vm = VecMap::new();
+        vm.insert(0, "file1");
+        vm.insert(1, "file2");
+        p2.v.val_names = Some(vm);
+
+        assert_eq!(&*format!("{}", p2), "<file1> <file2>");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/switched.rs
@@ -0,0 +1,40 @@
+use crate::Arg;
+
+#[derive(Debug)]
+pub struct Switched<'b> {
+    pub short: Option<char>,
+    pub long: Option<&'b str>,
+    pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible)
+    pub disp_ord: usize,
+    pub unified_ord: usize,
+}
+
+impl<'e> Default for Switched<'e> {
+    fn default() -> Self {
+        Switched {
+            short: None,
+            long: None,
+            aliases: None,
+            disp_ord: 999,
+            unified_ord: 999,
+        }
+    }
+}
+
+impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> {
+    fn from(a: &'z Arg<'n, 'e>) -> Self {
+        a.s.clone()
+    }
+}
+
+impl<'e> Clone for Switched<'e> {
+    fn clone(&self) -> Self {
+        Switched {
+            short: self.short,
+            long: self.long,
+            aliases: self.aliases.clone(),
+            disp_ord: self.disp_ord,
+            unified_ord: self.unified_ord,
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_builder/valued.rs
@@ -0,0 +1,70 @@
+use std::{
+    ffi::{OsStr, OsString},
+    rc::Rc,
+};
+
+use crate::{map::VecMap, Arg};
+
+#[allow(missing_debug_implementations)]
+#[derive(Clone)]
+pub struct Valued<'a, 'b>
+where
+    'a: 'b,
+{
+    pub possible_vals: Option<Vec<&'b str>>,
+    pub val_names: Option<VecMap<&'b str>>,
+    pub num_vals: Option<u64>,
+    pub max_vals: Option<u64>,
+    pub min_vals: Option<u64>,
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    pub validator: Option<Rc<Fn(String) -> Result<(), String>>>,
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    pub validator_os: Option<Rc<Fn(&OsStr) -> Result<(), OsString>>>,
+    pub val_delim: Option<char>,
+    pub default_val: Option<&'b OsStr>,
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
+    pub default_vals_ifs: Option<VecMap<(&'a str, Option<&'b OsStr>, &'b OsStr)>>,
+    pub env: Option<(&'a OsStr, Option<OsString>)>,
+    pub terminator: Option<&'b str>,
+}
+
+impl<'n, 'e> Default for Valued<'n, 'e> {
+    fn default() -> Self {
+        Valued {
+            possible_vals: None,
+            num_vals: None,
+            min_vals: None,
+            max_vals: None,
+            val_names: None,
+            validator: None,
+            validator_os: None,
+            val_delim: None,
+            default_val: None,
+            default_vals_ifs: None,
+            env: None,
+            terminator: None,
+        }
+    }
+}
+
+impl<'n, 'e> Valued<'n, 'e> {
+    pub fn fill_in(&mut self) {
+        if let Some(ref vec) = self.val_names {
+            if vec.len() > 1 {
+                self.num_vals = Some(vec.len() as u64);
+            }
+        }
+    }
+}
+
+impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Valued<'n, 'e> {
+    fn from(a: &'z Arg<'n, 'e>) -> Self {
+        let mut v = a.v.clone();
+        if let Some(ref vec) = a.v.val_names {
+            if vec.len() > 1 {
+                v.num_vals = Some(vec.len() as u64);
+            }
+        }
+        v
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_matcher.rs
@@ -0,0 +1,274 @@
+// Std
+use std::{
+    collections::{
+        hash_map::{Entry, Iter},
+        HashMap,
+    },
+    ffi::OsStr,
+    mem,
+    ops::Deref,
+};
+
+// Internal
+use crate::args::{settings::ArgSettings, AnyArg, ArgMatches, MatchedArg, SubCommand};
+
+#[doc(hidden)]
+#[allow(missing_debug_implementations)]
+pub struct ArgMatcher<'a>(pub ArgMatches<'a>);
+
+impl<'a> Default for ArgMatcher<'a> {
+    fn default() -> Self {
+        ArgMatcher(ArgMatches::default())
+    }
+}
+
+impl<'a> ArgMatcher<'a> {
+    pub fn new() -> Self {
+        ArgMatcher::default()
+    }
+
+    pub fn process_arg_overrides<'b>(
+        &mut self,
+        a: Option<&AnyArg<'a, 'b>>,
+        overrides: &mut Vec<(&'b str, &'a str)>,
+        required: &mut Vec<&'a str>,
+        check_all: bool,
+    ) {
+        debugln!(
+            "ArgMatcher::process_arg_overrides:{:?};",
+            a.map_or(None, |a| Some(a.name()))
+        );
+        if let Some(aa) = a {
+            let mut self_done = false;
+            if let Some(a_overrides) = aa.overrides() {
+                for overr in a_overrides {
+                    debugln!("ArgMatcher::process_arg_overrides:iter:{};", overr);
+                    if overr == &aa.name() {
+                        self_done = true;
+                        self.handle_self_overrides(a);
+                    } else if self.is_present(overr) {
+                        debugln!(
+                            "ArgMatcher::process_arg_overrides:iter:{}: removing from matches;",
+                            overr
+                        );
+                        self.remove(overr);
+                        for i in (0..required.len()).rev() {
+                            if &required[i] == overr {
+                                debugln!(
+                                    "ArgMatcher::process_arg_overrides:iter:{}: removing required;",
+                                    overr
+                                );
+                                required.swap_remove(i);
+                                break;
+                            }
+                        }
+                        overrides.push((overr, aa.name()));
+                    } else {
+                        overrides.push((overr, aa.name()));
+                    }
+                }
+            }
+            if check_all && !self_done {
+                self.handle_self_overrides(a);
+            }
+        }
+    }
+
+    pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) {
+        debugln!(
+            "ArgMatcher::handle_self_overrides:{:?};",
+            a.map_or(None, |a| Some(a.name()))
+        );
+        if let Some(aa) = a {
+            if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) {
+                // positional args can't override self or else we would never advance to the next
+
+                // Also flags with --multiple set are ignored otherwise we could never have more
+                // than one
+                return;
+            }
+            if let Some(ma) = self.get_mut(aa.name()) {
+                if ma.vals.len() > 1 {
+                    // swap_remove(0) would be O(1) but does not preserve order, which
+                    // we need
+                    ma.vals.remove(0);
+                    ma.occurs = 1;
+                } else if !aa.takes_value() && ma.occurs > 1 {
+                    ma.occurs = 1;
+                }
+            }
+        }
+    }
+
+    pub fn is_present(&self, name: &str) -> bool {
+        self.0.is_present(name)
+    }
+
+    pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) {
+        debugln!(
+            "ArgMatcher::get_global_values: global_arg_vec={:?}",
+            global_arg_vec
+        );
+        let mut vals_map = HashMap::new();
+        self.fill_in_global_values(global_arg_vec, &mut vals_map);
+    }
+
+    fn fill_in_global_values(
+        &mut self,
+        global_arg_vec: &[&'a str],
+        vals_map: &mut HashMap<&'a str, MatchedArg>,
+    ) {
+        for global_arg in global_arg_vec {
+            if let Some(ma) = self.get(global_arg) {
+                // We have to check if the parent's global arg wasn't used but still exists
+                // such as from a default value.
+                //
+                // For example, `myprog subcommand --global-arg=value` where --global-arg defines
+                // a default value of `other` myprog would have an existing MatchedArg for
+                // --global-arg where the value is `other`, however the occurs will be 0.
+                let to_update = if let Some(parent_ma) = vals_map.get(global_arg) {
+                    if parent_ma.occurs > 0 && ma.occurs == 0 {
+                        parent_ma.clone()
+                    } else {
+                        ma.clone()
+                    }
+                } else {
+                    ma.clone()
+                };
+                vals_map.insert(global_arg, to_update);
+            }
+        }
+        if let Some(ref mut sc) = self.0.subcommand {
+            let mut am = ArgMatcher(mem::replace(&mut sc.matches, ArgMatches::new()));
+            am.fill_in_global_values(global_arg_vec, vals_map);
+            mem::swap(&mut am.0, &mut sc.matches);
+        }
+
+        for (name, matched_arg) in vals_map.iter_mut() {
+            self.0.args.insert(name, matched_arg.clone());
+        }
+    }
+
+    pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> {
+        self.0.args.get_mut(arg)
+    }
+
+    pub fn get(&self, arg: &str) -> Option<&MatchedArg> {
+        self.0.args.get(arg)
+    }
+
+    pub fn remove(&mut self, arg: &str) {
+        self.0.args.remove(arg);
+    }
+
+    pub fn remove_all(&mut self, args: &[&str]) {
+        for &arg in args {
+            self.0.args.remove(arg);
+        }
+    }
+
+    pub fn insert(&mut self, name: &'a str) {
+        self.0.args.insert(name, MatchedArg::new());
+    }
+
+    pub fn contains(&self, arg: &str) -> bool {
+        self.0.args.contains_key(arg)
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.0.args.is_empty()
+    }
+
+    pub fn usage(&mut self, usage: String) {
+        self.0.usage = Some(usage);
+    }
+
+    pub fn arg_names(&'a self) -> Vec<&'a str> {
+        self.0.args.keys().map(Deref::deref).collect()
+    }
+
+    pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> {
+        self.0.args.entry(arg)
+    }
+
+    pub fn subcommand(&mut self, sc: SubCommand<'a>) {
+        self.0.subcommand = Some(Box::new(sc));
+    }
+
+    pub fn subcommand_name(&self) -> Option<&str> {
+        self.0.subcommand_name()
+    }
+
+    pub fn iter(&self) -> Iter<&str, MatchedArg> {
+        self.0.args.iter()
+    }
+
+    pub fn inc_occurrence_of(&mut self, arg: &'a str) {
+        debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg);
+        if let Some(a) = self.get_mut(arg) {
+            a.occurs += 1;
+            return;
+        }
+        debugln!("ArgMatcher::inc_occurrence_of: first instance");
+        self.insert(arg);
+    }
+
+    pub fn inc_occurrences_of(&mut self, args: &[&'a str]) {
+        debugln!("ArgMatcher::inc_occurrences_of: args={:?}", args);
+        for arg in args {
+            self.inc_occurrence_of(arg);
+        }
+    }
+
+    pub fn add_val_to(&mut self, arg: &'a str, val: &OsStr) {
+        let ma = self.entry(arg).or_insert(MatchedArg {
+            occurs: 0,
+            indices: Vec::with_capacity(1),
+            vals: Vec::with_capacity(1),
+        });
+        ma.vals.push(val.to_owned());
+    }
+
+    pub fn add_index_to(&mut self, arg: &'a str, idx: usize) {
+        let ma = self.entry(arg).or_insert(MatchedArg {
+            occurs: 0,
+            indices: Vec::with_capacity(1),
+            vals: Vec::new(),
+        });
+        ma.indices.push(idx);
+    }
+
+    pub fn needs_more_vals<'b, A>(&self, o: &A) -> bool
+    where
+        A: AnyArg<'a, 'b>,
+    {
+        debugln!("ArgMatcher::needs_more_vals: o={}", o.name());
+        if let Some(ma) = self.get(o.name()) {
+            if let Some(num) = o.num_vals() {
+                debugln!("ArgMatcher::needs_more_vals: num_vals...{}", num);
+                return if o.is_set(ArgSettings::Multiple) {
+                    ((ma.vals.len() as u64) % num) != 0
+                } else {
+                    num != (ma.vals.len() as u64)
+                };
+            } else if let Some(num) = o.max_vals() {
+                debugln!("ArgMatcher::needs_more_vals: max_vals...{}", num);
+                return (ma.vals.len() as u64) <= num;
+            } else if o.min_vals().is_some() {
+                debugln!("ArgMatcher::needs_more_vals: min_vals...true");
+                return true;
+            }
+            return o.is_set(ArgSettings::Multiple);
+        }
+        true
+    }
+}
+
+// Not changing to From just to not deal with possible breaking changes on v2 since v3 is coming
+// in the future anyways
+#[cfg_attr(feature = "cargo-clippy", allow(clippy::from_over_into))]
+impl<'a> Into<ArgMatches<'a>> for ArgMatcher<'a> {
+    fn into(self) -> ArgMatches<'a> {
+        self.0
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/arg_matches.rs
@@ -0,0 +1,1001 @@
+// Std
+use std::{
+    borrow::Cow,
+    collections::HashMap,
+    ffi::{OsStr, OsString},
+    iter::Map,
+    slice::Iter,
+};
+
+// Internal
+use crate::{
+    args::{MatchedArg, SubCommand},
+    INVALID_UTF8,
+};
+
+/// Used to get information about the arguments that were supplied to the program at runtime by
+/// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of
+/// methods.
+///
+/// # Examples
+///
+/// ```no_run
+/// # use clap::{App, Arg};
+/// let matches = App::new("MyApp")
+///     .arg(Arg::with_name("out")
+///         .long("output")
+///         .required(true)
+///         .takes_value(true))
+///     .arg(Arg::with_name("debug")
+///         .short("d")
+///         .multiple(true))
+///     .arg(Arg::with_name("cfg")
+///         .short("c")
+///         .takes_value(true))
+///     .get_matches(); // builds the instance of ArgMatches
+///
+/// // to get information about the "cfg" argument we created, such as the value supplied we use
+/// // various ArgMatches methods, such as ArgMatches::value_of
+/// if let Some(c) = matches.value_of("cfg") {
+///     println!("Value for -c: {}", c);
+/// }
+///
+/// // The ArgMatches::value_of method returns an Option because the user may not have supplied
+/// // that argument at runtime. But if we specified that the argument was "required" as we did
+/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually
+/// // used at runtime.
+/// println!("Value for --output: {}", matches.value_of("out").unwrap());
+///
+/// // You can check the presence of an argument
+/// if matches.is_present("out") {
+///     // Another way to check if an argument was present, or if it occurred multiple times is to
+///     // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the
+///     // number of times that it occurred, if it was. To allow an argument to appear more than
+///     // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0.
+///     if matches.occurrences_of("debug") > 2 {
+///         println!("Debug mode is REALLY on, don't be crazy");
+///     } else {
+///         println!("Debug mode kind of on");
+///     }
+/// }
+/// ```
+/// [`App::get_matches`]: ./struct.App.html#method.get_matches
+#[derive(Debug, Clone)]
+pub struct ArgMatches<'a> {
+    #[doc(hidden)]
+    pub args: HashMap<&'a str, MatchedArg>,
+    #[doc(hidden)]
+    pub subcommand: Option<Box<SubCommand<'a>>>,
+    #[doc(hidden)]
+    pub usage: Option<String>,
+}
+
+impl<'a> Default for ArgMatches<'a> {
+    fn default() -> Self {
+        ArgMatches {
+            args: HashMap::new(),
+            subcommand: None,
+            usage: None,
+        }
+    }
+}
+
+impl<'a> ArgMatches<'a> {
+    #[doc(hidden)]
+    pub fn new() -> Self {
+        ArgMatches {
+            ..Default::default()
+        }
+    }
+
+    /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes
+    /// an additional value at runtime). If the option wasn't present at runtime
+    /// it returns `None`.
+    ///
+    /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
+    /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first*
+    /// value.
+    ///
+    /// # Panics
+    ///
+    /// This method will [`panic!`] if the value contains invalid UTF-8 code points.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("output")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec!["myapp", "something"]);
+    ///
+    /// assert_eq!(m.value_of("output"), Some("something"));
+    /// ```
+    /// [option]: ./struct.Arg.html#method.takes_value
+    /// [positional]: ./struct.Arg.html#method.index
+    /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
+    /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
+    pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            if let Some(v) = arg.vals.get(0) {
+                return Some(v.to_str().expect(INVALID_UTF8));
+            }
+        }
+        None
+    }
+
+    /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime
+    /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those
+    /// invalid points will be replaced with `\u{FFFD}`
+    ///
+    /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
+    /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value.
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, Arg};
+    /// use std::ffi::OsString;
+    /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+    ///
+    /// let m = App::new("utf8")
+    ///     .arg(Arg::from_usage("<arg> 'some arg'"))
+    ///     .get_matches_from(vec![OsString::from("myprog"),
+    ///                             // "Hi {0xe9}!"
+    ///                             OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
+    /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!");
+    /// ```
+    /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy
+    pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            if let Some(v) = arg.vals.get(0) {
+                return Some(v.to_string_lossy());
+            }
+        }
+        None
+    }
+
+    /// Gets the OS version of a string value of a specific argument. If the option wasn't present
+    /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes,
+    /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in
+    /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument
+    /// value may contain invalid UTF-8 code points.
+    ///
+    /// *NOTE:* If getting a value for an option or positional argument that allows multiples,
+    /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first*
+    /// value.
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, Arg};
+    /// use std::ffi::OsString;
+    /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+    ///
+    /// let m = App::new("utf8")
+    ///     .arg(Arg::from_usage("<arg> 'some arg'"))
+    ///     .get_matches_from(vec![OsString::from("myprog"),
+    ///                             // "Hi {0xe9}!"
+    ///                             OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
+    /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
+    /// ```
+    /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
+    /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
+    pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr> {
+        self.args
+            .get(name.as_ref())
+            .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str()))
+    }
+
+    /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument
+    /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at
+    /// runtime it returns `None`
+    ///
+    /// # Panics
+    ///
+    /// This method will panic if any of the values contain invalid UTF-8 code points.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("output")
+    ///         .multiple(true)
+    ///         .short("o")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec![
+    ///         "myprog", "-o", "val1", "val2", "val3"
+    ///     ]);
+    /// let vals: Vec<&str> = m.values_of("output").unwrap().collect();
+    /// assert_eq!(vals, ["val1", "val2", "val3"]);
+    /// ```
+    /// [`Values`]: ./struct.Values.html
+    /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
+    pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            fn to_str_slice(o: &OsString) -> &str {
+                o.to_str().expect(INVALID_UTF8)
+            }
+            let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer
+            return Some(Values {
+                iter: arg.vals.iter().map(to_str_slice),
+            });
+        }
+        None
+    }
+
+    /// Gets the lossy values of a specific argument. If the option wasn't present at runtime
+    /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points,
+    /// those invalid points will be replaced with `\u{FFFD}`
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, Arg};
+    /// use std::ffi::OsString;
+    /// use std::os::unix::ffi::OsStringExt;
+    ///
+    /// let m = App::new("utf8")
+    ///     .arg(Arg::from_usage("<arg>... 'some arg'"))
+    ///     .get_matches_from(vec![OsString::from("myprog"),
+    ///                             // "Hi"
+    ///                             OsString::from_vec(vec![b'H', b'i']),
+    ///                             // "{0xe9}!"
+    ///                             OsString::from_vec(vec![0xe9, b'!'])]);
+    /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter();
+    /// assert_eq!(&itr.next().unwrap()[..], "Hi");
+    /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!");
+    /// assert_eq!(itr.next(), None);
+    /// ```
+    pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            return Some(
+                arg.vals
+                    .iter()
+                    .map(|v| v.to_string_lossy().into_owned())
+                    .collect(),
+            );
+        }
+        None
+    }
+
+    /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a
+    /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value
+    /// on Unix-like systems is any series of bytes, regardless of whether or not they contain
+    /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid
+    /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points.
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, Arg};
+    /// use std::ffi::{OsStr,OsString};
+    /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+    ///
+    /// let m = App::new("utf8")
+    ///     .arg(Arg::from_usage("<arg>... 'some arg'"))
+    ///     .get_matches_from(vec![OsString::from("myprog"),
+    ///                                 // "Hi"
+    ///                                 OsString::from_vec(vec![b'H', b'i']),
+    ///                                 // "{0xe9}!"
+    ///                                 OsString::from_vec(vec![0xe9, b'!'])]);
+    ///
+    /// let mut itr = m.values_of_os("arg").unwrap().into_iter();
+    /// assert_eq!(itr.next(), Some(OsStr::new("Hi")));
+    /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!'])));
+    /// assert_eq!(itr.next(), None);
+    /// ```
+    /// [`OsValues`]: ./struct.OsValues.html
+    /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html
+    /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
+    /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
+    pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> {
+        fn to_str_slice(o: &OsString) -> &OsStr {
+            &*o
+        }
+        let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            return Some(OsValues {
+                iter: arg.vals.iter().map(to_str_slice),
+            });
+        }
+        None
+    }
+
+    /// Returns `true` if an argument was present at runtime, otherwise `false`.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .get_matches_from(vec![
+    ///         "myprog", "-d"
+    ///     ]);
+    ///
+    /// assert!(m.is_present("debug"));
+    /// ```
+    pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool {
+        if let Some(ref sc) = self.subcommand {
+            if sc.name == name.as_ref() {
+                return true;
+            }
+        }
+        self.args.contains_key(name.as_ref())
+    }
+
+    /// Returns the number of times an argument was used at runtime. If an argument isn't present
+    /// it will return `0`.
+    ///
+    /// **NOTE:** This returns the number of times the argument was used, *not* the number of
+    /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4
+    /// values).
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d")
+    ///         .multiple(true))
+    ///     .get_matches_from(vec![
+    ///         "myprog", "-d", "-d", "-d"
+    ///     ]);
+    ///
+    /// assert_eq!(m.occurrences_of("debug"), 3);
+    /// ```
+    ///
+    /// This next example shows that counts actual uses of the argument, not just `-`'s
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d")
+    ///         .multiple(true))
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .get_matches_from(vec![
+    ///         "myprog", "-ddfd"
+    ///     ]);
+    ///
+    /// assert_eq!(m.occurrences_of("debug"), 3);
+    /// assert_eq!(m.occurrences_of("flag"), 1);
+    /// ```
+    pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64 {
+        self.args.get(name.as_ref()).map_or(0, |a| a.occurs)
+    }
+
+    /// Gets the starting index of the argument in respect to all other arguments. Indices are
+    /// similar to argv indices, but are not exactly 1:1.
+    ///
+    /// For flags (i.e. those arguments which don't have an associated value), indices refer
+    /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+    /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+    /// index for `val` would be recorded. This is by design.
+    ///
+    /// Besides the flag/option descrepancy, the primary difference between an argv index and clap
+    /// index, is that clap continues counting once all arguments have properly seperated, whereas
+    /// an argv index does not.
+    ///
+    /// The examples should clear this up.
+    ///
+    /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first*
+    /// index.
+    ///
+    /// # Examples
+    ///
+    /// The argv indices are listed in the comments below. See how they correspond to the clap
+    /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in
+    /// in an `ArgMatches` struct for querying.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec!["myapp", "-f", "-o", "val"]);
+    ///             // ARGV idices: ^0       ^1    ^2    ^3
+    ///             // clap idices:          ^1          ^3
+    ///
+    /// assert_eq!(m.index_of("flag"), Some(1));
+    /// assert_eq!(m.index_of("option"), Some(3));
+    /// ```
+    ///
+    /// Now notice, if we use one of the other styles of options:
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec!["myapp", "-f", "-o=val"]);
+    ///             // ARGV idices: ^0       ^1    ^2
+    ///             // clap idices:          ^1       ^3
+    ///
+    /// assert_eq!(m.index_of("flag"), Some(1));
+    /// assert_eq!(m.index_of("option"), Some(3));
+    /// ```
+    ///
+    /// Things become much more complicated, or clear if we look at a more complex combination of
+    /// flags. Let's also throw in the final option style for good measure.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("flag2")
+    ///         .short("F"))
+    ///     .arg(Arg::with_name("flag3")
+    ///         .short("z"))
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true))
+    ///     .get_matches_from(vec!["myapp", "-fzF", "-oval"]);
+    ///             // ARGV idices: ^0      ^1       ^2
+    ///             // clap idices:         ^1,2,3    ^5
+    ///             //
+    ///             // clap sees the above as 'myapp -f -z -F -o val'
+    ///             //                         ^0    ^1 ^2 ^3 ^4 ^5
+    /// assert_eq!(m.index_of("flag"), Some(1));
+    /// assert_eq!(m.index_of("flag2"), Some(3));
+    /// assert_eq!(m.index_of("flag3"), Some(2));
+    /// assert_eq!(m.index_of("option"), Some(5));
+    /// ```
+    ///
+    /// One final combination of flags/options to see how they combine:
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("flag2")
+    ///         .short("F"))
+    ///     .arg(Arg::with_name("flag3")
+    ///         .short("z"))
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myapp", "-fzFoval"]);
+    ///             // ARGV idices: ^0       ^1
+    ///             // clap idices:          ^1,2,3^5
+    ///             //
+    ///             // clap sees the above as 'myapp -f -z -F -o val'
+    ///             //                         ^0    ^1 ^2 ^3 ^4 ^5
+    /// assert_eq!(m.index_of("flag"), Some(1));
+    /// assert_eq!(m.index_of("flag2"), Some(3));
+    /// assert_eq!(m.index_of("flag3"), Some(2));
+    /// assert_eq!(m.index_of("option"), Some(5));
+    /// ```
+    ///
+    /// The last part to mention is when values are sent in multiple groups with a [delimiter].
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+    ///             // ARGV idices: ^0       ^1
+    ///             // clap idices:             ^2   ^3   ^4
+    ///             //
+    ///             // clap sees the above as 'myapp -o val1 val2 val3'
+    ///             //                         ^0    ^1 ^2   ^3   ^4
+    /// assert_eq!(m.index_of("option"), Some(2));
+    /// ```
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    /// [delimiter]: ./struct.Arg.html#method.value_delimiter
+    pub fn index_of<S: AsRef<str>>(&self, name: S) -> Option<usize> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            if let Some(i) = arg.indices.get(0) {
+                return Some(*i);
+            }
+        }
+        None
+    }
+
+    /// Gets all indices of the argument in respect to all other arguments. Indices are
+    /// similar to argv indices, but are not exactly 1:1.
+    ///
+    /// For flags (i.e. those arguments which don't have an associated value), indices refer
+    /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices
+    /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the
+    /// index for `val` would be recorded. This is by design.
+    ///
+    /// *NOTE:* For more information about how clap indices compare to argv indices, see
+    /// [`ArgMatches::index_of`]
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .use_delimiter(true)
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+    ///             // ARGV idices: ^0       ^1
+    ///             // clap idices:             ^2   ^3   ^4
+    ///             //
+    ///             // clap sees the above as 'myapp -o val1 val2 val3'
+    ///             //                         ^0    ^1 ^2   ^3   ^4
+    /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]);
+    /// ```
+    ///
+    /// Another quick example is when flags and options are used together
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true))
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f")
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]);
+    ///             // ARGV idices: ^0       ^1    ^2      ^3    ^4    ^5      ^6
+    ///             // clap idices:                ^2      ^3          ^5      ^6
+    ///
+    /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]);
+    /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]);
+    /// ```
+    ///
+    /// One final example, which is an odd case; if we *don't* use  value delimiter as we did with
+    /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they
+    /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a
+    /// single index.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg};
+    /// let m = App::new("myapp")
+    ///     .arg(Arg::with_name("option")
+    ///         .short("o")
+    ///         .takes_value(true)
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]);
+    ///             // ARGV idices: ^0       ^1
+    ///             // clap idices:             ^2
+    ///             //
+    ///             // clap sees the above as 'myapp -o "val1,val2,val3"'
+    ///             //                         ^0    ^1  ^2
+    /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]);
+    /// ```
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of
+    /// [delimiter]: ./struct.Arg.html#method.value_delimiter
+    pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>> {
+        if let Some(arg) = self.args.get(name.as_ref()) {
+            fn to_usize(i: &usize) -> usize {
+                *i
+            }
+            let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer
+            return Some(Indices {
+                iter: arg.indices.iter().map(to_usize),
+            });
+        }
+        None
+    }
+
+    /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
+    /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if
+    /// the subcommand wasn't present at runtime.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, SubCommand};
+    /// let app_m = App::new("myprog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .subcommand(SubCommand::with_name("test")
+    ///         .arg(Arg::with_name("opt")
+    ///             .long("option")
+    ///             .takes_value(true)))
+    ///     .get_matches_from(vec![
+    ///         "myprog", "-d", "test", "--option", "val"
+    ///     ]);
+    ///
+    /// // Both parent commands, and child subcommands can have arguments present at the same times
+    /// assert!(app_m.is_present("debug"));
+    ///
+    /// // Get the subcommand's ArgMatches instance
+    /// if let Some(sub_m) = app_m.subcommand_matches("test") {
+    ///     // Use the struct like normal
+    ///     assert_eq!(sub_m.value_of("opt"), Some("val"));
+    /// }
+    /// ```
+    /// [`Subcommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    pub fn subcommand_matches<S: AsRef<str>>(&self, name: S) -> Option<&ArgMatches<'a>> {
+        if let Some(ref s) = self.subcommand {
+            if s.name == name.as_ref() {
+                return Some(&s.matches);
+            }
+        }
+        None
+    }
+
+    /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`]
+    /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know
+    /// which subcommand was actually used. This method returns the name of the subcommand that was
+    /// used at runtime, or `None` if one wasn't.
+    ///
+    /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime,
+    /// but only a single subcommand from any group of sibling commands may used at once.
+    ///
+    /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as
+    /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is
+    /// aware these aren't actually all subcommands in the real `git` interface, but it makes
+    /// explanation easier)
+    ///
+    /// ```notrust
+    ///              Top Level App (git)                         TOP
+    ///                              |
+    ///       -----------------------------------------
+    ///      /             |                \          \
+    ///   clone          push              add       commit      LEVEL 1
+    ///     |           /    \            /    \       |
+    ///    url      origin   remote    ref    name   message     LEVEL 2
+    ///             /                  /\
+    ///          path            remote  local                   LEVEL 3
+    /// ```
+    ///
+    /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all
+    /// inclusive list, and not including argument options per command for brevity and clarity):
+    ///
+    /// ```sh
+    /// $ git clone url
+    /// $ git push origin path
+    /// $ git add ref local
+    /// $ git commit message
+    /// ```
+    ///
+    /// Notice only one command per "level" may be used. You could not, for example, do `$ git
+    /// clone url push origin path`
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    ///  let app_m = App::new("git")
+    ///      .subcommand(SubCommand::with_name("clone"))
+    ///      .subcommand(SubCommand::with_name("push"))
+    ///      .subcommand(SubCommand::with_name("commit"))
+    ///      .get_matches();
+    ///
+    /// match app_m.subcommand_name() {
+    ///     Some("clone")  => {}, // clone was used
+    ///     Some("push")   => {}, // push was used
+    ///     Some("commit") => {}, // commit was used
+    ///     _              => {}, // Either no subcommand or one not tested for...
+    /// }
+    /// ```
+    /// [`Subcommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    /// [`ArgMatches`]: ./struct.ArgMatches.html
+    pub fn subcommand_name(&self) -> Option<&str> {
+        self.subcommand.as_ref().map(|sc| &sc.name[..])
+    }
+
+    /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`]
+    /// by returning a tuple with both pieces of information.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    ///  let app_m = App::new("git")
+    ///      .subcommand(SubCommand::with_name("clone"))
+    ///      .subcommand(SubCommand::with_name("push"))
+    ///      .subcommand(SubCommand::with_name("commit"))
+    ///      .get_matches();
+    ///
+    /// match app_m.subcommand() {
+    ///     ("clone",  Some(sub_m)) => {}, // clone was used
+    ///     ("push",   Some(sub_m)) => {}, // push was used
+    ///     ("commit", Some(sub_m)) => {}, // commit was used
+    ///     _                       => {}, // Either no subcommand or one not tested for...
+    /// }
+    /// ```
+    ///
+    /// Another useful scenario is when you want to support third party, or external, subcommands.
+    /// In these cases you can't know the subcommand name ahead of time, so use a variable instead
+    /// with pattern matching!
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings};
+    /// // Assume there is an external subcommand named "subcmd"
+    /// let app_m = App::new("myprog")
+    ///     .setting(AppSettings::AllowExternalSubcommands)
+    ///     .get_matches_from(vec![
+    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
+    ///     ]);
+    ///
+    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
+    /// // string argument name
+    /// match app_m.subcommand() {
+    ///     (external, Some(sub_m)) => {
+    ///          let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect();
+    ///          assert_eq!(external, "subcmd");
+    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
+    ///     },
+    ///     _ => {},
+    /// }
+    /// ```
+    /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches
+    /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name
+    pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) {
+        self.subcommand
+            .as_ref()
+            .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches)))
+    }
+
+    /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`]
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// # use clap::{App, Arg, SubCommand};
+    /// let app_m = App::new("myprog")
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches();
+    ///
+    /// println!("{}", app_m.usage());
+    /// ```
+    /// [`Subcommand`]: ./struct.SubCommand.html
+    /// [`App`]: ./struct.App.html
+    pub fn usage(&self) -> &str {
+        self.usage.as_ref().map_or("", |u| &u[..])
+    }
+}
+
+// The following were taken and adapated from vec_map source
+// repo: https://github.com/contain-rs/vec-map
+// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33
+// license: MIT - Copyright (c) 2015 The Rust Project Developers
+
+/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`]
+/// method.
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{App, Arg};
+/// let m = App::new("myapp")
+///     .arg(Arg::with_name("output")
+///         .short("o")
+///         .multiple(true)
+///         .takes_value(true))
+///     .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
+///
+/// let mut values = m.values_of("output").unwrap();
+///
+/// assert_eq!(values.next(), Some("val1"));
+/// assert_eq!(values.next(), Some("val2"));
+/// assert_eq!(values.next(), None);
+/// ```
+/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
+#[derive(Debug, Clone)]
+pub struct Values<'a> {
+    iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a str>,
+}
+
+impl<'a> Iterator for Values<'a> {
+    type Item = &'a str;
+
+    fn next(&mut self) -> Option<&'a str> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
+}
+
+impl<'a> DoubleEndedIterator for Values<'a> {
+    fn next_back(&mut self) -> Option<&'a str> {
+        self.iter.next_back()
+    }
+}
+
+impl<'a> ExactSizeIterator for Values<'a> {}
+
+/// Creates an empty iterator.
+impl<'a> Default for Values<'a> {
+    fn default() -> Self {
+        static EMPTY: [OsString; 0] = [];
+        // This is never called because the iterator is empty:
+        fn to_str_slice(_: &OsString) -> &str {
+            unreachable!()
+        }
+        Values {
+            iter: EMPTY[..].iter().map(to_str_slice),
+        }
+    }
+}
+
+/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`]
+/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike
+/// [`Values`].
+///
+/// # Examples
+///
+#[cfg_attr(not(unix), doc = " ```ignore")]
+#[cfg_attr(unix, doc = " ```")]
+/// # use clap::{App, Arg};
+/// use std::ffi::OsString;
+/// use std::os::unix::ffi::{OsStrExt,OsStringExt};
+///
+/// let m = App::new("utf8")
+///     .arg(Arg::from_usage("<arg> 'some arg'"))
+///     .get_matches_from(vec![OsString::from("myprog"),
+///                             // "Hi {0xe9}!"
+///                             OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]);
+/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']);
+/// ```
+/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os
+/// [`Values`]: ./struct.Values.html
+#[derive(Debug, Clone)]
+pub struct OsValues<'a> {
+    iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a OsStr>,
+}
+
+impl<'a> Iterator for OsValues<'a> {
+    type Item = &'a OsStr;
+
+    fn next(&mut self) -> Option<&'a OsStr> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
+}
+
+impl<'a> DoubleEndedIterator for OsValues<'a> {
+    fn next_back(&mut self) -> Option<&'a OsStr> {
+        self.iter.next_back()
+    }
+}
+
+impl<'a> ExactSizeIterator for OsValues<'a> {}
+
+/// Creates an empty iterator.
+impl<'a> Default for OsValues<'a> {
+    fn default() -> Self {
+        static EMPTY: [OsString; 0] = [];
+        // This is never called because the iterator is empty:
+        fn to_str_slice(_: &OsString) -> &OsStr {
+            unreachable!()
+        }
+        OsValues {
+            iter: EMPTY[..].iter().map(to_str_slice),
+        }
+    }
+}
+
+/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`]
+/// method.
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{App, Arg};
+/// let m = App::new("myapp")
+///     .arg(Arg::with_name("output")
+///         .short("o")
+///         .multiple(true)
+///         .takes_value(true))
+///     .get_matches_from(vec!["myapp", "-o", "val1", "val2"]);
+///
+/// let mut indices = m.indices_of("output").unwrap();
+///
+/// assert_eq!(indices.next(), Some(2));
+/// assert_eq!(indices.next(), Some(3));
+/// assert_eq!(indices.next(), None);
+/// ```
+/// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of
+#[derive(Debug, Clone)]
+pub struct Indices<'a> {
+    // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469
+    iter: Map<Iter<'a, usize>, fn(&'a usize) -> usize>,
+}
+
+impl<'a> Iterator for Indices<'a> {
+    type Item = usize;
+
+    fn next(&mut self) -> Option<usize> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
+}
+
+impl<'a> DoubleEndedIterator for Indices<'a> {
+    fn next_back(&mut self) -> Option<usize> {
+        self.iter.next_back()
+    }
+}
+
+impl<'a> ExactSizeIterator for Indices<'a> {}
+
+/// Creates an empty iterator.
+impl<'a> Default for Indices<'a> {
+    fn default() -> Self {
+        static EMPTY: [usize; 0] = [];
+        // This is never called because the iterator is empty:
+        fn to_usize(_: &usize) -> usize {
+            unreachable!()
+        }
+        Indices {
+            iter: EMPTY[..].iter().map(to_usize),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_default_values() {
+        let mut values: Values = Values::default();
+        assert_eq!(values.next(), None);
+    }
+
+    #[test]
+    fn test_default_values_with_shorter_lifetime() {
+        let matches = ArgMatches::new();
+        let mut values = matches.values_of("").unwrap_or_default();
+        assert_eq!(values.next(), None);
+    }
+
+    #[test]
+    fn test_default_osvalues() {
+        let mut values: OsValues = OsValues::default();
+        assert_eq!(values.next(), None);
+    }
+
+    #[test]
+    fn test_default_osvalues_with_shorter_lifetime() {
+        let matches = ArgMatches::new();
+        let mut values = matches.values_of_os("").unwrap_or_default();
+        assert_eq!(values.next(), None);
+    }
+
+    #[test]
+    fn test_default_indices() {
+        let mut indices: Indices = Indices::default();
+        assert_eq!(indices.next(), None);
+    }
+
+    #[test]
+    fn test_default_indices_with_shorter_lifetime() {
+        let matches = ArgMatches::new();
+        let mut indices = matches.indices_of("").unwrap_or_default();
+        assert_eq!(indices.next(), None);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/group.rs
@@ -0,0 +1,637 @@
+#[cfg(feature = "yaml")]
+use std::collections::BTreeMap;
+use std::fmt::{Debug, Formatter, Result};
+
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+/// `ArgGroup`s are a family of related [arguments] and way for you to express, "Any of these
+/// arguments". By placing arguments in a logical group, you can create easier requirement and
+/// exclusion rules instead of having to list each argument individually, or when you want a rule
+/// to apply "any but not all" arguments.
+///
+/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is
+/// set, this means that at least one argument from that group must be present. If
+/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present.
+///
+/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for
+/// another argument, meaning any of the arguments that belong to that group will cause a failure
+/// if present, or must present respectively.
+///
+/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be
+/// present out of a given set. Imagine that you had multiple arguments, and you want one of them
+/// to be required, but making all of them required isn't feasible because perhaps they conflict
+/// with each other. For example, lets say that you were building an application where one could
+/// set a given version number by supplying a string with an option argument, i.e.
+/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number
+/// and simply incrementing one of the three numbers. So you create three flags `--major`,
+/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to
+/// specify that *at least one* of them is used. For this, you can create a group.
+///
+/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care
+/// exactly which argument was actually used at runtime.
+///
+/// # Examples
+///
+/// The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of
+/// the arguments from the specified group is present at runtime.
+///
+/// ```rust
+/// # use clap::{App, ArgGroup, ErrorKind};
+/// let result = App::new("app")
+///     .args_from_usage(
+///         "--set-ver [ver] 'set the version manually'
+///          --major         'auto increase major'
+///          --minor         'auto increase minor'
+///          --patch         'auto increase patch'")
+///     .group(ArgGroup::with_name("vers")
+///          .args(&["set-ver", "major", "minor", "patch"])
+///          .required(true))
+///     .get_matches_from_safe(vec!["app", "--major", "--patch"]);
+/// // Because we used two args in the group it's an error
+/// assert!(result.is_err());
+/// let err = result.unwrap_err();
+/// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
+/// ```
+/// This next example shows a passing parse of the same scenario
+///
+/// ```rust
+/// # use clap::{App, ArgGroup};
+/// let result = App::new("app")
+///     .args_from_usage(
+///         "--set-ver [ver] 'set the version manually'
+///          --major         'auto increase major'
+///          --minor         'auto increase minor'
+///          --patch         'auto increase patch'")
+///     .group(ArgGroup::with_name("vers")
+///          .args(&["set-ver", "major", "minor","patch"])
+///          .required(true))
+///     .get_matches_from_safe(vec!["app", "--major"]);
+/// assert!(result.is_ok());
+/// let matches = result.unwrap();
+/// // We may not know which of the args was used, so we can test for the group...
+/// assert!(matches.is_present("vers"));
+/// // we could also alternatively check each arg individually (not shown here)
+/// ```
+/// [`ArgGroup::multiple(true)`]: ./struct.ArgGroup.html#method.multiple
+/// [arguments]: ./struct.Arg.html
+/// [conflict]: ./struct.Arg.html#method.conflicts_with
+/// [requirement]: ./struct.Arg.html#method.requires
+#[derive(Default)]
+pub struct ArgGroup<'a> {
+    #[doc(hidden)]
+    pub name: &'a str,
+    #[doc(hidden)]
+    pub args: Vec<&'a str>,
+    #[doc(hidden)]
+    pub required: bool,
+    #[doc(hidden)]
+    pub requires: Option<Vec<&'a str>>,
+    #[doc(hidden)]
+    pub conflicts: Option<Vec<&'a str>>,
+    #[doc(hidden)]
+    pub multiple: bool,
+}
+
+impl<'a> ArgGroup<'a> {
+    /// Creates a new instance of `ArgGroup` using a unique string name. The name will be used to
+    /// get values from the group or refer to the group inside of conflict and requirement rules.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, ArgGroup};
+    /// ArgGroup::with_name("config")
+    /// # ;
+    /// ```
+    pub fn with_name(n: &'a str) -> Self {
+        ArgGroup {
+            name: n,
+            required: false,
+            args: vec![],
+            requires: None,
+            conflicts: None,
+            multiple: false,
+        }
+    }
+
+    /// Creates a new instance of `ArgGroup` from a .yml (YAML) file.
+    ///
+    /// # Examples
+    ///
+    /// ```ignore
+    /// # #[macro_use]
+    /// # extern crate clap;
+    /// # use clap::ArgGroup;
+    /// # fn main() {
+    /// let yml = load_yaml!("group.yml");
+    /// let ag = ArgGroup::from_yaml(yml);
+    /// # }
+    /// ```
+    #[cfg(feature = "yaml")]
+    pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> {
+        ArgGroup::from(y.as_hash().unwrap())
+    }
+
+    /// Adds an [argument] to this group by name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .arg("flag")
+    ///         .arg("color"))
+    ///     .get_matches_from(vec!["myprog", "-f"]);
+    /// // maybe we don't know which of the two flags was used...
+    /// assert!(m.is_present("req_flags"));
+    /// // but we can also check individually if needed
+    /// assert!(m.is_present("flag"));
+    /// ```
+    /// [argument]: ./struct.Arg.html
+    pub fn arg(mut self, n: &'a str) -> Self {
+        assert!(
+            self.name != n,
+            "ArgGroup '{}' can not have same name as arg inside it",
+            &*self.name
+        );
+        self.args.push(n);
+        self
+    }
+
+    /// Adds multiple [arguments] to this group by name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"]))
+    ///     .get_matches_from(vec!["myprog", "-f"]);
+    /// // maybe we don't know which of the two flags was used...
+    /// assert!(m.is_present("req_flags"));
+    /// // but we can also check individually if needed
+    /// assert!(m.is_present("flag"));
+    /// ```
+    /// [arguments]: ./struct.Arg.html
+    pub fn args(mut self, ns: &[&'a str]) -> Self {
+        for n in ns {
+            self = self.arg(n);
+        }
+        self
+    }
+
+    /// Allows more than one of the ['Arg']s in this group to be used. (Default: `false`)
+    ///
+    /// # Examples
+    ///
+    /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the
+    /// group
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup};
+    /// let m = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .multiple(true))
+    ///     .get_matches_from(vec!["myprog", "-f", "-c"]);
+    /// // maybe we don't know which of the two flags was used...
+    /// assert!(m.is_present("req_flags"));
+    /// ```
+    /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw
+    /// an error if more than one of the args in the group was used.
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"]))
+    ///     .get_matches_from_safe(vec!["myprog", "-f", "-c"]);
+    /// // Because we used both args in the group it's an error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
+    /// ```
+    /// ['Arg']: ./struct.Arg.html
+    pub fn multiple(mut self, m: bool) -> Self {
+        self.multiple = m;
+        self
+    }
+
+    /// Sets the group as required or not. A required group will be displayed in the usage string
+    /// of the application in the format `<arg|arg2|arg3>`. A required `ArgGroup` simply states
+    /// that one argument from this group *must* be present at runtime (unless
+    /// conflicting with another argument).
+    ///
+    /// **NOTE:** This setting only applies to the current [`App`] / [`SubCommand`], and not
+    /// globally.
+    ///
+    /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with
+    /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group.
+    /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which
+    /// states, '*At least* one arg from this group must be used. Using multiple is OK."
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .required(true))
+    ///     .get_matches_from_safe(vec!["myprog"]);
+    /// // Because we didn't use any of the args in the group, it's an error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [`App`]: ./struct.App.html
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`ArgGroup::multiple`]: ./struct.ArgGroup.html#method.multiple
+    pub fn required(mut self, r: bool) -> Self {
+        self.required = r;
+        self
+    }
+
+    /// Sets the requirement rules of this group. This is not to be confused with a
+    /// [required group]. Requirement rules function just like [argument requirement rules], you
+    /// can name other arguments or groups that must be present when any one of the arguments from
+    /// this group is used.
+    ///
+    /// **NOTE:** The name provided may be an argument, or group name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .requires("debug"))
+    ///     .get_matches_from_safe(vec!["myprog", "-c"]);
+    /// // because we used an arg from the group, and the group requires "-d" to be used, it's an
+    /// // error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [required group]: ./struct.ArgGroup.html#method.required
+    /// [argument requirement rules]: ./struct.Arg.html#method.requires
+    pub fn requires(mut self, n: &'a str) -> Self {
+        if let Some(ref mut reqs) = self.requires {
+            reqs.push(n);
+        } else {
+            self.requires = Some(vec![n]);
+        }
+        self
+    }
+
+    /// Sets the requirement rules of this group. This is not to be confused with a
+    /// [required group]. Requirement rules function just like [argument requirement rules], you
+    /// can name other arguments or groups that must be present when one of the arguments from this
+    /// group is used.
+    ///
+    /// **NOTE:** The names provided may be an argument, or group name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .arg(Arg::with_name("verb")
+    ///         .short("v"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .requires_all(&["debug", "verb"]))
+    ///     .get_matches_from_safe(vec!["myprog", "-c", "-d"]);
+    /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used,
+    /// // yet we only used "-d" it's an error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    /// [required group]: ./struct.ArgGroup.html#method.required
+    /// [argument requirement rules]: ./struct.Arg.html#method.requires_all
+    pub fn requires_all(mut self, ns: &[&'a str]) -> Self {
+        for n in ns {
+            self = self.requires(n);
+        }
+        self
+    }
+
+    /// Sets the exclusion rules of this group. Exclusion (aka conflict) rules function just like
+    /// [argument exclusion rules], you can name other arguments or groups that must *not* be
+    /// present when one of the arguments from this group are used.
+    ///
+    /// **NOTE:** The name provided may be an argument, or group name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .conflicts_with("debug"))
+    ///     .get_matches_from_safe(vec!["myprog", "-c", "-d"]);
+    /// // because we used an arg from the group, and the group conflicts with "-d", it's an error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
+    /// ```
+    /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with
+    pub fn conflicts_with(mut self, n: &'a str) -> Self {
+        if let Some(ref mut confs) = self.conflicts {
+            confs.push(n);
+        } else {
+            self.conflicts = Some(vec![n]);
+        }
+        self
+    }
+
+    /// Sets the exclusion rules of this group. Exclusion rules function just like
+    /// [argument exclusion rules], you can name other arguments or groups that must *not* be
+    /// present when one of the arguments from this group are used.
+    ///
+    /// **NOTE:** The names provided may be an argument, or group name
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ArgGroup, ErrorKind};
+    /// let result = App::new("myprog")
+    ///     .arg(Arg::with_name("flag")
+    ///         .short("f"))
+    ///     .arg(Arg::with_name("color")
+    ///         .short("c"))
+    ///     .arg(Arg::with_name("debug")
+    ///         .short("d"))
+    ///     .arg(Arg::with_name("verb")
+    ///         .short("v"))
+    ///     .group(ArgGroup::with_name("req_flags")
+    ///         .args(&["flag", "color"])
+    ///         .conflicts_with_all(&["debug", "verb"]))
+    ///     .get_matches_from_safe(vec!["myprog", "-c", "-v"]);
+    /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d"
+    /// // it's an error
+    /// assert!(result.is_err());
+    /// let err = result.unwrap_err();
+    /// assert_eq!(err.kind, ErrorKind::ArgumentConflict);
+    /// ```
+    /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with_all
+    pub fn conflicts_with_all(mut self, ns: &[&'a str]) -> Self {
+        for n in ns {
+            self = self.conflicts_with(n);
+        }
+        self
+    }
+}
+
+impl<'a> Debug for ArgGroup<'a> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        write!(
+            f,
+            "{{\n\
+             \tname: {:?},\n\
+             \targs: {:?},\n\
+             \trequired: {:?},\n\
+             \trequires: {:?},\n\
+             \tconflicts: {:?},\n\
+             }}",
+            self.name, self.args, self.required, self.requires, self.conflicts
+        )
+    }
+}
+
+impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> {
+    fn from(g: &'z ArgGroup<'a>) -> Self {
+        ArgGroup {
+            name: g.name,
+            required: g.required,
+            args: g.args.clone(),
+            requires: g.requires.clone(),
+            conflicts: g.conflicts.clone(),
+            multiple: g.multiple,
+        }
+    }
+}
+
+#[cfg(feature = "yaml")]
+impl<'a> From<&'a BTreeMap<Yaml, Yaml>> for ArgGroup<'a> {
+    fn from(b: &'a BTreeMap<Yaml, Yaml>) -> Self {
+        // We WANT this to panic on error...so expect() is good.
+        let mut a = ArgGroup::default();
+        let group_settings = if b.len() == 1 {
+            let name_yml = b.keys().nth(0).expect("failed to get name");
+            let name_str = name_yml
+                .as_str()
+                .expect("failed to convert arg YAML name to str");
+            a.name = name_str;
+            b.get(name_yml)
+                .expect("failed to get name_str")
+                .as_hash()
+                .expect("failed to convert to a hash")
+        } else {
+            b
+        };
+
+        for (k, v) in group_settings {
+            a = match k.as_str().unwrap() {
+                "required" => a.required(v.as_bool().unwrap()),
+                "multiple" => a.multiple(v.as_bool().unwrap()),
+                "args" => yaml_vec_or_str!(v, a, arg),
+                "arg" => {
+                    if let Some(ys) = v.as_str() {
+                        a = a.arg(ys);
+                    }
+                    a
+                }
+                "requires" => yaml_vec_or_str!(v, a, requires),
+                "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with),
+                "name" => {
+                    if let Some(ys) = v.as_str() {
+                        a.name = ys;
+                    }
+                    a
+                }
+                s => panic!(
+                    "Unknown ArgGroup setting '{}' in YAML file for \
+                     ArgGroup '{}'",
+                    s, a.name
+                ),
+            }
+        }
+
+        a
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::ArgGroup;
+    #[cfg(feature = "yaml")]
+    use yaml_rust::YamlLoader;
+
+    #[test]
+    fn groups() {
+        let g = ArgGroup::with_name("test")
+            .arg("a1")
+            .arg("a4")
+            .args(&["a2", "a3"])
+            .required(true)
+            .conflicts_with("c1")
+            .conflicts_with_all(&["c2", "c3"])
+            .conflicts_with("c4")
+            .requires("r1")
+            .requires_all(&["r2", "r3"])
+            .requires("r4");
+
+        let args = vec!["a1", "a4", "a2", "a3"];
+        let reqs = vec!["r1", "r2", "r3", "r4"];
+        let confs = vec!["c1", "c2", "c3", "c4"];
+
+        assert_eq!(g.args, args);
+        assert_eq!(g.requires, Some(reqs));
+        assert_eq!(g.conflicts, Some(confs));
+    }
+
+    #[test]
+    fn test_debug() {
+        let g = ArgGroup::with_name("test")
+            .arg("a1")
+            .arg("a4")
+            .args(&["a2", "a3"])
+            .required(true)
+            .conflicts_with("c1")
+            .conflicts_with_all(&["c2", "c3"])
+            .conflicts_with("c4")
+            .requires("r1")
+            .requires_all(&["r2", "r3"])
+            .requires("r4");
+
+        let args = vec!["a1", "a4", "a2", "a3"];
+        let reqs = vec!["r1", "r2", "r3", "r4"];
+        let confs = vec!["c1", "c2", "c3", "c4"];
+
+        let debug_str = format!(
+            "{{\n\
+             \tname: \"test\",\n\
+             \targs: {:?},\n\
+             \trequired: {:?},\n\
+             \trequires: {:?},\n\
+             \tconflicts: {:?},\n\
+             }}",
+            args,
+            true,
+            Some(reqs),
+            Some(confs)
+        );
+        assert_eq!(&*format!("{:?}", g), &*debug_str);
+    }
+
+    #[test]
+    fn test_from() {
+        let g = ArgGroup::with_name("test")
+            .arg("a1")
+            .arg("a4")
+            .args(&["a2", "a3"])
+            .required(true)
+            .conflicts_with("c1")
+            .conflicts_with_all(&["c2", "c3"])
+            .conflicts_with("c4")
+            .requires("r1")
+            .requires_all(&["r2", "r3"])
+            .requires("r4");
+
+        let args = vec!["a1", "a4", "a2", "a3"];
+        let reqs = vec!["r1", "r2", "r3", "r4"];
+        let confs = vec!["c1", "c2", "c3", "c4"];
+
+        let g2 = ArgGroup::from(&g);
+        assert_eq!(g2.args, args);
+        assert_eq!(g2.requires, Some(reqs));
+        assert_eq!(g2.conflicts, Some(confs));
+    }
+
+    #[cfg(feature = "yaml")]
+    #[cfg_attr(feature = "yaml", test)]
+    fn test_yaml() {
+        let g_yaml = "name: test
+args:
+- a1
+- a4
+- a2
+- a3
+conflicts_with:
+- c1
+- c2
+- c3
+- c4
+requires:
+- r1
+- r2
+- r3
+- r4";
+        let yml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0];
+        let g = ArgGroup::from_yaml(yml);
+        let args = vec!["a1", "a4", "a2", "a3"];
+        let reqs = vec!["r1", "r2", "r3", "r4"];
+        let confs = vec!["c1", "c2", "c3", "c4"];
+        assert_eq!(g.args, args);
+        assert_eq!(g.requires, Some(reqs));
+        assert_eq!(g.conflicts, Some(confs));
+    }
+}
+
+impl<'a> Clone for ArgGroup<'a> {
+    fn clone(&self) -> Self {
+        ArgGroup {
+            name: self.name,
+            required: self.required,
+            args: self.args.clone(),
+            requires: self.requires.clone(),
+            conflicts: self.conflicts.clone(),
+            multiple: self.multiple,
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/macros.rs
@@ -0,0 +1,121 @@
+#[cfg(feature = "yaml")]
+macro_rules! yaml_tuple2 {
+    ($a:ident, $v:ident, $c:ident) => {{
+        if let Some(vec) = $v.as_vec() {
+            for ys in vec {
+                if let Some(tup) = ys.as_vec() {
+                    debug_assert_eq!(2, tup.len());
+                    $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1]));
+                } else {
+                    panic!("Failed to convert YAML value to vec");
+                }
+            }
+        } else {
+            panic!("Failed to convert YAML value to vec");
+        }
+        $a
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_tuple3 {
+    ($a:ident, $v:ident, $c:ident) => {{
+        if let Some(vec) = $v.as_vec() {
+            for ys in vec {
+                if let Some(tup) = ys.as_vec() {
+                    debug_assert_eq!(3, tup.len());
+                    $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2]));
+                } else {
+                    panic!("Failed to convert YAML value to vec");
+                }
+            }
+        } else {
+            panic!("Failed to convert YAML value to vec");
+        }
+        $a
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_vec_or_str {
+    ($v:ident, $a:ident, $c:ident) => {{
+        let maybe_vec = $v.as_vec();
+        if let Some(vec) = maybe_vec {
+            for ys in vec {
+                if let Some(s) = ys.as_str() {
+                    $a = $a.$c(s);
+                } else {
+                    panic!("Failed to convert YAML value {:?} to a string", ys);
+                }
+            }
+        } else {
+            if let Some(s) = $v.as_str() {
+                $a = $a.$c(s);
+            } else {
+                panic!(
+                    "Failed to convert YAML value {:?} to either a vec or string",
+                    $v
+                );
+            }
+        }
+        $a
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_opt_str {
+    ($v:expr) => {{
+        if $v.is_null() {
+            Some(
+                $v.as_str()
+                    .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)),
+            )
+        } else {
+            None
+        }
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_str {
+    ($v:expr) => {{
+        $v.as_str()
+            .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_to_str {
+    ($a:ident, $v:ident, $c:ident) => {{
+        $a.$c(yaml_str!($v))
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_to_bool {
+    ($a:ident, $v:ident, $c:ident) => {{
+        $a.$c($v
+            .as_bool()
+            .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)))
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_to_u64 {
+    ($a:ident, $v:ident, $c:ident) => {{
+        $a.$c($v
+            .as_i64()
+            .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
+            as u64)
+    }};
+}
+
+#[cfg(feature = "yaml")]
+macro_rules! yaml_to_usize {
+    ($a:ident, $v:ident, $c:ident) => {{
+        $a.$c($v
+            .as_i64()
+            .unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))
+            as usize)
+    }};
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/matched_arg.rs
@@ -0,0 +1,29 @@
+// Std
+use std::ffi::OsString;
+
+#[doc(hidden)]
+#[derive(Debug, Clone)]
+pub struct MatchedArg {
+    #[doc(hidden)]
+    pub occurs: u64,
+    #[doc(hidden)]
+    pub indices: Vec<usize>,
+    #[doc(hidden)]
+    pub vals: Vec<OsString>,
+}
+
+impl Default for MatchedArg {
+    fn default() -> Self {
+        MatchedArg {
+            occurs: 1,
+            indices: Vec::new(),
+            vals: Vec::new(),
+        }
+    }
+}
+
+impl MatchedArg {
+    pub fn new() -> Self {
+        MatchedArg::default()
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/mod.rs
@@ -0,0 +1,21 @@
+pub use self::any_arg::{AnyArg, DispOrder};
+pub use self::arg::Arg;
+pub use self::arg_builder::{Base, FlagBuilder, OptBuilder, PosBuilder, Switched, Valued};
+pub use self::arg_matcher::ArgMatcher;
+pub use self::arg_matches::{ArgMatches, OsValues, Values};
+pub use self::group::ArgGroup;
+pub use self::matched_arg::MatchedArg;
+pub use self::settings::{ArgFlags, ArgSettings};
+pub use self::subcommand::SubCommand;
+
+#[macro_use]
+mod macros;
+pub mod any_arg;
+mod arg;
+mod arg_builder;
+mod arg_matcher;
+mod arg_matches;
+mod group;
+mod matched_arg;
+pub mod settings;
+mod subcommand;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/settings.rs
@@ -0,0 +1,237 @@
+// Std
+#[allow(deprecated, unused_imports)]
+use std::ascii::AsciiExt;
+use std::str::FromStr;
+
+bitflags! {
+    struct Flags: u32 {
+        const REQUIRED         = 1;
+        const MULTIPLE         = 1 << 1;
+        const EMPTY_VALS       = 1 << 2;
+        const GLOBAL           = 1 << 3;
+        const HIDDEN           = 1 << 4;
+        const TAKES_VAL        = 1 << 5;
+        const USE_DELIM        = 1 << 6;
+        const NEXT_LINE_HELP   = 1 << 7;
+        const R_UNLESS_ALL     = 1 << 8;
+        const REQ_DELIM        = 1 << 9;
+        const DELIM_NOT_SET    = 1 << 10;
+        const HIDE_POS_VALS    = 1 << 11;
+        const ALLOW_TAC_VALS   = 1 << 12;
+        const REQUIRE_EQUALS   = 1 << 13;
+        const LAST             = 1 << 14;
+        const HIDE_DEFAULT_VAL = 1 << 15;
+        const CASE_INSENSITIVE = 1 << 16;
+        const HIDE_ENV_VALS    = 1 << 17;
+        const HIDDEN_SHORT_H   = 1 << 18;
+        const HIDDEN_LONG_H    = 1 << 19;
+    }
+}
+
+#[doc(hidden)]
+#[derive(Debug, Clone, Copy)]
+pub struct ArgFlags(Flags);
+
+impl ArgFlags {
+    pub fn new() -> Self {
+        ArgFlags::default()
+    }
+
+    impl_settings! {ArgSettings,
+        Required => Flags::REQUIRED,
+        Multiple => Flags::MULTIPLE,
+        EmptyValues => Flags::EMPTY_VALS,
+        Global => Flags::GLOBAL,
+        Hidden => Flags::HIDDEN,
+        TakesValue => Flags::TAKES_VAL,
+        UseValueDelimiter => Flags::USE_DELIM,
+        NextLineHelp => Flags::NEXT_LINE_HELP,
+        RequiredUnlessAll => Flags::R_UNLESS_ALL,
+        RequireDelimiter => Flags::REQ_DELIM,
+        ValueDelimiterNotSet => Flags::DELIM_NOT_SET,
+        HidePossibleValues => Flags::HIDE_POS_VALS,
+        AllowLeadingHyphen => Flags::ALLOW_TAC_VALS,
+        RequireEquals => Flags::REQUIRE_EQUALS,
+        Last => Flags::LAST,
+        CaseInsensitive => Flags::CASE_INSENSITIVE,
+        HideEnvValues => Flags::HIDE_ENV_VALS,
+        HideDefaultValue => Flags::HIDE_DEFAULT_VAL,
+        HiddenShortHelp => Flags::HIDDEN_SHORT_H,
+        HiddenLongHelp => Flags::HIDDEN_LONG_H
+    }
+}
+
+impl Default for ArgFlags {
+    fn default() -> Self {
+        ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET)
+    }
+}
+
+/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter
+/// methods [`Arg::set`], [`Arg::unset`], and [`Arg::is_set`]
+///
+/// [`Arg::set`]: ./struct.Arg.html#method.set
+/// [`Arg::unset`]: ./struct.Arg.html#method.unset
+/// [`Arg::is_set`]: ./struct.Arg.html#method.is_set
+#[derive(Debug, PartialEq, Copy, Clone)]
+pub enum ArgSettings {
+    /// The argument must be used
+    Required,
+    /// The argument may be used multiple times such as `--flag --flag`
+    Multiple,
+    /// The argument allows empty values such as `--option ""`
+    EmptyValues,
+    /// The argument should be propagated down through all child [`SubCommand`]s
+    ///
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    Global,
+    /// The argument should **not** be shown in help text
+    Hidden,
+    /// The argument accepts a value, such as `--option <value>`
+    TakesValue,
+    /// Determines if the argument allows values to be grouped via a delimiter
+    UseValueDelimiter,
+    /// Prints the help text on the line after the argument
+    NextLineHelp,
+    /// Requires the use of a value delimiter for all multiple values
+    RequireDelimiter,
+    /// Hides the possible values from the help string
+    HidePossibleValues,
+    /// Allows vals that start with a '-'
+    AllowLeadingHyphen,
+    /// Require options use `--option=val` syntax
+    RequireEquals,
+    /// Specifies that the arg is the last positional argument and may be accessed early via `--`
+    /// syntax
+    Last,
+    /// Hides the default value from the help string
+    HideDefaultValue,
+    /// Makes `Arg::possible_values` case insensitive
+    CaseInsensitive,
+    /// Hides ENV values in the help message
+    HideEnvValues,
+    /// The argument should **not** be shown in short help text
+    HiddenShortHelp,
+    /// The argument should **not** be shown in long help text
+    HiddenLongHelp,
+    #[doc(hidden)]
+    RequiredUnlessAll,
+    #[doc(hidden)]
+    ValueDelimiterNotSet,
+}
+
+impl FromStr for ArgSettings {
+    type Err = String;
+    fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
+        match &*s.to_ascii_lowercase() {
+            "required" => Ok(ArgSettings::Required),
+            "multiple" => Ok(ArgSettings::Multiple),
+            "global" => Ok(ArgSettings::Global),
+            "emptyvalues" => Ok(ArgSettings::EmptyValues),
+            "hidden" => Ok(ArgSettings::Hidden),
+            "takesvalue" => Ok(ArgSettings::TakesValue),
+            "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter),
+            "nextlinehelp" => Ok(ArgSettings::NextLineHelp),
+            "requiredunlessall" => Ok(ArgSettings::RequiredUnlessAll),
+            "requiredelimiter" => Ok(ArgSettings::RequireDelimiter),
+            "valuedelimiternotset" => Ok(ArgSettings::ValueDelimiterNotSet),
+            "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues),
+            "allowleadinghyphen" => Ok(ArgSettings::AllowLeadingHyphen),
+            "requireequals" => Ok(ArgSettings::RequireEquals),
+            "last" => Ok(ArgSettings::Last),
+            "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue),
+            "caseinsensitive" => Ok(ArgSettings::CaseInsensitive),
+            "hideenvvalues" => Ok(ArgSettings::HideEnvValues),
+            "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp),
+            "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp),
+            _ => Err("unknown ArgSetting, cannot convert from str".to_owned()),
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::ArgSettings;
+
+    #[test]
+    fn arg_settings_fromstr() {
+        assert_eq!(
+            "allowleadinghyphen".parse::<ArgSettings>().unwrap(),
+            ArgSettings::AllowLeadingHyphen
+        );
+        assert_eq!(
+            "emptyvalues".parse::<ArgSettings>().unwrap(),
+            ArgSettings::EmptyValues
+        );
+        assert_eq!(
+            "global".parse::<ArgSettings>().unwrap(),
+            ArgSettings::Global
+        );
+        assert_eq!(
+            "hidepossiblevalues".parse::<ArgSettings>().unwrap(),
+            ArgSettings::HidePossibleValues
+        );
+        assert_eq!(
+            "hidden".parse::<ArgSettings>().unwrap(),
+            ArgSettings::Hidden
+        );
+        assert_eq!(
+            "multiple".parse::<ArgSettings>().unwrap(),
+            ArgSettings::Multiple
+        );
+        assert_eq!(
+            "nextlinehelp".parse::<ArgSettings>().unwrap(),
+            ArgSettings::NextLineHelp
+        );
+        assert_eq!(
+            "requiredunlessall".parse::<ArgSettings>().unwrap(),
+            ArgSettings::RequiredUnlessAll
+        );
+        assert_eq!(
+            "requiredelimiter".parse::<ArgSettings>().unwrap(),
+            ArgSettings::RequireDelimiter
+        );
+        assert_eq!(
+            "required".parse::<ArgSettings>().unwrap(),
+            ArgSettings::Required
+        );
+        assert_eq!(
+            "takesvalue".parse::<ArgSettings>().unwrap(),
+            ArgSettings::TakesValue
+        );
+        assert_eq!(
+            "usevaluedelimiter".parse::<ArgSettings>().unwrap(),
+            ArgSettings::UseValueDelimiter
+        );
+        assert_eq!(
+            "valuedelimiternotset".parse::<ArgSettings>().unwrap(),
+            ArgSettings::ValueDelimiterNotSet
+        );
+        assert_eq!(
+            "requireequals".parse::<ArgSettings>().unwrap(),
+            ArgSettings::RequireEquals
+        );
+        assert_eq!("last".parse::<ArgSettings>().unwrap(), ArgSettings::Last);
+        assert_eq!(
+            "hidedefaultvalue".parse::<ArgSettings>().unwrap(),
+            ArgSettings::HideDefaultValue
+        );
+        assert_eq!(
+            "caseinsensitive".parse::<ArgSettings>().unwrap(),
+            ArgSettings::CaseInsensitive
+        );
+        assert_eq!(
+            "hideenvvalues".parse::<ArgSettings>().unwrap(),
+            ArgSettings::HideEnvValues
+        );
+        assert_eq!(
+            "hiddenshorthelp".parse::<ArgSettings>().unwrap(),
+            ArgSettings::HiddenShortHelp
+        );
+        assert_eq!(
+            "hiddenlonghelp".parse::<ArgSettings>().unwrap(),
+            ArgSettings::HiddenLongHelp
+        );
+        assert!("hahahaha".parse::<ArgSettings>().is_err());
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/args/subcommand.rs
@@ -0,0 +1,71 @@
+// Third Party
+#[cfg(feature = "yaml")]
+use yaml_rust::Yaml;
+
+// Internal
+use crate::{App, ArgMatches};
+
+/// The abstract representation of a command line subcommand.
+///
+/// This struct describes all the valid options of the subcommand for the program. Subcommands are
+/// essentially "sub-[`App`]s" and contain all the same possibilities (such as their own
+/// [arguments], subcommands, and settings).
+///
+/// # Examples
+///
+/// ```rust
+/// # use clap::{App, Arg, SubCommand};
+/// App::new("myprog")
+///     .subcommand(
+///         SubCommand::with_name("config")
+///             .about("Used for configuration")
+///             .arg(Arg::with_name("config_file")
+///                 .help("The configuration file to use")
+///                 .index(1)))
+/// # ;
+/// ```
+/// [`App`]: ./struct.App.html
+/// [arguments]: ./struct.Arg.html
+#[derive(Debug, Clone)]
+pub struct SubCommand<'a> {
+    #[doc(hidden)]
+    pub name: String,
+    #[doc(hidden)]
+    pub matches: ArgMatches<'a>,
+}
+
+impl<'a> SubCommand<'a> {
+    /// Creates a new instance of a subcommand requiring a name. The name will be displayed
+    /// to the user when they print version or help and usage information.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, SubCommand};
+    /// App::new("myprog")
+    ///     .subcommand(
+    ///         SubCommand::with_name("config"))
+    /// # ;
+    /// ```
+    pub fn with_name<'b>(name: &str) -> App<'a, 'b> {
+        App::new(name)
+    }
+
+    /// Creates a new instance of a subcommand from a YAML (.yml) document
+    ///
+    /// # Examples
+    ///
+    /// ```ignore
+    /// # #[macro_use]
+    /// # extern crate clap;
+    /// # use clap::Subcommand;
+    /// # fn main() {
+    /// let sc_yaml = load_yaml!("test_subcommand.yml");
+    /// let sc = SubCommand::from_yaml(sc_yaml);
+    /// # }
+    /// ```
+    #[cfg(feature = "yaml")]
+    pub fn from_yaml(yaml: &Yaml) -> App {
+        App::from_yaml(yaml)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/bash.rs
@@ -0,0 +1,223 @@
+// Std
+use std::io::Write;
+
+// Internal
+use crate::{
+    app::parser::Parser,
+    args::{AnyArg, OptBuilder},
+    completions,
+};
+
+pub struct BashGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> BashGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        BashGen { p }
+    }
+
+    pub fn generate_to<W: Write>(&self, buf: &mut W) {
+        w!(
+            buf,
+            format!(
+                r#"_{name}() {{
+    local i cur prev opts cmds
+    COMPREPLY=()
+    cur="${{COMP_WORDS[COMP_CWORD]}}"
+    prev="${{COMP_WORDS[COMP_CWORD-1]}}"
+    cmd=""
+    opts=""
+
+    for i in ${{COMP_WORDS[@]}}
+    do
+        case "${{i}}" in
+            {name})
+                cmd="{name}"
+                ;;
+            {subcmds}
+            *)
+                ;;
+        esac
+    done
+
+    case "${{cmd}}" in
+        {name})
+            opts="{name_opts}"
+            if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then
+                COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
+                return 0
+            fi
+            case "${{prev}}" in
+                {name_opts_details}
+                *)
+                    COMPREPLY=()
+                    ;;
+            esac
+            COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
+            return 0
+            ;;
+        {subcmd_details}
+    esac
+}}
+
+complete -F _{name} -o bashdefault -o default {name}
+"#,
+                name = self.p.meta.bin_name.as_ref().unwrap(),
+                name_opts = self.all_options_for_path(self.p.meta.bin_name.as_ref().unwrap()),
+                name_opts_details =
+                    self.option_details_for_path(self.p.meta.bin_name.as_ref().unwrap()),
+                subcmds = self.all_subcommands(),
+                subcmd_details = self.subcommand_details()
+            )
+            .as_bytes()
+        );
+    }
+
+    fn all_subcommands(&self) -> String {
+        debugln!("BashGen::all_subcommands;");
+        let mut subcmds = String::new();
+        let scs = completions::all_subcommand_names(self.p);
+
+        for sc in &scs {
+            subcmds = format!(
+                r#"{}
+            {name})
+                cmd+="__{fn_name}"
+                ;;"#,
+                subcmds,
+                name = sc,
+                fn_name = sc.replace("-", "__")
+            );
+        }
+
+        subcmds
+    }
+
+    fn subcommand_details(&self) -> String {
+        debugln!("BashGen::subcommand_details;");
+        let mut subcmd_dets = String::new();
+        let mut scs = completions::get_all_subcommand_paths(self.p, true);
+        scs.sort();
+        scs.dedup();
+
+        for sc in &scs {
+            subcmd_dets = format!(
+                r#"{}
+        {subcmd})
+            opts="{sc_opts}"
+            if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then
+                COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
+                return 0
+            fi
+            case "${{prev}}" in
+                {opts_details}
+                *)
+                    COMPREPLY=()
+                    ;;
+            esac
+            COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") )
+            return 0
+            ;;"#,
+                subcmd_dets,
+                subcmd = sc.replace("-", "__"),
+                sc_opts = self.all_options_for_path(&*sc),
+                level = sc.split("__").count(),
+                opts_details = self.option_details_for_path(&*sc)
+            );
+        }
+
+        subcmd_dets
+    }
+
+    fn option_details_for_path(&self, path: &str) -> String {
+        debugln!("BashGen::option_details_for_path: path={}", path);
+        let mut p = self.p;
+        for sc in path.split("__").skip(1) {
+            debugln!("BashGen::option_details_for_path:iter: sc={}", sc);
+            p = &find_subcmd!(p, sc).unwrap().p;
+        }
+        let mut opts = String::new();
+        for o in p.opts() {
+            if let Some(l) = o.s.long {
+                opts = format!(
+                    "{}
+                --{})
+                    COMPREPLY=({})
+                    return 0
+                    ;;",
+                    opts,
+                    l,
+                    self.vals_for(o)
+                );
+            }
+            if let Some(s) = o.s.short {
+                opts = format!(
+                    "{}
+                    -{})
+                    COMPREPLY=({})
+                    return 0
+                    ;;",
+                    opts,
+                    s,
+                    self.vals_for(o)
+                );
+            }
+        }
+        opts
+    }
+
+    fn vals_for(&self, o: &OptBuilder) -> String {
+        debugln!("BashGen::vals_for: o={}", o.b.name);
+        if let Some(vals) = o.possible_vals() {
+            format!(r#"$(compgen -W "{}" -- "${{cur}}")"#, vals.join(" "))
+        } else {
+            String::from(r#"$(compgen -f "${cur}")"#)
+        }
+    }
+
+    fn all_options_for_path(&self, path: &str) -> String {
+        debugln!("BashGen::all_options_for_path: path={}", path);
+        let mut p = self.p;
+        for sc in path.split("__").skip(1) {
+            debugln!("BashGen::all_options_for_path:iter: sc={}", sc);
+            p = &find_subcmd!(p, sc).unwrap().p;
+        }
+        let mut opts = shorts!(p).fold(String::new(), |acc, s| format!("{} -{}", acc, s));
+        opts = format!(
+            "{} {}",
+            opts,
+            longs!(p).fold(String::new(), |acc, l| format!("{} --{}", acc, l))
+        );
+        opts = format!(
+            "{} {}",
+            opts,
+            p.positionals
+                .values()
+                .fold(String::new(), |acc, p| format!("{} {}", acc, p))
+        );
+        opts = format!(
+            "{} {}",
+            opts,
+            p.subcommands
+                .iter()
+                .fold(String::new(), |acc, s| format!("{} {}", acc, s.p.meta.name))
+        );
+        for sc in &p.subcommands {
+            if let Some(ref aliases) = sc.p.meta.aliases {
+                opts = format!(
+                    "{} {}",
+                    opts,
+                    aliases
+                        .iter()
+                        .map(|&(n, _)| n)
+                        .fold(String::new(), |acc, a| format!("{} {}", acc, a))
+                );
+            }
+        }
+        opts
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/elvish.rs
@@ -0,0 +1,127 @@
+// Std
+use std::io::Write;
+
+// Internal
+use crate::{app::parser::Parser, INTERNAL_ERROR_MSG};
+
+pub struct ElvishGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> ElvishGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        ElvishGen { p }
+    }
+
+    pub fn generate_to<W: Write>(&self, buf: &mut W) {
+        let bin_name = self.p.meta.bin_name.as_ref().unwrap();
+
+        let mut names = vec![];
+        let subcommands_cases = generate_inner(self.p, "", &mut names);
+
+        let result = format!(
+            r#"
+edit:completion:arg-completer[{bin_name}] = [@words]{{
+    fn spaces [n]{{
+        repeat $n ' ' | joins ''
+    }}
+    fn cand [text desc]{{
+        edit:complex-candidate $text &display-suffix=' '(spaces (- 14 (wcswidth $text)))$desc
+    }}
+    command = '{bin_name}'
+    for word $words[1:-1] {{
+        if (has-prefix $word '-') {{
+            break
+        }}
+        command = $command';'$word
+    }}
+    completions = [{subcommands_cases}
+    ]
+    $completions[$command]
+}}
+"#,
+            bin_name = bin_name,
+            subcommands_cases = subcommands_cases
+        );
+
+        w!(buf, result.as_bytes());
+    }
+}
+
+// Escape string inside single quotes
+fn escape_string(string: &str) -> String {
+    string.replace("'", "''")
+}
+
+fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
+    match help {
+        Some(help) => escape_string(help),
+        _ => data.to_string(),
+    }
+}
+
+fn generate_inner<'a, 'b, 'p>(
+    p: &'p Parser<'a, 'b>,
+    previous_command_name: &str,
+    names: &mut Vec<&'p str>,
+) -> String {
+    debugln!("ElvishGen::generate_inner;");
+    let command_name = if previous_command_name.is_empty() {
+        p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone()
+    } else {
+        format!("{};{}", previous_command_name, &p.meta.name)
+    };
+
+    let mut completions = String::new();
+    let preamble = String::from("\n            cand ");
+
+    for option in p.opts() {
+        if let Some(data) = option.s.short {
+            let tooltip = get_tooltip(option.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(format!("-{} '{}'", data, tooltip).as_str());
+        }
+        if let Some(data) = option.s.long {
+            let tooltip = get_tooltip(option.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(format!("--{} '{}'", data, tooltip).as_str());
+        }
+    }
+
+    for flag in p.flags() {
+        if let Some(data) = flag.s.short {
+            let tooltip = get_tooltip(flag.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(format!("-{} '{}'", data, tooltip).as_str());
+        }
+        if let Some(data) = flag.s.long {
+            let tooltip = get_tooltip(flag.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(format!("--{} '{}'", data, tooltip).as_str());
+        }
+    }
+
+    for subcommand in &p.subcommands {
+        let data = &subcommand.p.meta.name;
+        let tooltip = get_tooltip(subcommand.p.meta.about, data);
+        completions.push_str(&preamble);
+        completions.push_str(format!("{} '{}'", data, tooltip).as_str());
+    }
+
+    let mut subcommands_cases = format!(
+        r"
+        &'{}'= {{{}
+        }}",
+        &command_name, completions
+    );
+
+    for subcommand in &p.subcommands {
+        let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names);
+        subcommands_cases.push_str(&subcommand_subcommands_cases);
+    }
+
+    subcommands_cases
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/fish.rs
@@ -0,0 +1,103 @@
+// Std
+use std::io::Write;
+
+// Internal
+use crate::app::parser::Parser;
+
+pub struct FishGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> FishGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        FishGen { p }
+    }
+
+    pub fn generate_to<W: Write>(&self, buf: &mut W) {
+        let command = self.p.meta.bin_name.as_ref().unwrap();
+        let mut buffer = String::new();
+        gen_fish_inner(command, self, command, &mut buffer);
+        w!(buf, buffer.as_bytes());
+    }
+}
+
+// Escape string inside single quotes
+fn escape_string(string: &str) -> String {
+    string.replace("\\", "\\\\").replace("'", "\\'")
+}
+
+fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) {
+    debugln!("FishGen::gen_fish_inner;");
+    // example :
+    //
+    // complete
+    //      -c {command}
+    //      -d "{description}"
+    //      -s {short}
+    //      -l {long}
+    //      -a "{possible_arguments}"
+    //      -r # if require parameter
+    //      -f # don't use file completion
+    //      -n "__fish_use_subcommand"               # complete for command "myprog"
+    //      -n "__fish_seen_subcommand_from subcmd1" # complete for command "myprog subcmd1"
+
+    let mut basic_template = format!("complete -c {} -n ", root_command);
+    if root_command == subcommand {
+        basic_template.push_str("\"__fish_use_subcommand\"");
+    } else {
+        basic_template.push_str(format!("\"__fish_seen_subcommand_from {}\"", subcommand).as_str());
+    }
+
+    for option in comp_gen.p.opts() {
+        let mut template = basic_template.clone();
+        if let Some(data) = option.s.short {
+            template.push_str(format!(" -s {}", data).as_str());
+        }
+        if let Some(data) = option.s.long {
+            template.push_str(format!(" -l {}", data).as_str());
+        }
+        if let Some(data) = option.b.help {
+            template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
+        }
+        if let Some(ref data) = option.v.possible_vals {
+            template.push_str(format!(" -r -f -a \"{}\"", data.join(" ")).as_str());
+        }
+        buffer.push_str(template.as_str());
+        buffer.push('\n');
+    }
+
+    for flag in comp_gen.p.flags() {
+        let mut template = basic_template.clone();
+        if let Some(data) = flag.s.short {
+            template.push_str(format!(" -s {}", data).as_str());
+        }
+        if let Some(data) = flag.s.long {
+            template.push_str(format!(" -l {}", data).as_str());
+        }
+        if let Some(data) = flag.b.help {
+            template.push_str(format!(" -d '{}'", escape_string(data)).as_str());
+        }
+        buffer.push_str(template.as_str());
+        buffer.push('\n');
+    }
+
+    for subcommand in &comp_gen.p.subcommands {
+        let mut template = basic_template.clone();
+        template.push_str(" -f");
+        template.push_str(format!(" -a \"{}\"", &subcommand.p.meta.name).as_str());
+        if let Some(data) = subcommand.p.meta.about {
+            template.push_str(format!(" -d '{}'", escape_string(data)).as_str())
+        }
+        buffer.push_str(template.as_str());
+        buffer.push('\n');
+    }
+
+    // generate options of subcommands
+    for subcommand in &comp_gen.p.subcommands {
+        let sub_comp_gen = FishGen::new(&subcommand.p);
+        gen_fish_inner(root_command, &sub_comp_gen, &subcommand.to_string(), buffer);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/macros.rs
@@ -0,0 +1,28 @@
+macro_rules! w {
+    ($buf:expr, $to_w:expr) => {
+        match $buf.write_all($to_w) {
+            Ok(..) => (),
+            Err(..) => panic!("Failed to write to completions file"),
+        }
+    };
+}
+
+macro_rules! get_zsh_arg_conflicts {
+    ($p:ident, $arg:ident, $msg:ident) => {
+        if let Some(conf_vec) = $arg.blacklist() {
+            let mut v = vec![];
+            for arg_name in conf_vec {
+                let arg = $p.find_any_arg(arg_name).expect($msg);
+                if let Some(s) = arg.short() {
+                    v.push(format!("-{}", s));
+                }
+                if let Some(l) = arg.long() {
+                    v.push(format!("--{}", l));
+                }
+            }
+            v.join(" ")
+        } else {
+            String::new()
+        }
+    };
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/mod.rs
@@ -0,0 +1,182 @@
+#[macro_use]
+mod macros;
+mod bash;
+mod elvish;
+mod fish;
+mod powershell;
+mod shell;
+mod zsh;
+
+// Std
+use std::io::Write;
+
+// Internal
+pub use crate::completions::shell::Shell;
+use crate::{
+    app::parser::Parser,
+    completions::{
+        bash::BashGen, elvish::ElvishGen, fish::FishGen, powershell::PowerShellGen, zsh::ZshGen,
+    },
+};
+
+pub struct ComplGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> ComplGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        ComplGen { p }
+    }
+
+    pub fn generate<W: Write>(&self, for_shell: Shell, buf: &mut W) {
+        match for_shell {
+            Shell::Bash => BashGen::new(self.p).generate_to(buf),
+            Shell::Fish => FishGen::new(self.p).generate_to(buf),
+            Shell::Zsh => ZshGen::new(self.p).generate_to(buf),
+            Shell::PowerShell => PowerShellGen::new(self.p).generate_to(buf),
+            Shell::Elvish => ElvishGen::new(self.p).generate_to(buf),
+        }
+    }
+}
+
+// Gets all subcommands including child subcommands in the form of 'name' where the name
+// is a single word (i.e. "install")  of the path to said subcommand (i.e.
+// "rustup toolchain install")
+//
+// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
+// aliasing.
+pub fn all_subcommand_names(p: &Parser) -> Vec<String> {
+    debugln!("all_subcommand_names;");
+    let mut subcmds: Vec<_> = subcommands_of(p)
+        .iter()
+        .map(|&(ref n, _)| n.clone())
+        .collect();
+    for sc_v in p.subcommands.iter().map(|s| all_subcommand_names(&s.p)) {
+        subcmds.extend(sc_v);
+    }
+    subcmds.sort();
+    subcmds.dedup();
+    subcmds
+}
+
+// Gets all subcommands including child subcommands in the form of ('name', 'bin_name') where the name
+// is a single word (i.e. "install") of the path and full bin_name of said subcommand (i.e.
+// "rustup toolchain install")
+//
+// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
+// aliasing.
+pub fn all_subcommands(p: &Parser) -> Vec<(String, String)> {
+    debugln!("all_subcommands;");
+    let mut subcmds: Vec<_> = subcommands_of(p);
+    for sc_v in p.subcommands.iter().map(|s| all_subcommands(&s.p)) {
+        subcmds.extend(sc_v);
+    }
+    subcmds
+}
+
+// Gets all subcommands excluding child subcommands in the form of (name, bin_name) where the name
+// is a single word (i.e. "install") and the bin_name is a space delineated list of the path to said
+// subcommand (i.e. "rustup toolchain install")
+//
+// Also note, aliases are treated as their own subcommands but duplicates of whatever they're
+// aliasing.
+pub fn subcommands_of(p: &Parser) -> Vec<(String, String)> {
+    debugln!(
+        "subcommands_of: name={}, bin_name={}",
+        p.meta.name,
+        p.meta.bin_name.as_ref().unwrap()
+    );
+    let mut subcmds = vec![];
+
+    debugln!(
+        "subcommands_of: Has subcommands...{:?}",
+        p.has_subcommands()
+    );
+    if !p.has_subcommands() {
+        let mut ret = vec![];
+        debugln!("subcommands_of: Looking for aliases...");
+        if let Some(ref aliases) = p.meta.aliases {
+            for &(n, _) in aliases {
+                debugln!("subcommands_of:iter:iter: Found alias...{}", n);
+                let mut als_bin_name: Vec<_> =
+                    p.meta.bin_name.as_ref().unwrap().split(' ').collect();
+                als_bin_name.push(n);
+                let old = als_bin_name.len() - 2;
+                als_bin_name.swap_remove(old);
+                ret.push((n.to_owned(), als_bin_name.join(" ")));
+            }
+        }
+        return ret;
+    }
+    for sc in &p.subcommands {
+        debugln!(
+            "subcommands_of:iter: name={}, bin_name={}",
+            sc.p.meta.name,
+            sc.p.meta.bin_name.as_ref().unwrap()
+        );
+
+        debugln!("subcommands_of:iter: Looking for aliases...");
+        if let Some(ref aliases) = sc.p.meta.aliases {
+            for &(n, _) in aliases {
+                debugln!("subcommands_of:iter:iter: Found alias...{}", n);
+                let mut als_bin_name: Vec<_> =
+                    p.meta.bin_name.as_ref().unwrap().split(' ').collect();
+                als_bin_name.push(n);
+                let old = als_bin_name.len() - 2;
+                als_bin_name.swap_remove(old);
+                subcmds.push((n.to_owned(), als_bin_name.join(" ")));
+            }
+        }
+        subcmds.push((
+            sc.p.meta.name.clone(),
+            sc.p.meta.bin_name.as_ref().unwrap().clone(),
+        ));
+    }
+    subcmds
+}
+
+pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec<String> {
+    debugln!("get_all_subcommand_paths;");
+    let mut subcmds = vec![];
+    if !p.has_subcommands() {
+        if !first {
+            let name = &*p.meta.name;
+            let path = p.meta.bin_name.as_ref().unwrap().clone().replace(" ", "__");
+            let mut ret = vec![path.clone()];
+            if let Some(ref aliases) = p.meta.aliases {
+                for &(n, _) in aliases {
+                    ret.push(path.replace(name, n));
+                }
+            }
+            return ret;
+        }
+        return vec![];
+    }
+    for sc in &p.subcommands {
+        let name = &*sc.p.meta.name;
+        let path =
+            sc.p.meta
+                .bin_name
+                .as_ref()
+                .unwrap()
+                .clone()
+                .replace(" ", "__");
+        subcmds.push(path.clone());
+        if let Some(ref aliases) = sc.p.meta.aliases {
+            for &(n, _) in aliases {
+                subcmds.push(path.replace(name, n));
+            }
+        }
+    }
+    for sc_v in p
+        .subcommands
+        .iter()
+        .map(|s| get_all_subcommand_paths(&s.p, false))
+    {
+        subcmds.extend(sc_v);
+    }
+    subcmds
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/powershell.rs
@@ -0,0 +1,165 @@
+// Std
+use std::io::Write;
+
+// Internal
+use crate::{app::parser::Parser, INTERNAL_ERROR_MSG};
+
+pub struct PowerShellGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> PowerShellGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        PowerShellGen { p }
+    }
+
+    pub fn generate_to<W: Write>(&self, buf: &mut W) {
+        let bin_name = self.p.meta.bin_name.as_ref().unwrap();
+
+        let mut names = vec![];
+        let subcommands_cases = generate_inner(self.p, "", &mut names);
+
+        let result = format!(
+            r#"
+using namespace System.Management.Automation
+using namespace System.Management.Automation.Language
+
+Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{
+    param($wordToComplete, $commandAst, $cursorPosition)
+
+    $commandElements = $commandAst.CommandElements
+    $command = @(
+        '{bin_name}'
+        for ($i = 1; $i -lt $commandElements.Count; $i++) {{
+            $element = $commandElements[$i]
+            if ($element -isnot [StringConstantExpressionAst] -or
+                $element.StringConstantType -ne [StringConstantType]::BareWord -or
+                $element.Value.StartsWith('-')) {{
+                break
+        }}
+        $element.Value
+    }}) -join ';'
+
+    $completions = @(switch ($command) {{{subcommands_cases}
+    }})
+
+    $completions.Where{{ $_.CompletionText -like "$wordToComplete*" }} |
+        Sort-Object -Property ListItemText
+}}
+"#,
+            bin_name = bin_name,
+            subcommands_cases = subcommands_cases
+        );
+
+        w!(buf, result.as_bytes());
+    }
+}
+
+// Escape string inside single quotes
+fn escape_string(string: &str) -> String {
+    string.replace("'", "''")
+}
+
+fn get_tooltip<T: ToString>(help: Option<&str>, data: T) -> String {
+    match help {
+        Some(help) => escape_string(help),
+        _ => data.to_string(),
+    }
+}
+
+fn generate_inner<'a, 'b, 'p>(
+    p: &'p Parser<'a, 'b>,
+    previous_command_name: &str,
+    names: &mut Vec<&'p str>,
+) -> String {
+    debugln!("PowerShellGen::generate_inner;");
+    let command_name = if previous_command_name.is_empty() {
+        p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone()
+    } else {
+        format!("{};{}", previous_command_name, &p.meta.name)
+    };
+
+    let mut completions = String::new();
+    let preamble = String::from("\n            [CompletionResult]::new(");
+
+    for option in p.opts() {
+        if let Some(data) = option.s.short {
+            let tooltip = get_tooltip(option.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(
+                format!(
+                    "'-{}', '{}', {}, '{}')",
+                    data, data, "[CompletionResultType]::ParameterName", tooltip
+                )
+                .as_str(),
+            );
+        }
+        if let Some(data) = option.s.long {
+            let tooltip = get_tooltip(option.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(
+                format!(
+                    "'--{}', '{}', {}, '{}')",
+                    data, data, "[CompletionResultType]::ParameterName", tooltip
+                )
+                .as_str(),
+            );
+        }
+    }
+
+    for flag in p.flags() {
+        if let Some(data) = flag.s.short {
+            let tooltip = get_tooltip(flag.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(
+                format!(
+                    "'-{}', '{}', {}, '{}')",
+                    data, data, "[CompletionResultType]::ParameterName", tooltip
+                )
+                .as_str(),
+            );
+        }
+        if let Some(data) = flag.s.long {
+            let tooltip = get_tooltip(flag.b.help, data);
+            completions.push_str(&preamble);
+            completions.push_str(
+                format!(
+                    "'--{}', '{}', {}, '{}')",
+                    data, data, "[CompletionResultType]::ParameterName", tooltip
+                )
+                .as_str(),
+            );
+        }
+    }
+
+    for subcommand in &p.subcommands {
+        let data = &subcommand.p.meta.name;
+        let tooltip = get_tooltip(subcommand.p.meta.about, data);
+        completions.push_str(&preamble);
+        completions.push_str(
+            format!(
+                "'{}', '{}', {}, '{}')",
+                data, data, "[CompletionResultType]::ParameterValue", tooltip
+            )
+            .as_str(),
+        );
+    }
+
+    let mut subcommands_cases = format!(
+        r"
+        '{}' {{{}
+            break
+        }}",
+        &command_name, completions
+    );
+
+    for subcommand in &p.subcommands {
+        let subcommand_subcommands_cases = generate_inner(&subcommand.p, &command_name, names);
+        subcommands_cases.push_str(&subcommand_subcommands_cases);
+    }
+
+    subcommands_cases
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/shell.rs
@@ -0,0 +1,56 @@
+#[allow(deprecated, unused_imports)]
+use std::ascii::AsciiExt;
+use std::fmt;
+use std::str::FromStr;
+
+/// Describes which shell to produce a completions file for
+#[derive(Debug, Copy, Clone)]
+pub enum Shell {
+    /// Generates a .bash completion file for the Bourne Again SHell (BASH)
+    Bash,
+    /// Generates a .fish completion file for the Friendly Interactive SHell (fish)
+    Fish,
+    /// Generates a completion file for the Z SHell (ZSH)
+    Zsh,
+    /// Generates a completion file for PowerShell
+    PowerShell,
+    /// Generates a completion file for Elvish
+    Elvish,
+}
+
+impl Shell {
+    /// A list of possible variants in `&'static str` form
+    pub fn variants() -> [&'static str; 5] {
+        ["zsh", "bash", "fish", "powershell", "elvish"]
+    }
+}
+
+impl FromStr for Shell {
+    type Err = String;
+
+    #[cfg_attr(feature = "cargo-clippy", allow(clippy::wildcard_in_or_patterns))]
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        match s {
+            "ZSH" | _ if s.eq_ignore_ascii_case("zsh") => Ok(Shell::Zsh),
+            "FISH" | _ if s.eq_ignore_ascii_case("fish") => Ok(Shell::Fish),
+            "BASH" | _ if s.eq_ignore_ascii_case("bash") => Ok(Shell::Bash),
+            "POWERSHELL" | _ if s.eq_ignore_ascii_case("powershell") => Ok(Shell::PowerShell),
+            "ELVISH" | _ if s.eq_ignore_ascii_case("elvish") => Ok(Shell::Elvish),
+            _ => Err(String::from(
+                "[valid values: bash, fish, zsh, powershell, elvish]",
+            )),
+        }
+    }
+}
+
+impl fmt::Display for Shell {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match *self {
+            Shell::Bash => write!(f, "BASH"),
+            Shell::Fish => write!(f, "FISH"),
+            Shell::Zsh => write!(f, "ZSH"),
+            Shell::PowerShell => write!(f, "POWERSHELL"),
+            Shell::Elvish => write!(f, "ELVISH"),
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/completions/zsh.rs
@@ -0,0 +1,484 @@
+// Std
+#[allow(deprecated, unused_imports)]
+use std::{ascii::AsciiExt, io::Write};
+
+// Internal
+use crate::{
+    app::{parser::Parser, App},
+    args::{AnyArg, ArgSettings},
+    completions, INTERNAL_ERROR_MSG,
+};
+
+pub struct ZshGen<'a, 'b>
+where
+    'a: 'b,
+{
+    p: &'b Parser<'a, 'b>,
+}
+
+impl<'a, 'b> ZshGen<'a, 'b> {
+    pub fn new(p: &'b Parser<'a, 'b>) -> Self {
+        debugln!("ZshGen::new;");
+        ZshGen { p }
+    }
+
+    pub fn generate_to<W: Write>(&self, buf: &mut W) {
+        debugln!("ZshGen::generate_to;");
+        w!(
+            buf,
+            format!(
+                "\
+#compdef {name}
+
+autoload -U is-at-least
+
+_{name}() {{
+    typeset -A opt_args
+    typeset -a _arguments_options
+    local ret=1
+
+    if is-at-least 5.2; then
+        _arguments_options=(-s -S -C)
+    else
+        _arguments_options=(-s -C)
+    fi
+
+    local context curcontext=\"$curcontext\" state line
+    {initial_args}
+    {subcommands}
+}}
+
+{subcommand_details}
+
+_{name} \"$@\"",
+                name = self.p.meta.bin_name.as_ref().unwrap(),
+                initial_args = get_args_of(self.p),
+                subcommands = get_subcommands_of(self.p),
+                subcommand_details = subcommand_details(self.p)
+            )
+            .as_bytes()
+        );
+    }
+}
+
+// Displays the commands of a subcommand
+// (( $+functions[_[bin_name_underscore]_commands] )) ||
+// _[bin_name_underscore]_commands() {
+// 	local commands; commands=(
+// 		'[arg_name]:[arg_help]'
+// 	)
+// 	_describe -t commands '[bin_name] commands' commands "$@"
+//
+// Where the following variables are present:
+//    [bin_name_underscore]: The full space delineated bin_name, where spaces have been replaced by
+//                           underscore characters
+//    [arg_name]: The name of the subcommand
+//    [arg_help]: The help message of the subcommand
+//    [bin_name]: The full space delineated bin_name
+//
+// Here's a snippet from rustup:
+//
+// (( $+functions[_rustup_commands] )) ||
+// _rustup_commands() {
+// 	local commands; commands=(
+// 		'show:Show the active and installed toolchains'
+//      'update:Update Rust toolchains'
+//      # ... snip for brevity
+//      'help:Prints this message or the help of the given subcommand(s)'
+// 	)
+// 	_describe -t commands 'rustup commands' commands "$@"
+//
+fn subcommand_details(p: &Parser) -> String {
+    debugln!("ZshGen::subcommand_details;");
+    // First we do ourself
+    let mut ret = vec![format!(
+        "\
+(( $+functions[_{bin_name_underscore}_commands] )) ||
+_{bin_name_underscore}_commands() {{
+    local commands; commands=(
+        {subcommands_and_args}
+    )
+    _describe -t commands '{bin_name} commands' commands \"$@\"
+}}",
+        bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"),
+        bin_name = p.meta.bin_name.as_ref().unwrap(),
+        subcommands_and_args = subcommands_of(p)
+    )];
+
+    // Next we start looping through all the children, grandchildren, etc.
+    let mut all_subcommands = completions::all_subcommands(p);
+    all_subcommands.sort();
+    all_subcommands.dedup();
+    for &(_, ref bin_name) in &all_subcommands {
+        debugln!("ZshGen::subcommand_details:iter: bin_name={}", bin_name);
+        ret.push(format!(
+            "\
+(( $+functions[_{bin_name_underscore}_commands] )) ||
+_{bin_name_underscore}_commands() {{
+    local commands; commands=(
+        {subcommands_and_args}
+    )
+    _describe -t commands '{bin_name} commands' commands \"$@\"
+}}",
+            bin_name_underscore = bin_name.replace(" ", "__"),
+            bin_name = bin_name,
+            subcommands_and_args = subcommands_of(parser_of(p, bin_name))
+        ));
+    }
+
+    ret.join("\n")
+}
+
+// Generates subcommand completions in form of
+//
+// 		'[arg_name]:[arg_help]'
+//
+// Where:
+//    [arg_name]: the subcommand's name
+//    [arg_help]: the help message of the subcommand
+//
+// A snippet from rustup:
+// 		'show:Show the active and installed toolchains'
+//      'update:Update Rust toolchains'
+fn subcommands_of(p: &Parser) -> String {
+    debugln!("ZshGen::subcommands_of;");
+    let mut ret = vec![];
+    fn add_sc(sc: &App, n: &str, ret: &mut Vec<String>) {
+        debugln!("ZshGen::add_sc;");
+        let s = format!(
+            "\"{name}:{help}\" \\",
+            name = n,
+            help =
+                sc.p.meta
+                    .about
+                    .unwrap_or("")
+                    .replace("[", "\\[")
+                    .replace("]", "\\]")
+        );
+        if !s.is_empty() {
+            ret.push(s);
+        }
+    }
+
+    // The subcommands
+    for sc in p.subcommands() {
+        debugln!("ZshGen::subcommands_of:iter: subcommand={}", sc.p.meta.name);
+        add_sc(sc, &sc.p.meta.name, &mut ret);
+        if let Some(ref v) = sc.p.meta.aliases {
+            for alias in v.iter().filter(|&&(_, vis)| vis).map(|&(n, _)| n) {
+                add_sc(sc, alias, &mut ret);
+            }
+        }
+    }
+
+    ret.join("\n")
+}
+
+// Get's the subcommand section of a completion file
+// This looks roughly like:
+//
+// case $state in
+// ([bin_name]_args)
+//     curcontext=\"${curcontext%:*:*}:[name_hyphen]-command-$words[1]:\"
+//     case $line[1] in
+//
+//         ([name])
+//         _arguments -C -s -S \
+//             [subcommand_args]
+//         && ret=0
+//
+//         [RECURSIVE_CALLS]
+//
+//         ;;",
+//
+//         [repeat]
+//
+//     esac
+// ;;
+// esac",
+//
+// Where the following variables are present:
+//    [name] = The subcommand name in the form of "install" for "rustup toolchain install"
+//    [bin_name] = The full space delineated bin_name such as "rustup toolchain install"
+//    [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens
+//    [repeat] = From the same recursive calls, but for all subcommands
+//    [subcommand_args] = The same as zsh::get_args_of
+fn get_subcommands_of(p: &Parser) -> String {
+    debugln!("get_subcommands_of;");
+
+    debugln!(
+        "get_subcommands_of: Has subcommands...{:?}",
+        p.has_subcommands()
+    );
+    if !p.has_subcommands() {
+        return String::new();
+    }
+
+    let sc_names = completions::subcommands_of(p);
+
+    let mut subcmds = vec![];
+    for &(ref name, ref bin_name) in &sc_names {
+        let mut v = vec![format!("({})", name)];
+        let subcommand_args = get_args_of(parser_of(p, &*bin_name));
+        if !subcommand_args.is_empty() {
+            v.push(subcommand_args);
+        }
+        let subcommands = get_subcommands_of(parser_of(p, &*bin_name));
+        if !subcommands.is_empty() {
+            v.push(subcommands);
+        }
+        v.push(String::from(";;"));
+        subcmds.push(v.join("\n"));
+    }
+
+    format!(
+        "case $state in
+    ({name})
+        words=($line[{pos}] \"${{words[@]}}\")
+        (( CURRENT += 1 ))
+        curcontext=\"${{curcontext%:*:*}}:{name_hyphen}-command-$line[{pos}]:\"
+        case $line[{pos}] in
+            {subcommands}
+        esac
+    ;;
+esac",
+        name = p.meta.name,
+        name_hyphen = p.meta.bin_name.as_ref().unwrap().replace(" ", "-"),
+        subcommands = subcmds.join("\n"),
+        pos = p.positionals().len() + 1
+    )
+}
+
+fn parser_of<'a, 'b>(p: &'b Parser<'a, 'b>, sc: &str) -> &'b Parser<'a, 'b> {
+    debugln!("parser_of: sc={}", sc);
+    if sc == p.meta.bin_name.as_ref().unwrap_or(&String::new()) {
+        return p;
+    }
+    &p.find_subcommand(sc).expect(INTERNAL_ERROR_MSG).p
+}
+
+// Writes out the args section, which ends up being the flags, opts and postionals, and a jump to
+// another ZSH function if there are subcommands.
+// The structer works like this:
+//    ([conflicting_args]) [multiple] arg [takes_value] [[help]] [: :(possible_values)]
+//       ^-- list '-v -h'    ^--'*'          ^--'+'                   ^-- list 'one two three'
+//
+// An example from the rustup command:
+//
+// _arguments -C -s -S \
+// 		'(-h --help --verbose)-v[Enable verbose output]' \
+// 		'(-V -v --version --verbose --help)-h[Prints help information]' \
+//      # ... snip for brevity
+// 		':: :_rustup_commands' \    # <-- displays subcommands
+// 		'*::: :->rustup' \          # <-- displays subcommand args and child subcommands
+// 	&& ret=0
+//
+// The args used for _arguments are as follows:
+//    -C: modify the $context internal variable
+//    -s: Allow stacking of short args (i.e. -a -b -c => -abc)
+//    -S: Do not complete anything after '--' and treat those as argument values
+fn get_args_of(p: &Parser) -> String {
+    debugln!("get_args_of;");
+    let mut ret = vec![String::from("_arguments \"${_arguments_options[@]}\" \\")];
+    let opts = write_opts_of(p);
+    let flags = write_flags_of(p);
+    let positionals = write_positionals_of(p);
+    let sc_or_a = if p.has_subcommands() {
+        format!(
+            "\":: :_{name}_commands\" \\",
+            name = p.meta.bin_name.as_ref().unwrap().replace(" ", "__")
+        )
+    } else {
+        String::new()
+    };
+    let sc = if p.has_subcommands() {
+        format!("\"*::: :->{name}\" \\", name = p.meta.name)
+    } else {
+        String::new()
+    };
+
+    if !opts.is_empty() {
+        ret.push(opts);
+    }
+    if !flags.is_empty() {
+        ret.push(flags);
+    }
+    if !positionals.is_empty() {
+        ret.push(positionals);
+    }
+    if !sc_or_a.is_empty() {
+        ret.push(sc_or_a);
+    }
+    if !sc.is_empty() {
+        ret.push(sc);
+    }
+    ret.push(String::from("&& ret=0"));
+
+    ret.join("\n")
+}
+
+// Escape help string inside single quotes and brackets
+fn escape_help(string: &str) -> String {
+    string
+        .replace("\\", "\\\\")
+        .replace("'", "'\\''")
+        .replace("[", "\\[")
+        .replace("]", "\\]")
+}
+
+// Escape value string inside single quotes and parentheses
+fn escape_value(string: &str) -> String {
+    string
+        .replace("\\", "\\\\")
+        .replace("'", "'\\''")
+        .replace("(", "\\(")
+        .replace(")", "\\)")
+        .replace(" ", "\\ ")
+}
+
+fn write_opts_of(p: &Parser) -> String {
+    debugln!("write_opts_of;");
+    let mut ret = vec![];
+    for o in p.opts() {
+        debugln!("write_opts_of:iter: o={}", o.name());
+        let help = o.help().map_or(String::new(), escape_help);
+        let mut conflicts = get_zsh_arg_conflicts!(p, o, INTERNAL_ERROR_MSG);
+        conflicts = if conflicts.is_empty() {
+            String::new()
+        } else {
+            format!("({})", conflicts)
+        };
+
+        let multiple = if o.is_set(ArgSettings::Multiple) {
+            "*"
+        } else {
+            ""
+        };
+        let pv = if let Some(pv_vec) = o.possible_vals() {
+            format!(
+                ": :({})",
+                pv_vec
+                    .iter()
+                    .map(|v| escape_value(*v))
+                    .collect::<Vec<String>>()
+                    .join(" ")
+            )
+        } else {
+            String::new()
+        };
+        if let Some(short) = o.short() {
+            let s = format!(
+                "'{conflicts}{multiple}-{arg}+[{help}]{possible_values}' \\",
+                conflicts = conflicts,
+                multiple = multiple,
+                arg = short,
+                possible_values = pv,
+                help = help
+            );
+
+            debugln!("write_opts_of:iter: Wrote...{}", &*s);
+            ret.push(s);
+        }
+        if let Some(long) = o.long() {
+            let l = format!(
+                "'{conflicts}{multiple}--{arg}=[{help}]{possible_values}' \\",
+                conflicts = conflicts,
+                multiple = multiple,
+                arg = long,
+                possible_values = pv,
+                help = help
+            );
+
+            debugln!("write_opts_of:iter: Wrote...{}", &*l);
+            ret.push(l);
+        }
+    }
+
+    ret.join("\n")
+}
+
+fn write_flags_of(p: &Parser) -> String {
+    debugln!("write_flags_of;");
+    let mut ret = vec![];
+    for f in p.flags() {
+        debugln!("write_flags_of:iter: f={}", f.name());
+        let help = f.help().map_or(String::new(), escape_help);
+        let mut conflicts = get_zsh_arg_conflicts!(p, f, INTERNAL_ERROR_MSG);
+        conflicts = if conflicts.is_empty() {
+            String::new()
+        } else {
+            format!("({})", conflicts)
+        };
+
+        let multiple = if f.is_set(ArgSettings::Multiple) {
+            "*"
+        } else {
+            ""
+        };
+        if let Some(short) = f.short() {
+            let s = format!(
+                "'{conflicts}{multiple}-{arg}[{help}]' \\",
+                multiple = multiple,
+                conflicts = conflicts,
+                arg = short,
+                help = help
+            );
+
+            debugln!("write_flags_of:iter: Wrote...{}", &*s);
+            ret.push(s);
+        }
+
+        if let Some(long) = f.long() {
+            let l = format!(
+                "'{conflicts}{multiple}--{arg}[{help}]' \\",
+                conflicts = conflicts,
+                multiple = multiple,
+                arg = long,
+                help = help
+            );
+
+            debugln!("write_flags_of:iter: Wrote...{}", &*l);
+            ret.push(l);
+        }
+    }
+
+    ret.join("\n")
+}
+
+fn write_positionals_of(p: &Parser) -> String {
+    debugln!("write_positionals_of;");
+    let mut ret = vec![];
+    for arg in p.positionals() {
+        debugln!("write_positionals_of:iter: arg={}", arg.b.name);
+        let a = format!(
+            "'{optional}:{name}{help}:{action}' \\",
+            optional = if !arg.b.is_set(ArgSettings::Required) {
+                ":"
+            } else {
+                ""
+            },
+            name = arg.b.name,
+            help = arg
+                .b
+                .help
+                .map_or("".to_owned(), |v| " -- ".to_owned() + v)
+                .replace("[", "\\[")
+                .replace("]", "\\]"),
+            action = arg.possible_vals().map_or("_files".to_owned(), |values| {
+                format!(
+                    "({})",
+                    values
+                        .iter()
+                        .map(|v| escape_value(*v))
+                        .collect::<Vec<String>>()
+                        .join(" ")
+                )
+            })
+        );
+
+        debugln!("write_positionals_of:iter: Wrote...{}", a);
+        ret.push(a);
+    }
+
+    ret.join("\n")
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/errors.rs
@@ -0,0 +1,933 @@
+// Std
+use std::{
+    convert::From,
+    error::Error as StdError,
+    fmt as std_fmt,
+    fmt::Display,
+    io::{self, Write},
+    process,
+    result::Result as StdResult,
+};
+
+// Internal
+use crate::{
+    args::AnyArg,
+    fmt::{ColorWhen, Colorizer, ColorizerOption},
+    suggestions,
+};
+
+/// Short hand for [`Result`] type
+///
+/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
+pub type Result<T> = StdResult<T, Error>;
+
+/// Command line argument parser kind of error
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub enum ErrorKind {
+    /// Occurs when an [`Arg`] has a set of possible values,
+    /// and the user provides a value which isn't in that set.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("speed")
+    ///         .possible_value("fast")
+    ///         .possible_value("slow"))
+    ///     .get_matches_from_safe(vec!["prog", "other"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidValue);
+    /// ```
+    /// [`Arg`]: ./struct.Arg.html
+    InvalidValue,
+
+    /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::from_usage("--flag 'some flag'"))
+    ///     .get_matches_from_safe(vec!["prog", "--other"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnknownArgument);
+    /// ```
+    UnknownArgument,
+
+    /// Occurs when the user provides an unrecognized [`SubCommand`] which meets the threshold for
+    /// being similar enough to an existing subcommand.
+    /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled,
+    /// the more general [`UnknownArgument`] error is returned.
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")]
+    #[cfg_attr(feature = "suggestions", doc = " ```")]
+    /// # use clap::{App, Arg, ErrorKind, SubCommand};
+    /// let result = App::new("prog")
+    ///     .subcommand(SubCommand::with_name("config")
+    ///         .about("Used for configuration")
+    ///         .arg(Arg::with_name("config_file")
+    ///             .help("The configuration file to use")
+    ///             .index(1)))
+    ///     .get_matches_from_safe(vec!["prog", "confi"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidSubcommand);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
+    InvalidSubcommand,
+
+    /// Occurs when the user provides an unrecognized [`SubCommand`] which either
+    /// doesn't meet the threshold for being similar enough to an existing subcommand,
+    /// or the 'suggestions' feature is disabled.
+    /// Otherwise the more detailed [`InvalidSubcommand`] error is returned.
+    ///
+    /// This error typically happens when passing additional subcommand names to the `help`
+    /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind, SubCommand};
+    /// let result = App::new("prog")
+    ///     .subcommand(SubCommand::with_name("config")
+    ///         .about("Used for configuration")
+    ///         .arg(Arg::with_name("config_file")
+    ///             .help("The configuration file to use")
+    ///             .index(1)))
+    ///     .get_matches_from_safe(vec!["prog", "help", "nothing"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`InvalidSubcommand`]: ./enum.ErrorKind.html#variant.InvalidSubcommand
+    /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
+    UnrecognizedSubcommand,
+
+    /// Occurs when the user provides an empty value for an option that does not allow empty
+    /// values.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let res = App::new("prog")
+    ///     .arg(Arg::with_name("color")
+    ///          .long("color")
+    ///          .empty_values(false))
+    ///     .get_matches_from_safe(vec!["prog", "--color="]);
+    /// assert!(res.is_err());
+    /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
+    /// ```
+    EmptyValue,
+
+    /// Occurs when the user provides a value for an argument with a custom validation and the
+    /// value fails that validation.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// fn is_numeric(val: String) -> Result<(), String> {
+    ///     match val.parse::<i64>() {
+    ///         Ok(..) => Ok(()),
+    ///         Err(..) => Err(String::from("Value wasn't a number!")),
+    ///     }
+    /// }
+    ///
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("num")
+    ///          .validator(is_numeric))
+    ///     .get_matches_from_safe(vec!["prog", "NotANumber"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::ValueValidation);
+    /// ```
+    ValueValidation,
+
+    /// Occurs when a user provides more values for an argument than were defined by setting
+    /// [`Arg::max_values`].
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("arg")
+    ///         .multiple(true)
+    ///         .max_values(2))
+    ///     .get_matches_from_safe(vec!["prog", "too", "many", "values"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooManyValues);
+    /// ```
+    /// [`Arg::max_values`]: ./struct.Arg.html#method.max_values
+    TooManyValues,
+
+    /// Occurs when the user provides fewer values for an argument than were defined by setting
+    /// [`Arg::min_values`].
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("some_opt")
+    ///         .long("opt")
+    ///         .min_values(3))
+    ///     .get_matches_from_safe(vec!["prog", "--opt", "too", "few"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooFewValues);
+    /// ```
+    /// [`Arg::min_values`]: ./struct.Arg.html#method.min_values
+    TooFewValues,
+
+    /// Occurs when the user provides a different number of values for an argument than what's
+    /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by
+    /// [`Arg::value_names`].
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("some_opt")
+    ///         .long("opt")
+    ///         .takes_value(true)
+    ///         .number_of_values(2))
+    ///     .get_matches_from_safe(vec!["prog", "--opt", "wrong"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
+    /// ```
+    ///
+    /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values
+    /// [`Arg::value_names`]: ./struct.Arg.html#method.value_names
+    WrongNumberOfValues,
+
+    /// Occurs when the user provides two values which conflict with each other and can't be used
+    /// together.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug")
+    ///         .conflicts_with("color"))
+    ///     .arg(Arg::with_name("color")
+    ///         .long("color"))
+    ///     .get_matches_from_safe(vec!["prog", "--debug", "--color"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::ArgumentConflict);
+    /// ```
+    ArgumentConflict,
+
+    /// Occurs when the user does not provide one or more required arguments.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .required(true))
+    ///     .get_matches_from_safe(vec!["prog"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
+    /// ```
+    MissingRequiredArgument,
+
+    /// Occurs when a subcommand is required (as defined by [`AppSettings::SubcommandRequired`]),
+    /// but the user does not provide one.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, AppSettings, SubCommand, ErrorKind};
+    /// let err = App::new("prog")
+    ///     .setting(AppSettings::SubcommandRequired)
+    ///     .subcommand(SubCommand::with_name("test"))
+    ///     .get_matches_from_safe(vec![
+    ///         "myprog",
+    ///     ]);
+    /// assert!(err.is_err());
+    /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
+    /// # ;
+    /// ```
+    /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired
+    MissingSubcommand,
+
+    /// Occurs when either an argument or [`SubCommand`] is required, as defined by
+    /// [`AppSettings::ArgRequiredElseHelp`], but the user did not provide one.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, AppSettings, ErrorKind, SubCommand};
+    /// let result = App::new("prog")
+    ///     .setting(AppSettings::ArgRequiredElseHelp)
+    ///     .subcommand(SubCommand::with_name("config")
+    ///         .about("Used for configuration")
+    ///         .arg(Arg::with_name("config_file")
+    ///             .help("The configuration file to use")))
+    ///     .get_matches_from_safe(vec!["prog"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingArgumentOrSubcommand);
+    /// ```
+    /// [`SubCommand`]: ./struct.SubCommand.html
+    /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp
+    MissingArgumentOrSubcommand,
+
+    /// Occurs when the user provides multiple values to an argument which doesn't allow that.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .arg(Arg::with_name("debug")
+    ///         .long("debug")
+    ///         .multiple(false))
+    ///     .get_matches_from_safe(vec!["prog", "--debug", "--debug"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnexpectedMultipleUsage);
+    /// ```
+    UnexpectedMultipleUsage,
+
+    /// Occurs when the user provides a value containing invalid UTF-8 for an argument and
+    /// [`AppSettings::StrictUtf8`] is set.
+    ///
+    /// # Platform Specific
+    ///
+    /// Non-Windows platforms only (such as Linux, Unix, macOS, etc.)
+    ///
+    /// # Examples
+    ///
+    #[cfg_attr(not(unix), doc = " ```ignore")]
+    #[cfg_attr(unix, doc = " ```")]
+    /// # use clap::{App, Arg, ErrorKind, AppSettings};
+    /// # use std::os::unix::ffi::OsStringExt;
+    /// # use std::ffi::OsString;
+    /// let result = App::new("prog")
+    ///     .setting(AppSettings::StrictUtf8)
+    ///     .arg(Arg::with_name("utf8")
+    ///         .short("u")
+    ///         .takes_value(true))
+    ///     .get_matches_from_safe(vec![OsString::from("myprog"),
+    ///                                 OsString::from("-u"),
+    ///                                 OsString::from_vec(vec![0xE9])]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidUtf8);
+    /// ```
+    /// [`AppSettings::StrictUtf8`]: ./enum.AppSettings.html#variant.StrictUtf8
+    InvalidUtf8,
+
+    /// Not a true "error" as it means `--help` or similar was used.
+    /// The help message will be sent to `stdout`.
+    ///
+    /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will
+    /// be sent to `stderr` instead of `stdout`.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .get_matches_from_safe(vec!["prog", "--help"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::HelpDisplayed);
+    /// ```
+    HelpDisplayed,
+
+    /// Not a true "error" as it means `--version` or similar was used.
+    /// The message will be sent to `stdout`.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// # use clap::{App, Arg, ErrorKind};
+    /// let result = App::new("prog")
+    ///     .get_matches_from_safe(vec!["prog", "--version"]);
+    /// assert!(result.is_err());
+    /// assert_eq!(result.unwrap_err().kind, ErrorKind::VersionDisplayed);
+    /// ```
+    VersionDisplayed,
+
+    /// Occurs when using the [`value_t!`] and [`values_t!`] macros to convert an argument value
+    /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument
+    /// with name `config` to be converted, but `config` wasn't used by the user.
+    /// [`value_t!`]: ./macro.value_t!.html
+    /// [`values_t!`]: ./macro.values_t!.html
+    ArgumentNotFound,
+
+    /// Represents an [I/O error].
+    /// Can occur when writing to `stderr` or `stdout` or reading a configuration file.
+    /// [I/O error]: https://doc.rust-lang.org/std/io/struct.Error.html
+    Io,
+
+    /// Represents a [Format error] (which is a part of [`Display`]).
+    /// Typically caused by writing to `stderr` or `stdout`.
+    ///
+    /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
+    /// [Format error]: https://doc.rust-lang.org/std/fmt/struct.Error.html
+    Format,
+}
+
+/// Command Line Argument Parser Error
+#[derive(Debug)]
+pub struct Error {
+    /// Formatted error message
+    pub message: String,
+    /// The type of error
+    pub kind: ErrorKind,
+    /// Any additional information passed along, such as the argument name that caused the error
+    pub info: Option<Vec<String>>,
+}
+
+impl Error {
+    /// Should the message be written to `stdout` or not
+    pub fn use_stderr(&self) -> bool {
+        !matches!(
+            self.kind,
+            ErrorKind::HelpDisplayed | ErrorKind::VersionDisplayed
+        )
+    }
+
+    /// Prints the error message and exits. If `Error::use_stderr` evaluates to `true`, the message
+    /// will be written to `stderr` and exits with a status of `1`. Otherwise, `stdout` is used
+    /// with a status of `0`.
+    pub fn exit(&self) -> ! {
+        if self.use_stderr() {
+            wlnerr!(@nopanic "{}", self.message);
+            process::exit(1);
+        }
+        // We are deliberately dropping errors here. We could match on the error kind, and only
+        // drop things such as `std::io::ErrorKind::BrokenPipe`, however nothing is being bubbled
+        // up or reported back to the caller and we will be exit'ing the process anyways.
+        // Additionally, changing this API to bubble up the result would be a breaking change.
+        //
+        // Another approach could be to try and write to stdout, if that fails due to a broken pipe
+        // then use stderr. However, that would change the semantics in what could be argued is a
+        // breaking change. Simply dropping the error, can always be changed to this "use stderr if
+        // stdout is closed" approach later if desired.
+        //
+        // A good explanation of the types of errors are SIGPIPE where the read side of the pipe
+        // closes before the write side. See the README in `calm_io` for a good explanation:
+        //
+        // https://github.com/myrrlyn/calm_io/blob/a42845575a04cd8b65e92c19d104627f5fcad3d7/README.md
+        let _ = writeln!(&mut io::stdout().lock(), "{}", self.message);
+        process::exit(0);
+    }
+
+    #[doc(hidden)]
+    pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
+        write!(w, "{}", self.message)
+    }
+
+    #[doc(hidden)]
+    pub fn argument_conflict<O, U>(
+        arg: &AnyArg,
+        other: Option<O>,
+        usage: U,
+        color: ColorWhen,
+    ) -> Self
+    where
+        O: Into<String>,
+        U: Display,
+    {
+        let mut v = vec![arg.name().to_owned()];
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The argument '{}' cannot be used with {}\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(&*arg.to_string()),
+                match other {
+                    Some(name) => {
+                        let n = name.into();
+                        v.push(n.clone());
+                        c.warning(format!("'{}'", n))
+                    }
+                    None => c.none("one or more of the other specified arguments".to_owned()),
+                },
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::ArgumentConflict,
+            info: Some(v),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn empty_value<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self
+    where
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The argument '{}' requires a value but none was supplied\
+                 \n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(arg.to_string()),
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::EmptyValue,
+            info: Some(vec![arg.name().to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn invalid_value<B, G, U>(
+        bad_val: B,
+        good_vals: &[G],
+        arg: &AnyArg,
+        usage: U,
+        color: ColorWhen,
+    ) -> Self
+    where
+        B: AsRef<str>,
+        G: AsRef<str> + Display,
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        let suffix = suggestions::did_you_mean_value_suffix(bad_val.as_ref(), good_vals.iter());
+
+        let mut sorted = vec![];
+        for v in good_vals {
+            let val = format!("{}", c.good(v));
+            sorted.push(val);
+        }
+        sorted.sort();
+        let valid_values = sorted.join(", ");
+        Error {
+            message: format!(
+                "{} '{}' isn't a valid value for '{}'\n\t\
+                 [possible values: {}]\n\
+                 {}\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(bad_val.as_ref()),
+                c.warning(arg.to_string()),
+                valid_values,
+                suffix.0,
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::InvalidValue,
+            info: Some(vec![arg.name().to_owned(), bad_val.as_ref().to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn invalid_subcommand<S, D, N, U>(
+        subcmd: S,
+        did_you_mean: D,
+        name: N,
+        usage: U,
+        color: ColorWhen,
+    ) -> Self
+    where
+        S: Into<String>,
+        D: AsRef<str> + Display,
+        N: Display,
+        U: Display,
+    {
+        let s = subcmd.into();
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The subcommand '{}' wasn't recognized\n\t\
+                 Did you mean '{}'?\n\n\
+                 If you believe you received this message in error, try \
+                 re-running with '{} {} {}'\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(&*s),
+                c.good(did_you_mean.as_ref()),
+                name,
+                c.good("--"),
+                &*s,
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::InvalidSubcommand,
+            info: Some(vec![s]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn unrecognized_subcommand<S, N>(subcmd: S, name: N, color: ColorWhen) -> Self
+    where
+        S: Into<String>,
+        N: Display,
+    {
+        let s = subcmd.into();
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The subcommand '{}' wasn't recognized\n\n\
+                 {}\n\t\
+                 {} help <subcommands>...\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(&*s),
+                c.warning("USAGE:"),
+                name,
+                c.good("--help")
+            ),
+            kind: ErrorKind::UnrecognizedSubcommand,
+            info: Some(vec![s]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn missing_required_argument<R, U>(required: R, usage: U, color: ColorWhen) -> Self
+    where
+        R: Display,
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The following required arguments were not provided:{}\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                required,
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::MissingRequiredArgument,
+            info: None,
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn missing_subcommand<N, U>(name: N, usage: U, color: ColorWhen) -> Self
+    where
+        N: AsRef<str> + Display,
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} '{}' requires a subcommand, but one was not provided\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(name),
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::MissingSubcommand,
+            info: None,
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn invalid_utf8<U>(usage: U, color: ColorWhen) -> Self
+    where
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} Invalid UTF-8 was detected in one or more arguments\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::InvalidUtf8,
+            info: None,
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn too_many_values<V, U>(val: V, arg: &AnyArg, usage: U, color: ColorWhen) -> Self
+    where
+        V: AsRef<str> + Display + ToOwned,
+        U: Display,
+    {
+        let v = val.as_ref();
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The value '{}' was provided to '{}', but it wasn't expecting \
+                 any more values\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(v),
+                c.warning(arg.to_string()),
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::TooManyValues,
+            info: Some(vec![arg.name().to_owned(), v.to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn too_few_values<U>(
+        arg: &AnyArg,
+        min_vals: u64,
+        curr_vals: usize,
+        usage: U,
+        color: ColorWhen,
+    ) -> Self
+    where
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The argument '{}' requires at least {} values, but only {} w{} \
+                 provided\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(arg.to_string()),
+                c.warning(min_vals.to_string()),
+                c.warning(curr_vals.to_string()),
+                if curr_vals > 1 { "ere" } else { "as" },
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::TooFewValues,
+            info: Some(vec![arg.name().to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} Invalid value{}: {}",
+                c.error("error:"),
+                if let Some(a) = arg {
+                    format!(" for '{}'", c.warning(a.to_string()))
+                } else {
+                    "".to_string()
+                },
+                err
+            ),
+            kind: ErrorKind::ValueValidation,
+            info: None,
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn value_validation_auto(err: String) -> Self {
+        let n: Option<&AnyArg> = None;
+        Error::value_validation(n, err, ColorWhen::Auto)
+    }
+
+    #[doc(hidden)]
+    pub fn wrong_number_of_values<S, U>(
+        arg: &AnyArg,
+        num_vals: u64,
+        curr_vals: usize,
+        suffix: S,
+        usage: U,
+        color: ColorWhen,
+    ) -> Self
+    where
+        S: Display,
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The argument '{}' requires {} values, but {} w{} \
+                 provided\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(arg.to_string()),
+                c.warning(num_vals.to_string()),
+                c.warning(curr_vals.to_string()),
+                suffix,
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::WrongNumberOfValues,
+            info: Some(vec![arg.name().to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn unexpected_multiple_usage<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self
+    where
+        U: Display,
+    {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} The argument '{}' was provided more than once, but cannot \
+                 be used multiple times\n\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(arg.to_string()),
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::UnexpectedMultipleUsage,
+            info: Some(vec![arg.name().to_owned()]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn unknown_argument<A, U>(arg: A, did_you_mean: &str, usage: U, color: ColorWhen) -> Self
+    where
+        A: Into<String>,
+        U: Display,
+    {
+        let a = arg.into();
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!(
+                "{} Found argument '{}' which wasn't expected, or isn't valid in \
+                 this context{}\n\
+                 {}\n\n\
+                 For more information try {}",
+                c.error("error:"),
+                c.warning(&*a),
+                if did_you_mean.is_empty() {
+                    "\n".to_owned()
+                } else {
+                    format!("{}\n", did_you_mean)
+                },
+                usage,
+                c.good("--help")
+            ),
+            kind: ErrorKind::UnknownArgument,
+            info: Some(vec![a]),
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn io_error(e: &Error, color: ColorWhen) -> Self {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: color,
+        });
+        Error {
+            message: format!("{} {}", c.error("error:"), e.description()),
+            kind: ErrorKind::Io,
+            info: None,
+        }
+    }
+
+    #[doc(hidden)]
+    pub fn argument_not_found_auto<A>(arg: A) -> Self
+    where
+        A: Into<String>,
+    {
+        let a = arg.into();
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: ColorWhen::Auto,
+        });
+        Error {
+            message: format!("{} The argument '{}' wasn't found", c.error("error:"), a),
+            kind: ErrorKind::ArgumentNotFound,
+            info: Some(vec![a]),
+        }
+    }
+
+    /// Create an error with a custom description.
+    ///
+    /// This can be used in combination with `Error::exit` to exit your program
+    /// with a custom error message.
+    pub fn with_description(description: &str, kind: ErrorKind) -> Self {
+        let c = Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: ColorWhen::Auto,
+        });
+        Error {
+            message: format!("{} {}", c.error("error:"), description),
+            kind,
+            info: None,
+        }
+    }
+}
+
+impl StdError for Error {
+    fn description(&self) -> &str {
+        &*self.message
+    }
+}
+
+impl Display for Error {
+    fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result {
+        writeln!(f, "{}", self.message)
+    }
+}
+
+impl From<io::Error> for Error {
+    fn from(e: io::Error) -> Self {
+        Error::with_description(e.description(), ErrorKind::Io)
+    }
+}
+
+impl From<std_fmt::Error> for Error {
+    fn from(e: std_fmt::Error) -> Self {
+        Error::with_description(e.description(), ErrorKind::Format)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/fmt.rs
@@ -0,0 +1,192 @@
+#[cfg(all(feature = "color", not(target_os = "windows")))]
+use ansi_term::ANSIString;
+
+#[cfg(all(feature = "color", not(target_os = "windows")))]
+use ansi_term::Colour::{Green, Red, Yellow};
+
+use std::env;
+use std::fmt;
+
+#[doc(hidden)]
+#[derive(Debug, Copy, Clone, PartialEq)]
+pub enum ColorWhen {
+    Auto,
+    Always,
+    Never,
+}
+
+#[cfg(feature = "color")]
+pub fn is_a_tty(stderr: bool) -> bool {
+    debugln!("is_a_tty: stderr={:?}", stderr);
+    let stream = if stderr {
+        atty::Stream::Stderr
+    } else {
+        atty::Stream::Stdout
+    };
+    atty::is(stream)
+}
+
+#[cfg(not(feature = "color"))]
+pub fn is_a_tty(_: bool) -> bool {
+    debugln!("is_a_tty;");
+    false
+}
+
+pub fn is_term_dumb() -> bool {
+    env::var("TERM").ok() == Some(String::from("dumb"))
+}
+
+#[doc(hidden)]
+pub struct ColorizerOption {
+    pub use_stderr: bool,
+    pub when: ColorWhen,
+}
+
+#[doc(hidden)]
+pub struct Colorizer {
+    when: ColorWhen,
+}
+
+macro_rules! color {
+    ($_self:ident, $c:ident, $m:expr) => {
+        match $_self.when {
+            ColorWhen::Auto => Format::$c($m),
+            ColorWhen::Always => Format::$c($m),
+            ColorWhen::Never => Format::None($m),
+        }
+    };
+}
+
+impl Colorizer {
+    pub fn new(option: ColorizerOption) -> Colorizer {
+        let is_a_tty = is_a_tty(option.use_stderr);
+        let is_term_dumb = is_term_dumb();
+        Colorizer {
+            when: match option.when {
+                ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto,
+                ColorWhen::Auto => ColorWhen::Never,
+                when => when,
+            },
+        }
+    }
+
+    pub fn good<T>(&self, msg: T) -> Format<T>
+    where
+        T: fmt::Display + AsRef<str>,
+    {
+        debugln!("Colorizer::good;");
+        color!(self, Good, msg)
+    }
+
+    pub fn warning<T>(&self, msg: T) -> Format<T>
+    where
+        T: fmt::Display + AsRef<str>,
+    {
+        debugln!("Colorizer::warning;");
+        color!(self, Warning, msg)
+    }
+
+    pub fn error<T>(&self, msg: T) -> Format<T>
+    where
+        T: fmt::Display + AsRef<str>,
+    {
+        debugln!("Colorizer::error;");
+        color!(self, Error, msg)
+    }
+
+    pub fn none<T>(&self, msg: T) -> Format<T>
+    where
+        T: fmt::Display + AsRef<str>,
+    {
+        debugln!("Colorizer::none;");
+        Format::None(msg)
+    }
+}
+
+impl Default for Colorizer {
+    fn default() -> Self {
+        Colorizer::new(ColorizerOption {
+            use_stderr: true,
+            when: ColorWhen::Auto,
+        })
+    }
+}
+
+/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow,
+/// and Good=Green
+#[derive(Debug)]
+#[doc(hidden)]
+pub enum Format<T> {
+    /// Defines the style used for errors, defaults to Red
+    Error(T),
+    /// Defines the style used for warnings, defaults to Yellow
+    Warning(T),
+    /// Defines the style used for good values, defaults to Green
+    Good(T),
+    /// Defines no formatting style
+    None(T),
+}
+
+#[cfg(all(feature = "color", not(target_os = "windows")))]
+impl<T: AsRef<str>> Format<T> {
+    fn format(&self) -> ANSIString {
+        match *self {
+            Format::Error(ref e) => Red.bold().paint(e.as_ref()),
+            Format::Warning(ref e) => Yellow.paint(e.as_ref()),
+            Format::Good(ref e) => Green.paint(e.as_ref()),
+            Format::None(ref e) => ANSIString::from(e.as_ref()),
+        }
+    }
+}
+
+#[cfg(any(not(feature = "color"), target_os = "windows"))]
+#[cfg_attr(feature = "cargo-clippy", allow(clippy::match_same_arms))]
+impl<T: fmt::Display> Format<T> {
+    fn format(&self) -> &T {
+        match *self {
+            Format::Error(ref e) => e,
+            Format::Warning(ref e) => e,
+            Format::Good(ref e) => e,
+            Format::None(ref e) => e,
+        }
+    }
+}
+
+#[cfg(all(feature = "color", not(target_os = "windows")))]
+impl<T: AsRef<str>> fmt::Display for Format<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{}", &self.format())
+    }
+}
+
+#[cfg(any(not(feature = "color"), target_os = "windows"))]
+impl<T: fmt::Display> fmt::Display for Format<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{}", &self.format())
+    }
+}
+
+#[cfg(all(test, feature = "color", not(target_os = "windows")))]
+mod test {
+    use super::Format;
+    use ansi_term::ANSIString;
+    use ansi_term::Colour::{Green, Red, Yellow};
+
+    #[test]
+    fn colored_output() {
+        let err = Format::Error("error");
+        assert_eq!(
+            &*format!("{}", err),
+            &*format!("{}", Red.bold().paint("error"))
+        );
+        let good = Format::Good("good");
+        assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good")));
+        let warn = Format::Warning("warn");
+        assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn")));
+        let none = Format::None("none");
+        assert_eq!(
+            &*format!("{}", none),
+            &*format!("{}", ANSIString::from("none"))
+        );
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/lib.rs
@@ -0,0 +1,638 @@
+// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/v2.33.1/CONTRIBUTORS.md).
+// Licensed under the MIT license
+// (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the project carrying such
+// notice may not be copied, modified, or distributed except according to those terms.
+
+//! `clap` is a simple-to-use, efficient, and full-featured library for parsing command line
+//! arguments and subcommands when writing console/terminal applications.
+//!
+//! ## About
+//!
+//! `clap` is used to parse *and validate* the string of command line arguments provided by the user
+//! at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means
+//! you focus on your *applications* functionality, and less on the parsing and validating of
+//! arguments.
+//!
+//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning
+//! automatically with no configuration. It does this by checking the list of valid possibilities you
+//! supplied and adding only the ones you haven't already defined. If you are using subcommands,
+//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags.
+//!
+//! Once `clap` parses the user provided string of arguments, it returns the matches along with any
+//! applicable values. If the user made an error or typo, `clap` informs them of the mistake and
+//! exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to
+//! exit). Because of this, you can make reasonable assumptions in your code about the validity of
+//! the arguments.
+//!
+//!
+//! ## Quick Example
+//!
+//! The following examples show a quick example of some of the very basic functionality of `clap`.
+//! For more advanced usage, such as requirements, conflicts, groups, multiple values and
+//! occurrences see the [documentation](https://docs.rs/clap/), [examples/] directory of
+//! this repository or the [video tutorials].
+//!
+//! **NOTE:** All of these examples are functionally the same, but show different styles in which to
+//! use `clap`
+//!
+//! The first example shows a method that allows more advanced configuration options (not shown in
+//! this small example), or even dynamically generating arguments when desired. The downside is it's
+//! more verbose.
+//!
+//! ```no_run
+//! // (Full example with detailed comments in examples/01b_quick_example.rs)
+//! //
+//! // This example demonstrates clap's full 'builder pattern' style of creating arguments which is
+//! // more verbose, but allows easier editing, and at times more advanced options, or the possibility
+//! // to generate arguments dynamically.
+//! extern crate clap;
+//! use clap::{Arg, App, SubCommand};
+//!
+//! fn main() {
+//!     let matches = App::new("My Super Program")
+//!                           .version("1.0")
+//!                           .author("Kevin K. <kbknapp@gmail.com>")
+//!                           .about("Does awesome things")
+//!                           .arg(Arg::with_name("config")
+//!                                .short("c")
+//!                                .long("config")
+//!                                .value_name("FILE")
+//!                                .help("Sets a custom config file")
+//!                                .takes_value(true))
+//!                           .arg(Arg::with_name("INPUT")
+//!                                .help("Sets the input file to use")
+//!                                .required(true)
+//!                                .index(1))
+//!                           .arg(Arg::with_name("v")
+//!                                .short("v")
+//!                                .multiple(true)
+//!                                .help("Sets the level of verbosity"))
+//!                           .subcommand(SubCommand::with_name("test")
+//!                                       .about("controls testing features")
+//!                                       .version("1.3")
+//!                                       .author("Someone E. <someone_else@other.com>")
+//!                                       .arg(Arg::with_name("debug")
+//!                                           .short("d")
+//!                                           .help("print debug information verbosely")))
+//!                           .get_matches();
+//!
+//!     // Gets a value for config if supplied by user, or defaults to "default.conf"
+//!     let config = matches.value_of("config").unwrap_or("default.conf");
+//!     println!("Value for config: {}", config);
+//!
+//!     // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
+//!     // required we could have used an 'if let' to conditionally get the value)
+//!     println!("Using input file: {}", matches.value_of("INPUT").unwrap());
+//!
+//!     // Vary the output based on how many times the user used the "verbose" flag
+//!     // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
+//!     match matches.occurrences_of("v") {
+//!         0 => println!("No verbose info"),
+//!         1 => println!("Some verbose info"),
+//!         2 => println!("Tons of verbose info"),
+//!         3 | _ => println!("Don't be crazy"),
+//!     }
+//!
+//!     // You can handle information about subcommands by requesting their matches by name
+//!     // (as below), requesting just the name used, or both at the same time
+//!     if let Some(matches) = matches.subcommand_matches("test") {
+//!         if matches.is_present("debug") {
+//!             println!("Printing debug info...");
+//!         } else {
+//!             println!("Printing normally...");
+//!         }
+//!     }
+//!
+//!     // more program logic goes here...
+//! }
+//! ```
+//!
+//! The next example shows a far less verbose method, but sacrifices some of the advanced
+//! configuration options (not shown in this small example). This method also takes a *very* minor
+//! runtime penalty.
+//!
+//! ```no_run
+//! // (Full example with detailed comments in examples/01a_quick_example.rs)
+//! //
+//! // This example demonstrates clap's "usage strings" method of creating arguments
+//! // which is less verbose
+//! extern crate clap;
+//! use clap::{Arg, App, SubCommand};
+//!
+//! fn main() {
+//!     let matches = App::new("myapp")
+//!                           .version("1.0")
+//!                           .author("Kevin K. <kbknapp@gmail.com>")
+//!                           .about("Does awesome things")
+//!                           .args_from_usage(
+//!                               "-c, --config=[FILE] 'Sets a custom config file'
+//!                               <INPUT>              'Sets the input file to use'
+//!                               -v...                'Sets the level of verbosity'")
+//!                           .subcommand(SubCommand::with_name("test")
+//!                                       .about("controls testing features")
+//!                                       .version("1.3")
+//!                                       .author("Someone E. <someone_else@other.com>")
+//!                                       .arg_from_usage("-d, --debug 'Print debug information'"))
+//!                           .get_matches();
+//!
+//!     // Same as previous example...
+//! }
+//! ```
+//!
+//! This third method shows how you can use a YAML file to build your CLI and keep your Rust source
+//! tidy or support multiple localized translations by having different YAML files for each
+//! localization.
+//!
+//! First, create the `cli.yml` file to hold your CLI options, but it could be called anything we
+//! like:
+//!
+//! ```yaml
+//! name: myapp
+//! version: "1.0"
+//! author: Kevin K. <kbknapp@gmail.com>
+//! about: Does awesome things
+//! args:
+//!     - config:
+//!         short: c
+//!         long: config
+//!         value_name: FILE
+//!         help: Sets a custom config file
+//!         takes_value: true
+//!     - INPUT:
+//!         help: Sets the input file to use
+//!         required: true
+//!         index: 1
+//!     - verbose:
+//!         short: v
+//!         multiple: true
+//!         help: Sets the level of verbosity
+//! subcommands:
+//!     - test:
+//!         about: controls testing features
+//!         version: "1.3"
+//!         author: Someone E. <someone_else@other.com>
+//!         args:
+//!             - debug:
+//!                 short: d
+//!                 help: print debug information
+//! ```
+//!
+//! Since this feature requires additional dependencies that not everyone may want, it is *not*
+//! compiled in by default and we need to enable a feature flag in Cargo.toml:
+//!
+//! Simply change your `clap = "~2.27.0"` to `clap = {version = "~2.27.0", features = ["yaml"]}`.
+//!
+//! At last we create our `main.rs` file just like we would have with the previous two examples:
+//!
+//! ```ignore
+//! // (Full example with detailed comments in examples/17_yaml.rs)
+//! //
+//! // This example demonstrates clap's building from YAML style of creating arguments which is far
+//! // more clean, but takes a very small performance hit compared to the other two methods.
+//! #[macro_use]
+//! extern crate clap;
+//! use clap::App;
+//!
+//! fn main() {
+//!     // The YAML file is found relative to the current file, similar to how modules are found
+//!     let yaml = load_yaml!("cli.yml");
+//!     let matches = App::from_yaml(yaml).get_matches();
+//!
+//!     // Same as previous examples...
+//! }
+//! ```
+//!
+//! Finally there is a macro version, which is like a hybrid approach offering the speed of the
+//! builder pattern (the first example), but without all the verbosity.
+//!
+//! ```no_run
+//! #[macro_use]
+//! extern crate clap;
+//!
+//! fn main() {
+//!     let matches = clap_app!(myapp =>
+//!         (version: "1.0")
+//!         (author: "Kevin K. <kbknapp@gmail.com>")
+//!         (about: "Does awesome things")
+//!         (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
+//!         (@arg INPUT: +required "Sets the input file to use")
+//!         (@arg debug: -d ... "Sets the level of debugging information")
+//!         (@subcommand test =>
+//!             (about: "controls testing features")
+//!             (version: "1.3")
+//!             (author: "Someone E. <someone_else@other.com>")
+//!             (@arg verbose: -v --verbose "Print test information verbosely")
+//!         )
+//!     ).get_matches();
+//!
+//!     // Same as before...
+//! }
+//! ```
+//!
+//! If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or
+//! `help` subcommand, since we defined `test` as a subcommand) the following would be output
+//!
+//! ```text
+//! $ myprog --help
+//! My Super Program 1.0
+//! Kevin K. <kbknapp@gmail.com>
+//! Does awesome things
+//!
+//! USAGE:
+//!     MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND]
+//!
+//! FLAGS:
+//!     -h, --help       Prints this message
+//!     -v               Sets the level of verbosity
+//!     -V, --version    Prints version information
+//!
+//! OPTIONS:
+//!     -c, --config <FILE>    Sets a custom config file
+//!
+//! ARGS:
+//!     INPUT    The input file to use
+//!
+//! SUBCOMMANDS:
+//!     help    Prints this message
+//!     test    Controls testing features
+//! ```
+//!
+//! **NOTE:** You could also run `myapp test --help` to see similar output and options for the
+//! `test` subcommand.
+//!
+//! ## Try it!
+//!
+//! ### Pre-Built Test
+//!
+//! To try out the pre-built example, use the following steps:
+//!
+//! * Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests`
+//! * Compile the example `$ cargo build --release`
+//! * Run the help info `$ ./target/release/claptests --help`
+//! * Play with the arguments!
+//!
+//! ### BYOB (Build Your Own Binary)
+//!
+//! To test out `clap`'s default auto-generated help/version follow these steps:
+//!
+//! * Create a new cargo project `$ cargo new fake --bin && cd fake`
+//! * Add `clap` to your `Cargo.toml`
+//!
+//! ```toml
+//! [dependencies]
+//! clap = "2"
+//! ```
+//!
+//! * Add the following to your `src/main.rs`
+//!
+//! ```no_run
+//! extern crate clap;
+//! use clap::App;
+//!
+//! fn main() {
+//!   App::new("fake").version("v1.0-beta").get_matches();
+//! }
+//! ```
+//!
+//! * Build your program `$ cargo build --release`
+//! * Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake
+//! --version`
+//!
+//! ## Usage
+//!
+//! For full usage, add `clap` as a dependency in your `Cargo.toml` (it is **highly** recommended to
+//! use the `~major.minor.patch` style versions in your `Cargo.toml`, for more information see
+//! [Compatibility Policy](#compatibility-policy)) to use from crates.io:
+//!
+//! ```toml
+//! [dependencies]
+//! clap = "~2.27.0"
+//! ```
+//!
+//! Or get the latest changes from the master branch at github:
+//!
+//! ```toml
+//! [dependencies.clap]
+//! git = "https://github.com/clap-rs/clap.git"
+//! ```
+//!
+//! Add `extern crate clap;` to your crate root.
+//!
+//! Define a list of valid arguments for your program (see the
+//! [documentation](https://docs.rs/clap/) or [examples/] directory of this repo)
+//!
+//! Then run `cargo build` or `cargo update && cargo build` for your project.
+//!
+//! ### Optional Dependencies / Features
+//!
+//! #### Features enabled by default
+//!
+//! * `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`)
+//! * `color`: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` and `atty`)
+//! * `wrap_help`: Wraps the help at the actual terminal width when
+//!  available, instead of 120 characters. (builds dependency `textwrap`
+//! with feature `term_size`)
+//!
+//! To disable these, add this to your `Cargo.toml`:
+//!
+//! ```toml
+//! [dependencies.clap]
+//! version = "~2.27.0"
+//! default-features = false
+//! ```
+//!
+//! You can also selectively enable only the features you'd like to include, by adding:
+//!
+//! ```toml
+//! [dependencies.clap]
+//! version = "~2.27.0"
+//! default-features = false
+//!
+//! # Cherry-pick the features you'd like to use
+//! features = [ "suggestions", "color" ]
+//! ```
+//!
+//! #### Opt-in features
+//!
+//! * **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`)
+//! * **"unstable"**: Enables unstable `clap` features that may change from release to release
+//!
+//! ### Dependencies Tree
+//!
+//! The following graphic depicts `clap`s dependency graph (generated using
+//! [cargo-graph](https://github.com/kbknapp/cargo-graph)).
+//!
+//!  * **Dashed** Line: Optional dependency
+//!  * **Red** Color: **NOT** included by default (must use cargo `features` to enable)
+//!  * **Blue** Color: Dev dependency, only used while developing.
+//!
+//! ![clap dependencies](https://github.com/clap-rs/clap/blob/v2.34.0/clap_dep_graph.png)
+//!
+//! ### More Information
+//!
+//! You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project.
+//!
+//! You can also find usage examples in the [examples/] directory of this repo.
+//!
+//! #### Video Tutorials
+//!
+//! There's also the video tutorial series [Argument Parsing with Rust v2][video tutorials].
+//!
+//! These videos slowly trickle out as I finish them and currently a work in progress.
+//!
+//! ## How to Contribute
+//!
+//! Contributions are always welcome! And there is a multitude of ways in which you can help
+//! depending on what you like to do, or are good at. Anything from documentation, code cleanup,
+//! issue completion, new features, you name it, even filing issues is contributing and greatly
+//! appreciated!
+//!
+//! Another really great way to help is if you find an interesting, or helpful way in which to use
+//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell
+//! me. I'm all about giving credit where credit is due :)
+//!
+//! Please read [CONTRIBUTING.md](https://github.com/clap-rs/clap/blob/v2.34.0/.github/CONTRIBUTING.md) before you start contributing.
+//!
+//!
+//! ### Testing Code
+//!
+//! To test with all features both enabled and disabled, you can run theese commands:
+//!
+//! ```text
+//! $ cargo test --no-default-features
+//! $ cargo test --features "yaml unstable"
+//! ```
+//!
+//! Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the
+//! prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands
+//! automatically.
+//!
+//! For example, to test the code, as above simply run:
+//!
+//! ```text
+//! $ just run-tests
+//! ```
+//!
+//! From here on, I will list the appropriate `cargo` command as well as the `just` command.
+//!
+//! Sometimes it's helpful to only run a subset of the tests, which can be done via:
+//!
+//! ```text
+//! $ cargo test --test <test_name>
+//!
+//! # Or
+//!
+//! $ just run-test <test_name>
+//! ```
+//!
+//! ### Linting Code
+//!
+//! During the CI process `clap` runs against many different lints using
+//! [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on
+//! your own computer prior to submitting a PR you'll need a nightly compiler.
+//!
+//! In order to check the code for lints run either:
+//!
+//! ```text
+//! $ rustup override add nightly
+//! $ cargo build --features lints
+//! $ rustup override remove
+//!
+//! # Or
+//!
+//! $ just lint
+//! ```
+//!
+//! ### Debugging Code
+//!
+//! Another helpful technique is to see the `clap` debug output while developing features. In order
+//! to see the debug output while running the full test suite or individual tests, run:
+//!
+//! ```text
+//! $ cargo test --features debug
+//!
+//! # Or for individual tests
+//! $ cargo test --test <test_name> --features debug
+//!
+//! # The corresponding just command for individual debugging tests is:
+//! $ just debug <test_name>
+//! ```
+//!
+//! ### Goals
+//!
+//! There are a few goals of `clap` that I'd like to maintain throughout contributions. If your
+//! proposed changes break, or go against any of these goals we'll discuss the changes further
+//! before merging (but will *not* be ignored, all contributes are welcome!). These are by no means
+//! hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by
+//! mistake or ignorance).
+//!
+//! * Remain backwards compatible when possible
+//!   - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before
+//!   removing legacy code - This does not apply for security concerns
+//! * Parse arguments quickly
+//!   - Parsing of arguments shouldn't slow down usage of the main program - This is also true of
+//!   generating help and usage information (although *slightly* less stringent, as the program is about
+//!   to exit)
+//! * Try to be cognizant of memory usage
+//!   - Once parsing is complete, the memory footprint of `clap` should be low since the  main program
+//!   is the star of the show
+//! * `panic!` on *developer* error, exit gracefully on *end-user* error
+//!
+//! ### Compatibility Policy
+//!
+//! Because `clap` takes `SemVer` and compatibility seriously, this is the official policy regarding
+//! breaking changes and previous versions of Rust.
+//!
+//! `clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum
+//! version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version
+//! of `clap` will be bumped.
+//!
+//! In order to keep from being surprised by breaking changes, it is **highly** recommended to use
+//! the `~major.minor.patch` style in your `Cargo.toml`:
+//!
+//! ```toml
+//! [dependencies] clap = "~2.27.0"
+//! ```
+//!
+//! This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore
+//! cannot break due to new features, or bumped minimum versions of Rust.
+//!
+//! #### Minimum Version of Rust
+//!
+//! `clap` will officially support current stable Rust, minus two releases, but may work with prior
+//! releases as well. For example, current stable Rust at the time of this writing is 1.21.0,
+//! meaning `clap` is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, `clap`
+//! will be guaranteed to compile with 1.20.0 and beyond, etc.
+//!
+//! Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be
+//! clearly annotated in the `CHANGELOG.md`
+//!
+//! ## License
+//!
+//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in
+//! this repository for more information.
+//!
+//! [examples/]: https://github.com/clap-rs/clap/tree/v2.34.0/examples
+//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U
+//! [license]: https://github.com/clap-rs/clap/blob/v2.34.0/LICENSE-MIT
+
+#![crate_type = "lib"]
+#![doc(html_root_url = "https://docs.rs/clap/2.34.0")]
+#![deny(
+    missing_docs,
+    missing_debug_implementations,
+    missing_copy_implementations,
+    trivial_casts,
+    unused_import_braces,
+    unused_allocation
+)]
+// Lints we'd like to deny but are currently failing for upstream crates
+//      unused_qualifications       (bitflags, clippy)
+//      trivial_numeric_casts       (bitflags)
+#![cfg_attr(
+    not(any(feature = "cargo-clippy", feature = "nightly")),
+    forbid(unstable_features)
+)]
+//#![cfg_attr(feature = "lints", feature(plugin))]
+//#![cfg_attr(feature = "lints", plugin(clippy))]
+// Need to disable deny(warnings) while deprecations are active
+//#![cfg_attr(feature = "cargo-clippy", deny(warnings))]
+// Due to our "MSRV for 2.x will remain unchanged" policy, we can't fix these warnings
+#![allow(bare_trait_objects, deprecated)]
+
+#[cfg(all(feature = "color", not(target_os = "windows")))]
+extern crate ansi_term;
+#[cfg(feature = "color")]
+extern crate atty;
+#[macro_use]
+extern crate bitflags;
+#[cfg(feature = "suggestions")]
+extern crate strsim;
+#[cfg(feature = "wrap_help")]
+extern crate term_size;
+extern crate textwrap;
+extern crate unicode_width;
+#[cfg(feature = "vec_map")]
+extern crate vec_map;
+#[cfg(feature = "yaml")]
+extern crate yaml_rust;
+
+pub use app::{App, AppSettings};
+pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values};
+pub use completions::Shell;
+pub use errors::{Error, ErrorKind, Result};
+pub use fmt::Format;
+#[cfg(feature = "yaml")]
+pub use yaml_rust::YamlLoader;
+
+#[macro_use]
+mod macros;
+mod app;
+mod args;
+mod completions;
+mod errors;
+mod fmt;
+mod map;
+mod osstringext;
+mod strext;
+mod suggestions;
+mod usage_parser;
+
+const INTERNAL_ERROR_MSG: &str = "Fatal internal error. Please consider filing a bug \
+                                          report at https://github.com/clap-rs/clap/issues";
+const INVALID_UTF8: &str = "unexpected invalid UTF-8 code point";
+
+#[cfg(unstable)]
+pub use derive::{ArgEnum, ClapApp, FromArgMatches, IntoApp};
+
+#[cfg(unstable)]
+mod derive {
+    /// @TODO @release @docs
+    pub trait ClapApp: IntoApp + FromArgMatches + Sized {
+        /// @TODO @release @docs
+        fn parse() -> Self {
+            Self::from_argmatches(Self::into_app().get_matches())
+        }
+
+        /// @TODO @release @docs
+        fn parse_from<I, T>(argv: I) -> Self
+        where
+            I: IntoIterator<Item = T>,
+            T: Into<OsString> + Clone,
+        {
+            Self::from_argmatches(Self::into_app().get_matches_from(argv))
+        }
+
+        /// @TODO @release @docs
+        fn try_parse() -> Result<Self, clap::Error> {
+            Self::try_from_argmatches(Self::into_app().get_matches_safe()?)
+        }
+
+        /// @TODO @release @docs
+        fn try_parse_from<I, T>(argv: I) -> Result<Self, clap::Error>
+        where
+            I: IntoIterator<Item = T>,
+            T: Into<OsString> + Clone,
+        {
+            Self::try_from_argmatches(Self::into_app().get_matches_from_safe(argv)?)
+        }
+    }
+
+    /// @TODO @release @docs
+    pub trait IntoApp {
+        /// @TODO @release @docs
+        fn into_app<'a, 'b>() -> clap::App<'a, 'b>;
+    }
+
+    /// @TODO @release @docs
+    pub trait FromArgMatches: Sized {
+        /// @TODO @release @docs
+        fn from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Self;
+
+        /// @TODO @release @docs
+        fn try_from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Result<Self, clap::Error>;
+    }
+
+    /// @TODO @release @docs
+    pub trait ArgEnum {}
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/macros.rs
@@ -0,0 +1,1130 @@
+/// A convenience macro for loading the YAML file at compile time (relative to the current file,
+/// like modules work). That YAML object can then be passed to this function.
+///
+/// # Panics
+///
+/// The YAML file must be properly formatted or this function will panic!(). A good way to
+/// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
+/// without error, you needn't worry because the YAML is properly formatted.
+///
+/// # Examples
+///
+/// The following example shows how to load a properly formatted YAML file to build an instance
+/// of an `App` struct.
+///
+/// ```ignore
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let yml = load_yaml!("app.yml");
+/// let app = App::from_yaml(yml);
+///
+/// // continued logic goes here, such as `app.get_matches()` etc.
+/// # }
+/// ```
+#[cfg(feature = "yaml")]
+#[macro_export]
+macro_rules! load_yaml {
+    ($yml:expr) => {
+        &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0]
+    };
+}
+
+/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an
+/// argument value. This macro returns a `Result<T,String>` which allows you as the developer to
+/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures
+/// and those where the argument wasn't present (such as a non-required argument). You can use
+/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`]
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let matches = App::new("myapp")
+///               .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
+///               .get_matches();
+///
+/// let len      = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit());
+/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit());
+///
+/// println!("{} + 2: {}", len, len + 2);
+/// # }
+/// ```
+/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of
+/// [`Result<T,String>`]: https://doc.rust-lang.org/std/result/enum.Result.html
+#[macro_export]
+macro_rules! value_t {
+    ($m:ident, $v:expr, $t:ty) => {
+        value_t!($m.value_of($v), $t)
+    };
+    ($m:ident.value_of($v:expr), $t:ty) => {
+        if let Some(v) = $m.value_of($v) {
+            match v.parse::<$t>() {
+                Ok(val) => Ok(val),
+                Err(_) => Err(::clap::Error::value_validation_auto(format!(
+                    "The argument '{}' isn't a valid value",
+                    v
+                ))),
+            }
+        } else {
+            Err(::clap::Error::argument_not_found_auto($v))
+        }
+    };
+}
+
+/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or
+/// exiting upon error, instead of returning a [`Result`] type.
+///
+/// **NOTE:** This macro is for backwards compatibility sake. Prefer
+/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let matches = App::new("myapp")
+///               .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'")
+///               .get_matches();
+///
+/// let len      = value_t_or_exit!(matches.value_of("length"), u32);
+/// let also_len = value_t_or_exit!(matches, "length", u32);
+///
+/// println!("{} + 2: {}", len, len + 2);
+/// # }
+/// ```
+/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
+/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html
+#[macro_export]
+macro_rules! value_t_or_exit {
+    ($m:ident, $v:expr, $t:ty) => {
+        value_t_or_exit!($m.value_of($v), $t)
+    };
+    ($m:ident.value_of($v:expr), $t:ty) => {
+        if let Some(v) = $m.value_of($v) {
+            match v.parse::<$t>() {
+                Ok(val) => val,
+                Err(_) => ::clap::Error::value_validation_auto(format!(
+                    "The argument '{}' isn't a valid value",
+                    v
+                ))
+                .exit(),
+            }
+        } else {
+            ::clap::Error::argument_not_found_auto($v).exit()
+        }
+    };
+}
+
+/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
+/// This macro returns a [`clap::Result<Vec<T>>`] which allows you as the developer to decide
+/// what you'd like to do on a failed parse.
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let matches = App::new("myapp")
+///               .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
+///               .get_matches();
+///
+/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit());
+/// for v in &vals {
+///     println!("{} + 2: {}", v, v + 2);
+/// }
+///
+/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit());
+/// for v in &vals {
+///     println!("{} + 2: {}", v, v + 2);
+/// }
+/// # }
+/// ```
+/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
+/// [`clap::Result<Vec<T>>`]: ./type.Result.html
+#[macro_export]
+macro_rules! values_t {
+    ($m:ident, $v:expr, $t:ty) => {
+        values_t!($m.values_of($v), $t)
+    };
+    ($m:ident.values_of($v:expr), $t:ty) => {
+        if let Some(vals) = $m.values_of($v) {
+            let mut tmp = vec![];
+            let mut err = None;
+            for pv in vals {
+                match pv.parse::<$t>() {
+                    Ok(rv) => tmp.push(rv),
+                    Err(..) => {
+                        err = Some(::clap::Error::value_validation_auto(format!(
+                            "The argument '{}' isn't a valid value",
+                            pv
+                        )));
+                        break;
+                    }
+                }
+            }
+            match err {
+                Some(e) => Err(e),
+                None => Ok(tmp),
+            }
+        } else {
+            Err(::clap::Error::argument_not_found_auto($v))
+        }
+    };
+}
+
+/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`]
+/// or exiting upon error.
+///
+/// **NOTE:** This macro is for backwards compatibility sake. Prefer
+/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let matches = App::new("myapp")
+///               .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'")
+///               .get_matches();
+///
+/// let vals = values_t_or_exit!(matches.values_of("seq"), u32);
+/// for v in &vals {
+///     println!("{} + 2: {}", v, v + 2);
+/// }
+///
+/// // type for example only
+/// let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32);
+/// for v in &vals {
+///     println!("{} + 2: {}", v, v + 2);
+/// }
+/// # }
+/// ```
+/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html
+/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
+#[macro_export]
+macro_rules! values_t_or_exit {
+    ($m:ident, $v:expr, $t:ty) => {
+        values_t_or_exit!($m.values_of($v), $t)
+    };
+    ($m:ident.values_of($v:expr), $t:ty) => {
+        if let Some(vals) = $m.values_of($v) {
+            vals.map(|v| {
+                v.parse::<$t>().unwrap_or_else(|_| {
+                    ::clap::Error::value_validation_auto(format!(
+                        "One or more arguments aren't valid values"
+                    ))
+                    .exit()
+                })
+            })
+            .collect::<Vec<$t>>()
+        } else {
+            ::clap::Error::argument_not_found_auto($v).exit()
+        }
+    };
+}
+
+// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag
+// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07
+// License: MIT
+// Copyright ⓒ 2015 grabbag contributors.
+// Licensed under the MIT license (see LICENSE or <http://opensource.org
+// /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
+// <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
+// files in the project carrying such notice may not be copied, modified,
+// or distributed except according to those terms.
+//
+/// Counts the number of comma-delimited expressions passed to it.  The result is a compile-time
+/// evaluable expression, suitable for use as a static array size, or the value of a `const`.
+///
+/// # Examples
+///
+/// ```
+/// # #[macro_use] extern crate clap;
+/// # fn main() {
+/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string());
+/// assert_eq!(COUNT, 3);
+/// # }
+/// ```
+#[macro_export]
+macro_rules! _clap_count_exprs {
+    () => { 0 };
+    ($e:expr) => { 1 };
+    ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) };
+}
+
+/// Convenience macro to generate more complete enums with variants to be used as a type when
+/// parsing arguments. This enum also provides a `variants()` function which can be used to
+/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and
+/// [`Display`] automatically.
+///
+/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to
+/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums
+///
+/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`]
+///
+/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits
+///
+/// # Examples
+///
+/// ```rust
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::{App, Arg};
+/// arg_enum!{
+///     #[derive(PartialEq, Debug)]
+///     pub enum Foo {
+///         Bar,
+///         Baz,
+///         Qux
+///     }
+/// }
+/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc
+/// // and implements std::str::FromStr to use with the value_t! macros
+/// fn main() {
+///     let m = App::new("app")
+///                 .arg(Arg::from_usage("<foo> 'the foo'")
+///                     .possible_values(&Foo::variants())
+///                     .case_insensitive(true))
+///                 .get_matches_from(vec![
+///                     "app", "baz"
+///                 ]);
+///     let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit());
+///
+///     assert_eq!(f, Foo::Baz);
+/// }
+/// ```
+/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
+/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
+/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
+/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive
+#[macro_export]
+macro_rules! arg_enum {
+    (@as_item $($i:item)*) => ($($i)*);
+    (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => {
+        arg_enum!(@as_item
+        $($tts)*
+
+        impl ::std::str::FromStr for $e {
+            type Err = String;
+
+            fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
+                #[allow(deprecated, unused_imports)]
+                use ::std::ascii::AsciiExt;
+                match s {
+                    $(stringify!($v) |
+                    _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+,
+                    _ => Err({
+                        let v = vec![
+                            $(stringify!($v),)+
+                        ];
+                        format!("valid values: {}",
+                            v.join(", "))
+                    }),
+                }
+            }
+        }
+        impl ::std::fmt::Display for $e {
+            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+                match *self {
+                    $($e::$v => write!(f, stringify!($v)),)+
+                }
+            }
+        }
+        impl $e {
+            #[allow(dead_code)]
+            pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] {
+                [
+                    $(stringify!($v),)+
+                ]
+            }
+        });
+    };
+    ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
+        arg_enum!(@impls
+            ($(#[$($m),+])+
+            pub enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
+        arg_enum!(@impls
+            ($(#[$($m),+])+
+            pub enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
+        arg_enum!(@impls
+            ($(#[$($m),+])+
+             enum $e {
+                 $($v$(=$val)*),+
+             }) -> ($e, $($v),+)
+        );
+    };
+    ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
+        arg_enum!(@impls
+            ($(#[$($m),+])+
+            enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
+        arg_enum!(@impls
+            (pub enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
+        arg_enum!(@impls
+            (pub enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => {
+        arg_enum!(@impls
+            (enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+    (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => {
+        arg_enum!(@impls
+            (enum $e {
+                $($v$(=$val)*),+
+            }) -> ($e, $($v),+)
+        );
+    };
+}
+
+/// Allows you to pull the version from your Cargo.toml at compile time as
+/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE`
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let m = App::new("app")
+///             .version(crate_version!())
+///             .get_matches();
+/// # }
+/// ```
+#[cfg(not(feature = "no_cargo"))]
+#[macro_export]
+macro_rules! crate_version {
+    () => {
+        env!("CARGO_PKG_VERSION")
+    };
+}
+
+/// Allows you to pull the authors for the app from your Cargo.toml at
+/// compile time in the form:
+/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"`
+///
+/// You can replace the colons with a custom separator by supplying a
+/// replacement string, so, for example,
+/// `crate_authors!(",\n")` would become
+/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"`
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let m = App::new("app")
+///             .author(crate_authors!("\n"))
+///             .get_matches();
+/// # }
+/// ```
+#[cfg(not(feature = "no_cargo"))]
+#[macro_export]
+macro_rules! crate_authors {
+    ($sep:expr) => {{
+        use std::ops::Deref;
+        #[allow(deprecated)]
+        use std::sync::{Once, ONCE_INIT};
+
+        #[allow(missing_copy_implementations)]
+        #[allow(dead_code)]
+        struct CargoAuthors {
+            __private_field: (),
+        };
+
+        impl Deref for CargoAuthors {
+            type Target = str;
+
+            #[allow(unsafe_code)]
+            fn deref(&self) -> &'static str {
+                #[allow(deprecated)]
+                static ONCE: Once = ONCE_INIT;
+                static mut VALUE: *const String = 0 as *const String;
+
+                unsafe {
+                    ONCE.call_once(|| {
+                        let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep);
+                        VALUE = Box::into_raw(Box::new(s));
+                    });
+
+                    &(*VALUE)[..]
+                }
+            }
+        }
+
+        &*CargoAuthors {
+            __private_field: (),
+        }
+    }};
+    () => {
+        env!("CARGO_PKG_AUTHORS")
+    };
+}
+
+/// Allows you to pull the description from your Cargo.toml at compile time.
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let m = App::new("app")
+///             .about(crate_description!())
+///             .get_matches();
+/// # }
+/// ```
+#[cfg(not(feature = "no_cargo"))]
+#[macro_export]
+macro_rules! crate_description {
+    () => {
+        env!("CARGO_PKG_DESCRIPTION")
+    };
+}
+
+/// Allows you to pull the name from your Cargo.toml at compile time.
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # use clap::App;
+/// # fn main() {
+/// let m = App::new(crate_name!())
+///             .get_matches();
+/// # }
+/// ```
+#[cfg(not(feature = "no_cargo"))]
+#[macro_export]
+macro_rules! crate_name {
+    () => {
+        env!("CARGO_PKG_NAME")
+    };
+}
+
+/// Allows you to build the `App` instance from your Cargo.toml at compile time.
+///
+/// Equivalent to using the `crate_*!` macros with their respective fields.
+///
+/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro,
+/// refer to the documentation therefor.
+///
+/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically,
+/// and therefore won't change the generated output until you recompile.
+///
+/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your
+/// `Cargo.toml` is changed by including this in your `src/main.rs` file
+/// `include_str!("../Cargo.toml");`
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # fn main() {
+/// let m = app_from_crate!().get_matches();
+/// # }
+/// ```
+#[cfg(not(feature = "no_cargo"))]
+#[macro_export]
+macro_rules! app_from_crate {
+    () => {
+        $crate::App::new(crate_name!())
+            .version(crate_version!())
+            .author(crate_authors!())
+            .about(crate_description!())
+    };
+    ($sep:expr) => {
+        $crate::App::new(crate_name!())
+            .version(crate_version!())
+            .author(crate_authors!($sep))
+            .about(crate_description!())
+    };
+}
+
+/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input
+/// but without the associated parsing runtime cost.
+///
+/// `clap_app!` also supports several shorthand syntaxes.
+///
+/// # Examples
+///
+/// ```no_run
+/// # #[macro_use]
+/// # extern crate clap;
+/// # fn main() {
+/// let matches = clap_app!(myapp =>
+///     (version: "1.0")
+///     (author: "Kevin K. <kbknapp@gmail.com>")
+///     (about: "Does awesome things")
+///     (@arg CONFIG: -c --config +takes_value "Sets a custom config file")
+///     (@arg INPUT: +required "Sets the input file to use")
+///     (@arg debug: -d ... "Sets the level of debugging information")
+///     (@group difficulty =>
+///         (@arg hard: -h --hard "Sets hard mode")
+///         (@arg normal: -n --normal "Sets normal mode")
+///         (@arg easy: -e --easy "Sets easy mode")
+///     )
+///     (@subcommand test =>
+///         (about: "controls testing features")
+///         (version: "1.3")
+///         (author: "Someone E. <someone_else@other.com>")
+///         (@arg verbose: -v --verbose "Print test information verbosely")
+///     )
+/// )
+/// .get_matches();
+/// # }
+/// ```
+/// # Shorthand Syntax for Args
+///
+/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`]
+/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`]
+///   * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you
+///     must use `--("config-file")` due to limitations of the Rust macro system.
+/// * Three dots (`...`) sets [`Arg::multiple(true)`]
+/// * Angled brackets after either a short or long will set [`Arg::value_name`] and
+/// `Arg::required(true)` such as `--config <FILE>` = `Arg::value_name("FILE")` and
+/// `Arg::required(true)`
+/// * Square brackets after either a short or long will set [`Arg::value_name`] and
+/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and
+/// `Arg::required(false)`
+/// * There are short hand syntaxes for Arg methods that accept booleans
+///   * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)`
+///   * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)`
+/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`]
+/// * An asterisk (`*`) will set `Arg::required(true)`
+/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)`
+/// * An Arg method that accepts a string followed by square brackets will set that method such as
+/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around
+/// `FOO` in the macro)
+/// * An Arg method that takes a string and can be set multiple times (such as
+/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces
+/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set
+/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")`
+/// (note the lack of quotes around the values in the macro)
+///
+/// # Shorthand Syntax for Groups
+///
+/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans
+///   * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)`
+///   * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)`
+///
+/// [`Arg::short`]: ./struct.Arg.html#method.short
+/// [`Arg::long`]: ./struct.Arg.html#method.long
+/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
+/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name
+/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values
+/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values
+/// [`Arg::validator`]: ./struct.Arg.html#method.validator
+/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
+#[macro_export]
+macro_rules! clap_app {
+    (@app ($builder:expr)) => { $builder };
+    (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            ($builder.arg(
+                clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* }))
+            $($tt)*
+        }
+    };
+    (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            ($builder.arg(
+                clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* }))
+            $($tt)*
+        }
+    };
+    (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => {
+        clap_app!{ @app
+            ($builder.setting($crate::AppSettings::$setting))
+            $($tt)*
+        }
+    };
+// Treat the application builder as an argument to set its attributes
+    (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* }
+    };
+    (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* })
+            $($tt)*
+        }
+    };
+    (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* })
+            $($tt)*
+        }
+    };
+    (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* })
+            $($tt)*
+        }
+    };
+// Handle subcommand creation
+    (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @app
+            ($builder.subcommand(
+                clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
+            ))
+            $($tt)*
+        }
+    };
+// Yaml like function calls - used for setting various meta directly against the app
+    (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => {
+// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* }
+        clap_app!{ @app
+            ($builder.$ident($($v),*))
+            $($tt)*
+        }
+    };
+
+// Add members to group and continue argument handling with the parent builder
+    (@group ($builder:expr, $group:expr)) => { $builder.group($group) };
+    // Treat the group builder as an argument to set its attributes
+    (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => {
+        clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* }
+    };
+    (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => {
+        clap_app!{ @group
+            (clap_app!{ @app ($builder) (@arg $name: $($tail)*) },
+             $group.arg(stringify!($name)))
+            $($tt)*
+        }
+    };
+
+// No more tokens to munch
+    (@arg ($arg:expr) $modes:tt) => { $arg };
+// Shorthand tokens influenced by the usage_string
+    (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.long($long)) $modes $($tail)* }
+    };
+    (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* }
+    };
+    (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* }
+    };
+    (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* }
+    };
+    (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
+    };
+    (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* }
+    };
+    (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* }
+    };
+    (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => {
+        clap_app!{ @arg ($arg) $modes +multiple $($tail)* }
+    };
+// Shorthand magic
+    (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => {
+        clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* }
+    };
+    (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => {
+        clap_app!{ @arg ($arg) $modes +required $($tail)* }
+    };
+// !foo -> .foo(false)
+    (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* }
+    };
+// +foo -> .foo(true)
+    (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* }
+    };
+// Validator
+    (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* }
+    };
+    (@as_expr $expr:expr) => { $expr };
+// Help
+    (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) };
+// Handle functions that need to be called multiple times for each argument
+    (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => {
+        clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* }
+    };
+// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")`
+    (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* }
+    };
+// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)`
+    (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => {
+        clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* }
+    };
+
+// Build a subcommand outside of an app.
+    (@subcommand $name:ident => $($tail:tt)*) => {
+        clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* }
+    };
+// Start the magic
+    (($name:expr) => $($tail:tt)*) => {{
+        clap_app!{ @app ($crate::App::new($name)) $($tail)*}
+    }};
+
+    ($name:ident => $($tail:tt)*) => {{
+        clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*}
+    }};
+}
+
+macro_rules! impl_settings {
+    ($n:ident, $($v:ident => $c:path),+) => {
+        pub fn set(&mut self, s: $n) {
+            match s {
+                $($n::$v => self.0.insert($c)),+
+            }
+        }
+
+        pub fn unset(&mut self, s: $n) {
+            match s {
+                $($n::$v => self.0.remove($c)),+
+            }
+        }
+
+        pub fn is_set(&self, s: $n) -> bool {
+            match s {
+                $($n::$v => self.0.contains($c)),+
+            }
+        }
+    };
+}
+
+// Convenience for writing to stderr thanks to https://github.com/BurntSushi
+macro_rules! wlnerr(
+    (@nopanic $($arg:tt)*) => ({
+        use std::io::{Write, stderr};
+        let _ = writeln!(&mut stderr().lock(), $($arg)*);
+    });
+    ($($arg:tt)*) => ({
+        use std::io::{Write, stderr};
+        writeln!(&mut stderr(), $($arg)*).ok();
+    })
+);
+
+#[cfg(feature = "debug")]
+#[cfg_attr(feature = "debug", macro_use)]
+#[cfg_attr(feature = "debug", allow(unused_macros))]
+mod debug_macros {
+    macro_rules! debugln {
+        ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt)));
+        ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*));
+    }
+    macro_rules! sdebugln {
+        ($fmt:expr) => (println!($fmt));
+        ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*));
+    }
+    macro_rules! debug {
+        ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt)));
+        ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*));
+    }
+    macro_rules! sdebug {
+        ($fmt:expr) => (print!($fmt));
+        ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*));
+    }
+}
+
+#[cfg(not(feature = "debug"))]
+#[cfg_attr(not(feature = "debug"), macro_use)]
+mod debug_macros {
+    macro_rules! debugln {
+        ($fmt:expr) => {};
+        ($fmt:expr, $($arg:tt)*) => {};
+    }
+    macro_rules! sdebugln {
+        ($fmt:expr) => {};
+        ($fmt:expr, $($arg:tt)*) => {};
+    }
+    macro_rules! debug {
+        ($fmt:expr) => {};
+        ($fmt:expr, $($arg:tt)*) => {};
+    }
+}
+
+// Helper/deduplication macro for printing the correct number of spaces in help messages
+// used in:
+//    src/args/arg_builder/*.rs
+//    src/app/mod.rs
+macro_rules! write_nspaces {
+    ($dst:expr, $num:expr) => {{
+        debugln!("write_spaces!: num={}", $num);
+        for _ in 0..$num {
+            $dst.write_all(b" ")?;
+        }
+    }};
+}
+
+// convenience macro for remove an item from a vec
+//macro_rules! vec_remove_all {
+//    ($vec:expr, $to_rem:expr) => {
+//        debugln!("vec_remove_all! to_rem={:?}", $to_rem);
+//        for i in (0 .. $vec.len()).rev() {
+//            let should_remove = $to_rem.any(|name| name == &$vec[i]);
+//            if should_remove { $vec.swap_remove(i); }
+//        }
+//    };
+//}
+macro_rules! find_from {
+    ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
+        let mut ret = None;
+        for k in $matcher.arg_names() {
+            if let Some(f) = find_by_name!($_self, k, flags, iter) {
+                if let Some(ref v) = f.$from() {
+                    if v.contains($arg_name) {
+                        ret = Some(f.to_string());
+                    }
+                }
+            }
+            if let Some(o) = find_by_name!($_self, k, opts, iter) {
+                if let Some(ref v) = o.$from() {
+                    if v.contains(&$arg_name) {
+                        ret = Some(o.to_string());
+                    }
+                }
+            }
+            if let Some(pos) = find_by_name!($_self, k, positionals, values) {
+                if let Some(ref v) = pos.$from() {
+                    if v.contains($arg_name) {
+                        ret = Some(pos.b.name.to_owned());
+                    }
+                }
+            }
+        }
+        ret
+    }};
+}
+
+//macro_rules! find_name_from {
+//    ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{
+//        let mut ret = None;
+//        for k in $matcher.arg_names() {
+//            if let Some(f) = find_by_name!($_self, k, flags, iter) {
+//                if let Some(ref v) = f.$from() {
+//                    if v.contains($arg_name) {
+//                        ret = Some(f.b.name);
+//                    }
+//                }
+//            }
+//            if let Some(o) = find_by_name!($_self, k, opts, iter) {
+//                if let Some(ref v) = o.$from() {
+//                    if v.contains(&$arg_name) {
+//                        ret = Some(o.b.name);
+//                    }
+//                }
+//            }
+//            if let Some(pos) = find_by_name!($_self, k, positionals, values) {
+//                if let Some(ref v) = pos.$from() {
+//                    if v.contains($arg_name) {
+//                        ret = Some(pos.b.name);
+//                    }
+//                }
+//            }
+//        }
+//        ret
+//    }};
+//}
+
+macro_rules! find_any_by_name {
+    ($p:expr, $name:expr) => {{
+        fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> {
+            x
+        }
+        find_by_name!($p, $name, flags, iter)
+            .map(as_trait_obj)
+            .or(find_by_name!($p, $name, opts, iter)
+                .map(as_trait_obj)
+                .or(find_by_name!($p, $name, positionals, values).map(as_trait_obj)))
+    }};
+}
+// Finds an arg by name
+macro_rules! find_by_name {
+    ($p:expr, $name:expr, $what:ident, $how:ident) => {
+        $p.$what.$how().find(|o| o.b.name == $name)
+    };
+}
+
+// Finds an option including if it's aliased
+macro_rules! find_opt_by_long {
+    (@os $_self:ident, $long:expr) => {{
+        _find_by_long!($_self, $long, opts)
+    }};
+    ($_self:ident, $long:expr) => {{
+        _find_by_long!($_self, $long, opts)
+    }};
+}
+
+macro_rules! find_flag_by_long {
+    (@os $_self:ident, $long:expr) => {{
+        _find_by_long!($_self, $long, flags)
+    }};
+    ($_self:ident, $long:expr) => {{
+        _find_by_long!($_self, $long, flags)
+    }};
+}
+
+macro_rules! _find_by_long {
+    ($_self:ident, $long:expr, $what:ident) => {{
+        $_self
+            .$what
+            .iter()
+            .filter(|a| a.s.long.is_some())
+            .find(|a| {
+                a.s.long.unwrap() == $long
+                    || (a.s.aliases.is_some()
+                        && a.s
+                            .aliases
+                            .as_ref()
+                            .unwrap()
+                            .iter()
+                            .any(|&(alias, _)| alias == $long))
+            })
+    }};
+}
+
+// Finds an option
+macro_rules! find_opt_by_short {
+    ($_self:ident, $short:expr) => {{
+        _find_by_short!($_self, $short, opts)
+    }};
+}
+
+macro_rules! find_flag_by_short {
+    ($_self:ident, $short:expr) => {{
+        _find_by_short!($_self, $short, flags)
+    }};
+}
+
+macro_rules! _find_by_short {
+    ($_self:ident, $short:expr, $what:ident) => {{
+        $_self
+            .$what
+            .iter()
+            .filter(|a| a.s.short.is_some())
+            .find(|a| a.s.short.unwrap() == $short)
+    }};
+}
+
+macro_rules! find_subcmd {
+    ($_self:expr, $sc:expr) => {{
+        $_self.subcommands.iter().find(|s| {
+            &*s.p.meta.name == $sc
+                || (s.p.meta.aliases.is_some()
+                    && s.p
+                        .meta
+                        .aliases
+                        .as_ref()
+                        .unwrap()
+                        .iter()
+                        .any(|&(n, _)| n == $sc))
+        })
+    }};
+}
+
+macro_rules! shorts {
+    ($_self:ident) => {{
+        _shorts_longs!($_self, short)
+    }};
+}
+
+macro_rules! longs {
+    ($_self:ident) => {{
+        _shorts_longs!($_self, long)
+    }};
+}
+
+macro_rules! _shorts_longs {
+    ($_self:ident, $what:ident) => {{
+        $_self
+            .flags
+            .iter()
+            .filter(|f| f.s.$what.is_some())
+            .map(|f| f.s.$what.as_ref().unwrap())
+            .chain(
+                $_self
+                    .opts
+                    .iter()
+                    .filter(|o| o.s.$what.is_some())
+                    .map(|o| o.s.$what.as_ref().unwrap()),
+            )
+    }};
+}
+
+macro_rules! arg_names {
+    ($_self:ident) => {{
+        _names!(@args $_self)
+    }};
+}
+
+macro_rules! sc_names {
+    ($_self:ident) => {{
+        _names!(@sc $_self)
+    }};
+}
+
+macro_rules! _names {
+    (@args $_self:ident) => {{
+        $_self.flags.iter().map(|f| &*f.b.name).chain(
+            $_self
+                .opts
+                .iter()
+                .map(|o| &*o.b.name)
+                .chain($_self.positionals.values().map(|p| &*p.b.name)),
+        )
+    }};
+    (@sc $_self:ident) => {{
+        $_self.subcommands.iter().map(|s| &*s.p.meta.name).chain(
+            $_self
+                .subcommands
+                .iter()
+                .filter(|s| s.p.meta.aliases.is_some())
+                .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n)),
+        )
+    }};
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/map.rs
@@ -0,0 +1,88 @@
+#[cfg(feature = "vec_map")]
+pub use vec_map::{Values, VecMap};
+
+#[cfg(not(feature = "vec_map"))]
+pub use self::vec_map::{Values, VecMap};
+
+#[cfg(not(feature = "vec_map"))]
+mod vec_map {
+    use std::collections::btree_map;
+    use std::collections::BTreeMap;
+    use std::fmt::{self, Debug, Formatter};
+
+    #[derive(Clone, Default, Debug)]
+    pub struct VecMap<V> {
+        inner: BTreeMap<usize, V>,
+    }
+
+    impl<V> VecMap<V> {
+        pub fn new() -> Self {
+            VecMap {
+                inner: Default::default(),
+            }
+        }
+
+        pub fn len(&self) -> usize {
+            self.inner.len()
+        }
+
+        pub fn is_empty(&self) -> bool {
+            self.inner.is_empty()
+        }
+
+        pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
+            self.inner.insert(key, value)
+        }
+
+        pub fn values(&self) -> Values<V> {
+            self.inner.values()
+        }
+
+        pub fn iter(&self) -> Iter<V> {
+            Iter {
+                inner: self.inner.iter(),
+            }
+        }
+
+        pub fn contains_key(&self, key: usize) -> bool {
+            self.inner.contains_key(&key)
+        }
+
+        pub fn entry(&mut self, key: usize) -> Entry<V> {
+            self.inner.entry(key)
+        }
+
+        pub fn get(&self, key: usize) -> Option<&V> {
+            self.inner.get(&key)
+        }
+    }
+
+    pub type Values<'a, V> = btree_map::Values<'a, usize, V>;
+
+    pub type Entry<'a, V> = btree_map::Entry<'a, usize, V>;
+
+    #[derive(Clone)]
+    pub struct Iter<'a, V: 'a> {
+        inner: btree_map::Iter<'a, usize, V>,
+    }
+
+    impl<'a, V: 'a + Debug> Debug for Iter<'a, V> {
+        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+            f.debug_list().entries(self.inner.clone()).finish()
+        }
+    }
+
+    impl<'a, V: 'a> Iterator for Iter<'a, V> {
+        type Item = (usize, &'a V);
+
+        fn next(&mut self) -> Option<Self::Item> {
+            self.inner.next().map(|(k, v)| (*k, v))
+        }
+    }
+
+    impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> {
+        fn next_back(&mut self) -> Option<Self::Item> {
+            self.inner.next_back().map(|(k, v)| (*k, v))
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/osstringext.rs
@@ -0,0 +1,203 @@
+use std::ffi::OsStr;
+#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
+use std::os::unix::ffi::OsStrExt;
+#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
+use crate::INVALID_UTF8;
+
+#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
+pub trait OsStrExt3 {
+    fn from_bytes(b: &[u8]) -> &Self;
+    fn as_bytes(&self) -> &[u8];
+}
+
+#[doc(hidden)]
+pub trait OsStrExt2 {
+    fn starts_with(&self, s: &[u8]) -> bool;
+    fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr);
+    fn split_at(&self, i: usize) -> (&OsStr, &OsStr);
+    fn trim_left_matches(&self, b: u8) -> &OsStr;
+    fn contains_byte(&self, b: u8) -> bool;
+    fn split(&self, b: u8) -> OsSplit;
+}
+
+// A starts-with implementation that does not panic when the OsStr contains
+// invalid Unicode.
+//
+// A Windows OsStr is usually UTF-16. If `prefix` is valid UTF-8, we can
+// re-encode it as UTF-16, and ask whether `osstr` starts with the same series
+// of u16 code units. If `prefix` is not valid UTF-8, then this comparison
+// isn't meaningful, and we just return false.
+#[cfg(target_os = "windows")]
+fn windows_osstr_starts_with(osstr: &OsStr, prefix: &[u8]) -> bool {
+    use std::os::windows::ffi::OsStrExt;
+    let prefix_str = if let Ok(s) = std::str::from_utf8(prefix) {
+        s
+    } else {
+        return false;
+    };
+    let mut osstr_units = osstr.encode_wide();
+    let mut prefix_units = prefix_str.encode_utf16();
+    loop {
+        match (osstr_units.next(), prefix_units.next()) {
+            // These code units match. Keep looping.
+            (Some(o), Some(p)) if o == p => continue,
+            // We've reached the end of the prefix. It's a match.
+            (_, None) => return true,
+            // Otherwise, it's not a match.
+            _ => return false,
+        }
+    }
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+fn test_windows_osstr_starts_with() {
+    use std::ffi::OsString;
+    use std::os::windows::ffi::OsStringExt;
+
+    fn from_ascii(ascii: &[u8]) -> OsString {
+        let u16_vec: Vec<u16> = ascii.iter().map(|&c| c as u16).collect();
+        OsString::from_wide(&u16_vec)
+    }
+
+    // Test all the basic cases.
+    assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abc"));
+    assert!(windows_osstr_starts_with(&from_ascii(b"abcdef"), b"abcdef"));
+    assert!(!windows_osstr_starts_with(&from_ascii(b"abcdef"), b"def"));
+    assert!(!windows_osstr_starts_with(&from_ascii(b"abc"), b"abcd"));
+
+    // Test the case where the candidate prefix is not valid UTF-8. Note that a
+    // standalone \xff byte is valid ASCII but not valid UTF-8. Thus although
+    // these strings look identical, they do not match.
+    assert!(!windows_osstr_starts_with(&from_ascii(b"\xff"), b"\xff"));
+
+    // Test the case where the OsString is not valid UTF-16. It should still be
+    // possible to match the valid characters at the front.
+    //
+    // UTF-16 surrogate characters are only valid in pairs. Including one on
+    // the end by itself makes this invalid UTF-16.
+    let surrogate_char: u16 = 0xDC00;
+    let invalid_unicode =
+        OsString::from_wide(&['a' as u16, 'b' as u16, 'c' as u16, surrogate_char]);
+    assert!(
+        invalid_unicode.to_str().is_none(),
+        "This string is invalid Unicode, and conversion to &str should fail.",
+    );
+    assert!(windows_osstr_starts_with(&invalid_unicode, b"abc"));
+    assert!(!windows_osstr_starts_with(&invalid_unicode, b"abcd"));
+}
+
+#[cfg(any(target_os = "windows", target_arch = "wasm32"))]
+impl OsStrExt3 for OsStr {
+    fn from_bytes(b: &[u8]) -> &Self {
+        use std::mem;
+        unsafe { mem::transmute(b) }
+    }
+    fn as_bytes(&self) -> &[u8] {
+        self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8)
+    }
+}
+
+impl OsStrExt2 for OsStr {
+    fn starts_with(&self, s: &[u8]) -> bool {
+        #[cfg(target_os = "windows")]
+        {
+            // On Windows, the as_bytes() method will panic if the OsStr
+            // contains invalid Unicode. To avoid this, we use a
+            // Windows-specific starts-with function that doesn't rely on
+            // as_bytes(). This is necessary for Windows command line
+            // applications to handle non-Unicode arguments successfully. This
+            // allows common cases like `clap.exe [invalid]` to succeed, though
+            // cases that require string splitting will still fail, like
+            // `clap.exe --arg=[invalid]`. Note that this entire module is
+            // replaced in Clap 3.x, so this workaround is specific to the 2.x
+            // branch.
+            windows_osstr_starts_with(self, s)
+        }
+        #[cfg(not(target_os = "windows"))]
+        {
+            self.as_bytes().starts_with(s)
+        }
+    }
+
+    fn contains_byte(&self, byte: u8) -> bool {
+        for b in self.as_bytes() {
+            if b == &byte {
+                return true;
+            }
+        }
+        false
+    }
+
+    fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) {
+        for (i, b) in self.as_bytes().iter().enumerate() {
+            if b == &byte {
+                return (
+                    OsStr::from_bytes(&self.as_bytes()[..i]),
+                    OsStr::from_bytes(&self.as_bytes()[i + 1..]),
+                );
+            }
+        }
+        (
+            &*self,
+            OsStr::from_bytes(&self.as_bytes()[self.len()..self.len()]),
+        )
+    }
+
+    fn trim_left_matches(&self, byte: u8) -> &OsStr {
+        let mut found = false;
+        for (i, b) in self.as_bytes().iter().enumerate() {
+            if b != &byte {
+                return OsStr::from_bytes(&self.as_bytes()[i..]);
+            } else {
+                found = true;
+            }
+        }
+        if found {
+            return OsStr::from_bytes(&self.as_bytes()[self.len()..]);
+        }
+        &*self
+    }
+
+    fn split_at(&self, i: usize) -> (&OsStr, &OsStr) {
+        (
+            OsStr::from_bytes(&self.as_bytes()[..i]),
+            OsStr::from_bytes(&self.as_bytes()[i..]),
+        )
+    }
+
+    fn split(&self, b: u8) -> OsSplit {
+        OsSplit {
+            sep: b,
+            val: self.as_bytes(),
+            pos: 0,
+        }
+    }
+}
+
+#[doc(hidden)]
+#[derive(Clone, Debug)]
+pub struct OsSplit<'a> {
+    sep: u8,
+    val: &'a [u8],
+    pos: usize,
+}
+
+impl<'a> Iterator for OsSplit<'a> {
+    type Item = &'a OsStr;
+
+    fn next(&mut self) -> Option<&'a OsStr> {
+        debugln!("OsSplit::next: self={:?}", self);
+        if self.pos == self.val.len() {
+            return None;
+        }
+        let start = self.pos;
+        for b in &self.val[start..] {
+            self.pos += 1;
+            if *b == self.sep {
+                return Some(OsStr::from_bytes(&self.val[start..self.pos - 1]));
+            }
+        }
+        Some(OsStr::from_bytes(&self.val[start..]))
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/strext.rs
@@ -0,0 +1,16 @@
+pub trait _StrExt {
+    fn _is_char_boundary(&self, index: usize) -> bool;
+}
+
+impl _StrExt for str {
+    #[inline]
+    fn _is_char_boundary(&self, index: usize) -> bool {
+        if index == self.len() {
+            return true;
+        }
+        match self.as_bytes().get(index) {
+            None => false,
+            Some(&b) => !(128..192).contains(&b),
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/suggestions.rs
@@ -0,0 +1,141 @@
+// Internal
+use crate::{app::App, fmt::Format};
+
+/// Produces a string from a given list of possible values which is similar to
+/// the passed in value `v` with a certain confidence.
+/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield
+/// `Some("foo")`, whereas "blark" would yield `None`.
+#[cfg(feature = "suggestions")]
+#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_lifetimes))]
+pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str>
+where
+    T: AsRef<str> + 'a,
+    I: IntoIterator<Item = &'a T>,
+{
+    let mut candidate: Option<(f64, &str)> = None;
+    for pv in possible_values {
+        let confidence = strsim::jaro_winkler(v, pv.as_ref());
+        if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence))
+        {
+            candidate = Some((confidence, pv.as_ref()));
+        }
+    }
+    match candidate {
+        None => None,
+        Some((_, candidate)) => Some(candidate),
+    }
+}
+
+#[cfg(not(feature = "suggestions"))]
+pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str>
+where
+    T: AsRef<str> + 'a,
+    I: IntoIterator<Item = &'a T>,
+{
+    None
+}
+
+/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
+pub fn did_you_mean_flag_suffix<'z, T, I>(
+    arg: &str,
+    args_rest: &'z [&str],
+    longs: I,
+    subcommands: &'z [App],
+) -> (String, Option<&'z str>)
+where
+    T: AsRef<str> + 'z,
+    I: IntoIterator<Item = &'z T>,
+{
+    if let Some(candidate) = did_you_mean(arg, longs) {
+        let suffix = format!(
+            "\n\tDid you mean {}{}?",
+            Format::Good("--"),
+            Format::Good(candidate)
+        );
+        return (suffix, Some(candidate));
+    }
+
+    subcommands
+        .iter()
+        .filter_map(|subcommand| {
+            let opts = subcommand
+                .p
+                .flags
+                .iter()
+                .filter_map(|f| f.s.long)
+                .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long));
+
+            let candidate = match did_you_mean(arg, opts) {
+                Some(candidate) => candidate,
+                None => return None,
+            };
+            let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) {
+                Some(score) => score,
+                None => return None,
+            };
+
+            let suffix = format!(
+                "\n\tDid you mean to put '{}{}' after the subcommand '{}'?",
+                Format::Good("--"),
+                Format::Good(candidate),
+                Format::Good(subcommand.get_name())
+            );
+
+            Some((score, (suffix, Some(candidate))))
+        })
+        .min_by_key(|&(score, _)| score)
+        .map(|(_, suggestion)| suggestion)
+        .unwrap_or_else(|| (String::new(), None))
+}
+
+/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase
+pub fn did_you_mean_value_suffix<'z, T, I>(arg: &str, values: I) -> (String, Option<&'z str>)
+where
+    T: AsRef<str> + 'z,
+    I: IntoIterator<Item = &'z T>,
+{
+    match did_you_mean(arg, values) {
+        Some(candidate) => {
+            let suffix = format!("\n\tDid you mean '{}'?", Format::Good(candidate));
+            (suffix, Some(candidate))
+        }
+        None => (String::new(), None),
+    }
+}
+
+#[cfg(all(test, features = "suggestions"))]
+mod test {
+    use super::*;
+
+    #[test]
+    fn possible_values_match() {
+        let p_vals = ["test", "possible", "values"];
+        assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test"));
+    }
+
+    #[test]
+    fn possible_values_nomatch() {
+        let p_vals = ["test", "possible", "values"];
+        assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none());
+    }
+
+    #[test]
+    fn suffix_long() {
+        let p_vals = ["test", "possible", "values"];
+        let suffix = "\n\tDid you mean \'--test\'?";
+        assert_eq!(
+            did_you_mean_flag_suffix("tst", p_vals.iter(), []),
+            (suffix, Some("test"))
+        );
+    }
+
+    #[test]
+    fn suffix_enum() {
+        let p_vals = ["test", "possible", "values"];
+        let suffix = "\n\tDid you mean \'test\'?";
+        assert_eq!(
+            did_you_mean_value_suffix("tst", p_vals.iter()),
+            (suffix, Some("test"))
+        );
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/clap-2.34.0/src/usage_parser.rs
@@ -0,0 +1,1356 @@
+// Internal
+use crate::{
+    args::{settings::ArgSettings, Arg},
+    map::VecMap,
+    INTERNAL_ERROR_MSG,
+};
+
+#[derive(PartialEq, Debug)]
+enum UsageToken {
+    Name,
+    ValName,
+    Short,
+    Long,
+    Help,
+    Multiple,
+    Unknown,
+}
+
+#[doc(hidden)]
+#[derive(Debug)]
+pub struct UsageParser<'a> {
+    usage: &'a str,
+    pos: usize,
+    start: usize,
+    prev: UsageToken,
+    explicit_name_set: bool,
+}
+
+impl<'a> UsageParser<'a> {
+    fn new(usage: &'a str) -> Self {
+        debugln!("UsageParser::new: usage={:?}", usage);
+        UsageParser {
+            usage,
+            pos: 0,
+            start: 0,
+            prev: UsageToken::Unknown,
+            explicit_name_set: false,
+        }
+    }
+
+    pub fn from_usage(usage: &'a str) -> Self {
+        debugln!("UsageParser::from_usage;");
+        UsageParser::new(usage)
+    }
+
+    pub fn parse(mut self) -> Arg<'a, 'a> {
+        debugln!("UsageParser::parse;");
+        let mut arg = Arg::default();
+        loop {
+            debugln!("UsageParser::parse:iter: pos={};", self.pos);
+            self.stop_at(token);
+            if let Some(&c) = self.usage.as_bytes().get(self.pos) {
+                match c {
+                    b'-' => self.short_or_long(&mut arg),
+                    b'.' => self.multiple(&mut arg),
+                    b'\'' => self.help(&mut arg),
+                    _ => self.name(&mut arg),
+                }
+            } else {
+                break;
+            }
+        }
+        debug_assert!(
+            !arg.b.name.is_empty(),
+            "No name found for Arg when parsing usage string: {}",
+            self.usage
+        );
+        arg.v.num_vals = match arg.v.val_names {
+            Some(ref v) if v.len() >= 2 => Some(v.len() as u64),
+            _ => None,
+        };
+        debugln!("UsageParser::parse: vals...{:?}", arg.v.val_names);
+        arg
+    }
+
+    fn name(&mut self, arg: &mut Arg<'a, 'a>) {
+        debugln!("UsageParser::name;");
+        if *self
+            .usage
+            .as_bytes()
+            .get(self.pos)
+            .expect(INTERNAL_ERROR_MSG)
+            == b'<'
+            && !self.explicit_name_set
+        {
+            arg.setb(ArgSettings::Required);
+        }
+        self.pos += 1;
+        self.stop_at(name_end);
+        let name = &self.usage[self.start..self.pos];
+        if self.prev == UsageToken::Unknown {
+            debugln!("UsageParser::name: setting name...{}", name);
+            arg.b.name = name;
+            if arg.s.long.is_none() && arg.s.short.is_none() {
+                debugln!("UsageParser::name: explicit name set...");
+                self.explicit_name_set = true;
+                self.prev = UsageToken::Name;
+            }
+        } else {
+            debugln!("UsageParser::name: setting val name...{}", name);
+            if let Some(ref mut v) = arg.v.val_names {
+                let len = v.len();
+                v.insert(len, name);
+            } else {
+                let mut v = VecMap::new();
+                v.insert(0, name);
+                arg.v.val_names = Some(v);
+                arg.setb(ArgSettings::TakesValue);
+            }
+            self.prev = UsageToken::ValName;
+        }
+    }
+
+    fn stop_at<F>(&mut self, f: F)
+    where
+        F: Fn(u8) -> bool,
+    {
+        debugln!("UsageParser::stop_at;");
+        self.start = self.pos;
+        self.pos += self.usage[self.start..]
+            .bytes()
+            .take_while(|&b| f(b))
+            .count();
+    }
+
+    fn short_or_long(&mut self, arg: &mut Arg<'a, 'a>) {
+        debugln!("UsageParser::short_or_long;");
+        self.pos += 1;
+        if *self
+            .usage
+            .as_bytes()
+            .get(self.pos)
+            .expect(INTERNAL_ERROR_MSG)
+            == b'-'
+        {
+            self.pos += 1;
+            self.long(arg);
+            return;
+        }
+        self.short(arg)
+    }
+
+    fn long(&mut self, arg: &mut Arg<'a, 'a>) {
+        debugln!("UsageParser::long;");
+        self.stop_at(long_end);
+        let name = &self.usage[self.start..self.pos];
+        if !self.explicit_name_set {
+            debugln!("UsageParser::long: setting name...{}", name);
+            arg.b.name = name;
+        }
+        debugln!("UsageParser::long: setting long...{}", name);
+        arg.s.long = Some(name);
+        self.prev = UsageToken::Long;
+    }
+
+    fn short(&mut self, arg: &mut Arg<'a, 'a>) {
+        debugln!("UsageParser::short;");
+        let start = &self.usage[self.pos..];
+        let short = start.chars().next().expect(INTERNAL_ERROR_MSG);
+        debugln!("UsageParser::short: setting short...{}", short);
+        arg.s.short = Some(short);
+        if arg.b.name.is_empty() {
+            // --long takes precedence but doesn't set self.explicit_name_set
+            let name = &start[..short.len_utf8()];
+            debugln!("UsageParser::short: setting name...{}", name);
+            arg.b.name = name;
+        }
+        self.prev = UsageToken::Short;
+    }
+
+    // "something..."
+    fn multiple(&mut self, arg: &mut Arg) {
+        debugln!("UsageParser::multiple;");
+        let mut dot_counter = 1;
+        let start = self.pos;
+        let mut bytes = self.usage[start..].bytes();
+        while bytes.next() == Some(b'.') {
+            dot_counter += 1;
+            self.pos += 1;
+            if dot_counter == 3 {
+                debugln!("UsageParser::multiple: setting multiple");
+                arg.setb(ArgSettings::Multiple);
+                if arg.is_set(ArgSettings::TakesValue) {
+                    arg.setb(ArgSettings::UseValueDelimiter);
+                    arg.unsetb(ArgSettings::ValueDelimiterNotSet);
+                    if arg.v.val_delim.is_none() {
+                        arg.v.val_delim = Some(',');
+                    }
+                }
+                self.prev = UsageToken::Multiple;
+                self.pos += 1;
+                break;
+            }
+        }
+    }
+
+    fn help(&mut self, arg: &mut Arg<'a, 'a>) {
+        debugln!("UsageParser::help;");
+        self.stop_at(help_start);
+        self.start = self.pos + 1;
+        self.pos = self.usage.len() - 1;
+        debugln!(
+            "UsageParser::help: setting help...{}",
+            &self.usage[self.start..self.pos]
+        );
+        arg.b.help = Some(&self.usage[self.start..self.pos]);
+        self.pos += 1; // Move to next byte to keep from thinking ending ' is a start
+        self.prev = UsageToken::Help;
+    }
+}
+
+#[inline]
+fn name_end(b: u8) -> bool {
+    b != b']' && b != b'>'
+}
+
+#[inline]
+fn token(b: u8) -> bool {
+    b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-'
+}
+
+#[inline]
+fn long_end(b: u8) -> bool {
+    b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' '
+}
+
+#[inline]
+fn help_start(b: u8) -> bool {
+    b != b'\''
+}
+
+#[cfg(test)]
+mod test {
+    use crate::args::{Arg, ArgSettings};
+
+    #[test]
+    fn create_flag_usage() {
+        let a = Arg::from_usage("[flag] -f 'some help info'");
+        assert_eq!(a.b.name, "flag");
+        assert_eq!(a.s.short.unwrap(), 'f');
+        assert!(a.s.long.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.v.val_names.is_none());
+        assert!(a.v.num_vals.is_none());
+
+        let b = Arg::from_usage("[flag] --flag 'some help info'");
+        assert_eq!(b.b.name, "flag");
+        assert_eq!(b.s.long.unwrap(), "flag");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(a.v.val_names.is_none());
+        assert!(a.v.num_vals.is_none());
+
+        let b = Arg::from_usage("--flag 'some help info'");
+        assert_eq!(b.b.name, "flag");
+        assert_eq!(b.s.long.unwrap(), "flag");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.v.val_names.is_none());
+        assert!(b.v.num_vals.is_none());
+
+        let c = Arg::from_usage("[flag] -f --flag 'some help info'");
+        assert_eq!(c.b.name, "flag");
+        assert_eq!(c.s.short.unwrap(), 'f');
+        assert_eq!(c.s.long.unwrap(), "flag");
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+
+        let d = Arg::from_usage("[flag] -f... 'some help info'");
+        assert_eq!(d.b.name, "flag");
+        assert_eq!(d.s.short.unwrap(), 'f');
+        assert!(d.s.long.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.v.val_names.is_none());
+        assert!(d.v.num_vals.is_none());
+
+        let e = Arg::from_usage("[flag] -f --flag... 'some help info'");
+        assert_eq!(e.b.name, "flag");
+        assert_eq!(e.s.long.unwrap(), "flag");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert_eq!(e.b.help.unwrap(), "some help info");
+        assert!(e.is_set(ArgSettings::Multiple));
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("-f --flag... 'some help info'");
+        assert_eq!(e.b.name, "flag");
+        assert_eq!(e.s.long.unwrap(), "flag");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert_eq!(e.b.help.unwrap(), "some help info");
+        assert!(e.is_set(ArgSettings::Multiple));
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("--flags");
+        assert_eq!(e.b.name, "flags");
+        assert_eq!(e.s.long.unwrap(), "flags");
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("--flags...");
+        assert_eq!(e.b.name, "flags");
+        assert_eq!(e.s.long.unwrap(), "flags");
+        assert!(e.is_set(ArgSettings::Multiple));
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("[flags] -f");
+        assert_eq!(e.b.name, "flags");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("[flags] -f...");
+        assert_eq!(e.b.name, "flags");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert!(e.is_set(ArgSettings::Multiple));
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let a = Arg::from_usage("-f 'some help info'");
+        assert_eq!(a.b.name, "f");
+        assert_eq!(a.s.short.unwrap(), 'f');
+        assert!(a.s.long.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.v.val_names.is_none());
+        assert!(a.v.num_vals.is_none());
+
+        let e = Arg::from_usage("-f");
+        assert_eq!(e.b.name, "f");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+
+        let e = Arg::from_usage("-f...");
+        assert_eq!(e.b.name, "f");
+        assert_eq!(e.s.short.unwrap(), 'f');
+        assert!(e.is_set(ArgSettings::Multiple));
+        assert!(e.v.val_names.is_none());
+        assert!(e.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage0() {
+        // Short only
+        let a = Arg::from_usage("[option] -o [opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert!(a.s.long.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage1() {
+        let b = Arg::from_usage("-o [opt] 'some help info'");
+        assert_eq!(b.b.name, "o");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert!(b.s.long.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage2() {
+        let c = Arg::from_usage("<option> -o <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert!(c.s.long.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage3() {
+        let d = Arg::from_usage("-o <opt> 'some help info'");
+        assert_eq!(d.b.name, "o");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert!(d.s.long.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage4() {
+        let a = Arg::from_usage("[option] -o [opt]... 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert!(a.s.long.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage5() {
+        let a = Arg::from_usage("[option]... -o [opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert!(a.s.long.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage6() {
+        let b = Arg::from_usage("-o [opt]... 'some help info'");
+        assert_eq!(b.b.name, "o");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert!(b.s.long.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage7() {
+        let c = Arg::from_usage("<option> -o <opt>... 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert!(c.s.long.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage8() {
+        let c = Arg::from_usage("<option>... -o <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert!(c.s.long.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage9() {
+        let d = Arg::from_usage("-o <opt>... 'some help info'");
+        assert_eq!(d.b.name, "o");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert!(d.s.long.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long1() {
+        let a = Arg::from_usage("[option] --opt [opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long2() {
+        let b = Arg::from_usage("--opt [option] 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long3() {
+        let c = Arg::from_usage("<option> --opt <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long4() {
+        let d = Arg::from_usage("--opt <option> 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long5() {
+        let a = Arg::from_usage("[option] --opt [opt]... 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long6() {
+        let a = Arg::from_usage("[option]... --opt [opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long7() {
+        let b = Arg::from_usage("--opt [option]... 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long8() {
+        let c = Arg::from_usage("<option> --opt <opt>... 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long9() {
+        let c = Arg::from_usage("<option>... --opt <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long10() {
+        let d = Arg::from_usage("--opt <option>... 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals1() {
+        let a = Arg::from_usage("[option] --opt=[opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals2() {
+        let b = Arg::from_usage("--opt=[option] 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals3() {
+        let c = Arg::from_usage("<option> --opt=<opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals4() {
+        let d = Arg::from_usage("--opt=<option> 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals5() {
+        let a = Arg::from_usage("[option] --opt=[opt]... 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals6() {
+        let a = Arg::from_usage("[option]... --opt=[opt] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert!(a.s.short.is_none());
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals7() {
+        let b = Arg::from_usage("--opt=[option]... 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert!(b.s.short.is_none());
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals8() {
+        let c = Arg::from_usage("<option> --opt=<opt>... 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals9() {
+        let c = Arg::from_usage("<option>... --opt=<opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert!(c.s.short.is_none());
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_long_equals10() {
+        let d = Arg::from_usage("--opt=<option>... 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both1() {
+        let a = Arg::from_usage("[option] -o --opt [option] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both2() {
+        let b = Arg::from_usage("-o --opt [option] 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both3() {
+        let c = Arg::from_usage("<option> -o --opt <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both4() {
+        let d = Arg::from_usage("-o --opt <option> 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both5() {
+        let a = Arg::from_usage("[option]... -o --opt [option] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both6() {
+        let b = Arg::from_usage("-o --opt [option]... 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both7() {
+        let c = Arg::from_usage("<option>... -o --opt <opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both8() {
+        let d = Arg::from_usage("-o --opt <option>... 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals1() {
+        let a = Arg::from_usage("[option] -o --opt=[option] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals2() {
+        let b = Arg::from_usage("-o --opt=[option] 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals3() {
+        let c = Arg::from_usage("<option> -o --opt=<opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(!c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals4() {
+        let d = Arg::from_usage("-o --opt=<option> 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals5() {
+        let a = Arg::from_usage("[option]... -o --opt=[option] 'some help info'");
+        assert_eq!(a.b.name, "option");
+        assert_eq!(a.s.long.unwrap(), "opt");
+        assert_eq!(a.s.short.unwrap(), 'o');
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(a.is_set(ArgSettings::Multiple));
+        assert!(a.is_set(ArgSettings::TakesValue));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals6() {
+        let b = Arg::from_usage("-o --opt=[option]... 'some help info'");
+        assert_eq!(b.b.name, "opt");
+        assert_eq!(b.s.long.unwrap(), "opt");
+        assert_eq!(b.s.short.unwrap(), 'o');
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::TakesValue));
+        assert!(!b.is_set(ArgSettings::Required));
+        assert_eq!(
+            b.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals7() {
+        let c = Arg::from_usage("<option>... -o --opt=<opt> 'some help info'");
+        assert_eq!(c.b.name, "option");
+        assert_eq!(c.s.long.unwrap(), "opt");
+        assert_eq!(c.s.short.unwrap(), 'o');
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(c.is_set(ArgSettings::TakesValue));
+        assert!(c.is_set(ArgSettings::Required));
+        assert_eq!(
+            c.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"opt"]
+        );
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_usage_both_equals8() {
+        let d = Arg::from_usage("-o --opt=<option>... 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"option"]
+        );
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_option_with_vals1() {
+        let d = Arg::from_usage("-o <file> <mode> 'some help info'");
+        assert_eq!(d.b.name, "o");
+        assert!(d.s.long.is_none());
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"file", &"mode"]
+        );
+        assert_eq!(d.v.num_vals.unwrap(), 2);
+    }
+
+    #[test]
+    fn create_option_with_vals2() {
+        let d = Arg::from_usage("-o <file> <mode>... 'some help info'");
+        assert_eq!(d.b.name, "o");
+        assert!(d.s.long.is_none());
+        assert_eq!(d.s.short.unwrap(), 'o');
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"file", &"mode"]
+        );
+        assert_eq!(d.v.num_vals.unwrap(), 2);
+    }
+
+    #[test]
+    fn create_option_with_vals3() {
+        let d = Arg::from_usage("--opt <file> <mode>... 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"file", &"mode"]
+        );
+        assert_eq!(d.v.num_vals.unwrap(), 2);
+    }
+
+    #[test]
+    fn create_option_with_vals4() {
+        let d = Arg::from_usage("[myopt] --opt <file> <mode> 'some help info'");
+        assert_eq!(d.b.name, "myopt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(!d.is_set(ArgSettings::Required));
+        assert_eq!(
+            d.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"file", &"mode"]
+        );
+        assert_eq!(d.v.num_vals.unwrap(), 2);
+    }
+
+    #[test]
+    fn create_option_with_vals5() {
+        let d = Arg::from_usage("--opt <file> <mode> 'some help info'");
+        assert_eq!(d.b.name, "opt");
+        assert!(d.s.short.is_none());
+        assert_eq!(d.s.long.unwrap(), "opt");
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(!d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::TakesValue));
+        assert!(d.is_set(ArgSettings::Required));
+        assert_eq!(d.v.num_vals.unwrap(), 2);
+    }
+
+    #[test]
+    fn create_positional_usage() {
+        let a = Arg::from_usage("[pos] 'some help info'");
+        assert_eq!(a.b.name, "pos");
+        assert_eq!(a.b.help.unwrap(), "some help info");
+        assert!(!a.is_set(ArgSettings::Multiple));
+        assert!(!a.is_set(ArgSettings::Required));
+        assert!(a.v.val_names.is_none());
+        assert!(a.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn create_positional_usage0() {
+        let b = Arg::from_usage("<pos> 'some help info'");
+        assert_eq!(b.b.name, "pos");
+        assert_eq!(b.b.help.unwrap(), "some help info");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::Required));
+        assert!(b.v.val_names.is_none());
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_mult_help() {
+        let c = Arg::from_usage("[pos]... 'some help info'");
+        assert_eq!(c.b.name, "pos");
+        assert_eq!(c.b.help.unwrap(), "some help info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_help_lit_single_quote() {
+        let c = Arg::from_usage("[pos]... 'some help\' info'");
+        assert_eq!(c.b.name, "pos");
+        assert_eq!(c.b.help.unwrap(), "some help' info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_help_double_lit_single_quote() {
+        let c = Arg::from_usage("[pos]... 'some \'help\' info'");
+        assert_eq!(c.b.name, "pos");
+        assert_eq!(c.b.help.unwrap(), "some 'help' info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_help_newline() {
+        let c = Arg::from_usage(
+            "[pos]... 'some help{n}\
+             info'",
+        );
+        assert_eq!(c.b.name, "pos");
+        assert_eq!(c.b.help.unwrap(), "some help{n}info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_help_newline_lit_sq() {
+        let c = Arg::from_usage(
+            "[pos]... 'some help\' stuff{n}\
+             info'",
+        );
+        assert_eq!(c.b.name, "pos");
+        assert_eq!(c.b.help.unwrap(), "some help' stuff{n}info");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_req_mult_help() {
+        let d = Arg::from_usage("<pos>... 'some help info'");
+        assert_eq!(d.b.name, "pos");
+        assert_eq!(d.b.help.unwrap(), "some help info");
+        assert!(d.is_set(ArgSettings::Multiple));
+        assert!(d.is_set(ArgSettings::Required));
+        assert!(d.v.val_names.is_none());
+        assert!(d.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_req() {
+        let b = Arg::from_usage("<pos>");
+        assert_eq!(b.b.name, "pos");
+        assert!(!b.is_set(ArgSettings::Multiple));
+        assert!(b.is_set(ArgSettings::Required));
+        assert!(b.v.val_names.is_none());
+        assert!(b.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn pos_mult() {
+        let c = Arg::from_usage("[pos]...");
+        assert_eq!(c.b.name, "pos");
+        assert!(c.is_set(ArgSettings::Multiple));
+        assert!(!c.is_set(ArgSettings::Required));
+        assert!(c.v.val_names.is_none());
+        assert!(c.v.num_vals.is_none());
+    }
+
+    #[test]
+    fn nonascii() {
+        let a = Arg::from_usage("<ASCII> 'üñíčöĐ€'");
+        assert_eq!(a.b.name, "ASCII");
+        assert_eq!(a.b.help, Some("üñíčöĐ€"));
+        let a = Arg::from_usage("<üñíčöĐ€> 'ASCII'");
+        assert_eq!(a.b.name, "üñíčöĐ€");
+        assert_eq!(a.b.help, Some("ASCII"));
+        let a = Arg::from_usage("<üñíčöĐ€> 'üñíčöĐ€'");
+        assert_eq!(a.b.name, "üñíčöĐ€");
+        assert_eq!(a.b.help, Some("üñíčöĐ€"));
+        let a = Arg::from_usage("-ø 'ø'");
+        assert_eq!(a.b.name, "ø");
+        assert_eq!(a.s.short, Some('ø'));
+        assert_eq!(a.b.help, Some("ø"));
+        let a = Arg::from_usage("--üñíčöĐ€ 'Nōṫ ASCII'");
+        assert_eq!(a.b.name, "üñíčöĐ€");
+        assert_eq!(a.s.long, Some("üñíčöĐ€"));
+        assert_eq!(a.b.help, Some("Nōṫ ASCII"));
+        let a = Arg::from_usage("[ñämê] --ôpt=[üñíčöĐ€] 'hælp'");
+        assert_eq!(a.b.name, "ñämê");
+        assert_eq!(a.s.long, Some("ôpt"));
+        assert_eq!(
+            a.v.val_names.unwrap().values().collect::<Vec<_>>(),
+            [&"üñíčöĐ€"]
+        );
+        assert_eq!(a.b.help, Some("hælp"));
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.toml":"ff5bac5ffe795109feabd656a03c823b02fcad9186f6e6a957c2fb7201cd1bd8","LICENSE-APACHE":"453745410e3be8cf25d56872ea2aec975a78e6c9f217443d0bf908a5bce7c8ff","LICENSE-MIT":"de3911c2d98c8bd2d701ee721347053d9b55995a11f9a8c955e44d3ca1b376bf","examples/adv_server.rs":"45526c1ebeabad80e5dd5e8ecf071ea7a5e4870c58e47fad194f849fa347ef3a","examples/argument_guide.md":"b9824fc2b20c6478b3d42195f7d2486d11401aa9f72267e81ec3878bd6882e95","examples/client.rs":"56579c1a4fc3386ca41ddb350d9283d270e31cdf117fb815c84b6b0dd6548335","examples/properties.rs":"dac7eef86e17af1bc4b8d37f431686d3cc1f5890214ea880894c7cbd04ba2ad7","examples/properties_msgitem.rs":"b51e2cd87dc38696e8f0f98bac974d802ba00d69e0aff1102460fdfbf4448ffc","examples/rtkit.rs":"20b46aecac84aa90f0daa423dd9e2c118f1195ac777732bc4cedf9a0d85c4861","examples/server.rs":"9c286b26e45990cab5a7300bb5dd20048dd4dde6366d0e1cb6cdc85b7bf76eb6","examples/unity_focused_window.rs":"f1098e4ebce0feda47af862c6f3e755d6d74f78928731a75f15416bd76577fe1","src/arg/array_impl.rs":"bd18d93fe37a8053c0eb6e4e2d29cfc619adec69ba5ee3411cf03f6ad01fa0c0","src/arg/basic_impl.rs":"7c596da14de18220eb2258c80bc6eb0db9a7cd72bc85ba8d60da78cbf0232454","src/arg/mod.rs":"63274e49ed6f6dd632349e336504e0508d191f35403a7eec2ea20fee7e4ed4a2","src/arg/msgarg.rs":"1df0674603ef7d3e6d3fc1674aa7ffe6a048c3631ea76b533757b9daed958a7b","src/arg/variantstruct_impl.rs":"d9ddc73c44f1e57b67a7a73e8204f6915b51365cd47b1caf68573eb802b93a01","src/connection.rs":"8178688223b392ba5c29bb66b7e89ab642a129da7c777e34014ff9fb6a0daae8","src/connection2.rs":"ef0ba9ace17c8465bf25f3b8d97666e4ab1a6db048653cde408f946206592dcf","src/crossroads/crossroads.rs":"a1f17a5359bb38a54c89553f08c41b2268265fcd195f757c8f409c4ea1b43272","src/crossroads/handlers.rs":"21fbc36bb79aeeb02ac05b11f02ababd544b019d3ec258d73894344fc742c58a","src/crossroads/info.rs":"88a1648d367d0b8a4870bf2fc276c576ad60a23976e2f67f6d784f2dc0c3bc28","src/crossroads/mod.rs":"3e7e03ace37f0a18422d4a724b9db166c114216b2e6d1991ca9453380aa42dff","src/crossroads/stdimpl.rs":"1ded85e9efa18e55d3e65a8cc253b0544869093723157a99b8f7bdd7c3d3149f","src/dispatcher.rs":"b98c29a2063d6e9b263854256487dedf644d3fdb9071623f1e30e7132abedc7a","src/lib.rs":"2fad04e6f162e8121a72c0bad95b77ceabf4bc1c4a86c648602a929983272dc4","src/matchrule.rs":"502fc71bfb5c8bec2b3f0b92d95679513e656b0aa89094164223042fac26435b","src/message.rs":"d07db0c6208f5057961e904e5da8aa12352d0a1d1917c07d0ab0d18a981637aa","src/methoddisp.rs":"57d5b0e7eef7b76393dfd80e2e5125b266521f3252edbc402b893f12791b933e","src/objpath.rs":"e9f662d6cc81ea0717553787773261e7fb3221b36fab1799fb281f21de961b72","src/prop.rs":"60541e569ff06f503d889a7b62dd0aa980d39be60cde01f917503a80e0b7b27f","src/signalargs.rs":"7f0a380d51788208d153e2b51a1759d43a9e4bc41b38b3268a31cd9d681b0cce","src/stdintf.rs":"29027f8cffde7354fc432b306a3ade149bc12440f08fe86d1a72074d514d7101","src/strings.rs":"49635568c8e7f5993e67bfc72941f4ef9407671c63d57c37489620386fbed724","src/tree/factory.rs":"77bfdfa9074e653b43e9c51b3e0b2dcfc9bc02948b7f9eb8e2fc0fe1a9009d14","src/tree/leaves.rs":"9c8b07925c07424a3977b8effa154e63d32addcbab1f59331025039592705bc1","src/tree/methodtype.rs":"6e77276ad1ca4040cd4bea320f525e49165e1d21df89281de4d9b1913129e0e2","src/tree/mod.rs":"471ff6e4bbd9c360326ed92867744b78235d769ba4483e0a8c20137153ab1e82","src/tree/objectpath.rs":"727fa86029f3ebd1d5de183e8f105deb1b3a273f1f89d0e02a5b227c6b1ff515","src/tree/utils.rs":"d15e64ed288ffa7477c2c35532d7f61feafb50ef6068606014101622bcd36caa","src/watch.rs":"9f323ea92206c77e184169e4b7f2a01f2014bf761d3aa5228431109283a1a4fe"},"package":"48b5f0f36f1eebe901b0e6bee369a77ed3396334bf3f09abd46454a576f71819"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/Cargo.toml
@@ -0,0 +1,38 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "dbus"
+version = "0.6.5"
+authors = ["David Henningsson <diwic@ubuntu.com>"]
+description = "Bindings to D-Bus, which is a bus commonly used on Linux for inter-process communication."
+documentation = "http://docs.rs/dbus"
+readme = "../README.md"
+keywords = ["D-Bus", "DBus", "IPC"]
+categories = ["os::unix-apis", "api-bindings"]
+license = "Apache-2.0/MIT"
+repository = "https://github.com/diwic/dbus-rs"
+[dependencies.libc]
+version = "0.2.7"
+
+[dependencies.libdbus-sys]
+version = "0.2"
+[dev-dependencies.tempdir]
+version = "0.3"
+
+[features]
+no-string-validation = []
+[badges.is-it-maintained-issue-resolution]
+repository = "diwic/dbus-rs"
+
+[badges.is-it-maintained-open-issues]
+repository = "diwic/dbus-rs"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/LICENSE-APACHE
@@ -0,0 +1,202 @@
+Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/LICENSE-MIT
@@ -0,0 +1,19 @@
+Copyright (c) 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
rename from third_party/rust/dbus/examples/adv_server.rs
rename to third_party/rust/dbus-0.6.5/examples/adv_server.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/argument_guide.md
@@ -0,0 +1,193 @@
+Preamble
+--------
+
+The different ways you can append and get message arguments can be a bit bewildering. I've iterated a few times on the design and didn't want to lose backwards compatibility.
+
+This guide is to help you on your way. In addition, many of the examples in the examples directory append and read arguments.
+
+Code generation
+---------------
+
+First - if you can get D-Bus introspection data, you can use the the `dbus-codegen` tool to generate some boilerplate code for you. E g, if you want to talk to NetworkManager:
+
+```rust
+cargo install dbus-codegen
+dbus-codegen-rust -s -g -m None -d org.freedesktop.NetworkManager -p /org/freedesktop/NetworkManager > networkmanager.rs
+```
+
+You would then use this code like:
+
+```rust
+// main.rs
+mod networkmanager;
+
+/* ... */
+
+// Start a connection to the system bus.
+let c = Connection::get_private(BusType::System)?;
+
+// Make a "ConnPath" struct that just contains a Connection, a destination and a path.
+let p = c.with_path("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", 5000);
+
+// Bring our generated code into scope.
+use networkmanager::OrgFreedesktopNetworkManager;
+
+// Now we can call methods on our connpath from the "org.freedesktop.NetworkManager" interface.
+let devices = c.get_all_devices()?;
+```
+
+There is also pre-generated code for standard D-Bus interfaces in the `stdintf` module. A similar example:
+
+```rust
+let c = Connection::get_private(BusType::Session)?;
+
+// Make a "ConnPath" struct that just contains a Connection, a destination and a path.
+let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000);
+
+// The ConnPath struct implements many traits, e g `org.freedesktop.DBus.Properties`. Bring the trait into scope.
+use stdintf::org_freedesktop_dbus::Properties;
+
+// Now we can call org.freedesktop.DBus.Properties.Get just like an ordinary method and get the result back.
+let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
+```
+
+For more details, see `dbus-codegen-rust --help` and the `README.md` in the dbus-codegen directory.
+
+Now, if you want to make a service yourself, the generated code is more complex. And for some use cases, codegen isn't really an option, so let's move on:
+
+Append / get basic types
+------------------------
+
+If you just want to get/append simple types, just use `append1` / `append2` / `append3`, and 
+`read1` / `read2` / `read3`. The imaginary method below takes one byte parameter and one string parameter, and returns one string parameter and one int parameter.
+
+```rust
+let m = Message::new_method_call(dest, path, intf, member)?.append2(5u8, "Foo");
+let r = c.send_with_reply_and_block(m, 2000)?;
+let (data1, data2): (&str, i32) = c.read2()?;
+```
+
+Arrays and dictionaries
+-----------------------
+
+D-Bus arrays and dictionaries usually correspond to `Vec` and `HashMap`. You can just append and get them like basic types:
+
+```rust
+let v = vec![3i32, 4i32, 5i32];
+let mut map = HashMap::new();
+map.insert("Funghi", 5u16);
+map.insert("Mold", 8u16);
+
+let m = Message::new_method_call(dest, path, intf, member)?.append2(v, map);
+let r = c.send_with_reply_and_block(m, 2000)?;
+let (data1, data2): (Vec<i32>, HashMap<&str, u16>) = r.read2()?;
+```
+
+Or combine them as you wish, e g, use a `Vec<Vec<u8>>`, a `HashMap<u64, Vec<String>>` or `HashMap<String, HashMap<String, i32>>` to construct more difficult types.
+
+Slices can sometimes be used as arrays - e g, `&[&str]` can be appended, but only very simple types can be used with `get` and `read`, e g `&[u8]`.
+
+This is the easiest way to get started, but in case you want to avoid the overhead of creating `Vec` or `HashMap`s, the "Array and Dict types" and "Iter / IterAppend" sections offer useful alternatives.
+
+Variants
+--------
+
+Things are getting slightly more complex with Variants, because they are not strongly typed and thus not fit as well into Rust's strongly typed as arrays and dicts.
+
+If you know the type beforehand, it's still easy:
+
+```rust
+let v = Variant("This is a variant containing a &str");
+let m = Message::new_method_call(dest, path, intf, member)?.append1(v);
+let r = c.send_with_reply_and_block(m, 2000)?;
+let z: Variant<i32> = r.read1()?;
+println!("Method returned {}", z.0);
+```
+
+The `Variant` struct is just a wrapper with a public interior, so you can easily both read from it and write to it with the `.0` accessor.
+
+Sometimes you don't know the type beforehand. We can solve this in two ways (choose whichever is more appropriate for your use case), either through the trait object `Box<RefArg>` or through `Iter` / `IterAppend` (see later sections).
+
+Through trait objects:
+
+```rust
+let x = Box::new(5000i32) as Box<RefArg>;
+let m = Message::new_method_call(dest, path, intf, member)?.append1(Variant(x));
+let r = c.send_with_reply_and_block(m, 2000)?;
+let z: Variant<Box<RefArg>> = r.read1()?;
+```
+
+Ok, so we retrieved our `Box<RefArg>`. We now need to use the `RefArg` methods to probe it, to see what's inside. Easiest is to use `as_i64` or `as_str` if you want to test for integer or string types. Use `as_iter` if the variant contains a complex type you need to iterate over.
+For floating point values, use `arg::cast` (this requires that the RefArg is `static` though, due to Rust type system limitations).
+Match over `arg_type` if you need to know the exact type. 
+
+
+```rust
+let z: Variant<Box<RefArg + 'static>> = r.read1()?;
+let value = &z.0;
+
+if let Some(s) = value.as_str() { println!("It's a string: {}", s); }
+else if let Some(i) = value.as_i64() { println!("It's an integer: {}", i); }
+else if let Some(f) = arg::cast::<f64>(value) { println!("It's a float: {}", f); }
+else { println!("Don't know how to handle a {:?}", value.arg_type()) }
+```
+
+Dicts and variants are sometimes combined, e g, you might need to read a D-Bus dictionary of String to Variants. You can then read these as `HashMap<String, Variant<Box<RefArg>>>`.
+
+Structs
+-------
+
+D-Bus structs are implemented as Rust tuples. You can append and get tuples like you do with other types of arguments.
+
+TODO: Example
+
+Declare method arguments
+------------------------
+
+When you make a `Tree`, you want to declare what input and output arguments your method expects - so that correct D-Bus introspection data can be generated. You'll use the same types as you learned earlier in this guide:
+
+```rust
+factory.method( /* ... */ )
+.inarg::<HashMap<i32, Vec<(i32, bool, String)>>,_>("request")
+.outarg::<&str,_>("reply")
+```
+
+The types are just for generating a correct signature, they are never instantiated. Many different types can generate the same signature - e g, `Array<u8, _>`, `Vec<u8>` and `&[u8]` will all generate the same signature. `Variant` will generate the same type signature regardless of what's inside, so just write `Variant<()>` for simplicity.
+
+
+Iter / IterAppend
+-----------------
+
+Iter and IterAppend are more low-level, direct methods to get and append arguments. They can, e g, come handy if you have more than five arguments to read.
+
+E g, for appending a variant with IterAppend you can use `IterAppend::new(&msg).append_variant(|i| i.append(5000i32))` to append what you need to your variant inside the closure.
+To read a variant you can use `let i = msg.read1::<Variant<Iter>>::()?` and then examine the methods on `i.0` to probe the variant.
+
+Array and Dict types
+--------------------
+
+These provide slightly better flexibility than using `Vec` and `HashMap` by instead integrating with `Iterator`. Here's an example where you can append and get a dictionary without having to create a HashMap:
+
+```rust
+let x = &[("Hello", true), ("World", false)];
+let m = Message::new_method_call(dest, path, intf, member)?.append1(Dict::new(x));
+let r = c.send_with_reply_and_block(m, 2000)?;
+let z: Dict<i32, &str, _> = r.read1()?;
+for (key, value) in z { /* do something */ }
+```
+
+An edge case where this is necessary is having floating point keys in a dictionary - this is supported in D-Bus but not in Rust's `HashMap`. I have never seen this in practice, though.
+
+Unusual types
+-------------
+
+The types `Path`, `Signature` and `OwnedFd` are not often used, but they can be appended and read as other argument types. `Path` and `Signature` will return strings with a borrowed lifetime - use `.into_static()` if you want to untie that lifetime.
+
+For `OwnedFd`, which a wrapper around a file descriptor, remember that the file descriptor will be closed when it goes out of scope.
+
+MessageItem
+-----------
+
+MessageItem was the first design - an enum representing a D-Bus argument. It still works, but I doubt you'll ever need to use it. Newer methods provide better type safety, speed, and ergonomics.
+
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/client.rs
@@ -0,0 +1,14 @@
+extern crate dbus;
+
+use dbus::{Connection, BusType, Message};
+use dbus::arg::Array;
+
+fn main() {
+    let c = Connection::get_private(BusType::Session).unwrap();
+    let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
+    let r = c.send_with_reply_and_block(m, 2000).unwrap();
+    // ListNames returns one argument, which is an array of strings.
+    let arr: Array<&str, _>  = r.get1().unwrap();
+    for name in arr { println!("{}", name); }
+}
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/properties.rs
@@ -0,0 +1,50 @@
+extern crate dbus;
+
+use dbus::{Connection, BusType, stdintf, arg};
+use std::collections::HashMap;
+
+fn print_refarg(value: &arg::RefArg) {
+    // We don't know what type the value is. We'll try a few and fall back to
+    // debug printing if the value is more complex than that.
+    if let Some(s) = value.as_str() { println!("{}", s); }
+    else if let Some(i) = value.as_i64() { println!("{}", i); }
+    else { println!("{:?}", value); }
+}
+
+fn main() {
+    // Connect to server and create a ConnPath. A ConnPath implements several interfaces,
+    // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get".
+    let c = Connection::get_private(BusType::Session).unwrap();
+    let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000);
+    use stdintf::org_freedesktop_dbus::Properties;
+
+    // The Metadata property is a Dict<String, Variant>. 
+
+    // Option 1: we can get the dict straight into a hashmap, like this:
+
+    let metadata: HashMap<String, arg::Variant<Box<arg::RefArg>>> = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap();
+
+    println!("Option 1:");
+
+    // We now iterate over the hashmap.
+    for (key, value) in metadata.iter() {
+        print!("  {}: ", key);
+        print_refarg(&value);
+    }
+
+
+    // Option 2: we can get the entire dict as a RefArg and get the values out by iterating over it.
+
+    let metadata: Box<arg::RefArg> = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap();
+
+    // When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc.
+    let mut iter = metadata.as_iter().unwrap();
+
+    println!("Option 2:");
+    while let Some(key) = iter.next() {
+        // Printing the key is easy, since we know it's a String.
+        print!("  {}: ", key.as_str().unwrap());
+        let value = iter.next().unwrap();
+        print_refarg(&value);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/properties_msgitem.rs
@@ -0,0 +1,10 @@
+extern crate dbus;
+
+use dbus::{Connection, BusType, Props};
+
+fn main() {
+    let c = Connection::get_private(BusType::System).unwrap();
+    let p = Props::new(&c, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority",
+        "org.freedesktop.PolicyKit1.Authority", 10000);
+    println!("BackendVersion: {:?}", p.get("BackendVersion").unwrap())
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/rtkit.rs
@@ -0,0 +1,67 @@
+/* This example asks the rtkit service to make our thread realtime priority.
+   Rtkit puts a few limitations on us to let us become realtime, such as setting
+   RLIMIT_RTTIME correctly, hence the syscalls. */
+
+extern crate dbus;
+extern crate libc;
+
+use std::cmp;
+
+use dbus::{Connection, BusType, Props, MessageItem, Message};
+
+fn item_as_i64(i: MessageItem) -> Result<i64, Box<std::error::Error>> {
+    match i {
+        MessageItem::Int32(i) => Ok(i as i64),
+        MessageItem::Int64(i) => Ok(i),
+        _ => Err(Box::from(&*format!("Property is not integer ({:?})", i)))
+    }
+}
+
+fn rtkit_set_realtime(c: &Connection, thread: u64, prio: u32) -> Result<(), ::dbus::Error> {
+    let mut m = Message::new_method_call("org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
+        "org.freedesktop.RealtimeKit1", "MakeThreadRealtime").unwrap();
+    m.append_items(&[thread.into(), prio.into()]);
+    let mut r = try!(c.send_with_reply_and_block(m, 10000));
+    r.as_result().map(|_| ())
+}
+
+fn make_realtime(prio: u32) -> Result<u32, Box<std::error::Error>> {
+    let c = try!(Connection::get_private(BusType::System));
+
+    let p = Props::new(&c, "org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
+        "org.freedesktop.RealtimeKit1", 10000);
+
+    // Make sure we don't fail by wanting too much
+    let max_prio = try!(item_as_i64(try!(p.get("MaxRealtimePriority")))) as u32;
+    let prio = cmp::min(prio, max_prio);
+
+    // Enforce RLIMIT_RTPRIO, also a must before asking rtkit for rtprio
+    let max_rttime = try!(item_as_i64(try!(p.get("RTTimeUSecMax")))) as u64;
+    let new_limit = libc::rlimit64 { rlim_cur: max_rttime, rlim_max: max_rttime };
+    let mut old_limit = new_limit;
+    if unsafe { libc::getrlimit64(libc::RLIMIT_RTTIME, &mut old_limit) } < 0 {
+        return Err(Box::from("getrlimit failed"));
+    }
+    if unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &new_limit) } < 0 {
+        return Err(Box::from("setrlimit failed"));
+    }
+
+    // Finally, let's ask rtkit to make us realtime
+    let thread_id = unsafe { libc::syscall(libc::SYS_gettid) };
+    let r = rtkit_set_realtime(&c, thread_id as u64, prio);
+
+    if r.is_err() {
+        unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &old_limit) };
+    }
+
+    try!(r);
+    Ok(prio)
+}
+
+
+fn main() {
+    match make_realtime(5) {
+        Ok(n) => println!("Got rtprio, level {}", n),
+        Err(e) => println!("No rtprio: {}", e),
+    }
+}
rename from third_party/rust/dbus/examples/server.rs
rename to third_party/rust/dbus-0.6.5/examples/server.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/examples/unity_focused_window.rs
@@ -0,0 +1,25 @@
+extern crate dbus;
+
+// Tracks currently focused window under the Unity desktop by listening to the
+// FocusedWindowChanged signal. The signal contains "window_id", "app_id" and "stage",
+// we print only "app_id". 
+
+use dbus::{Connection, BusType, ConnectionItem};
+
+fn focus_msg(ci: &ConnectionItem) -> Option<&str> {
+    let m = if let &ConnectionItem::Signal(ref s) = ci { s } else { return None };
+    if &*m.interface().unwrap() != "com.canonical.Unity.WindowStack" { return None };
+    if &*m.member().unwrap() != "FocusedWindowChanged" { return None };
+    let (_, app) = m.get2::<u32, &str>();
+    app
+}
+
+fn main() {
+    let c = Connection::get_private(BusType::Session).unwrap();
+    c.add_match("interface='com.canonical.Unity.WindowStack',member='FocusedWindowChanged'").unwrap();
+
+    for i in c.iter(1000) {
+        if let Some(app) = focus_msg(&i) { println!("{} has now focus.", app) };
+    }
+}
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/arg/array_impl.rs
@@ -0,0 +1,483 @@
+use super::*;
+use {Signature, Path, Message, ffi, OwnedFd};
+use std::marker::PhantomData;
+use std::{ptr, mem, any, fmt};
+use super::check;
+use std::ffi::{CString};
+use std::os::raw::{c_void, c_int};
+use std::collections::HashMap;
+use std::hash::Hash;
+
+// Map DBus-Type -> Alignment. Copied from _dbus_marshal_write_fixed_multi in
+// http://dbus.freedesktop.org/doc/api/html/dbus-marshal-basic_8c_source.html#l01020
+// Note that Rust booleans are one byte, dbus booleans are four bytes!
+const FIXED_ARRAY_ALIGNMENTS: [(ArgType, usize); 9] = [
+    (ArgType::Byte, 1),
+    (ArgType::Int16, 2),
+    (ArgType::UInt16, 2),	
+    (ArgType::UInt32, 4),
+    (ArgType::Int32, 4),
+    (ArgType::Boolean, 4),
+    (ArgType::Int64, 8),
+    (ArgType::UInt64, 8),
+    (ArgType::Double, 8)
+];
+
+/// Represents a D-Bus array.
+impl<'a, T: Arg> Arg for &'a [T] {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> { Signature::from(format!("a{}", T::signature())) }
+}
+
+fn array_append<T: Arg, F: FnMut(&T, &mut IterAppend)>(z: &[T], i: &mut IterAppend, mut f: F) {
+    let zptr = z.as_ptr();
+    let zlen = z.len() as i32;
+
+    // Can we do append_fixed_array?
+    let a = (T::ARG_TYPE, mem::size_of::<T>());
+    let can_fixed_array = (zlen > 1) && (z.len() == zlen as usize) && FIXED_ARRAY_ALIGNMENTS.iter().any(|&v| v == a);
+
+    i.append_container(ArgType::Array, Some(T::signature().as_cstr()), |s|
+        if can_fixed_array { unsafe { check("dbus_message_iter_append_fixed_array",
+            ffi::dbus_message_iter_append_fixed_array(&mut s.0, a.0 as c_int, &zptr as *const _ as *const c_void, zlen)) }}
+        else { for arg in z { f(arg, s); }}
+    );
+}
+
+/// Appends a D-Bus array. Note: In case you have a large array of a type that implements FixedArray,
+/// using this method will be more efficient than using an Array.
+impl<'a, T: Arg + Append + Clone> Append for &'a [T] {
+    fn append(self, i: &mut IterAppend) {
+        array_append(self, i, |arg, s| arg.clone().append(s));
+    }
+}
+
+impl<'a, T: Arg + RefArg> RefArg for &'a [T] {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
+    fn append(&self, i: &mut IterAppend) {
+        array_append(self, i, |arg, s| (arg as &RefArg).append(s));
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalArray {
+            inner_sig: <T as Arg>::signature(),
+            data: self.iter().map(|x| x.box_clone()).collect(),
+        })
+    }
+}
+
+impl<T: Arg + RefArg> RefArg for Vec<T> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
+    fn append(&self, i: &mut IterAppend) {
+        array_append(&self, i, |arg, s| (arg as &RefArg).append(s));
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+        Some(Box::new(self.iter().map(|b| b as &RefArg)))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+}
+
+
+impl<'a, T: FixedArray> Get<'a> for &'a [T] {
+    fn get(i: &mut Iter<'a>) -> Option<&'a [T]> {
+        debug_assert!(FIXED_ARRAY_ALIGNMENTS.iter().any(|&v| v == (T::ARG_TYPE, mem::size_of::<T>())));
+        i.recurse(Self::ARG_TYPE).and_then(|mut si| unsafe {
+            let etype = ffi::dbus_message_iter_get_element_type(&mut i.0);
+
+            if etype != T::ARG_TYPE as c_int { return None };
+
+            let mut v = ptr::null_mut();
+            let mut i = 0;
+            ffi::dbus_message_iter_get_fixed_array(&mut si.0, &mut v as *mut _ as *mut c_void, &mut i);
+            if v == ptr::null_mut() {
+                assert_eq!(i, 0);
+                Some(&[][..])
+            } else {
+                Some(::std::slice::from_raw_parts(v, i as usize))
+            }
+        })
+    }
+}
+
+
+#[derive(Copy, Clone, Debug)]
+/// Append a D-Bus dict type (i e, an array of dict entries).
+///
+/// See the argument guide and module level documentation for details and alternatives.
+pub struct Dict<'a, K: DictKey, V: Arg, I>(I, PhantomData<(&'a Message, *const K, *const V)>);
+
+impl<'a, K: DictKey, V: Arg, I> Dict<'a, K, V, I> {
+    fn entry_sig() -> String { format!("{{{}{}}}", K::signature(), V::signature()) } 
+}
+
+impl<'a, K: 'a + DictKey, V: 'a + Append + Arg, I: Iterator<Item=(K, V)>> Dict<'a, K, V, I> {
+    /// Creates a new Dict from an iterator. The iterator is consumed when appended.
+    pub fn new<J: IntoIterator<IntoIter=I, Item=(K, V)>>(j: J) -> Dict<'a, K, V, I> { Dict(j.into_iter(), PhantomData) }
+}
+
+impl<'a, K: DictKey, V: Arg, I> Arg for Dict<'a, K, V, I> {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> {
+        Signature::from(format!("a{}", Self::entry_sig())) }
+}
+
+impl<'a, K: 'a + DictKey + Append, V: 'a + Append + Arg, I: Iterator<Item=(K, V)>> Append for Dict<'a, K, V, I> {
+    fn append(self, i: &mut IterAppend) {
+        let z = self.0;
+        i.append_container(Self::ARG_TYPE, Some(&CString::new(Self::entry_sig()).unwrap()), |s| for (k, v) in z {
+            s.append_container(ArgType::DictEntry, None, |ss| {
+                k.append(ss);
+                v.append(ss);
+            })
+        });
+    }
+}
+
+
+impl<'a, K: DictKey + Get<'a>, V: Arg + Get<'a>> Get<'a> for Dict<'a, K, V, Iter<'a>> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        i.recurse(Self::ARG_TYPE).map(|si| Dict(si, PhantomData))
+        // TODO: Verify full element signature?
+    }
+}
+
+impl<'a, K: DictKey + Get<'a>, V: Arg + Get<'a>> Iterator for Dict<'a, K, V, Iter<'a>> {
+    type Item = (K, V);
+    fn next(&mut self) -> Option<(K, V)> {
+        let i = self.0.recurse(ArgType::DictEntry).and_then(|mut si| {
+            let k = si.get();
+            if k.is_none() { return None };
+            assert!(si.next());
+            let v = si.get(); 
+            if v.is_none() { return None };
+            Some((k.unwrap(), v.unwrap()))
+        });
+        self.0.next();
+        i
+    }
+}
+
+impl<K: DictKey, V: Arg> Arg for HashMap<K, V> {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> {
+        Signature::from(format!("a{{{}{}}}", K::signature(), V::signature())) }
+}
+
+impl<K: DictKey + Append + Eq + Hash, V: Arg + Append> Append for HashMap<K, V> {
+    fn append(self, i: &mut IterAppend) {
+        Dict::new(self.into_iter()).append(i);
+    }
+}
+
+impl<'a, K: DictKey + Get<'a> + Eq + Hash, V: Arg + Get<'a>> Get<'a> for HashMap<K, V> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        // TODO: Full element signature is not verified.
+        Dict::get(i).map(|d| d.into_iter().collect())
+    }
+}
+
+impl<K: DictKey + RefArg + Eq + Hash, V: RefArg + Arg> RefArg for HashMap<K, V> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { format!("a{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature()).into() }
+    fn append(&self, i: &mut IterAppend) {
+        let sig = CString::new(format!("{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature())).unwrap();
+        i.append_container(ArgType::Array, Some(&sig), |s| for (k, v) in self {
+            s.append_container(ArgType::DictEntry, None, |ss| {
+                k.append(ss);
+                v.append(ss);
+            })
+        });
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
+        Some(Box::new(self.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalDict {
+            outer_sig: self.signature(),
+            data: self.iter().map(|(k, v)| (k.box_clone(), v.box_clone())).collect(),
+        })
+    }
+}
+
+impl<T: Arg> Arg for Vec<T> {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> { Signature::from(format!("a{}", T::signature())) }
+}
+
+impl<T: Arg + Append> Append for Vec<T> {
+    fn append(self, i: &mut IterAppend) {
+        Array::new(self).append(i);
+    }
+}
+
+impl<'a, T: Arg + Get<'a>> Get<'a> for Vec<T> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        <Array<T, Iter<'a>>>::get(i).map(|a| a.collect())
+    }
+}
+
+
+#[derive(Copy, Clone, Debug)]
+/// Represents a D-Bus Array. Maximum flexibility (wraps an iterator of items to append). 
+///
+/// See the argument guide and module level documentation for details and alternatives.
+pub struct Array<'a, T, I>(I, PhantomData<(*const T, &'a Message)>);
+
+impl<'a, T: 'a, I: Iterator<Item=T>> Array<'a, T, I> {
+    /// Creates a new Array from an iterator. The iterator is consumed when appending.
+    pub fn new<J: IntoIterator<IntoIter=I, Item=T>>(j: J) -> Array<'a, T, I> { Array(j.into_iter(), PhantomData) }
+}
+
+impl<'a, T: Arg, I> Arg for Array<'a, T, I> {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> { Signature::from(format!("a{}", T::signature())) }
+}
+
+impl<'a, T: 'a + Arg + Append, I: Iterator<Item=T>> Append for Array<'a, T, I> {
+    fn append(self, i: &mut IterAppend) {
+        let z = self.0;
+        i.append_container(ArgType::Array, Some(T::signature().as_cstr()), |s| for arg in z { arg.append(s) });
+    }
+}
+
+impl<'a, T: Arg + Get<'a>> Get<'a> for Array<'a, T, Iter<'a>> {
+    fn get(i: &mut Iter<'a>) -> Option<Array<'a, T, Iter<'a>>> {
+        i.recurse(Self::ARG_TYPE).map(|si| Array(si, PhantomData))
+        // TODO: Verify full element signature?
+    }
+}
+
+impl<'a, T: Get<'a>> Iterator for Array<'a, T, Iter<'a>> {
+    type Item = T;
+    fn next(&mut self) -> Option<T> {
+        let i = self.0.get();
+        self.0.next();
+        i
+    }
+}
+
+// Due to the strong typing here; RefArg is implemented only for T's that are both Arg and RefArg.
+// We need Arg for this to work for empty arrays (we can't get signature from first element if there is no elements).
+// We need RefArg for non-consuming append.
+impl<'a, T: 'a + Arg + fmt::Debug + RefArg, I: fmt::Debug + Clone + Iterator<Item=&'a T>> RefArg for Array<'static, T, I> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
+    fn append(&self, i: &mut IterAppend) {
+        let z = self.0.clone();
+        i.append_container(ArgType::Array, Some(<T as Arg>::signature().as_cstr()), |s|
+            for arg in z { (arg as &RefArg).append(s) }
+        );
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalArray {
+            inner_sig: <T as Arg>::signature(),
+            data: self.0.clone().map(|x| x.box_clone()).collect(),
+        })
+    }
+}
+
+fn get_fixed_array_refarg<'a, T: FixedArray + Clone + RefArg>(i: &mut Iter<'a>) -> Box<RefArg> {
+    let s = <&[T]>::get(i).unwrap();
+    Box::new(s.to_vec())
+}
+
+fn get_var_array_refarg<'a, T: 'static + RefArg + Arg, F: FnMut(&mut Iter<'a>) -> Option<T>>
+    (i: &mut Iter<'a>, mut f: F) -> Box<RefArg> {
+    let mut v: Vec<T> = vec!(); // dbus_message_iter_get_element_count might be O(n), better not use it
+    let mut si = i.recurse(ArgType::Array).unwrap();
+    while let Some(q) = f(&mut si) { v.push(q); si.next(); }
+    Box::new(v)
+}
+
+
+#[derive(Debug)]
+struct InternalDict<K> {
+   data: Vec<(K, Box<RefArg>)>,
+   outer_sig: Signature<'static>,
+}
+
+fn get_dict_refarg<'a, K, F: FnMut(&mut Iter<'a>) -> Option<K>>(i: &mut Iter<'a>, mut f: F) -> Box<RefArg>
+    where K: DictKey + 'static + RefArg + Clone
+ {
+    let mut data = vec!();
+    let outer_sig = i.signature();
+    let mut si = i.recurse(ArgType::Array).unwrap();
+    while let Some(mut d) = si.recurse(ArgType::DictEntry) {
+        let k = f(&mut d).unwrap();
+        d.next();
+        data.push((k, d.get_refarg().unwrap()));
+        si.next();
+    }
+    Box::new(InternalDict { data, outer_sig })
+}
+
+// This only happens from box_clone
+impl RefArg for InternalDict<Box<RefArg>> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { self.outer_sig.clone() }
+    fn append(&self, i: &mut IterAppend) {
+        let inner_sig = &self.outer_sig.as_cstr().to_bytes_with_nul()[1..];
+        let inner_sig = CStr::from_bytes_with_nul(inner_sig).unwrap();
+        i.append_container(ArgType::Array, Some(inner_sig), |s| for (k, v) in &self.data {
+            s.append_container(ArgType::DictEntry, None, |ss| {
+                k.append(ss);
+                v.append(ss);
+            })
+        });
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
+        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalDict {
+            data: self.data.iter().map(|(k, v)| (k.box_clone(), v.box_clone())).collect(),
+            outer_sig: self.outer_sig.clone(),
+        })
+    }
+}
+
+
+impl<K: DictKey + RefArg + Clone + 'static> RefArg for InternalDict<K> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { self.outer_sig.clone() }
+    fn append(&self, i: &mut IterAppend) {
+        let inner_sig = &self.outer_sig.as_cstr().to_bytes_with_nul()[1..];
+        let inner_sig = CStr::from_bytes_with_nul(inner_sig).unwrap();
+        i.append_container(ArgType::Array, Some(inner_sig), |s| for (k, v) in &self.data {
+            s.append_container(ArgType::DictEntry, None, |ss| {
+                k.append(ss);
+                v.append(ss);
+            })
+        });
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
+        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalDict {
+            data: self.data.iter().map(|(k, v)| (k.clone(), v.box_clone())).collect(),
+            outer_sig: self.outer_sig.clone(),
+        })
+    }
+} 
+
+
+// Fallback for Arrays of Arrays and Arrays of Structs.
+// We store the signature manually here and promise that it is correct for all elements
+// has that signature.
+#[derive(Debug)]
+struct InternalArray {
+   data: Vec<Box<RefArg>>,
+   inner_sig: Signature<'static>,
+}
+
+fn get_internal_array<'a>(i: &mut Iter<'a>) -> Box<RefArg> {
+    let mut si = i.recurse(ArgType::Array).unwrap();
+    let inner_sig = si.signature();
+    let data = si.collect::<Vec<_>>();
+    Box::new(InternalArray { data, inner_sig })
+}
+
+impl RefArg for InternalArray {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", self.inner_sig)) }
+    fn append(&self, i: &mut IterAppend) {
+        i.append_container(ArgType::Array, Some(self.inner_sig.as_cstr()), |s|
+            for arg in &self.data { (arg as &RefArg).append(s) }
+        );
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+        Some(Box::new(self.data.iter().map(|b| b as &RefArg)))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        Box::new(InternalArray {
+            data: self.data.iter().map(|x| x.box_clone()).collect(),
+            inner_sig: self.inner_sig.clone(),
+        })
+    }
+}
+
+pub fn get_array_refarg<'a>(i: &mut Iter<'a>) -> Box<RefArg> {
+    debug_assert!(i.arg_type() == ArgType::Array);
+    let etype = ArgType::from_i32(unsafe { ffi::dbus_message_iter_get_element_type(&mut i.0) } as i32).unwrap();
+
+    let x = match etype {
+        ArgType::Byte => get_fixed_array_refarg::<u8>(i),
+        ArgType::Int16 => get_fixed_array_refarg::<i16>(i),
+        ArgType::UInt16 => get_fixed_array_refarg::<u16>(i),
+        ArgType::Int32 => get_fixed_array_refarg::<i32>(i),
+        ArgType::UInt32 => get_fixed_array_refarg::<u32>(i),
+        ArgType::Int64 => get_fixed_array_refarg::<i64>(i),
+        ArgType::UInt64 => get_fixed_array_refarg::<u64>(i),
+        ArgType::Double => get_fixed_array_refarg::<f64>(i),
+	ArgType::String => get_var_array_refarg::<String, _>(i, |si| si.get()),
+	ArgType::ObjectPath => get_var_array_refarg::<Path<'static>, _>(i, |si| si.get::<Path>().map(|s| s.into_static())),
+	ArgType::Signature => get_var_array_refarg::<Signature<'static>, _>(i, |si| si.get::<Signature>().map(|s| s.into_static())),
+	ArgType::Variant => get_var_array_refarg::<Variant<Box<RefArg>>, _>(i, |si| Variant::new_refarg(si)),
+	ArgType::Boolean => get_var_array_refarg::<bool, _>(i, |si| si.get()),
+	ArgType::Invalid => panic!("Array with Invalid ArgType"),
+        ArgType::Array => get_internal_array(i),
+        ArgType::DictEntry => {
+            let key = ArgType::from_i32(i.signature().as_bytes()[2] as i32).unwrap(); // The third character, after "a{", is our key.
+            match key {
+                ArgType::Byte => get_dict_refarg::<u8, _>(i, |si| si.get()),
+                ArgType::Int16 => get_dict_refarg::<i16, _>(i, |si| si.get()),
+                ArgType::UInt16 => get_dict_refarg::<u16, _>(i, |si| si.get()),
+                ArgType::Int32 => get_dict_refarg::<i32, _>(i, |si| si.get()),
+                ArgType::UInt32 => get_dict_refarg::<u32, _>(i, |si| si.get()),
+                ArgType::Int64 => get_dict_refarg::<i64, _>(i, |si| si.get()),
+                ArgType::UInt64 => get_dict_refarg::<u64, _>(i, |si| si.get()),
+                ArgType::Double => get_dict_refarg::<f64, _>(i, |si| si.get()),
+                ArgType::Boolean => get_dict_refarg::<bool, _>(i, |si| si.get()),
+                // ArgType::UnixFd => get_dict_refarg::<OwnedFd, _>(i, |si| si.get()),
+                ArgType::String => get_dict_refarg::<String, _>(i, |si| si.get()),
+                ArgType::ObjectPath => get_dict_refarg::<Path<'static>, _>(i, |si| si.get::<Path>().map(|s| s.into_static())),
+                ArgType::Signature => get_dict_refarg::<Signature<'static>, _>(i, |si| si.get::<Signature>().map(|s| s.into_static())),
+                _ => panic!("Array with invalid dictkey ({:?})", key),
+            }
+        }
+        ArgType::UnixFd => get_var_array_refarg::<OwnedFd, _>(i, |si| si.get()),
+        ArgType::Struct => get_internal_array(i),
+    };
+
+    debug_assert_eq!(i.signature(), x.signature());
+    x
+}
+
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/arg/basic_impl.rs
@@ -0,0 +1,308 @@
+use ffi;
+use super::*;
+use super::check;
+use {Signature, Path, OwnedFd};
+use std::{ptr, any, mem};
+use std::ffi::CStr;
+use std::os::raw::{c_void, c_char, c_int};
+
+
+fn arg_append_basic<T>(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: T) {
+    let p = &v as *const _ as *const c_void;
+    unsafe {
+        check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, p));
+    };
+}
+
+fn arg_get_basic<T>(i: *mut ffi::DBusMessageIter, arg_type: ArgType) -> Option<T> {
+    unsafe {
+        let mut c: T = mem::zeroed();
+        if ffi::dbus_message_iter_get_arg_type(i) != arg_type as c_int { return None };
+        ffi::dbus_message_iter_get_basic(i, &mut c as *mut _ as *mut c_void);
+        Some(c)
+    }
+}
+
+fn arg_append_f64(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: f64) {
+    let p = &v as *const _ as *const c_void;
+    unsafe {
+        check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, p));
+    };
+}
+
+fn arg_get_f64(i: *mut ffi::DBusMessageIter, arg_type: ArgType) -> Option<f64> {
+    let mut c = 0f64;
+    unsafe {
+        if ffi::dbus_message_iter_get_arg_type(i) != arg_type as c_int { return None };
+        ffi::dbus_message_iter_get_basic(i, &mut c as *mut _ as *mut c_void);
+    }
+    Some(c)
+}
+
+fn arg_append_str(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: &CStr) {
+    let p = v.as_ptr();
+    let q = &p as *const _ as *const c_void;
+    unsafe {
+        check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, q));
+    };
+}
+
+unsafe fn arg_get_str<'a>(i: *mut ffi::DBusMessageIter, arg_type: ArgType) -> Option<&'a CStr> {
+    if ffi::dbus_message_iter_get_arg_type(i) != arg_type as c_int { return None };
+    let mut p = ptr::null_mut();
+    ffi::dbus_message_iter_get_basic(i, &mut p as *mut _ as *mut c_void);
+    Some(CStr::from_ptr(p as *const c_char))
+}
+
+
+
+
+// Implementation for basic types.
+
+macro_rules! integer_impl {
+    ($t: ident, $s: ident, $f: expr, $i: ident, $ii: expr, $u: ident, $uu: expr, $fff: ident, $ff: expr) => {
+
+impl Arg for $t {
+    const ARG_TYPE: ArgType = ArgType::$s;
+    #[inline]
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
+}
+
+impl Append for $t {
+    fn append(self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::$s, self) }
+}
+
+impl<'a> Get<'a> for $t {
+    fn get(i: &mut Iter) -> Option<Self> { arg_get_basic(&mut i.0, ArgType::$s) }
+}
+
+impl RefArg for $t {
+    #[inline]
+    fn arg_type(&self) -> ArgType { ArgType::$s }
+    #[inline]
+    fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
+    #[inline]
+    fn append(&self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::$s, *self) }
+    #[inline]
+    fn as_any(&self) -> &any::Any { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { let $i = *self; $ii }
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { let $u = *self; $uu }
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { let $fff = *self; $ff }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
+}
+
+impl DictKey for $t {}
+unsafe impl FixedArray for $t {}
+
+}} // End of macro_rules
+
+integer_impl!(u8, Byte, b"y\0", i, Some(i as i64),    u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i16, Int16, b"n\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
+integer_impl!(u16, UInt16, b"q\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i32, Int32, b"i\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
+integer_impl!(u32, UInt32, b"u\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i64, Int64, b"x\0", i, Some(i),         _u, None,          _f, None);
+integer_impl!(u64, UInt64, b"t\0", _i, None,          u, Some(u as u64), _f, None);
+
+
+macro_rules! refarg_impl {
+    ($t: ty, $i: ident, $ii: expr, $ss: expr, $uu: expr, $ff: expr) => {
+
+impl RefArg for $t {
+    #[inline]
+    fn arg_type(&self) -> ArgType { <$t as Arg>::ARG_TYPE }
+    #[inline]
+    fn signature(&self) -> Signature<'static> { <$t as Arg>::signature() }
+    #[inline]
+    fn append(&self, i: &mut IterAppend) { <$t as Append>::append(self.clone(), i) }
+    #[inline]
+    fn as_any(&self) -> &any::Any { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { let $i = self; $ii }
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { let $i = self; $uu }
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { let $i = self; $ff }
+    #[inline]
+    fn as_str(&self) -> Option<&str> { let $i = self; $ss }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
+}
+
+    }
+}
+
+
+impl Arg for bool {
+    const ARG_TYPE: ArgType = ArgType::Boolean;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"b\0") } }
+}
+impl Append for bool {
+    fn append(self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::Boolean, if self {1} else {0}) }
+}
+impl DictKey for bool {}
+impl<'a> Get<'a> for bool {
+    fn get(i: &mut Iter) -> Option<Self> { arg_get_basic::<u32>(&mut i.0, ArgType::Boolean).map(|q| q != 0) }
+}
+
+refarg_impl!(bool, _i, Some(if *_i { 1 } else { 0 }), None, Some(if *_i { 1 as u64 } else { 0 as u64 }), Some(if *_i { 1 as f64 } else { 0 as f64 }));
+
+impl Arg for f64 {
+    const ARG_TYPE: ArgType = ArgType::Double;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"d\0") } }
+}
+impl Append for f64 {
+    fn append(self, i: &mut IterAppend) { arg_append_f64(&mut i.0, ArgType::Double, self) }
+}
+impl DictKey for f64 {}
+impl<'a> Get<'a> for f64 {
+    fn get(i: &mut Iter) -> Option<Self> { arg_get_f64(&mut i.0, ArgType::Double) }
+}
+unsafe impl FixedArray for f64 {}
+
+refarg_impl!(f64, _i, None, None, None, Some(*_i));
+
+/// Represents a D-Bus string.
+impl<'a> Arg for &'a str {
+    const ARG_TYPE: ArgType = ArgType::String;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+}
+
+impl<'a> Append for &'a str {
+    fn append(self, i: &mut IterAppend) {
+        use std::borrow::Cow;
+        let b: &[u8] = self.as_bytes();
+        let v: Cow<[u8]> = if b.len() > 0 && b[b.len()-1] == 0 { Cow::Borrowed(b) }
+        else {
+            let mut bb: Vec<u8> = b.into();
+            bb.push(0);
+            Cow::Owned(bb)
+        };
+        let z = unsafe { CStr::from_ptr(v.as_ptr() as *const c_char) };
+        arg_append_str(&mut i.0, ArgType::String, &z)
+    }
+}
+impl<'a> DictKey for &'a str {}
+impl<'a> Get<'a> for &'a str {
+    fn get(i: &mut Iter<'a>) -> Option<&'a str> { unsafe { arg_get_str(&mut i.0, ArgType::String) }
+        .and_then(|s| s.to_str().ok()) }
+}
+
+impl<'a> Arg for String {
+    const ARG_TYPE: ArgType = ArgType::String;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+}
+impl<'a> Append for String {
+    fn append(mut self, i: &mut IterAppend) {
+        self.push_str("\0");
+        let s: &str = &self;
+        s.append(i)
+    }
+}
+impl<'a> DictKey for String {}
+impl<'a> Get<'a> for String {
+    fn get(i: &mut Iter<'a>) -> Option<String> { <&str>::get(i).map(|s| String::from(s)) }
+}
+
+refarg_impl!(String, _i, None, Some(&_i), None, None);
+
+/// Represents a D-Bus string.
+impl<'a> Arg for &'a CStr {
+    const ARG_TYPE: ArgType = ArgType::String;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+}
+
+/*
+/// Note: Will give D-Bus errors in case the CStr is not valid UTF-8.
+impl<'a> Append for &'a CStr {
+    fn append(self, i: &mut IterAppend) {
+        arg_append_str(&mut i.0, Self::arg_type(), &self)
+    }
+}
+*/
+
+impl<'a> DictKey for &'a CStr {}
+impl<'a> Get<'a> for &'a CStr {
+    fn get(i: &mut Iter<'a>) -> Option<&'a CStr> { unsafe { arg_get_str(&mut i.0, Self::ARG_TYPE) }}
+}
+
+impl Arg for OwnedFd {
+    const ARG_TYPE: ArgType = ArgType::UnixFd;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"h\0") } }
+}
+impl Append for OwnedFd {
+    fn append(self, i: &mut IterAppend) {
+        use std::os::unix::io::AsRawFd;
+        arg_append_basic(&mut i.0, ArgType::UnixFd, self.as_raw_fd())
+    }
+}
+impl DictKey for OwnedFd {}
+impl<'a> Get<'a> for OwnedFd {
+    fn get(i: &mut Iter) -> Option<Self> {
+        arg_get_basic(&mut i.0, ArgType::UnixFd).map(|q| OwnedFd::new(q)) 
+    }
+}
+
+refarg_impl!(OwnedFd, _i, { use std::os::unix::io::AsRawFd; Some(_i.as_raw_fd() as i64) }, None, None, None);
+
+macro_rules! string_impl {
+    ($t: ident, $s: ident, $f: expr) => {
+
+impl<'a> Arg for $t<'a> {
+    const ARG_TYPE: ArgType = ArgType::$s;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
+}
+
+impl RefArg for $t<'static> {
+    fn arg_type(&self) -> ArgType { ArgType::$s }
+    fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
+    fn append(&self, i: &mut IterAppend) { arg_append_str(&mut i.0, ArgType::$s, self.as_cstr()) }
+    #[inline]
+    fn as_any(&self) -> &any::Any { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    #[inline]
+    fn as_str(&self) -> Option<&str> { Some(self) }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone().into_static()) }
+}
+
+impl<'a> DictKey for $t<'a> {}
+
+impl<'a> Append for $t<'a> {
+    fn append(self, i: &mut IterAppend) {
+        arg_append_str(&mut i.0, ArgType::$s, self.as_cstr())
+    }
+}
+
+/*
+
+Unfortunately, this does not work because it conflicts with getting a $t<'static>.
+
+impl<'a> Get<'a> for $t<'a> {
+    fn get(i: &mut Iter<'a>) -> Option<$t<'a>> { unsafe { arg_get_str(&mut i.0, ArgType::$s) }
+        .map(|s| unsafe { $t::from_slice_unchecked(s.to_bytes_with_nul()) } ) }
+}
+*/
+
+impl<'a> Get<'a> for $t<'static> {
+    fn get(i: &mut Iter<'a>) -> Option<$t<'static>> { unsafe {
+        arg_get_str(&mut i.0, ArgType::$s).map(|s| $t::from_slice_unchecked(s.to_bytes_with_nul()).into_static())
+    }}
+}
+
+
+    }
+}
+
+string_impl!(Path, ObjectPath, b"o\0");
+string_impl!(Signature, Signature, b"g\0");
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/arg/mod.rs
@@ -0,0 +1,440 @@
+//! Types and traits for easily getting a message's arguments, or appening a message with arguments.
+//!
+//! Also see the arguments guide (in the examples directory).
+//!
+//! A message has `read1`, `read2` etc, and `append1`, `append2` etc, which is your
+//! starting point into this module's types. 
+//!
+//! **Append a**:
+//!
+//! `bool, u8, u16, u32, u64, i16, i32, i64, f64` - the corresponding D-Bus basic type
+//!
+//! `&str` - a D-Bus string. D-Bus strings do not allow null characters, so 
+//! if the string contains null characters, it will be cropped
+//! to only include the data before the null character. (Tip: This allows for skipping an
+//! allocation by writing a string literal which ends with a null character.)
+//!
+//! `&[T] where T: Append` - a D-Bus array. Note: can use an efficient fast-path in case of 
+//! T being an FixedArray type.
+//!
+//! `Array<T, I> where T: Append, I: Iterator<Item=T>` - a D-Bus array, maximum flexibility.
+//!
+//! `Variant<T> where T: Append` - a D-Bus variant.
+//!
+//! `(T1, T2) where T1: Append, T2: Append` - tuples are D-Bus structs. Implemented up to 12.
+//!
+//! `Dict<K, V, I> where K: Append + DictKey, V: Append, I: Iterator<Item=(&K, &V)>` - A D-Bus dict (array of dict entries).
+//!
+//! `Path` - a D-Bus object path.
+//!
+//! `Signature` - a D-Bus signature.
+//!
+//! `OwnedFd` - shares the file descriptor with the remote side.
+//!
+//! **Get / read a**:
+//!
+//! `bool, u8, u16, u32, u64, i16, i32, i64, f64` - the corresponding D-Bus basic type
+//!
+//! `&str`, `&CStr` - a D-Bus string. D-Bus strings are always UTF-8 and do not contain null characters.
+//!
+//! `&[T] where T: FixedArray` - a D-Bus array of integers or f64.
+//!
+//! `Array<T, Iter> where T: Get` - a D-Bus array, maximum flexibility. Implements Iterator so you can easily
+//! collect it into, e g, a `Vec`.
+//!
+//! `Variant<T> where T: Get` - a D-Bus variant. Use this type of Variant if you know the inner type.
+//!
+//! `Variant<Iter>` - a D-Bus variant. This type of Variant allows you to examine the inner type.
+//!
+//! `(T1, T2) where T1: Get, T2: Get` - tuples are D-Bus structs. Implemented up to 12.
+//!
+//! `Dict<K, V, Iter> where K: Get + DictKey, V: Get` - A D-Bus dict (array of dict entries). Implements Iterator so you can easily
+//! collect it into, e g, a `HashMap`.
+//!
+//! `Path` - a D-Bus object path.
+//!
+//! `Signature` - a D-Bus signature.
+//!
+//! `OwnedFd` - a file descriptor sent from the remote side.
+//!
+
+mod msgarg;
+mod basic_impl;
+mod variantstruct_impl;
+mod array_impl;
+
+pub use self::msgarg::{Arg, FixedArray, Get, DictKey, Append, RefArg, AppendAll, ReadAll, cast, cast_mut};
+pub use self::array_impl::{Array, Dict};
+pub use self::variantstruct_impl::Variant;
+
+use std::{fmt, mem, ptr, error};
+use {ffi, Message, Signature, Path, OwnedFd};
+use std::ffi::{CStr, CString};
+use std::os::raw::{c_void, c_int};
+
+
+fn check(f: &str, i: u32) { if i == 0 { panic!("D-Bus error: '{}' failed", f) }} 
+
+fn ffi_iter() -> ffi::DBusMessageIter { unsafe { mem::zeroed() }} 
+
+#[derive(Clone, Copy)]
+/// Helper struct for appending one or more arguments to a Message. 
+pub struct IterAppend<'a>(ffi::DBusMessageIter, &'a Message);
+
+impl<'a> IterAppend<'a> {
+    /// Creates a new IterAppend struct.
+    pub fn new(m: &'a mut Message) -> IterAppend<'a> { 
+        let mut i = ffi_iter();
+        unsafe { ffi::dbus_message_iter_init_append(m.ptr(), &mut i) };
+        IterAppend(i, m)
+    }
+
+    /// Appends the argument.
+    pub fn append<T: Append>(&mut self, a: T) { a.append(self) }
+
+    fn append_container<F: FnOnce(&mut IterAppend<'a>)>(&mut self, arg_type: ArgType, sig: Option<&CStr>, f: F) {
+        let mut s = IterAppend(ffi_iter(), self.1);
+        let p = sig.map(|s| s.as_ptr()).unwrap_or(ptr::null());
+        check("dbus_message_iter_open_container",
+            unsafe { ffi::dbus_message_iter_open_container(&mut self.0, arg_type as c_int, p, &mut s.0) });
+        f(&mut s);
+        check("dbus_message_iter_close_container",
+            unsafe { ffi::dbus_message_iter_close_container(&mut self.0, &mut s.0) });
+    }
+
+    /// Low-level function to append a variant.
+    ///
+    /// Use in case the `Variant` struct is not flexible enough -
+    /// the easier way is to just call e g "append1" on a message and supply a `Variant` parameter.
+    ///
+    /// In order not to get D-Bus errors: during the call to "f" you need to call "append" on
+    /// the supplied `IterAppend` exactly once,
+    /// and with a value which has the same signature as inner_sig.  
+    pub fn append_variant<F: FnOnce(&mut IterAppend<'a>)>(&mut self, inner_sig: &Signature, f: F) {
+        self.append_container(ArgType::Variant, Some(inner_sig.as_cstr()), f)
+    }
+
+    /// Low-level function to append an array.
+    ///
+    /// Use in case the `Array` struct is not flexible enough -
+    /// the easier way is to just call e g "append1" on a message and supply an `Array` parameter.
+    ///
+    /// In order not to get D-Bus errors: during the call to "f", you should only call "append" on
+    /// the supplied `IterAppend` with values which has the same signature as inner_sig.
+    pub fn append_array<F: FnOnce(&mut IterAppend<'a>)>(&mut self, inner_sig: &Signature, f: F) {
+        self.append_container(ArgType::Array, Some(inner_sig.as_cstr()), f)
+    }
+
+    /// Low-level function to append a struct.
+    ///
+    /// Use in case tuples are not flexible enough -
+    /// the easier way is to just call e g "append1" on a message and supply a tuple parameter.
+    pub fn append_struct<F: FnOnce(&mut IterAppend<'a>)>(&mut self, f: F) {
+        self.append_container(ArgType::Struct, None, f)
+    }
+
+    /// Low-level function to append a dict entry.
+    ///
+    /// Use in case the `Dict` struct is not flexible enough -
+    /// the easier way is to just call e g "append1" on a message and supply a `Dict` parameter.
+    ///
+    /// In order not to get D-Bus errors: during the call to "f", you should call "append" once
+    /// for the key, then once for the value. You should only call this function for a subiterator
+    /// you got from calling "append_dict", and signatures need to match what you specified in "append_dict".
+    pub fn append_dict_entry<F: FnOnce(&mut IterAppend<'a>)>(&mut self, f: F) {
+        self.append_container(ArgType::DictEntry, None, f)
+    }
+
+    /// Low-level function to append a dict.
+    ///
+    /// Use in case the `Dict` struct is not flexible enough -
+    /// the easier way is to just call e g "append1" on a message and supply a `Dict` parameter.
+    ///
+    /// In order not to get D-Bus errors: during the call to "f", you should only call "append_dict_entry"
+    /// for the subiterator - do this as many times as the number of dict entries.
+    pub fn append_dict<F: FnOnce(&mut IterAppend<'a>)>(&mut self, key_sig: &Signature, value_sig: &Signature, f: F) {
+        let sig = format!("{{{}{}}}", key_sig, value_sig);
+        self.append_container(Array::<bool,()>::ARG_TYPE, Some(&CString::new(sig).unwrap()), f);
+    }
+}
+
+
+
+#[derive(Clone, Copy)]
+/// Helper struct for retrieve one or more arguments from a Message.
+pub struct Iter<'a>(ffi::DBusMessageIter, &'a Message, u32);
+
+impl<'a> Iter<'a> {
+    /// Creates a new struct for iterating over the arguments of a message, starting with the first argument. 
+    pub fn new(m: &'a Message) -> Iter<'a> { 
+        let mut i = ffi_iter();
+        unsafe { ffi::dbus_message_iter_init(m.ptr(), &mut i) };
+        Iter(i, m, 0)
+    }
+
+    /// Returns the current argument, if T is the argument type. Otherwise returns None.
+    pub fn get<T: Get<'a>>(&mut self) -> Option<T> {
+        T::get(self)
+    }
+
+    /// Returns the current argument as a trait object (experimental).
+    ///
+    /// Note: For the more complex arguments (arrays / dicts / structs, and especially
+    /// combinations thereof), their internal representations are still a bit in flux.
+    /// Instead, use as_iter() to read the values of those.
+    ///
+    /// The rest are unlikely to change - Variants are `Variant<Box<RefArg>>`, strings are `String`,
+    /// paths are `Path<'static>`, signatures are `Signature<'static>`, Int32 are `i32s` and so on.
+    pub fn get_refarg(&mut self) -> Option<Box<RefArg + 'static>> {
+        Some(match self.arg_type() {
+	    ArgType::Array => array_impl::get_array_refarg(self),
+	    ArgType::Variant => Box::new(Variant::new_refarg(self).unwrap()),
+	    ArgType::Boolean => Box::new(self.get::<bool>().unwrap()),
+	    ArgType::Invalid => return None,
+	    ArgType::String => Box::new(self.get::<String>().unwrap()),
+	    ArgType::DictEntry => unimplemented!(),
+	    ArgType::Byte => Box::new(self.get::<u8>().unwrap()),
+	    ArgType::Int16 => Box::new(self.get::<i16>().unwrap()),
+	    ArgType::UInt16 => Box::new(self.get::<u16>().unwrap()),
+	    ArgType::Int32 => Box::new(self.get::<i32>().unwrap()),
+	    ArgType::UInt32 => Box::new(self.get::<u32>().unwrap()),
+	    ArgType::Int64 => Box::new(self.get::<i64>().unwrap()),
+	    ArgType::UInt64 => Box::new(self.get::<u64>().unwrap()),
+	    ArgType::Double => Box::new(self.get::<f64>().unwrap()),
+	    ArgType::UnixFd => Box::new(self.get::<OwnedFd>().unwrap()),
+	    ArgType::Struct => Box::new(self.recurse(ArgType::Struct).unwrap().collect::<Vec<_>>()),
+	    ArgType::ObjectPath => Box::new(self.get::<Path>().unwrap().into_static()),
+	    ArgType::Signature => Box::new(self.get::<Signature>().unwrap().into_static()),
+        })
+    }
+
+    /// Returns the type signature for the current argument.
+    pub fn signature(&mut self) -> Signature<'static> {
+        unsafe {
+            let c = ffi::dbus_message_iter_get_signature(&mut self.0);
+            assert!(c != ptr::null_mut());
+            let cc = CStr::from_ptr(c);
+            let r = Signature::new(cc.to_bytes());
+            ffi::dbus_free(c as *mut c_void);
+            r.unwrap()
+        }
+    }
+
+    /// The raw arg_type for the current item.
+    ///
+    /// Unlike Arg::arg_type, this requires access to self and is not a static method.
+    /// You can match this against Arg::arg_type for different types to understand what type the current item is.
+    /// In case you're past the last argument, this function will return 0.
+    pub fn arg_type(&mut self) -> ArgType {
+        let s = unsafe { ffi::dbus_message_iter_get_arg_type(&mut self.0) };
+        ArgType::from_i32(s as i32).unwrap()
+    }
+
+    /// Returns false if there are no more items.
+    pub fn next(&mut self) -> bool {
+        self.2 += 1;
+        unsafe { ffi::dbus_message_iter_next(&mut self.0) != 0 } 
+    }
+
+    /// Wrapper around `get` and `next`. Calls `get`, and then `next` if `get` succeeded. 
+    ///
+    /// Also returns a `Result` rather than an `Option` to give an error if successful.
+    ///
+    /// # Example
+    /// ```ignore
+    /// struct ServiceBrowserItemNew {
+    ///     interface: i32,
+    ///     protocol: i32,
+    ///     name: String,
+    ///     item_type: String,
+    ///     domain: String,
+    ///     flags: u32,
+    /// }
+    ///
+    /// fn service_browser_item_new_msg(m: &Message) -> Result<ServiceBrowserItemNew, TypeMismatchError> {
+    ///     let mut iter = m.iter_init();
+    ///     Ok(ServiceBrowserItemNew {
+    ///         interface: iter.read()?,
+    ///         protocol: iter.read()?,
+    ///         name: iter.read()?,
+    ///         item_type: iter.read()?,
+    ///         domain: iter.read()?,
+    ///         flags: iter.read()?,
+    ///     })
+    /// }
+    /// ```
+    pub fn read<T: Arg + Get<'a>>(&mut self) -> Result<T, TypeMismatchError> {
+        let r = try!(self.get().ok_or_else(||
+             TypeMismatchError { expected: T::ARG_TYPE, found: self.arg_type(), position: self.2 }));
+        self.next();
+        Ok(r)
+    }
+
+    /// If the current argument is a container of the specified arg_type, then a new
+    /// Iter is returned which is for iterating over the contents inside the container.
+    ///
+    /// Primarily for internal use (the "get" function is more ergonomic), but could be
+    /// useful for recursing into containers with unknown types.
+    pub fn recurse(&mut self, arg_type: ArgType) -> Option<Iter<'a>> {
+        let containers = [ArgType::Array, ArgType::DictEntry, ArgType::Struct, ArgType::Variant];
+        if !containers.iter().any(|&t| t == arg_type) { return None; }
+
+        let mut subiter = ffi_iter();
+        unsafe {
+            if ffi::dbus_message_iter_get_arg_type(&mut self.0) != arg_type as c_int { return None };
+            ffi::dbus_message_iter_recurse(&mut self.0, &mut subiter)
+        }
+        Some(Iter(subiter, self.1, 0))
+    }
+}
+
+impl<'a> fmt::Debug for Iter<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let mut z = self.clone();
+        let mut t = f.debug_tuple("Iter");
+        loop {
+            t.field(&z.arg_type());
+            if !z.next() { break }
+        }
+        t.finish()
+    }
+}
+
+impl<'a> Iterator for Iter<'a> {
+    type Item = Box<RefArg + 'static>;
+    fn next(&mut self) -> Option<Self::Item> {
+        let r = self.get_refarg();
+        if r.is_some() { self.next(); }
+        r
+    }
+}
+
+/// Type of Argument
+///
+/// use this to figure out, e g, which type of argument is at the current position of Iter. 
+#[repr(u8)]
+#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
+pub enum ArgType {
+    /// Dicts are Arrays of dict entries, so Dict types will have Array as ArgType.
+    Array = ffi::DBUS_TYPE_ARRAY as u8,
+    /// Variant
+    Variant = ffi::DBUS_TYPE_VARIANT as u8,
+    /// bool
+    Boolean = ffi::DBUS_TYPE_BOOLEAN as u8,
+    /// Invalid arg type - this is also the ArgType returned when there are no more arguments available.
+    Invalid = ffi::DBUS_TYPE_INVALID as u8,
+    /// String
+    String = ffi::DBUS_TYPE_STRING as u8,
+    /// Dict entry; you'll usually not encounter this one as dicts are arrays of dict entries.
+    DictEntry = ffi::DBUS_TYPE_DICT_ENTRY as u8,
+    /// u8
+    Byte = ffi::DBUS_TYPE_BYTE as u8,
+    /// i16
+    Int16 = ffi::DBUS_TYPE_INT16 as u8,
+    /// u16
+    UInt16 = ffi::DBUS_TYPE_UINT16 as u8,
+    /// i32
+    Int32 = ffi::DBUS_TYPE_INT32 as u8,
+    /// u32
+    UInt32 = ffi::DBUS_TYPE_UINT32 as u8,
+    /// i64
+    Int64 = ffi::DBUS_TYPE_INT64 as u8,
+    /// u64
+    UInt64 = ffi::DBUS_TYPE_UINT64 as u8,
+    /// f64
+    Double = ffi::DBUS_TYPE_DOUBLE as u8,
+    /// OwnedFd
+    UnixFd = ffi::DBUS_TYPE_UNIX_FD as u8,
+    /// Use tuples or Vec<Box<RefArg>> to read/write structs.
+    Struct = ffi::DBUS_TYPE_STRUCT as u8,
+    /// Path
+    ObjectPath = ffi::DBUS_TYPE_OBJECT_PATH as u8,
+    /// Signature
+    Signature = ffi::DBUS_TYPE_SIGNATURE as u8,
+}
+
+const ALL_ARG_TYPES: [(ArgType, &'static str); 18] =
+    [(ArgType::Variant, "Variant"),
+    (ArgType::Array, "Array/Dict"),
+    (ArgType::Struct, "Struct"),
+    (ArgType::String, "String"),
+    (ArgType::DictEntry, "Dict entry"),
+    (ArgType::ObjectPath, "Path"),
+    (ArgType::Signature, "Signature"),
+    (ArgType::UnixFd, "OwnedFd"),
+    (ArgType::Boolean, "bool"),
+    (ArgType::Byte, "u8"),
+    (ArgType::Int16, "i16"),
+    (ArgType::Int32, "i32"),
+    (ArgType::Int64, "i64"),
+    (ArgType::UInt16, "u16"),
+    (ArgType::UInt32, "u32"),
+    (ArgType::UInt64, "u64"),
+    (ArgType::Double, "f64"),
+    (ArgType::Invalid, "nothing")];
+
+impl ArgType {
+    /// A str corresponding to the name of a Rust type. 
+    pub fn as_str(self) -> &'static str {
+        ALL_ARG_TYPES.iter().skip_while(|a| a.0 != self).next().unwrap().1
+    }
+
+    /// Converts an i32 to an ArgType (or an error).
+    pub fn from_i32(i: i32) -> Result<ArgType, String> {
+        for &(a, _) in &ALL_ARG_TYPES {
+            if a as i32 == i { return Ok(a); }
+        }
+        Err(format!("Invalid ArgType {} ({})", i, i as u8 as char))
+    }
+}
+
+
+/// Error struct to indicate a D-Bus argument type mismatch.
+///
+/// Might be returned from `iter::read()`. 
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct TypeMismatchError {
+    expected: ArgType,
+    found: ArgType,
+    position: u32,
+}
+
+impl TypeMismatchError {
+    /// The ArgType we were trying to read, but failed
+    pub fn expected_arg_type(&self) -> ArgType { self.expected }
+
+    /// The ArgType we should have been trying to read, if we wanted the read to succeed 
+    pub fn found_arg_type(&self) -> ArgType { self.found }
+
+    /// At what argument was the error found?
+    ///
+    /// Returns 0 for first argument, 1 for second argument, etc.
+    pub fn pos(&self) -> u32 { self.position }
+}
+
+impl error::Error for TypeMismatchError {
+    fn description(&self) -> &str { "D-Bus argument type mismatch" }
+    fn cause(&self) -> Option<&error::Error> { None }
+}
+
+impl fmt::Display for TypeMismatchError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{} at position {}: expected {}, found {}",
+            (self as &error::Error).description(),
+            self.position, self.expected.as_str(),
+            if self.expected == self.found { "same but still different somehow" } else { self.found.as_str() }
+        )
+    }
+}
+
+
+#[allow(dead_code)]
+fn test_compile() {
+    let mut q = IterAppend::new(unsafe { mem::transmute(0usize) });
+
+    q.append(5u8);
+    q.append(Array::new(&[5u8, 6, 7]));
+    q.append((8u8, &[9u8, 6, 7][..]));
+    q.append(Variant((6u8, 7u8)));
+}
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/arg/msgarg.rs
@@ -0,0 +1,426 @@
+#![allow(dead_code)]
+
+use {Signature, Message, arg::TypeMismatchError};
+use std::{fmt, any};
+use std::sync::Arc;
+use std::rc::Rc;
+
+use super::{Iter, IterAppend, ArgType};
+
+/// Types that can represent a D-Bus message argument implement this trait.
+///
+/// Types should also implement either Append or Get to be useful. 
+pub trait Arg {
+    /// The corresponding D-Bus argument type code. 
+    const ARG_TYPE: ArgType;
+    /// The corresponding D-Bus argument type code; just returns ARG_TYPE. 
+    ///
+    /// For backwards compatibility.
+    #[deprecated(note = "Use associated constant ARG_TYPE instead")]
+    fn arg_type() -> ArgType { return Self::ARG_TYPE; }
+    /// The corresponding D-Bus type signature for this type. 
+    fn signature() -> Signature<'static>;
+}
+
+/// Types that can be appended to a message as arguments implement this trait.
+pub trait Append: Sized {
+    /// Performs the append operation.
+    fn append(self, &mut IterAppend);
+}
+
+/// Helper trait to append many arguments to a message.
+pub trait AppendAll: Sized {
+    /// Performs the append operation.
+    fn append(self, &mut IterAppend);
+}
+
+/// Types that can be retrieved from a message as arguments implement this trait.
+pub trait Get<'a>: Sized {
+    /// Performs the get operation.
+    fn get(i: &mut Iter<'a>) -> Option<Self>;
+}
+
+/// Helper trait to read all arguments from a message.
+pub trait ReadAll: Sized {
+    /// Performs the read operation.
+    fn read(i: &mut Iter) -> Result<Self, TypeMismatchError>;
+}
+
+
+/// Object safe version of Arg + Append + Get.
+pub trait RefArg: fmt::Debug {
+    /// The corresponding D-Bus argument type code.
+    fn arg_type(&self) -> ArgType;
+    /// The corresponding D-Bus type signature for this type. 
+    fn signature(&self) -> Signature<'static>;
+    /// Performs the append operation.
+    fn append(&self, &mut IterAppend);
+    /// Transforms this argument to Any (which can be downcasted to read the current value).
+    ///
+    /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
+    /// and as_any should not be relied upon for these types. Use as_iter instead.
+    fn as_any(&self) -> &any::Any where Self: 'static;
+    /// Transforms this argument to Any (which can be downcasted to read the current value).
+    ///
+    /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
+    /// and as_any should not be relied upon for these types. Use as_iter instead.
+    ///
+    /// # Panic
+    /// Will panic if the interior cannot be made mutable, e g, if encapsulated
+    /// inside a Rc with a reference count > 1.
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static;
+    /// Try to read the argument as an i64.
+    ///
+    /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UnixFd.
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { None }
+    /// Try to read the argument as an u64.
+    ///
+    /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, UInt64.
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { None }
+    /// Try to read the argument as an f64.
+    ///
+    /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, Double.
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { None }
+    /// Try to read the argument as a str.
+    ///
+    /// Works for: String, ObjectPath, Signature.
+    #[inline]
+    fn as_str(&self) -> Option<&str> { None }
+    /// Try to read the argument as an iterator.
+    ///
+    /// Works for: Array/Dict, Struct, Variant.
+    #[inline]
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { None }
+    /// Deep clone of the RefArg, causing the result to be 'static.
+    ///
+    /// Usable as an escape hatch in case of lifetime problems with RefArg.
+    ///
+    /// In case of complex types (Array, Dict, Struct), the clone is not guaranteed
+    /// to have the same internal representation as the original.
+    fn box_clone(&self) -> Box<RefArg + 'static> { unimplemented!() /* Needed for backwards comp */ }
+}
+
+impl<'a> Get<'a> for Box<RefArg> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> { i.get_refarg() }
+}
+
+/// Cast a RefArg as a specific type (shortcut for any + downcast)
+#[inline]
+pub fn cast<'a, T: 'static>(a: &'a (RefArg + 'static)) -> Option<&'a T> { a.as_any().downcast_ref() }
+
+/// Cast a RefArg as a specific type (shortcut for any_mut + downcast_mut)
+///
+/// # Panic
+/// Will panic if the interior cannot be made mutable, e g, if encapsulated
+/// inside a Rc with a reference count > 1.
+#[inline]
+pub fn cast_mut<'a, T: 'static>(a: &'a mut (RefArg + 'static)) -> Option<&'a mut T> { a.as_any_mut().downcast_mut() }
+
+/// If a type implements this trait, it means the size and alignment is the same
+/// as in D-Bus. This means that you can quickly append and get slices of this type.
+///
+/// Note: Booleans do not implement this trait because D-Bus booleans are 4 bytes and Rust booleans are 1 byte.
+pub unsafe trait FixedArray: Arg + 'static + Clone + Copy {}
+
+/// Types that can be used as keys in a dict type implement this trait. 
+pub trait DictKey: Arg {}
+
+
+
+/// Simple lift over reference to value - this makes some iterators more ergonomic to use
+impl<'a, T: Arg> Arg for &'a T {
+    const ARG_TYPE: ArgType = T::ARG_TYPE;
+    fn signature() -> Signature<'static> { T::signature() }
+}
+impl<'a, T: Append + Clone> Append for &'a T {
+    fn append(self, i: &mut IterAppend) { self.clone().append(i) }
+}
+impl<'a, T: DictKey> DictKey for &'a T {}
+
+impl<'a, T: RefArg + ?Sized> RefArg for &'a T {
+    #[inline]
+    fn arg_type(&self) -> ArgType { (&**self).arg_type() }
+    #[inline]
+    fn signature(&self) -> Signature<'static> { (&**self).signature() }
+    #[inline]
+    fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
+    #[inline]
+    fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where T: 'static { unreachable!() }
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
+    #[inline]
+    fn as_str(&self) -> Option<&str> { (&**self).as_str() }
+    #[inline]
+    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> { (&**self).as_iter() }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+}
+
+
+
+macro_rules! deref_impl {
+    ($t: ident, $ss: ident, $make_mut: expr) => {
+
+impl<T: RefArg + ?Sized> RefArg for $t<T> {
+    #[inline]
+    fn arg_type(&self) -> ArgType { (&**self).arg_type() }
+    #[inline]
+    fn signature(&self) -> Signature<'static> { (&**self).signature() }
+    #[inline]
+    fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
+    #[inline]
+    fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
+    #[inline]
+    fn as_any_mut<'a>(&'a mut $ss) -> &'a mut any::Any where T: 'static { $make_mut.as_any_mut() }
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
+    #[inline]
+    fn as_str(&self) -> Option<&str> { (&**self).as_str() }
+    #[inline]
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { (&**self).as_iter() }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+}
+impl<T: DictKey> DictKey for $t<T> {}
+
+impl<T: Arg> Arg for $t<T> {
+    const ARG_TYPE: ArgType = T::ARG_TYPE;
+    fn signature() -> Signature<'static> { T::signature() }
+}
+impl<'a, T: Get<'a>> Get<'a> for $t<T> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> { T::get(i).map(|v| $t::new(v)) }
+}
+
+    }
+}
+
+impl<T: Append> Append for Box<T> {
+    fn append(self, i: &mut IterAppend) { let q: T = *self; q.append(i) }
+}
+
+deref_impl!(Box, self, &mut **self );
+deref_impl!(Rc, self, Rc::get_mut(self).unwrap());
+deref_impl!(Arc, self, Arc::get_mut(self).unwrap());
+
+/// Internal trait to help generics. Implemented for (), (A1), (A1, A2) and so on (where A1: Arg, A2: Arg etc).
+///
+/// You would probably not use this trait directly, instead use generic functions which
+/// take ArgBuilder as an argument. It helps reading and appending multiple arguments
+/// to/from a message in one go.
+pub trait ArgBuilder: Sized {
+    /// A tuple of &static str. Used for introspection.
+    type strs;
+    /// Low-level introspection helper method.
+    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(a: Self::strs, f: F);
+    /// Low-level method to read arguments from a message.
+    fn read(msg: &Message) -> Result<Self, TypeMismatchError>;
+    /// Low-level method to append arguments to a message.
+    fn append(self, msg: &mut Message);
+}
+
+impl ArgBuilder for () {
+    type strs = ();
+    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(_: Self::strs, _: F) {}
+    fn read(_: &Message) -> Result<Self, TypeMismatchError> { Ok(()) }
+    fn append(self, _: &mut Message) {}
+}
+
+macro_rules! argbuilder_impl {
+    ($($n: ident $t: ident $s: ty,)+) => {
+
+impl<$($t: Arg + Append + for<'z> Get<'z>),*> ArgBuilder for ($($t,)*) {
+    type strs = ($(&'static $s,)*); 
+    fn strs_sig<Q: FnMut(&'static str, Signature<'static>)>(z: Self::strs, mut q: Q) {
+        let ( $($n,)*) = z;
+        $( q($n, $t::signature()); )*
+    }
+
+    fn read(msg: &Message) -> Result<Self, TypeMismatchError> {
+        let mut ii = msg.iter_init();
+        $( let $n = ii.read()?; )*
+        Ok(($( $n, )* ))
+    }
+
+    fn append(self, msg: &mut Message) {
+        let ( $($n,)*) = self;
+        let mut ia = IterAppend::new(msg);
+        $( ia.append($n); )*
+    }
+}
+
+impl<$($t: Append),*> AppendAll for ($($t,)*) {
+    fn append(self, ia: &mut IterAppend) {
+        let ( $($n,)*) = self;
+        $( ia.append($n); )*
+    }
+}
+
+impl<$($t: Arg + for<'z> Get<'z>),*> ReadAll for ($($t,)*) {
+    fn read(ii: &mut Iter) -> Result<Self, TypeMismatchError> {
+        $( let $n = ii.read()?; )*
+        Ok(($( $n, )* ))
+    }
+}
+
+
+    }
+}
+
+argbuilder_impl!(a A str,);
+argbuilder_impl!(a A str, b B str,);
+argbuilder_impl!(a A str, b B str, c C str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str,);
+argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str,);
+
+
+
+#[cfg(test)]
+mod test {
+    extern crate tempdir;
+
+    use {Connection, ConnectionItem, Message, BusType, Path, Signature};
+    use arg::{Array, Variant, Dict, Iter, ArgType, TypeMismatchError, RefArg, cast};
+
+    use std::collections::HashMap;
+
+    #[test]
+    fn refarg() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/mooh").unwrap();
+        let m = Message::new_method_call(&c.unique_name(), "/mooh", "com.example.hello", "Hello").unwrap();
+
+        let mut vv: Vec<Variant<Box<RefArg>>> = vec!();
+        vv.push(Variant(Box::new(5i32)));
+        vv.push(Variant(Box::new(String::from("Hello world"))));
+        let m = m.append_ref(&vv);
+
+        let (f1, f2) = (false, 7u64);
+        let mut v: Vec<&RefArg> = vec!();
+        v.push(&f1);
+        v.push(&f2);
+        let m = m.append_ref(&v);
+        let vi32 = vec![7i32, 9i32];
+        let vstr: Vec<String> = ["This", "is", "dbus", "rs"].iter().map(|&s| s.into()).collect();
+        let m = m.append_ref(&[&vi32 as &RefArg, &vstr as &RefArg]);
+        let mut map = HashMap::new();
+        map.insert(true, String::from("Yes"));
+        map.insert(false, String::from("No"));
+        let m = m.append_ref(&[&map as &RefArg, &1.5f64 as &RefArg]);
+
+        c.send(m).unwrap();
+
+        for n in c.iter(1000) {
+            if let ConnectionItem::MethodCall(m) = n {
+                let rv: Vec<Box<RefArg + 'static>> = m.iter_init().collect();
+                println!("Receiving {:?}", rv);
+                let rv0: &Variant<Box<RefArg>> = cast(&rv[0]).unwrap(); 
+                let rv00: &i32 = cast(&rv0.0).unwrap();
+                assert_eq!(rv00, &5i32);
+                assert_eq!(Some(&false), rv[2].as_any().downcast_ref::<bool>());
+                assert_eq!(Some(&vi32), rv[4].as_any().downcast_ref::<Vec<i32>>());
+                assert_eq!(Some(&vstr), rv[5].as_any().downcast_ref::<Vec<String>>());
+                let mut diter = rv[6].as_iter().unwrap();
+                {
+                    let mut mmap: HashMap<bool, String> = HashMap::new();
+                    while let Some(k) = diter.next() {
+                        let x: String = diter.next().unwrap().as_str().unwrap().into();
+                        mmap.insert(*cast::<bool>(&k.box_clone()).unwrap(), x);
+                    }
+                    assert_eq!(mmap[&true], "Yes");
+                }
+                let mut iter = rv[6].as_iter().unwrap();
+                assert!(iter.next().unwrap().as_i64().is_some());
+                assert!(iter.next().unwrap().as_str().is_some());
+                assert!(iter.next().unwrap().as_str().is_none());
+                assert!(iter.next().unwrap().as_i64().is_none());
+                assert!(iter.next().is_none());
+                assert!(rv[7].as_f64().unwrap() > 1.0);
+                assert!(rv[7].as_f64().unwrap() < 2.0);
+                break;
+            }
+        }
+    }
+
+    #[test]
+    fn message_types() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        let m = m.append1(2000u16);
+        let m = m.append1(Array::new(&vec![129u8, 5, 254]));
+        let m = m.append2(Variant(&["Hello", "world"][..]), &[32768u16, 16u16, 12u16][..]);
+        let m = m.append3(-1i32, &*format!("Hello world"), -3.14f64);
+        let m = m.append1((256i16, Variant(18_446_744_073_709_551_615u64)));
+        let m = m.append2(Path::new("/a/valid/path").unwrap(), Signature::new("a{sv}").unwrap());
+        let mut z = HashMap::new();
+        z.insert(123543u32, true);
+        z.insert(0u32, false);
+        let m = m.append1(Dict::new(&z));
+        let sending = format!("{:?}", m.iter_init());
+        println!("Sending {}", sending);
+        c.send(m).unwrap();
+
+        for n in c.iter(1000) {
+            match n {
+                ConnectionItem::MethodCall(m) => {
+                    use super::Arg;
+                    let receiving = format!("{:?}", m.iter_init());
+                    println!("Receiving {}", receiving);
+                    assert_eq!(sending, receiving);
+
+                    assert_eq!(2000u16, m.get1().unwrap());
+                    assert_eq!(m.get2(), (Some(2000u16), Some(&[129u8, 5, 254][..])));
+                    assert_eq!(m.read2::<u16, bool>().unwrap_err(),
+                        TypeMismatchError { position: 1, found: ArgType::Array, expected: ArgType::Boolean });
+
+                    let mut g = m.iter_init();
+                    let e = g.read::<u32>().unwrap_err();
+                    assert_eq!(e.pos(), 0);
+                    assert_eq!(e.expected_arg_type(), ArgType::UInt32);
+                    assert_eq!(e.found_arg_type(), ArgType::UInt16);
+
+                    assert!(g.next() && g.next());
+                    let v: Variant<Iter> = g.get().unwrap();
+                    let mut viter = v.0;
+                    assert_eq!(viter.arg_type(), Array::<&str,()>::ARG_TYPE);
+                    let a: Array<&str, _> = viter.get().unwrap();
+                    assert_eq!(a.collect::<Vec<&str>>(), vec!["Hello", "world"]);
+
+                    assert!(g.next());
+                    assert_eq!(g.get::<u16>(), None); // It's an array, not a single u16
+                    assert!(g.next() && g.next() && g.next() && g.next());
+
+                    assert_eq!(g.get(), Some((256i16, Variant(18_446_744_073_709_551_615u64))));
+                    assert!(g.next());
+                    assert_eq!(g.get(), Some(Path::new("/a/valid/path").unwrap()));
+                    assert!(g.next());
+                    assert_eq!(g.get(), Some(Signature::new("a{sv}").unwrap()));
+                    assert!(g.next());
+                    let d: Dict<u32, bool, _> = g.get().unwrap();
+                    let z2: HashMap<_, _> = d.collect();
+                    assert_eq!(z, z2);
+                    break;
+                }
+                _ => println!("Got {:?}", n),
+            }
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/arg/variantstruct_impl.rs
@@ -0,0 +1,242 @@
+use super::*;
+use {message, Signature};
+use std::any;
+
+#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
+/// A simple wrapper to specify a D-Bus variant.
+///
+/// See the argument guide and module level documentation for details and examples.
+pub struct Variant<T>(pub T);
+
+impl Variant<Box<RefArg>> {
+    /// Creates a new refarg from an Iter. Mainly for internal use.
+    pub fn new_refarg<'a>(i: &mut Iter<'a>) -> Option<Self> {
+        i.recurse(ArgType::Variant).and_then(|mut si| si.get_refarg()).map(|v| Variant(v))
+    }
+}
+
+impl Default for Variant<Box<RefArg>> {
+    // This is a bit silly, because there is no such thing as a default argument.
+    // Unfortunately due to a design mistake while making the SignalArgs trait, we'll
+    // have to work around that by adding a default implementation here.
+    // https://github.com/diwic/dbus-rs/issues/136
+    fn default() -> Self { Variant(Box::new(0u8) as Box<RefArg>) }
+}
+
+impl<T:Default> Default for Variant<T> {
+    fn default() -> Self { Variant(T::default()) }
+}
+
+
+impl<T> Arg for Variant<T> {
+    const ARG_TYPE: ArgType = ArgType::Variant;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"v\0") } }
+}
+
+impl<T: Arg + Append> Append for Variant<T> {
+    fn append(self, i: &mut IterAppend) {
+        let z = self.0;
+        i.append_container(ArgType::Variant, Some(T::signature().as_cstr()), |s| z.append(s));
+    }
+}
+
+impl Append for Variant<message::MessageItem> {
+    fn append(self, i: &mut IterAppend) {
+        let z = self.0;
+        let asig = z.signature();
+        let sig = asig.as_cstr();
+        i.append_container(ArgType::Variant, Some(&sig), |s| z.append(s));
+    }
+}
+
+impl Append for Variant<Box<RefArg>> {
+    fn append(self, i: &mut IterAppend) {
+        let z = self.0;
+        i.append_container(ArgType::Variant, Some(z.signature().as_cstr()), |s| z.append(s));
+    }
+}
+
+impl<'a, T: Get<'a>> Get<'a> for Variant<T> {
+    fn get(i: &mut Iter<'a>) -> Option<Variant<T>> {
+        i.recurse(ArgType::Variant).and_then(|mut si| si.get().map(|v| Variant(v)))
+    }
+}
+
+impl<'a> Get<'a> for Variant<Iter<'a>> {
+    fn get(i: &mut Iter<'a>) -> Option<Variant<Iter<'a>>> {
+        i.recurse(ArgType::Variant).map(|v| Variant(v))
+    }
+}
+/*
+impl<'a> Get<'a> for Variant<Box<RefArg>> {
+    fn get(i: &mut Iter<'a>) -> Option<Variant<Box<RefArg>>> {
+        i.recurse(ArgType::Variant).and_then(|mut si| si.get_refarg().map(|v| Variant(v)))
+    }
+}
+*/
+impl<T: RefArg> RefArg for Variant<T> {
+    fn arg_type(&self) -> ArgType { ArgType::Variant } 
+    fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"v\0") } }
+    fn append(&self, i: &mut IterAppend) {
+        let z = &self.0;
+        i.append_container(ArgType::Variant, Some(z.signature().as_cstr()), |s| z.append(s));
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where T: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where T: 'static { self }
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { self.0.as_i64() }
+    #[inline]
+    fn as_u64(&self) -> Option<u64> { self.0.as_u64() }
+    #[inline]
+    fn as_f64(&self) -> Option<f64> { self.0.as_f64() }
+    #[inline]
+    fn as_str(&self) -> Option<&str> { self.0.as_str() }
+    #[inline]
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+        use std::iter;
+        let z: &RefArg = &self.0;
+        Some(Box::new(iter::once(z)))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(Variant(self.0.box_clone())) }
+}
+
+macro_rules! struct_impl {
+    ( $($n: ident $t: ident,)+ ) => {
+
+/// Tuples are represented as D-Bus structs. 
+impl<$($t: Arg),*> Arg for ($($t,)*) {
+    const ARG_TYPE: ArgType = ArgType::Struct;
+    fn signature() -> Signature<'static> {
+        let mut s = String::from("(");
+        $( s.push_str(&$t::signature()); )*
+        s.push_str(")");
+        Signature::from(s)
+    }
+}
+
+impl<$($t: Append),*> Append for ($($t,)*) {
+    fn append(self, i: &mut IterAppend) {
+        let ( $($n,)*) = self;
+        i.append_container(ArgType::Struct, None, |s| { $( $n.append(s); )* });
+    }
+}
+
+impl<'a, $($t: Get<'a>),*> Get<'a> for ($($t,)*) {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        let si = i.recurse(ArgType::Struct);
+        if si.is_none() { return None; }
+        let mut si = si.unwrap();
+        let mut _valid_item = true;
+        $(
+            if !_valid_item { return None; }
+            let $n: Option<$t> = si.get();
+            if $n.is_none() { return None; }
+            _valid_item = si.next();
+        )*
+        Some(($( $n.unwrap(), )* ))
+    }
+}
+
+impl<$($t: RefArg),*> RefArg for ($($t,)*) {
+    fn arg_type(&self) -> ArgType { ArgType::Struct }
+    fn signature(&self) -> Signature<'static> {
+        let &( $(ref $n,)*) = self;
+        let mut s = String::from("(");
+        $( s.push_str(&$n.signature()); )*
+        s.push_str(")");
+        Signature::from(s)
+    }
+    fn append(&self, i: &mut IterAppend) {
+        let &( $(ref $n,)*) = self;
+        i.append_container(ArgType::Struct, None, |s| { $( $n.append(s); )* });
+    }
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+        let &( $(ref $n,)*) = self;
+        let v = vec!(
+        $( $n as &RefArg, )*
+        );
+        Some(Box::new(v.into_iter()))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        let &( $(ref $n,)*) = self;
+        let mut z = vec!();
+        $( z.push($n.box_clone()); )*
+        Box::new(z)
+    }
+}
+
+
+}} // macro_rules end
+
+struct_impl!(a A,);
+struct_impl!(a A, b B,);
+struct_impl!(a A, b B, c C,);
+struct_impl!(a A, b B, c C, d D,);
+struct_impl!(a A, b B, c C, d D, e E,);
+struct_impl!(a A, b B, c C, d D, e E, f F,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K,);
+struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K, l L,);
+
+impl RefArg for Vec<Box<RefArg>> {
+    fn arg_type(&self) -> ArgType { ArgType::Struct }
+    fn signature(&self) -> Signature<'static> {
+        let mut s = String::from("(");
+        for z in self {
+            s.push_str(&z.signature());
+        }
+        s.push_str(")");
+        Signature::from(s)
+    }
+    fn append(&self, i: &mut IterAppend) {
+        i.append_container(ArgType::Struct, None, |s| {
+            for z in self { z.append(s); }
+        });
+    }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+        Some(Box::new(self.iter().map(|b| &**b)))
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> {
+        let t: Vec<Box<RefArg + 'static>> = self.iter().map(|x| x.box_clone()).collect();
+        Box::new(t)
+    }
+}
+
+impl Append for message::MessageItem {
+    fn append(self, i: &mut IterAppend) {
+        message::append_messageitem(&mut i.0, &self)
+    }
+}
+
+impl<'a> Get<'a> for message::MessageItem {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        message::get_messageitem(&mut i.0)
+    }
+}
+
+impl RefArg for message::MessageItem {
+    fn arg_type(&self) -> ArgType { ArgType::from_i32(self.array_type()).unwrap() }
+    fn signature(&self) -> Signature<'static> { message::MessageItem::signature(&self) }
+    fn append(&self, i: &mut IterAppend) { message::append_messageitem(&mut i.0, self) }
+    #[inline]
+    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    #[inline]
+    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
+}
+
rename from third_party/rust/dbus/src/connection.rs
rename to third_party/rust/dbus-0.6.5/src/connection.rs
rename from third_party/rust/dbus/src/connection2.rs
rename to third_party/rust/dbus-0.6.5/src/connection2.rs
rename from third_party/rust/dbus/src/crossroads/crossroads.rs
rename to third_party/rust/dbus-0.6.5/src/crossroads/crossroads.rs
rename from third_party/rust/dbus/src/crossroads/handlers.rs
rename to third_party/rust/dbus-0.6.5/src/crossroads/handlers.rs
rename from third_party/rust/dbus/src/crossroads/info.rs
rename to third_party/rust/dbus-0.6.5/src/crossroads/info.rs
rename from third_party/rust/dbus/src/crossroads/mod.rs
rename to third_party/rust/dbus-0.6.5/src/crossroads/mod.rs
rename from third_party/rust/dbus/src/crossroads/stdimpl.rs
rename to third_party/rust/dbus-0.6.5/src/crossroads/stdimpl.rs
rename from third_party/rust/dbus/src/dispatcher.rs
rename to third_party/rust/dbus-0.6.5/src/dispatcher.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/lib.rs
@@ -0,0 +1,284 @@
+//! D-Bus bindings for Rust
+//!
+//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
+//! for communication between processes. It is present by default on almost every
+//! Linux distribution out there, and runs in two instances - one per session, and one
+//! system-wide.
+//!
+//! In addition to the API documentation, which you're currently reading, you might want to
+//! look in the examples directory, which contains many examples and an argument guide.
+//! README.md also contain a few quick "getting started" examples.
+//!
+//! In addition to this crate, there are two companion crates, dbus-codegen for generating Rust
+//! code from D-Bus introspection data, and dbus-tokio for integrating D-Bus with [Tokio](http://tokio.rs).
+//! However, at the time of this writing, these are far less mature than this crate. 
+
+#![warn(missing_docs)]
+
+extern crate libc;
+
+pub use ffi::DBusBusType as BusType;
+pub use connection::DBusNameFlag as NameFlag;
+pub use ffi::DBusRequestNameReply as RequestNameReply;
+pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
+pub use ffi::DBusMessageType as MessageType;
+
+pub use message::{Message, MessageItem, MessageItemArray, FromMessageItem, OwnedFd, ArrayError, ConnPath};
+pub use connection::{Connection, ConnectionItems, ConnectionItem, ConnMsgs, MsgHandler, MsgHandlerResult, MsgHandlerType, MessageCallback};
+pub use prop::PropHandler;
+pub use prop::Props;
+pub use watch::{Watch, WatchEvent};
+pub use signalargs::SignalArgs;
+
+/// A TypeSig describes the type of a MessageItem.
+#[deprecated(note="Use Signature instead")]
+pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
+
+use std::ffi::{CString, CStr};
+use std::ptr;
+use std::os::raw::c_char;
+
+#[allow(missing_docs)]
+extern crate libdbus_sys as ffi;
+mod message;
+mod prop;
+mod watch;
+mod connection;
+mod signalargs;
+
+mod matchrule;
+pub use matchrule::MatchRule;
+
+mod strings;
+pub use strings::{Signature, Path, Interface, Member, ErrorName, BusName};
+
+pub mod arg;
+
+pub mod stdintf;
+
+pub mod tree;
+
+static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
+
+fn init_dbus() {
+    INITDBUS.call_once(|| {
+        if unsafe { ffi::dbus_threads_init_default() } == 0 {
+            panic!("Out of memory when trying to initialize D-Bus library!");
+        }
+    });
+}
+
+/// D-Bus Error wrapper.
+pub struct Error {
+    e: ffi::DBusError,
+}
+
+unsafe impl Send for Error {}
+
+// Note! For this Sync impl to be safe, it requires that no functions that take &self,
+// actually calls into FFI. All functions that call into FFI with a ffi::DBusError
+// must take &mut self.
+
+unsafe impl Sync for Error {}
+
+fn c_str_to_slice(c: & *const c_char) -> Option<&str> {
+    if *c == ptr::null() { None }
+    else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
+}
+
+fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
+
+impl Error {
+
+    /// Create a new custom D-Bus Error.
+    pub fn new_custom(name: &str, message: &str) -> Error {
+        let n = to_c_str(name);
+        let m = to_c_str(&message.replace("%","%%"));
+        let mut e = Error::empty();
+
+        unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
+        e
+    }
+
+    fn empty() -> Error {
+        init_dbus();
+        let mut e = ffi::DBusError {
+            name: ptr::null(),
+            message: ptr::null(),
+            dummy: 0,
+            padding1: ptr::null()
+        };
+        unsafe { ffi::dbus_error_init(&mut e); }
+        Error{ e: e }
+    }
+
+    /// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
+    pub fn name(&self) -> Option<&str> {
+        c_str_to_slice(&self.e.name)
+    }
+
+    /// Custom message, e g 'Could not find a matching object path'
+    pub fn message(&self) -> Option<&str> {
+        c_str_to_slice(&self.e.message)
+    }
+
+    fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
+}
+
+impl Drop for Error {
+    fn drop(&mut self) {
+        unsafe { ffi::dbus_error_free(&mut self.e); }
+    }
+}
+
+impl std::fmt::Debug for Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
+        write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
+            self.name().unwrap_or(""))
+    }
+}
+
+impl std::error::Error for Error {
+    fn description(&self) -> &str { "D-Bus error" }
+}
+
+impl std::fmt::Display for Error {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
+        if let Some(x) = self.message() {
+             write!(f, "{:?}", x.to_string())
+        } else { Ok(()) }
+    }
+}
+
+impl From<arg::TypeMismatchError> for Error {
+    fn from(t: arg::TypeMismatchError) -> Error {
+        Error::new_custom("org.freedesktop.DBus.Error.Failed", &format!("{}", t))
+    }
+}
+
+impl From<tree::MethodErr> for Error {
+    fn from(t: tree::MethodErr) -> Error {
+        Error::new_custom(t.errorname(), t.description())
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
+        RequestNameReply, ReleaseNameReply};
+
+    #[test]
+    fn connection() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = c.unique_name();
+        assert!(n.starts_with(":1."));
+        println!("Connected to DBus, unique name: {}", n);
+    }
+
+    #[test]
+    fn invalid_message() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
+        let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
+        assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
+    }
+
+    #[test]
+    fn message_listnames() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let m = Message::method_call(&"org.freedesktop.DBus".into(), &"/".into(),
+            &"org.freedesktop.DBus".into(), &"ListNames".into());
+        let r = c.send_with_reply_and_block(m, 2000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+    }
+
+    #[test]
+    fn message_namehasowner() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
+        m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
+        let r = c.send_with_reply_and_block(m, 2000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+        assert_eq!(reply, vec!(MessageItem::Bool(true)));
+    }
+
+    #[test]
+    fn object_path() {
+        use  std::sync::mpsc;
+        let (tx, rx) = mpsc::channel();
+        let thread = ::std::thread::spawn(move || {
+            let c = Connection::get_private(BusType::Session).unwrap();
+            c.register_object_path("/hello").unwrap();
+            // println!("Waiting...");
+            tx.send(c.unique_name()).unwrap();
+            for n in c.iter(1000) {
+                // println!("Found message... ({})", n);
+                match n {
+                    ConnectionItem::MethodCall(ref m) => {
+                        let reply = Message::new_method_return(m).unwrap();
+                        c.send(reply).unwrap();
+                        break;
+                    }
+                    _ => {}
+                }
+            }
+            c.unregister_object_path("/hello");
+        });
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = rx.recv().unwrap();
+        let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
+        println!("Sending...");
+        let r = c.send_with_reply_and_block(m, 8000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+        thread.join().unwrap();
+
+    }
+
+    #[test]
+    fn register_name() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = format!("com.example.hello.test.register_name");
+        assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
+        assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
+    }
+
+    #[test]
+    fn signal() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let iface = "com.example.signaltest";
+        let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
+        c.add_match(&mstr).unwrap();
+        let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
+        let uname = c.unique_name();
+        c.send(m).unwrap();
+        for n in c.iter(1000) {
+            match n {
+                ConnectionItem::Signal(s) => {
+                    let (_, p, i, m) = s.headers();
+                    match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
+                        ("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
+                            assert_eq!(&*s.sender().unwrap(), &*uname);
+                            break;
+                        },
+                        (_, _, _) => println!("Other signal: {:?}", s.headers()),
+                    }
+                }
+                _ => {},
+            }
+        }
+        c.remove_match(&mstr).unwrap();
+    }
+
+
+    #[test]
+    fn watch() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let d = c.watch_fds();
+        assert!(d.len() > 0);
+        println!("Fds to watch: {:?}", d);
+    }
+}
rename from third_party/rust/dbus/src/matchrule.rs
rename to third_party/rust/dbus-0.6.5/src/matchrule.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/message.rs
@@ -0,0 +1,1152 @@
+use std::borrow::Cow;
+use std::{fmt, mem, ptr, ops};
+use super::{ffi, Error, MessageType, Signature, libc, to_c_str, c_str_to_slice, init_dbus};
+use super::{BusName, Path, Interface, Member, ErrorName, Connection, SignalArgs};
+use std::os::unix::io::{RawFd, AsRawFd};
+use std::ffi::CStr;
+use std::os::raw::{c_void, c_char, c_int};
+
+use super::arg::{Append, IterAppend, Get, Iter, Arg, RefArg, TypeMismatchError};
+
+#[derive(Debug,Copy,Clone)]
+/// Errors that can happen when creating a MessageItem::Array.
+pub enum ArrayError {
+    /// The array is empty.
+    EmptyArray,
+    /// The array is composed of different element types.
+    DifferentElementTypes,
+    /// The supplied signature is not a valid array signature
+    InvalidSignature,
+}
+
+fn new_dbus_message_iter() -> ffi::DBusMessageIter { unsafe { mem::zeroed() }}
+
+
+/// An RAII wrapper around Fd to ensure that file descriptor is closed
+/// when the scope ends.
+#[derive(Debug, PartialEq, PartialOrd)]
+pub struct OwnedFd {
+    fd: RawFd
+}
+
+impl OwnedFd {
+    /// Create a new OwnedFd from a RawFd.
+    pub fn new(fd: RawFd) -> OwnedFd {
+        OwnedFd { fd: fd }
+    }
+
+    /// Convert an OwnedFD back into a RawFd.
+    pub fn into_fd(self) -> RawFd {
+        let s = self.fd;
+        ::std::mem::forget(self);
+        s
+    }
+}
+
+impl Drop for OwnedFd {
+    fn drop(&mut self) {
+        unsafe { libc::close(self.fd); }
+    }
+}
+
+impl Clone for OwnedFd {
+    fn clone(&self) -> OwnedFd {
+        OwnedFd::new(unsafe { libc::dup(self.fd) } ) // FIXME: handle errors
+    }
+}
+
+impl AsRawFd for OwnedFd {
+    fn as_raw_fd(&self) -> RawFd {
+        self.fd
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, PartialOrd)]
+/// An array of MessageItem where every MessageItem is of the same type.
+pub struct MessageItemArray {
+    v: Vec<MessageItem>,
+    // signature includes the "a"!
+    sig: Signature<'static>,
+}
+
+impl MessageItemArray {
+    /// Creates a new array where every element has the supplied signature.
+    ///
+    /// Signature is the full array signature, not the signature of the element.
+    pub fn new(v: Vec<MessageItem>, sig: Signature<'static>) -> Result<MessageItemArray, ArrayError> {
+        let a = MessageItemArray {v: v, sig: sig };
+        if a.sig.as_bytes()[0] != ffi::DBUS_TYPE_ARRAY as u8 { return Err(ArrayError::InvalidSignature) }
+        {
+            let esig = a.element_signature();
+            for i in &a.v {
+                let b = if let MessageItem::DictEntry(ref k, ref v) = *i {
+                     let s = format!("{{{}{}}}", k.signature(), v.signature());
+                     s.as_bytes() == esig.to_bytes()
+                } else {
+                     i.signature().as_cstr() == esig
+                };
+                if !b { return Err(ArrayError::DifferentElementTypes) }
+            }
+        }
+        Ok(a)
+    }
+
+    fn element_signature(&self) -> &CStr {
+        let z = &self.sig.as_cstr().to_bytes_with_nul()[1..];
+        unsafe { CStr::from_bytes_with_nul_unchecked(z) }
+    }
+
+    fn make_sig(m: &MessageItem) -> Signature<'static> {
+        if let MessageItem::DictEntry(ref k, ref v) = *m {
+            Signature::new(format!("a{{{}{}}}", k.signature(), v.signature())).unwrap()
+        } else {
+            Signature::new(format!("a{}", m.signature())).unwrap()
+        }
+    }
+
+    /// Signature of array (full array signature)
+    pub fn signature(&self) -> &Signature<'static> { &self.sig }
+
+    /// Consumes the MessageItemArray in order to allow you to modify the individual items of the array.
+    pub fn into_vec(self) -> Vec<MessageItem> { self.v }
+}
+
+impl ops::Deref for MessageItemArray {
+    type Target = [MessageItem];
+    fn deref(&self) -> &Self::Target { &self.v }
+}
+
+
+/// MessageItem - used as parameters and return values from
+/// method calls, or as data added to a signal (old, enum version).
+///
+/// Note that the newer generic design (see `arg` module) is both faster
+/// and less error prone than MessageItem, and should be your first hand choice
+/// whenever applicable.
+#[derive(Debug, PartialEq, PartialOrd, Clone)]
+pub enum MessageItem {
+    /// A D-Bus array requires all elements to be of the same type.
+    /// All elements must match the Signature.
+    Array(MessageItemArray),
+    /// A D-Bus struct allows for values of different types.
+    Struct(Vec<MessageItem>),
+    /// A D-Bus variant is a wrapper around another `MessageItem`, which
+    /// can be of any type.
+    Variant(Box<MessageItem>),
+    /// A D-Bus dictionary entry. These are only allowed inside an array.
+    DictEntry(Box<MessageItem>, Box<MessageItem>),
+    /// A D-Bus objectpath requires its content to be a valid objectpath,
+    /// so this cannot be any string.
+    ObjectPath(Path<'static>),
+    /// A D-Bus String is zero terminated, so no \0 s in the String, please.
+    /// (D-Bus strings are also - like Rust strings - required to be valid UTF-8.)
+    Str(String),
+    /// A D-Bus boolean type.
+    Bool(bool),
+    /// A D-Bus unsigned 8 bit type.
+    Byte(u8),
+    /// A D-Bus signed 16 bit type.
+    Int16(i16),
+    /// A D-Bus signed 32 bit type.
+    Int32(i32),
+    /// A D-Bus signed 64 bit type.
+    Int64(i64),
+    /// A D-Bus unsigned 16 bit type.
+    UInt16(u16),
+    /// A D-Bus unsigned 32 bit type.
+    UInt32(u32),
+    /// A D-Bus unsigned 64 bit type.
+    UInt64(u64),
+    /// A D-Bus IEEE-754 double-precision floating point type.
+    Double(f64),
+    /// D-Bus allows for sending file descriptors, which can be used to
+    /// set up SHM, unix pipes, or other communication channels.
+    UnixFd(OwnedFd),
+}
+
+fn iter_get_basic<T>(i: &mut ffi::DBusMessageIter) -> T {
+    unsafe {
+        let mut c: T = mem::zeroed();
+        let p = &mut c as *mut _ as *mut c_void;
+        ffi::dbus_message_iter_get_basic(i, p);
+        c
+    }
+}
+
+fn iter_append_array(i: &mut ffi::DBusMessageIter, a: &[MessageItem], t: &CStr) {
+    let mut subiter = new_dbus_message_iter();
+
+    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_ARRAY, t.as_ptr(), &mut subiter) } != 0);
+    for item in a.iter() {
+//        assert!(item.type_sig() == t);
+        item.iter_append(&mut subiter);
+    }
+    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
+}
+
+fn iter_append_struct(i: &mut ffi::DBusMessageIter, a: &[MessageItem]) {
+    let mut subiter = new_dbus_message_iter();
+    let res = unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_STRUCT, ptr::null(), &mut subiter) };
+    assert!(res != 0);
+    for item in a.iter() {
+        item.iter_append(&mut subiter);
+    }
+    let res2 = unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) };
+    assert!(res2 != 0);
+}
+
+fn iter_append_variant(i: &mut ffi::DBusMessageIter, a: &MessageItem) {
+    let mut subiter = new_dbus_message_iter();
+    let asig = a.signature();
+    let atype = asig.as_cstr();
+    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_VARIANT, atype.as_ptr(), &mut subiter) } != 0);
+    a.iter_append(&mut subiter);
+    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
+}
+
+fn iter_append_dict(i: &mut ffi::DBusMessageIter, k: &MessageItem, v: &MessageItem) {
+    let mut subiter = new_dbus_message_iter();
+    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_DICT_ENTRY, ptr::null(), &mut subiter) } != 0);
+    k.iter_append(&mut subiter);
+    v.iter_append(&mut subiter);
+    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
+}
+
+impl MessageItem {
+    /// Get the D-Bus Signature for this MessageItem.
+    ///
+    /// Note: Since dictionary entries have no valid signature, calling this function for a dict entry will cause a panic.
+    pub fn signature(&self) -> Signature<'static> {
+        use arg::Variant;
+        match *self {
+            MessageItem::Str(_) => <String as Arg>::signature(),
+            MessageItem::Bool(_) => <bool as Arg>::signature(),
+            MessageItem::Byte(_) => <u8 as Arg>::signature(),
+            MessageItem::Int16(_) => <i16 as Arg>::signature(),
+            MessageItem::Int32(_) => <i32 as Arg>::signature(),
+            MessageItem::Int64(_) => <i64 as Arg>::signature(),
+            MessageItem::UInt16(_) => <u16 as Arg>::signature(),
+            MessageItem::UInt32(_) => <u32 as Arg>::signature(),
+            MessageItem::UInt64(_) => <u64 as Arg>::signature(),
+            MessageItem::Double(_) => <f64 as Arg>::signature(),
+            MessageItem::Array(ref a) => a.sig.clone(),
+            MessageItem::Struct(ref s) => Signature::new(format!("({})", s.iter().fold(String::new(), |s, i| s + &*i.signature()))).unwrap(),
+            MessageItem::Variant(_) => <Variant<u8> as Arg>::signature(),
+            MessageItem::DictEntry(_, _) => { panic!("Dict entries are only valid inside arrays, and therefore has no signature on their own") },
+            MessageItem::ObjectPath(_) => <Path as Arg>::signature(),
+            MessageItem::UnixFd(_) => <OwnedFd as Arg>::signature(),
+        }
+    }
+
+    /// Get the D-Bus ASCII type-code for this MessageItem.
+    #[deprecated(note="superseded by signature")]
+    #[allow(deprecated)]
+    pub fn type_sig(&self) -> super::TypeSig<'static> {
+        Cow::Owned(format!("{}", self.signature()))
+    }
+
+    /// Get the integer value for this MessageItem's type-code.
+    pub fn array_type(&self) -> i32 {
+        let s = match self {
+            &MessageItem::Str(_) => ffi::DBUS_TYPE_STRING,
+            &MessageItem::Bool(_) => ffi::DBUS_TYPE_BOOLEAN,
+            &MessageItem::Byte(_) => ffi::DBUS_TYPE_BYTE,
+            &MessageItem::Int16(_) => ffi::DBUS_TYPE_INT16,
+            &MessageItem::Int32(_) => ffi::DBUS_TYPE_INT32,
+            &MessageItem::Int64(_) => ffi::DBUS_TYPE_INT64,
+            &MessageItem::UInt16(_) => ffi::DBUS_TYPE_UINT16,
+            &MessageItem::UInt32(_) => ffi::DBUS_TYPE_UINT32,
+            &MessageItem::UInt64(_) => ffi::DBUS_TYPE_UINT64,
+            &MessageItem::Double(_) => ffi::DBUS_TYPE_DOUBLE,
+            &MessageItem::Array(_) => ffi::DBUS_TYPE_ARRAY,
+            &MessageItem::Struct(_) => ffi::DBUS_TYPE_STRUCT,
+            &MessageItem::Variant(_) => ffi::DBUS_TYPE_VARIANT,
+            &MessageItem::DictEntry(_,_) => ffi::DBUS_TYPE_DICT_ENTRY,
+            &MessageItem::ObjectPath(_) => ffi::DBUS_TYPE_OBJECT_PATH,
+            &MessageItem::UnixFd(_) => ffi::DBUS_TYPE_UNIX_FD,
+        };
+        s as i32
+    }
+
+    /// Creates a (String, Variant) dictionary from an iterator with Result passthrough (an Err will abort and return that Err)
+    pub fn from_dict<E, I: Iterator<Item=Result<(String, MessageItem),E>>>(i: I) -> Result<MessageItem, E> {
+        let mut v = Vec::new();
+        for r in i {
+            let (s, vv) = try!(r);
+            v.push((s.into(), Box::new(vv).into()).into());
+        }
+        Ok(MessageItem::Array(MessageItemArray::new(v, Signature::new("a{sv}").unwrap()).unwrap()))
+    }
+
+    /// Creates an MessageItem::Array from a list of MessageItems.
+    ///
+    /// Note: This requires `v` to be non-empty. See also
+    /// `MessageItem::from(&[T])`, which can handle empty arrays as well.
+    pub fn new_array(v: Vec<MessageItem>) -> Result<MessageItem,ArrayError> {
+        if v.len() == 0 {
+            return Err(ArrayError::EmptyArray);
+        }
+        let s = MessageItemArray::make_sig(&v[0]);
+        Ok(MessageItem::Array(MessageItemArray::new(v, s)?))
+    }
+
+
+    fn new_array2<D, I>(i: I) -> MessageItem
+    where D: Into<MessageItem>, D: Default, I: Iterator<Item=D> {
+        let v: Vec<MessageItem> = i.map(|ii| ii.into()).collect();
+        let s = {
+            let d;
+            let t = if v.len() == 0 { d = D::default().into(); &d } else { &v[0] };
+            MessageItemArray::make_sig(t)
+        };
+        MessageItem::Array(MessageItemArray::new(v, s).unwrap())
+    }
+
+    fn new_array3<'b, D: 'b, I>(i: I) -> MessageItem
+    where D: Into<MessageItem> + Default + Clone, I: Iterator<Item=&'b D> {
+        MessageItem::new_array2(i.map(|ii| ii.clone()))
+    }
+
+    fn from_iter_single(i: &mut ffi::DBusMessageIter) -> Option<MessageItem> {
+        let t = unsafe { ffi::dbus_message_iter_get_arg_type(i) };
+        match t {
+            ffi::DBUS_TYPE_INVALID => { None },
+            ffi::DBUS_TYPE_DICT_ENTRY => {
+                let mut subiter = new_dbus_message_iter();
+                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
+                let a = MessageItem::from_iter(&mut subiter);
+                if a.len() != 2 { panic!("D-Bus dict entry error"); }
+                let mut a = a.into_iter();
+                let key = Box::new(a.next().unwrap());
+                let value = Box::new(a.next().unwrap());
+                Some(MessageItem::DictEntry(key, value))
+            }
+            ffi::DBUS_TYPE_VARIANT => {
+                let mut subiter = new_dbus_message_iter();
+                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
+                let a = MessageItem::from_iter(&mut subiter);
+                if a.len() != 1 { panic!("D-Bus variant error"); }
+                Some(MessageItem::Variant(Box::new(a.into_iter().next().unwrap())))
+            }
+            ffi::DBUS_TYPE_ARRAY => {
+                let mut subiter = new_dbus_message_iter();
+                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
+                let c = unsafe { ffi::dbus_message_iter_get_signature(&mut subiter) };
+                let s = format!("a{}", c_str_to_slice(&(c as *const c_char)).unwrap());
+                unsafe { ffi::dbus_free(c as *mut c_void) };
+                let t = Signature::new(s).unwrap();
+
+                let a = MessageItem::from_iter(&mut subiter);
+                Some(MessageItem::Array(MessageItemArray { v: a, sig: t }))
+            },
+            ffi::DBUS_TYPE_STRUCT => {
+                let mut subiter = new_dbus_message_iter();
+                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
+                Some(MessageItem::Struct(MessageItem::from_iter(&mut subiter)))
+            },
+            ffi::DBUS_TYPE_STRING => {
+                let mut c: *const c_char = ptr::null();
+                unsafe {
+                    let p: *mut c_void = mem::transmute(&mut c);
+                    ffi::dbus_message_iter_get_basic(i, p);
+                };
+                Some(MessageItem::Str(c_str_to_slice(&c).expect("D-Bus string error").to_string()))
+            },
+            ffi::DBUS_TYPE_OBJECT_PATH => {
+                let mut c: *const c_char = ptr::null();
+                unsafe {
+                    let p: *mut c_void = mem::transmute(&mut c);
+                    ffi::dbus_message_iter_get_basic(i, p);
+                };
+                let o = Path::new(c_str_to_slice(&c).expect("D-Bus object path error")).ok().expect("D-Bus object path error");
+                Some(MessageItem::ObjectPath(o))
+            },
+            ffi::DBUS_TYPE_UNIX_FD => Some(MessageItem::UnixFd(OwnedFd::new(iter_get_basic(i)))),
+            ffi::DBUS_TYPE_BOOLEAN => Some(MessageItem::Bool(iter_get_basic::<u32>(i) != 0)),
+            ffi::DBUS_TYPE_BYTE => Some(MessageItem::Byte(iter_get_basic(i))),
+            ffi::DBUS_TYPE_INT16 => Some(MessageItem::Int16(iter_get_basic(i))),
+            ffi::DBUS_TYPE_INT32 => Some(MessageItem::Int32(iter_get_basic(i))),
+            ffi::DBUS_TYPE_INT64 => Some(MessageItem::Int64(iter_get_basic(i))),
+            ffi::DBUS_TYPE_UINT16 => Some(MessageItem::UInt16(iter_get_basic(i))),
+            ffi::DBUS_TYPE_UINT32 => Some(MessageItem::UInt32(iter_get_basic(i))),
+            ffi::DBUS_TYPE_UINT64 => Some(MessageItem::UInt64(iter_get_basic(i))),
+            ffi::DBUS_TYPE_DOUBLE => Some(MessageItem::Double(iter_get_basic(i))),
+            _ => { None /* Only the new msgarg module supports signatures */ }
+        }
+    }
+
+    fn from_iter(i: &mut ffi::DBusMessageIter) -> Vec<MessageItem> {
+        let mut v = Vec::new();
+        while let Some(m) = Self::from_iter_single(i) {
+            v.push(m);
+            unsafe { ffi::dbus_message_iter_next(i) };
+        }
+        v
+    }
+
+    fn iter_append_basic<T>(&self, i: &mut ffi::DBusMessageIter, v: T) {
+        let t = self.array_type() as c_int;
+        let p = &v as *const _ as *const c_void;
+        unsafe {
+            ffi::dbus_message_iter_append_basic(i, t, p);
+        }
+    }
+
+    fn iter_append(&self, i: &mut ffi::DBusMessageIter) {
+        match self {
+            &MessageItem::Str(ref s) => unsafe {
+                let c = to_c_str(s);
+                let p = mem::transmute(&c);
+                ffi::dbus_message_iter_append_basic(i, ffi::DBUS_TYPE_STRING, p);
+            },
+            &MessageItem::Bool(b) => self.iter_append_basic(i, if b { 1u32 } else { 0u32 }),
+            &MessageItem::Byte(b) => self.iter_append_basic(i, b),
+            &MessageItem::Int16(b) => self.iter_append_basic(i, b),
+            &MessageItem::Int32(b) => self.iter_append_basic(i, b),
+            &MessageItem::Int64(b) => self.iter_append_basic(i, b),
+            &MessageItem::UInt16(b) => self.iter_append_basic(i, b),
+            &MessageItem::UInt32(b) => self.iter_append_basic(i, b),
+            &MessageItem::UInt64(b) => self.iter_append_basic(i, b),
+            &MessageItem::UnixFd(ref b) => self.iter_append_basic(i, b.as_raw_fd()),
+            &MessageItem::Double(b) => self.iter_append_basic(i, b),
+            &MessageItem::Array(ref a) => iter_append_array(i, &a.v, a.element_signature()),
+            &MessageItem::Struct(ref v) => iter_append_struct(i, &**v),
+            &MessageItem::Variant(ref b) => iter_append_variant(i, &**b),
+            &MessageItem::DictEntry(ref k, ref v) => iter_append_dict(i, &**k, &**v),
+            &MessageItem::ObjectPath(ref s) => unsafe {
+                let c: *const libc::c_char = s.as_ref().as_ptr();
+                let p = mem::transmute(&c);
+                ffi::dbus_message_iter_append_basic(i, ffi::DBUS_TYPE_OBJECT_PATH, p);
+            }
+        }
+    }
+
+    fn copy_to_iter(i: &mut ffi::DBusMessageIter, v: &[MessageItem]) {
+        for item in v.iter() {
+            item.iter_append(i);
+        }
+    }
+
+    /// Conveniently get the inner value of a `MessageItem`
+    ///
+    /// # Example
+    /// ```
+    /// use dbus::MessageItem;
+    /// let m: MessageItem = 5i64.into();
+    /// let s: i64 = m.inner().unwrap();
+    /// assert_eq!(s, 5i64);
+    /// ```
+    pub fn inner<'a, T: FromMessageItem<'a>>(&'a self) -> Result<T, ()> {
+        T::from(self)
+    }
+}
+
+
+// For use by the msgarg module
+pub fn append_messageitem(i: &mut ffi::DBusMessageIter, m: &MessageItem) {
+    m.iter_append(i)
+}
+
+// For use by the msgarg module
+pub fn get_messageitem(i: &mut ffi::DBusMessageIter) -> Option<MessageItem> {
+    MessageItem::from_iter_single(i)
+}
+
+
+macro_rules! msgitem_convert {
+    ($t: ty, $s: ident) => {
+        impl From<$t> for MessageItem { fn from(i: $t) -> MessageItem { MessageItem::$s(i) } }
+
+        impl<'a> FromMessageItem<'a> for $t {
+            fn from(i: &'a MessageItem) -> Result<$t,()> {
+                if let &MessageItem::$s(ref b) = i { Ok(*b) } else { Err(()) }
+            }
+        }
+    }
+}
+
+msgitem_convert!(u8, Byte);
+msgitem_convert!(u64, UInt64);
+msgitem_convert!(u32, UInt32);
+msgitem_convert!(u16, UInt16);
+msgitem_convert!(i16, Int16);
+msgitem_convert!(i32, Int32);
+msgitem_convert!(i64, Int64);
+msgitem_convert!(f64, Double);
+msgitem_convert!(bool, Bool);
+
+
+/// Create a `MessageItem::Array`.
+impl<'a, T> From<&'a [T]> for MessageItem
+where T: Into<MessageItem> + Clone + Default {
+    fn from(i: &'a [T]) -> MessageItem {
+        MessageItem::new_array3(i.iter())
+    }
+}
+
+impl<'a> From<&'a str> for MessageItem { fn from(i: &str) -> MessageItem { MessageItem::Str(i.to_string()) } }
+
+impl From<String> for MessageItem { fn from(i: String) -> MessageItem { MessageItem::Str(i) } }
+
+impl From<Path<'static>> for MessageItem { fn from(i: Path<'static>) -> MessageItem { MessageItem::ObjectPath(i) } }
+
+impl From<OwnedFd> for MessageItem { fn from(i: OwnedFd) -> MessageItem { MessageItem::UnixFd(i) } }
+
+/// Create a `MessageItem::Variant`
+impl From<Box<MessageItem>> for MessageItem {
+    fn from(i: Box<MessageItem>) -> MessageItem { MessageItem::Variant(i) }
+}
+
+/// Create a `MessageItem::DictEntry`
+impl From<(MessageItem, MessageItem)> for MessageItem {
+    fn from(i: (MessageItem, MessageItem)) -> MessageItem {
+        MessageItem::DictEntry(Box::new(i.0), Box::new(i.1))
+    }
+}
+
+/// Helper trait for `MessageItem::inner()`
+pub trait FromMessageItem<'a> :Sized {
+    /// Allows converting from a MessageItem into the type it contains.
+    fn from(i: &'a MessageItem) -> Result<Self, ()>;
+}
+
+impl<'a> FromMessageItem<'a> for &'a str {
+    fn from(i: &'a MessageItem) -> Result<&'a str,()> {
+        match i {
+            &MessageItem::Str(ref b) => Ok(&b),
+            &MessageItem::ObjectPath(ref b) => Ok(&b),
+            _ => Err(()),
+        }
+    }
+}
+
+impl<'a> FromMessageItem<'a> for &'a String {
+    fn from(i: &'a MessageItem) -> Result<&'a String,()> { if let &MessageItem::Str(ref b) = i { Ok(&b) } else { Err(()) } }
+}
+
+impl<'a> FromMessageItem<'a> for &'a Path<'static> {
+    fn from(i: &'a MessageItem) -> Result<&'a Path<'static>,()> { if let &MessageItem::ObjectPath(ref b) = i { Ok(&b) } else { Err(()) } }
+}
+
+impl<'a> FromMessageItem<'a> for &'a MessageItem {
+    fn from(i: &'a MessageItem) -> Result<&'a MessageItem,()> { if let &MessageItem::Variant(ref b) = i { Ok(&**b) } else { Err(()) } }
+}
+
+impl<'a> FromMessageItem<'a> for &'a Vec<MessageItem> {
+    fn from(i: &'a MessageItem) -> Result<&'a Vec<MessageItem>,()> {
+        match i {
+            &MessageItem::Array(ref b) => Ok(&b.v),
+            &MessageItem::Struct(ref b) => Ok(&b),
+            _ => Err(()),
+        }
+    }
+}
+
+impl<'a> FromMessageItem<'a> for &'a [MessageItem] {
+    fn from(i: &'a MessageItem) -> Result<&'a [MessageItem],()> { i.inner::<&Vec<MessageItem>>().map(|s| &**s) }
+}
+
+impl<'a> FromMessageItem<'a> for &'a OwnedFd {
+    fn from(i: &'a MessageItem) -> Result<&'a OwnedFd,()> { if let &MessageItem::UnixFd(ref b) = i { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> FromMessageItem<'a> for (&'a MessageItem, &'a MessageItem) {
+    fn from(i: &'a MessageItem) -> Result<(&'a MessageItem, &'a MessageItem),()> {
+        if let &MessageItem::DictEntry(ref k, ref v) = i { Ok((&**k, &**v)) } else { Err(()) }
+    }
+}
+
+
+/// A D-Bus message. A message contains some headers (e g sender and destination address)
+/// and a list of MessageItems.
+pub struct Message {
+    msg: *mut ffi::DBusMessage,
+}
+
+unsafe impl Send for Message {}
+
+impl Message {
+    /// Creates a new method call message.
+    pub fn new_method_call<'d, 'p, 'i, 'm, D, P, I, M>(destination: D, path: P, iface: I, method: M) -> Result<Message, String>
+    where D: Into<BusName<'d>>, P: Into<Path<'p>>, I: Into<Interface<'i>>, M: Into<Member<'m>> {
+        init_dbus();
+        let (d, p, i, m) = (destination.into(), path.into(), iface.into(), method.into());
+        let ptr = unsafe {
+            ffi::dbus_message_new_method_call(d.as_ref().as_ptr(), p.as_ref().as_ptr(), i.as_ref().as_ptr(), m.as_ref().as_ptr())
+        };
+        if ptr == ptr::null_mut() { Err("D-Bus error: dbus_message_new_method_call failed".into()) }
+        else { Ok(Message { msg: ptr}) }
+    }
+
+    /// Creates a new method call message.
+    pub fn method_call(destination: &BusName, path: &Path, iface: &Interface, name: &Member) -> Message {
+        init_dbus();
+        let ptr = unsafe {
+            ffi::dbus_message_new_method_call(destination.as_ref().as_ptr(), path.as_ref().as_ptr(),
+                iface.as_ref().as_ptr(), name.as_ref().as_ptr())
+        };
+        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_signal failed") }
+        Message { msg: ptr}
+    }
+
+    /// Creates a new signal message.
+    pub fn new_signal<P, I, M>(path: P, iface: I, name: M) -> Result<Message, String>
+    where P: Into<Vec<u8>>, I: Into<Vec<u8>>, M: Into<Vec<u8>> {
+        init_dbus();
+
+        let p = try!(Path::new(path));
+        let i = try!(Interface::new(iface));
+        let m = try!(Member::new(name));
+
+        let ptr = unsafe {
+            ffi::dbus_message_new_signal(p.as_ref().as_ptr(), i.as_ref().as_ptr(), m.as_ref().as_ptr())
+        };
+        if ptr == ptr::null_mut() { Err("D-Bus error: dbus_message_new_signal failed".into()) }
+        else { Ok(Message { msg: ptr}) }
+    }
+
+    /// Creates a new signal message.
+    pub fn signal(path: &Path, iface: &Interface, name: &Member) -> Message {
+        init_dbus();
+        let ptr = unsafe {
+            ffi::dbus_message_new_signal(path.as_ref().as_ptr(), iface.as_ref().as_ptr(), name.as_ref().as_ptr())
+        };
+        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_signal failed") }
+        Message { msg: ptr}
+    }
+
+    /// Creates a method reply for this method call.
+    pub fn new_method_return(m: &Message) -> Option<Message> {
+        let ptr = unsafe { ffi::dbus_message_new_method_return(m.msg) };
+        if ptr == ptr::null_mut() { None } else { Some(Message { msg: ptr} ) }
+    }
+
+    /// Creates a method return (reply) for this method call.
+    pub fn method_return(&self) -> Message {
+        let ptr = unsafe { ffi::dbus_message_new_method_return(self.msg) };
+        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_method_return failed") }
+        Message {msg: ptr}
+    }
+
+    /// The old way to create a new error reply
+    pub fn new_error(m: &Message, error_name: &str, error_message: &str) -> Option<Message> {
+        let (en, em) = (to_c_str(error_name), to_c_str(error_message));
+        let ptr = unsafe { ffi::dbus_message_new_error(m.msg, en.as_ptr(), em.as_ptr()) };
+        if ptr == ptr::null_mut() { None } else { Some(Message { msg: ptr} ) }
+    }
+
+    /// Creates a new error reply
+    pub fn error(&self, error_name: &ErrorName, error_message: &CStr) -> Message {
+        let ptr = unsafe { ffi::dbus_message_new_error(self.msg, error_name.as_ref().as_ptr(), error_message.as_ptr()) };
+        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_error failed") }
+        Message { msg: ptr}
+    }
+
+    /// Get the MessageItems that make up the message.
+    ///
+    /// Note: use `iter_init` or `get1`/`get2`/etc instead for faster access to the arguments.
+    /// This method is provided for backwards compatibility.
+    pub fn get_items(&self) -> Vec<MessageItem> {
+        let mut i = new_dbus_message_iter();
+        match unsafe { ffi::dbus_message_iter_init(self.msg, &mut i) } {
+            0 => Vec::new(),
+            _ => MessageItem::from_iter(&mut i)
+        }
+    }
+
+    /// Get the D-Bus serial of a message, if one was specified.
+    pub fn get_serial(&self) -> u32 {
+        unsafe { ffi::dbus_message_get_serial(self.msg) }
+    }
+
+    /// Get the serial of the message this message is a reply to, if present.
+    pub fn get_reply_serial(&self) -> Option<u32> {
+        let s = unsafe { ffi::dbus_message_get_reply_serial(self.msg) };
+        if s == 0 { None } else { Some(s) }
+    }
+
+    /// Returns true if the message does not expect a reply.
+    pub fn get_no_reply(&self) -> bool { unsafe { ffi::dbus_message_get_no_reply(self.msg) != 0 } }
+
+    /// Set whether or not the message expects a reply.
+    ///
+    /// Set to true if you send a method call and do not want a reply.
+    pub fn set_no_reply(&self, v: bool) {
+        unsafe { ffi::dbus_message_set_no_reply(self.msg, if v { 1 } else { 0 }) }
+    }
+
+    /// Returns true if the message can cause a service to be auto-started.
+    pub fn get_auto_start(&self) -> bool { unsafe { ffi::dbus_message_get_auto_start(self.msg) != 0 } }
+
+    /// Sets whether or not the message can cause a service to be auto-started.
+    ///
+    /// Defaults to true.
+    pub fn set_auto_start(&self, v: bool) {
+        unsafe { ffi::dbus_message_set_auto_start(self.msg, if v { 1 } else { 0 }) }
+    }
+
+    /// Add one or more MessageItems to this Message.
+    ///
+    /// Note: using `append1`, `append2` or `append3` might be faster, especially for large arrays.
+    /// This method is provided for backwards compatibility.
+    pub fn append_items(&mut self, v: &[MessageItem]) {
+        let mut i = new_dbus_message_iter();
+        unsafe { ffi::dbus_message_iter_init_append(self.msg, &mut i) };
+        MessageItem::copy_to_iter(&mut i, v);
+    }
+
+    /// Appends one MessageItem to a message.
+    /// Use in builder style: e g `m.method_return().append(7i32)`
+    ///
+    /// Note: using `append1`, `append2` or `append3` might be faster, especially for large arrays.
+    /// This method is provided for backwards compatibility.
+    pub fn append<I: Into<MessageItem>>(self, v: I) -> Self {
+        let mut i = new_dbus_message_iter();
+        unsafe { ffi::dbus_message_iter_init_append(self.msg, &mut i) };
+        MessageItem::copy_to_iter(&mut i, &[v.into()]);
+        self
+    }
+
+    /// Appends one argument to this message.
+    /// Use in builder style: e g `m.method_return().append1(7i32)`
+    pub fn append1<A: Append>(mut self, a: A) -> Self {
+        {
+            let mut m = IterAppend::new(&mut self);
+            m.append(a);
+        }
+        self
+    }
+
+    /// Appends two arguments to this message.
+    /// Use in builder style: e g `m.method_return().append2(7i32, 6u8)`
+    pub fn append2<A1: Append, A2: Append>(mut self, a1: A1, a2: A2) -> Self {
+        {
+            let mut m = IterAppend::new(&mut self);
+            m.append(a1); m.append(a2);
+        }
+        self
+    }
+
+    /// Appends three arguments to this message.
+    /// Use in builder style: e g `m.method_return().append3(7i32, 6u8, true)`
+    pub fn append3<A1: Append, A2: Append, A3: Append>(mut self, a1: A1, a2: A2, a3: A3) -> Self {
+        {
+            let mut m = IterAppend::new(&mut self);
+            m.append(a1); m.append(a2); m.append(a3);
+        }
+        self
+    }
+
+    /// Appends RefArgs to this message.
+    /// Use in builder style: e g `m.method_return().append_ref(&[7i32, 6u8, true])`
+    pub fn append_ref<A: RefArg>(mut self, r: &[A]) -> Self {
+        {
+            let mut m = IterAppend::new(&mut self);
+            for rr in r {
+                rr.append(&mut m);
+            }
+        }
+        self
+    } 
+
+    /// Gets the first argument from the message, if that argument is of type G1.
+    /// Returns None if there are not enough arguments, or if types don't match.
+    pub fn get1<'a, G1: Get<'a>>(&'a self) -> Option<G1> {
+        let mut i = Iter::new(&self);
+        i.get()
+    }
+
+    /// Gets the first two arguments from the message, if those arguments are of type G1 and G2.
+    /// Returns None if there are not enough arguments, or if types don't match.
+    pub fn get2<'a, G1: Get<'a>, G2: Get<'a>>(&'a self) -> (Option<G1>, Option<G2>) {
+        let mut i = Iter::new(&self);
+        let g1 = i.get();
+        if !i.next() { return (g1, None); }
+        (g1, i.get())
+    }
+
+    /// Gets the first three arguments from the message, if those arguments are of type G1, G2 and G3.
+    /// Returns None if there are not enough arguments, or if types don't match.
+    pub fn get3<'a, G1: Get<'a>, G2: Get<'a>, G3: Get<'a>>(&'a self) -> (Option<G1>, Option<G2>, Option<G3>) {
+        let mut i = Iter::new(&self);
+        let g1 = i.get();
+        if !i.next() { return (g1, None, None) }
+        let g2 = i.get();
+        if !i.next() { return (g1, g2, None) }
+        (g1, g2, i.get())
+    }
+
+    /// Gets the first four arguments from the message, if those arguments are of type G1, G2, G3 and G4.
+    /// Returns None if there are not enough arguments, or if types don't match.
+    pub fn get4<'a, G1: Get<'a>, G2: Get<'a>, G3: Get<'a>, G4: Get<'a>>(&'a self) -> (Option<G1>, Option<G2>, Option<G3>, Option<G4>) {
+        let mut i = Iter::new(&self);
+        let g1 = i.get();
+        if !i.next() { return (g1, None, None, None) }
+        let g2 = i.get();
+        if !i.next() { return (g1, g2, None, None) }
+        let g3 = i.get();
+        if !i.next() { return (g1, g2, g3, None) }
+        (g1, g2, g3, i.get())
+    }
+
+    /// Gets the first five arguments from the message, if those arguments are of type G1, G2, G3 and G4.
+    /// Returns None if there are not enough arguments, or if types don't match.
+    /// Note: If you need more than five arguments, use `iter_init` instead.
+    pub fn get5<'a, G1: Get<'a>, G2: Get<'a>, G3: Get<'a>, G4: Get<'a>, G5: Get<'a>>(&'a self) -> (Option<G1>, Option<G2>, Option<G3>, Option<G4>, Option<G5>) {
+        let mut i = Iter::new(&self);
+        let g1 = i.get();
+        if !i.next() { return (g1, None, None, None, None) }
+        let g2 = i.get();
+        if !i.next() { return (g1, g2, None, None, None) }
+        let g3 = i.get();
+        if !i.next() { return (g1, g2, g3, None, None) }
+        let g4 = i.get();
+        if !i.next() { return (g1, g2, g3, g4, None) }
+        (g1, g2, g3, g4, i.get())
+    }
+
+    /// Gets the first argument from the message, if that argument is of type G1.
+    ///
+    /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
+    pub fn read1<'a, G1: Arg + Get<'a>>(&'a self) -> Result<G1, TypeMismatchError> {
+        let mut i = Iter::new(&self);
+        i.read()
+    }
+
+    /// Gets the first two arguments from the message, if those arguments are of type G1 and G2.
+    ///
+    /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
+    pub fn read2<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>>(&'a self) -> Result<(G1, G2), TypeMismatchError> {
+        let mut i = Iter::new(&self);
+        Ok((try!(i.read()), try!(i.read())))
+    }
+
+    /// Gets the first three arguments from the message, if those arguments are of type G1, G2 and G3.
+    ///
+    /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
+    pub fn read3<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>>(&'a self) -> 
+        Result<(G1, G2, G3), TypeMismatchError> {
+        let mut i = Iter::new(&self);
+        Ok((try!(i.read()), try!(i.read()), try!(i.read())))
+    }
+
+    /// Gets the first four arguments from the message, if those arguments are of type G1, G2, G3 and G4.
+    ///
+    /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
+    pub fn read4<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>, G4: Arg + Get<'a>>(&'a self) ->
+        Result<(G1, G2, G3, G4), TypeMismatchError> {
+        let mut i = Iter::new(&self);
+        Ok((try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read())))
+    }
+
+    /// Gets the first five arguments from the message, if those arguments are of type G1, G2, G3, G4 and G5.
+    ///
+    /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
+    /// Note: If you need more than five arguments, use `iter_init` instead.
+    pub fn read5<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>, G4: Arg + Get<'a>, G5: Arg + Get<'a>>(&'a self) ->
+        Result<(G1, G2, G3, G4, G5), TypeMismatchError> {
+        let mut i = Iter::new(&self);
+        Ok((try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read())))
+    }
+
+    /// Returns a struct for retreiving the arguments from a message. Supersedes get_items().
+    pub fn iter_init<'a>(&'a self) -> Iter<'a> { Iter::new(&self) }
+
+    /// Gets the MessageType of the Message.
+    pub fn msg_type(&self) -> MessageType {
+        unsafe { mem::transmute(ffi::dbus_message_get_type(self.msg)) }
+    }
+
+    fn msg_internal_str<'a>(&'a self, c: *const libc::c_char) -> Option<&'a [u8]> {
+        if c == ptr::null() { None }
+        else { Some( unsafe { CStr::from_ptr(c) }.to_bytes_with_nul()) }
+    }
+
+    /// Gets the name of the connection that originated this message.
+    pub fn sender<'a>(&'a self) -> Option<BusName<'a>> {
+        self.msg_internal_str(unsafe { ffi::dbus_message_get_sender(self.msg) })
+            .map(|s| unsafe { BusName::from_slice_unchecked(s) })
+    }
+
+    /// Returns a tuple of (Message type, Path, Interface, Member) of the current message.
+    pub fn headers(&self) -> (MessageType, Option<String>, Option<String>, Option<String>) {
+        let p = unsafe { ffi::dbus_message_get_path(self.msg) };
+        let i = unsafe { ffi::dbus_message_get_interface(self.msg) };
+        let m = unsafe { ffi::dbus_message_get_member(self.msg) };
+        (self.msg_type(),
+         c_str_to_slice(&p).map(|s| s.to_string()),
+         c_str_to_slice(&i).map(|s| s.to_string()),
+         c_str_to_slice(&m).map(|s| s.to_string()))
+    }
+
+    /// Gets the object path this Message is being sent to.
+    pub fn path<'a>(&'a self) -> Option<Path<'a>> {
+        self.msg_internal_str(unsafe { ffi::dbus_message_get_path(self.msg) })
+            .map(|s| unsafe { Path::from_slice_unchecked(s) })
+    }
+
+    /// Gets the destination this Message is being sent to.
+    pub fn destination<'a>(&'a self) -> Option<BusName<'a>> {
+        self.msg_internal_str(unsafe { ffi::dbus_message_get_destination(self.msg) })
+            .map(|s| unsafe { BusName::from_slice_unchecked(s) })
+    }
+
+    /// Sets the destination of this Message
+    ///
+    /// If dest is none, that means broadcast to all relevant destinations.
+    pub fn set_destination(&mut self, dest: Option<BusName>) {
+        let c_dest = dest.as_ref().map(|d| d.as_cstr().as_ptr()).unwrap_or(ptr::null());
+        assert!(unsafe { ffi::dbus_message_set_destination(self.msg, c_dest) } != 0);
+    }
+
+    /// Gets the interface this Message is being sent to.
+    pub fn interface<'a>(&'a self) -> Option<Interface<'a>> {
+        self.msg_internal_str(unsafe { ffi::dbus_message_get_interface(self.msg) })
+            .map(|s| unsafe { Interface::from_slice_unchecked(s) })
+    }
+
+    /// Gets the interface member being called.
+    pub fn member<'a>(&'a self) -> Option<Member<'a>> {
+        self.msg_internal_str(unsafe { ffi::dbus_message_get_member(self.msg) })
+            .map(|s| unsafe { Member::from_slice_unchecked(s) })
+    }
+
+    /// When the remote end returns an error, the message itself is
+    /// correct but its contents is an error. This method will
+    /// transform such an error to a D-Bus Error or otherwise return
+    /// the original message.
+    pub fn as_result(&mut self) -> Result<&mut Message, Error> {
+        self.set_error_from_msg().map(|_| self)
+    }
+
+    pub (super) fn set_error_from_msg(&self) -> Result<(), Error> {
+        let mut e = Error::empty();
+        if unsafe { ffi::dbus_set_error_from_message(e.get_mut(), self.msg) } != 0 { Err(e) }
+        else { Ok(()) }
+    }
+
+    pub (crate) fn ptr(&self) -> *mut ffi::DBusMessage { self.msg }
+
+    pub (crate) fn from_ptr(ptr: *mut ffi::DBusMessage, add_ref: bool) -> Message {
+        if add_ref {
+            unsafe { ffi::dbus_message_ref(ptr) };
+        }
+        Message { msg: ptr }
+    }
+
+}
+
+impl Drop for Message {
+    fn drop(&mut self) {
+        unsafe {
+            ffi::dbus_message_unref(self.msg);
+        }
+    }
+}
+
+impl fmt::Debug for Message {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        write!(f, "{:?}", self.headers())
+    }
+}
+
+/// A convenience struct that wraps connection, destination and path.
+///
+/// Useful if you want to make many method calls to the same destination path.
+#[derive(Clone, Debug)]
+pub struct ConnPath<'a, C> {
+    /// Some way to access the connection, e g a &Connection or Rc<Connection>
+    pub conn: C,
+    /// Destination, i e what D-Bus service you're communicating with
+    pub dest: BusName<'a>,
+    /// Object path on the destination
+    pub path: Path<'a>,
+    /// Timeout in milliseconds for blocking method calls
+    pub timeout: i32,
+}
+
+impl<'a, C: ::std::ops::Deref<Target=Connection>> ConnPath<'a, C> {
+    /// Make a D-Bus method call, where you can append arguments inside the closure.
+    pub fn method_call_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<Message, Error> {
+        let mut msg = Message::method_call(&self.dest, &self.path, i, m);
+        f(&mut msg);
+        self.conn.send_with_reply_and_block(msg, self.timeout)
+    }
+
+    /// Emit a D-Bus signal, where you can append arguments inside the closure.
+    pub fn signal_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<u32, Error> {
+        let mut msg = Message::signal(&self.path, i, m);
+        f(&mut msg);
+        self.conn.send(msg).map_err(|_| Error::new_custom("org.freedesktop.DBus.Error.Failed", "Sending signal failed"))
+    }
+
+    /// Emit a D-Bus signal, where the arguments are in a struct.
+    pub fn emit<S: SignalArgs>(&self, signal: &S) -> Result<u32, Error> {
+        let msg = signal.to_emit_message(&self.path);
+        self.conn.send(msg).map_err(|_| Error::new_custom("org.freedesktop.DBus.Error.Failed", "Sending signal failed"))
+    }
+}
+
+// For purpose of testing the library only.
+#[cfg(test)]
+pub (crate) fn message_set_serial(m: &mut Message, s: u32) {
+    unsafe { ffi::dbus_message_set_serial(m.msg, s) };
+}
+
+#[cfg(test)]
+mod test {
+    extern crate tempdir;
+
+    use super::super::{Connection, Message, MessageType, BusType, MessageItem, OwnedFd, libc, Path, BusName};
+
+    #[test]
+    fn unix_fd() {
+        use std::io::prelude::*;
+        use std::io::SeekFrom;
+        use std::fs::OpenOptions;
+        use std::os::unix::io::AsRawFd;
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        let tempdir = tempdir::TempDir::new("dbus-rs-test").unwrap();
+        let mut filename = tempdir.path().to_path_buf();
+        filename.push("test");
+        println!("Creating file {:?}", filename);
+        let mut file = OpenOptions::new().create(true).read(true).write(true).open(&filename).unwrap();
+        file.write_all(b"z").unwrap();
+        file.seek(SeekFrom::Start(0)).unwrap();
+        let ofd = OwnedFd::new(file.as_raw_fd());
+        m.append_items(&[MessageItem::UnixFd(ofd.clone())]);
+        println!("Sending {:?}", m.get_items());
+        c.send(m).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                let z: OwnedFd = n.read1().unwrap();
+                println!("Got {:?}", z);
+                let mut q: libc::c_char = 100;
+                assert_eq!(1, unsafe { libc::read(z.as_raw_fd(), &mut q as *mut _ as *mut libc::c_void, 1) });
+                assert_eq!(q, 'z' as libc::c_char);
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        }}
+    }
+
+    #[test]
+    fn message_types() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        m.append_items(&[
+            2000u16.into(),
+            MessageItem::new_array(vec!(129u8.into())).unwrap(),
+            ["Hello", "world"][..].into(),
+            987654321u64.into(),
+            (-1i32).into(),
+            format!("Hello world").into(),
+            (-3.14f64).into(),
+            MessageItem::Struct(vec!(256i16.into())),
+            Path::new("/some/path").unwrap().into(),
+            MessageItem::new_array(vec!((123543u32.into(), true.into()).into())).unwrap()
+        ]);
+        let sending = format!("{:?}", m.get_items());
+        println!("Sending {}", sending);
+        c.send(m).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                let receiving = format!("{:?}", n.get_items());
+                println!("Receiving {}", receiving);
+                assert_eq!(sending, receiving);
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        }}
+    }
+
+    #[test]
+    fn dict_of_dicts() {
+        use std::collections::BTreeMap;
+
+        let officeactions: BTreeMap<&'static str, MessageItem> = BTreeMap::new();
+        let mut officethings = BTreeMap::new();
+        officethings.insert("pencil", 2u16.into());
+        officethings.insert("paper", 5u16.into());
+        let mut homethings = BTreeMap::new();
+        homethings.insert("apple", 11u16.into());
+        let mut homeifaces = BTreeMap::new();
+        homeifaces.insert("getThings", homethings);
+        let mut officeifaces = BTreeMap::new();
+        officeifaces.insert("getThings", officethings);
+        officeifaces.insert("getActions", officeactions);
+        let mut paths = BTreeMap::new();
+        paths.insert("/hello/office", officeifaces);
+        paths.insert("/hello/home", homeifaces);
+
+        println!("Original treemap: {:?}", paths);
+        let m = MessageItem::new_array(paths.iter().map(
+            |(path, ifaces)| (MessageItem::ObjectPath(Path::new(*path).unwrap()),
+                MessageItem::new_array(ifaces.iter().map(
+                    |(iface, props)| (iface.to_string().into(),
+                        MessageItem::from_dict::<(),_>(props.iter().map(
+                            |(name, value)| Ok((name.to_string(), value.clone()))
+                        )).unwrap()
+                    ).into()
+                ).collect()).unwrap()
+            ).into()
+        ).collect()).unwrap();
+        println!("As MessageItem: {:?}", m);
+        assert_eq!(&*m.signature(), "a{oa{sa{sv}}}");
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut msg = Message::new_method_call(&c.unique_name(), "/hello", "org.freedesktop.DBusObjectManager", "GetManagedObjects").unwrap();
+        msg.append_items(&[m]);
+        let sending = format!("{:?}", msg.get_items());
+        println!("Sending {}", sending);
+        c.send(msg).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                let receiving = format!("{:?}", n.get_items());
+                println!("Receiving {}", receiving);
+                assert_eq!(sending, receiving);
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        } }
+    }
+
+    #[test]
+    fn issue24() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let mut m = Message::new_method_call("org.test.rust", "/", "org.test.rust", "Test").unwrap();
+
+        let a = MessageItem::from("test".to_string());
+        let b = MessageItem::from("test".to_string());
+        let foo = MessageItem::Struct(vec!(a, b));
+        let bar = foo.clone();
+
+        let args = [MessageItem::new_array(vec!(foo, bar)).unwrap()];
+        println!("{:?}", args);
+
+        m.append_items(&args);
+        c.send(m).unwrap();
+    }
+
+    #[test]
+    fn set_valid_destination() {
+        let mut m = Message::new_method_call("org.test.rust", "/", "org.test.rust", "Test").unwrap();
+        let d = Some(BusName::new(":1.14").unwrap());
+        m.set_destination(d);
+
+        assert!(!m.get_no_reply());
+        m.set_no_reply(true);
+        assert!(m.get_no_reply());
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/methoddisp.rs
@@ -0,0 +1,1058 @@
+/// NOTE: No longer used - replaced with files in the "tree" directory.
+
+
+#![allow(dead_code)]
+
+use {MessageItem, Message, MessageType, Connection, ConnectionItem, Error, ErrorName};
+use {Signature, Member, Path};
+use Interface as IfaceName;
+use std::cell::RefCell;
+use std::sync::{Arc, Mutex};
+use std::collections::BTreeMap;
+use std::marker::PhantomData;
+use std::ffi::{CStr, CString};
+use std::fmt;
+use super::arg;
+
+type ArcMap<K, V> = BTreeMap<Arc<K>, Arc<V>>;
+
+#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
+/// A D-Bus Argument.
+pub struct Argument(Option<String>, Signature<'static>);
+
+impl Argument {
+    /// Create a new Argument.
+    pub fn new(name: Option<String>, sig: Signature<'static>) -> Argument { Argument(name, sig) }
+
+    fn introspect(&self, indent: &str, dir: &str) -> String { 
+        let n = self.0.as_ref().map(|n| format!("name=\"{}\" ", n)).unwrap_or("".into());
+        format!("{}<arg {}type=\"{}\"{}/>\n", indent, n, self.1, dir)
+    }
+    fn introspect_all(args: &[Argument], indent: &str, dir: &str) -> String {
+        args.iter().fold("".to_string(), |aa, az| format!("{}{}", aa, az.introspect(indent, dir)))
+    }
+}
+
+// Small helper struct to reduce memory somewhat for objects without annotations
+#[derive(Clone, Debug, Default)]
+struct Annotations(Option<BTreeMap<String, String>>);
+
+impl Annotations {
+    fn new() -> Annotations { Annotations(None) }
+
+    fn insert<N: Into<String>, V: Into<String>>(&mut self, n: N, v: V) {
+       if self.0.is_none() { self.0 = Some(BTreeMap::new()) }
+        self.0.as_mut().unwrap().insert(n.into(), v.into());
+    }
+
+    fn introspect(&self, indent: &str) -> String {
+        self.0.as_ref().map(|s| s.iter().fold("".into(), |aa, (ak, av)| {
+            format!("{}{}<annotation name=\"{}\" value=\"{}\"/>\n", aa, indent, ak, av)
+        })).unwrap_or(String::new())
+    }
+}
+
+// Doesn't work, conflicting impls
+// impl<S: Into<Signature>> From<S> for Argument
+
+impl From<Signature<'static>> for Argument {
+    fn from(t: Signature<'static>) -> Argument { Argument(None, t) }
+}
+
+impl<'a> From<&'a str> for Argument {
+    fn from(t: &'a str) -> Argument { Argument(None, String::from(t).into()) }
+}
+
+impl<N: Into<String>, S: Into<Signature<'static>>> From<(N, S)> for Argument {
+    fn from((n, s): (N, S)) -> Argument { Argument(Some(n.into()), s.into()) }
+}
+
+#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
+/// A D-Bus Method Error.
+pub struct MethodErr(ErrorName<'static>, String);
+
+impl MethodErr {
+    /// Create an Invalid Args MethodErr.
+    pub fn invalid_arg<T: fmt::Debug>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.InvalidArgs", format!("Invalid argument {:?}", a)).into()
+    }
+    /// Create a MethodErr that there are not enough arguments given.
+    pub fn no_arg() -> MethodErr {
+        ("org.freedesktop.DBus.Error.InvalidArgs", "Not enough arguments").into()
+    }
+    /// Create a MethodErr that the method failed in the way specified.
+    pub fn failed<T: fmt::Display>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.Failed", a.to_string()).into()
+    }
+    /// Create a MethodErr that the Interface was unknown.
+    pub fn no_interface<T: fmt::Display>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownInterface", format!("Unknown interface {}", a)).into()
+    }
+    /// Create a MethodErr that the Property was unknown.
+    pub fn no_property<T: fmt::Display>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownProperty", format!("Unknown property {}", a)).into()
+    }
+    /// Create a MethodErr that the Property was read-only.
+    pub fn ro_property<T: fmt::Display>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.PropertyReadOnly", format!("Property {} is read only", a)).into()
+    }
+}
+
+impl<T: Into<ErrorName<'static>>, M: Into<String>> From<(T, M)> for MethodErr {
+    fn from((t, m): (T, M)) -> MethodErr { MethodErr(t.into(), m.into()) }
+}
+
+/// Result containing the Messages returned from the Method, or a MethodErr.
+pub type MethodResult = Result<Vec<Message>, MethodErr>;
+
+/// A MethodType that wraps an Fn function
+pub struct MethodFn<'a>(Box<Fn(&Message, &ObjectPath<MethodFn<'a>>, &Tree<MethodFn<'a>>) -> MethodResult + 'a>);
+/// A MethodType that wraps an FnMut function. Calling this recursively will cause a refcell panic.
+pub struct MethodFnMut<'a>(Box<RefCell<FnMut(&Message, &ObjectPath<MethodFnMut<'a>>, &Tree<MethodFnMut<'a>>) -> MethodResult + 'a>>);
+/// A MethodType that wraps an Fn+Send+Sync function, so it can be called from several threads in parallel.
+pub struct MethodSync(Box<Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static>);
+
+impl<'a> fmt::Debug for MethodFn<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Fn>") }
+}
+
+impl<'a> fmt::Debug for MethodFnMut<'a> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<FnMut>") }
+}
+
+impl fmt::Debug for MethodSync {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Fn + Send + Sync>") }
+}
+
+/// A helper trait used internally to make the tree generic over MethodFn, MethodFnMut and MethodSync.
+pub trait MethodType: Sized {
+    fn call_method(&self, m: &Message, o: &ObjectPath<Self>, i: &Tree<Self>) -> MethodResult;
+    fn box_method<H>(h: H) -> Self
+    where H: Fn(&Message, &ObjectPath<Self>, &Tree<Self>) -> MethodResult + Send + Sync + 'static;
+}
+
+impl<'a> MethodType for MethodFn<'a> {
+    fn call_method(&self, m: &Message, o: &ObjectPath<MethodFn<'a>>, i: &Tree<MethodFn<'a>>) -> MethodResult { self.0(m, o, i) }
+
+    fn box_method<H>(h: H) -> Self
+    where H: Fn(&Message, &ObjectPath<MethodFn<'a>>, &Tree<MethodFn<'a>>) -> MethodResult + Send + Sync + 'static {
+        MethodFn(Box::new(h))
+    }
+}
+
+impl MethodType for MethodSync {
+    fn call_method(&self, m: &Message, o: &ObjectPath<MethodSync>, i: &Tree<MethodSync>) -> MethodResult { self.0(m, o, i) }
+
+    fn box_method<H>(h: H) -> Self
+    where H: Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static {
+        MethodSync(Box::new(h))
+    }
+}
+
+impl<'a> MethodType for MethodFnMut<'a> {
+    fn call_method(&self, m: &Message, o: &ObjectPath<MethodFnMut<'a>>, i: &Tree<MethodFnMut<'a>>) -> MethodResult {
+        let mut z = self.0.borrow_mut();
+        (&mut *z)(m, o, i)
+    }
+
+    fn box_method<H>(h: H) -> Self
+    where H: Fn(&Message, &ObjectPath<MethodFnMut<'a>>, &Tree<MethodFnMut<'a>>) -> MethodResult + Send + Sync + 'static {
+        MethodFnMut(Box::new(RefCell::new(h)))
+    }
+}
+
+#[derive(Debug)]
+/// A D-Bus Method.
+pub struct Method<M> {
+    cb: M,
+    name: Arc<Member<'static>>,
+    i_args: Vec<Argument>,
+    o_args: Vec<Argument>,
+    anns: Annotations,
+}
+
+impl<M> Method<M> {
+    /// Builder method that adds an "in" Argument to this Method.
+    pub fn in_arg<A: Into<Argument>>(mut self, a: A) -> Self { self.i_args.push(a.into()); self }
+    /// Builder method that adds an "in" Argument to this Method.
+    pub fn inarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.i_args.push((s.into(), A::signature()).into()); self }
+    /// Builder method that adds multiple "in" Arguments to this Method.
+    pub fn in_args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.i_args.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Builder method that adds an "out" Argument to this Method.
+    pub fn out_arg<A: Into<Argument>>(mut self, a: A) -> Self { self.o_args.push(a.into()); self }
+    /// Builder method that adds an "out" Argument to this Method.
+    pub fn outarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.o_args.push((s.into(), A::signature()).into()); self }
+    /// Builder method that adds multiple "out" Arguments to this Method.
+    pub fn out_args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.o_args.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Add an annotation to the method.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+    /// Add an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+}
+
+impl<M: MethodType> Method<M> {
+    /// Call the Method.
+    pub fn call(&self, m: &Message, o: &ObjectPath<M>, i: &Tree<M>) -> MethodResult { self.cb.call_method(m, o, i) }
+
+    fn new(n: Member<'static>, cb: M) -> Self { Method { name: Arc::new(n), i_args: vec!(),
+        o_args: vec!(), anns: Annotations::new(), cb: cb } }
+}
+
+
+#[derive(Debug)]
+/// Represents a D-Bus interface.
+pub struct Interface<M> {
+    name: Arc<IfaceName<'static>>,
+    methods: ArcMap<Member<'static>, Method<M>>,
+    signals: ArcMap<Member<'static>, Signal>,
+    properties: ArcMap<String, Property<M>>,
+    anns: Annotations,
+}
+
+impl<M> Interface<M> {
+    /// Adds a method to the interface.
+    pub fn add_m(mut self, m: Method<M>) -> Self { self.methods.insert(m.name.clone(), Arc::new(m)); self }
+    /// Adds a signal to the interface.
+    pub fn add_s(mut self, s: Signal) -> Self { self.signals.insert(s.name.clone(), Arc::new(s)); self }
+    /// Adds a signal to the interface. Lets you keep another clone of the signal
+    /// (which you can use to emit the signal, once it belongs to an object path).
+    ///
+    /// Note: You are not allowed to add a signal to more than one interface.
+    pub fn add_s_arc(mut self, s: Arc<Signal>) -> Self { self.signals.insert(s.name.clone(), s); self }
+    /// Adds a signal to the interface. Returns a reference to the signal
+    /// (which you can use to emit the signal, once it belongs to an object path).
+    pub fn add_s_ref(&mut self, s: Signal) -> Arc<Signal> {
+        let s = Arc::new(s);
+        self.signals.insert(s.name.clone(), s.clone());
+        s
+    }
+
+    /// Adds a property to the interface.
+    pub fn add_p(mut self, p: Property<M>) -> Self { self.properties.insert(p.name.clone(), Arc::new(p)); self }
+    /// Adds a property to the interface. Lets you keep another clone of the property
+    /// (which you can use to get and set the current value of the property).
+    ///
+    /// Note: You are not allowed to add a property to more than one interface. Later function calls might panic if you do so.
+    pub fn add_p_arc(mut self, p: Arc<Property<M>>) -> Self { self.properties.insert(p.name.clone(), p); self }
+    /// Adds a property to the interface. Returns a reference to the property
+    /// (which you can use to get and set the current value of the property).
+    pub fn add_p_ref(&mut self, p: Property<M>) -> Arc<Property<M>> {
+        let p = Arc::new(p);
+        self.properties.insert(p.name.clone(), p.clone());
+        p
+    }
+
+    /// Add an annotation to this Inteface.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+    /// Add an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    fn new(t: IfaceName<'static>) -> Interface<M> {
+        Interface { name: Arc::new(t), methods: BTreeMap::new(), signals: BTreeMap::new(),
+            properties: BTreeMap::new(), anns: Annotations::new()
+        }
+    }
+
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
+/// Enumerates the different signaling behaviors a Property can have
+/// to being changed.
+pub enum EmitsChangedSignal {
+    /// The Property emits a signal that includes the new value.
+    True,
+    /// The Property emits a signal that does not include the new value.
+    Invalidates,
+    /// The Property cannot be changed.
+    Const,
+    /// The Property does not emit a signal when changed.
+    False,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
+/// The possible access characteristics a Property can have.
+pub enum Access {
+    /// The Property can only be read (Get).
+    Read,
+    /// The Property can be read or written.
+    ReadWrite,
+    /// The Property can only be written (Set).
+    Write,
+}
+
+impl Access {
+    fn introspect(&self) -> &'static str {
+        match self {
+            &Access::Read => "read",
+            &Access::ReadWrite => "readwrite",
+            &Access::Write => "write",
+        }
+    }
+}
+
+#[derive(Debug)]
+/// A D-Bus Property.
+pub struct Property<M> {
+    name: Arc<String>,
+    value: Mutex<MessageItem>,
+    emits: EmitsChangedSignal,
+    rw: Access,
+    set_cb: Option<M>,
+    owner: Mutex<Option<(Arc<Path<'static>>, Arc<IfaceName<'static>>)>>,
+    anns: Annotations,
+}
+
+impl<M: MethodType> Property<M> {
+    /// Gets the value of the Property.
+    pub fn get_value(&self) -> MessageItem {
+        self.value.lock().unwrap().clone()
+    }
+
+    /// Gets the signal (if any) associated with the Property.
+    pub fn get_signal(&self) -> Option<Message> {
+        self.owner.lock().unwrap().as_ref().map(|&(ref p, ref i)| {
+            Message::signal(&p, &"org.freedesktop.DBus.Properties".into(), &"PropertiesChanged".into())
+                .append(String::from(&***i))
+        })
+    }
+
+    /// Returns error if "emits" is "Const", and the property is in a
+    /// tree.  Returns messages to be sent over a connection, this
+    /// could be the PropertiesChanged signal.
+    pub fn set_value(&self, m: MessageItem) -> Result<Vec<Message>,()> {
+        let ss = match self.emits {
+            EmitsChangedSignal::False => None,
+            EmitsChangedSignal::Const => if self.get_signal().is_some() { return Err(()) } else { None },
+            EmitsChangedSignal::True => self.get_signal().map(|s|
+                s.append2(arg::Dict::new(vec!((&**self.name, arg::Variant(m.clone())))), arg::Array::<&str, _>::new(vec!()))
+            ),
+            EmitsChangedSignal::Invalidates => self.get_signal().map(|s| {
+                s.append2(arg::Dict::<&str, arg::Variant<MessageItem>, _>::new(vec!()), arg::Array::new(vec!(&**self.name)))
+            }),
+        };
+        *self.value.lock().unwrap() = m;
+        Ok(ss.map(|s| vec!(s)).unwrap_or(vec!()))
+    }
+
+    /// Builder method that allows setting the Property's signal
+    /// behavior when changed.
+    pub fn emits_changed(mut self, e: EmitsChangedSignal) -> Self {
+        self.emits = e;
+        assert!(self.rw == Access::Read || self.emits != EmitsChangedSignal::Const);
+        self
+    }
+
+    /// Builder method that allows setting the Property as readable,
+    /// writable, or both.
+    pub fn access(mut self, e: Access) -> Self {
+        self.rw = e;
+        assert!(self.rw == Access::Read || self.emits != EmitsChangedSignal::Const);
+        self
+    }
+
+    /// Helper method to check accessibility before getting a value.
+    pub fn remote_get(&self, _: &Message) -> Result<MessageItem, MethodErr> {
+        // TODO: We should be able to call a user-defined callback here instead...
+        if self.rw == Access::Write { return Err(MethodErr::failed(&format!("Property {} is write only", &self.name))) }
+        Ok(self.get_value())
+    }
+
+    /// Helper method to verify and extract a MessageItem from a Set message
+    pub fn verify_remote_set(&self, m: &Message) -> Result<MessageItem, MethodErr> {
+        let items = m.get_items();
+        let s: &MessageItem = try!(items.get(2).ok_or_else(|| MethodErr::no_arg())
+            .and_then(|i| i.inner().map_err(|_| MethodErr::invalid_arg(&i))));
+
+        if self.rw == Access::Read { Err(MethodErr::ro_property(&self.name)) }
+        else if s.type_sig() != self.value.lock().unwrap().type_sig() {
+            Err(MethodErr::failed(&format!("Property {} cannot change type to {}", &self.name, s.type_sig())))
+        }
+        else { Ok(s.clone()) }
+    }
+
+    fn remote_set(&self, m: &Message, o: &ObjectPath<M>, t: &Tree<M>) -> Result<Vec<Message>, MethodErr> {
+        if let Some(ref cb) = self.set_cb {
+            cb.call_method(m, o, t)
+        }
+        else {
+            let s = try!(self.verify_remote_set(m));
+            self.set_value(s).map_err(|_| MethodErr::ro_property(&self.name))
+        }
+    }
+
+    /// Add an annotation to this Property.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+
+    /// Add an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    fn new(s: String, i: MessageItem) -> Property<M> {
+        Property { name: Arc::new(s), emits: EmitsChangedSignal::True, rw: Access::Read,
+            value: Mutex::new(i), owner: Mutex::new(None), anns: Annotations::new(), set_cb: None }
+    }
+}
+
+impl Property<MethodSync> {
+    /// Sets a callback to be called when a "Set" call is coming in from the remote side.
+    /// Might change to something more ergonomic.
+    /// For multi-thread use.
+    pub fn on_set<H>(mut self, m: H) -> Self
+    where H: Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static {
+        self.set_cb = Some(MethodSync::box_method(m));
+        self
+    }
+}
+
+impl<'a> Property<MethodFn<'a>> {
+    /// Sets a callback to be called when a "Set" call is coming in from the remote side.
+    /// Might change to something more ergonomic.
+    /// For single-thread use.
+    pub fn on_set<H: 'a>(mut self, m: H) -> Self
+    where H: Fn(&Message, &ObjectPath<MethodFn<'a>>, &Tree<MethodFn<'a>>) -> MethodResult {
+        self.set_cb = Some(MethodFn(Box::new(m)));
+        self
+    }
+}
+
+impl<'a> Property<MethodFnMut<'a>> {
+    /// Sets a callback to be called when a "Set" call is coming in from the remote side.
+    /// Might change to something more ergonomic.
+    /// For single-thread use.
+    pub fn on_set<H: 'a>(mut self, m: H) -> Self
+    where H: FnMut(&Message, &ObjectPath<MethodFnMut<'a>>, &Tree<MethodFnMut<'a>>) -> MethodResult {
+        self.set_cb = Some(MethodFnMut(Box::new(RefCell::new(m))));
+        self
+    }
+}
+
+
+#[derive(Debug)]
+/// A D-Bus Signal.
+pub struct Signal {
+    name: Arc<Member<'static>>,
+    arguments: Vec<Argument>,
+    owner: Mutex<Option<(Arc<Path<'static>>, Arc<IfaceName<'static>>)>>,
+    anns: Annotations,
+}
+
+impl Signal {
+    /// Returns a message which emits the signal when sent.
+    /// Panics if the signal is not inserted in an object path.
+    pub fn emit(&self, items: &[MessageItem]) -> Message {
+        let mut m = {
+            let lock = self.owner.lock().unwrap();
+            let &(ref p, ref i) = lock.as_ref().unwrap();
+            Message::signal(p, i, &self.name)
+        };
+        m.append_items(items);
+        m
+    }
+
+    /// Returns a message which emits the signal when sent.
+    /// Panics if the signal is not inserted in an object path.
+    ///
+    /// Same as "emit" but does not take a "MessageItem" argument.
+    pub fn msg(&self) -> Message { self.emit(&[]) }
+
+    /// Builder method that adds an Argument to the Signal.
+    pub fn arg<A: Into<Argument>>(mut self, a: A) -> Self { self.arguments.push(a.into()); self }
+    /// Builder method that adds an Argument to the Signal.
+    pub fn sarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.arguments.push((s.into(), A::signature()).into()); self }
+    /// Builder method that adds multiple "rguments to the Signel.
+    pub fn args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.arguments.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Add an annotation to this Signal.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+    /// Add an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+}
+
+fn introspect_map<T, I: fmt::Display, C: Fn(&T) -> (String, String)>
+    (h: &ArcMap<I, T>, name: &str, indent: &str, func: C) -> String {
+
+    h.iter().fold("".into(), |a, (k, v)| {
+        let (params, contents) = func(v);
+        format!("{}{}<{} name=\"{}\"{}{}>\n",
+            a, indent, name, &**k, params, if contents.len() > 0 {
+                format!(">\n{}{}</{}", contents, indent, name)
+            }
+            else { format!("/") }
+        )
+    })
+}
+
+#[derive(Debug)]
+/// A D-Bus Object Path.
+pub struct ObjectPath<M> {
+    name: Arc<Path<'static>>,
+    ifaces: ArcMap<IfaceName<'static>, Interface<M>>,
+}
+
+impl<M: MethodType> ObjectPath<M> {
+    fn new(p: Path<'static>) -> ObjectPath<M> {
+        ObjectPath { name: Arc::new(p), ifaces: BTreeMap::new() }
+    }
+
+    fn get_iface<'a>(&'a self, i: Option<&'a CStr>) -> Result<&Arc<Interface<M>>, MethodErr> {
+        let iface_name = try!(i.ok_or_else(|| MethodErr::invalid_arg(&0)));
+        let j = try!(IfaceName::from_slice(iface_name.to_bytes_with_nul()).map_err(|e| MethodErr::invalid_arg(&e)));
+        self.ifaces.get(&j).ok_or_else(|| MethodErr::no_interface(&j))
+    }
+
+    fn prop_set(&self, m: &Message, o: &ObjectPath<M>, t: &Tree<M>) -> MethodResult {
+        let (iname, p) = m.get2();
+        let iface = try!(self.get_iface(iname));
+        let prop_name: &str = try!(p.ok_or_else(|| MethodErr::invalid_arg(&1)));
+        let prop: &Property<M> = try!(iface.properties.get(&String::from(prop_name))
+            .ok_or_else(|| MethodErr::no_property(&prop_name)));
+        let mut r = try!(prop.remote_set(m, o, t));
+        r.push(m.method_return());
+        Ok(r)
+    }
+
+    fn prop_get(&self, m: &Message) -> MethodResult {
+        let (iname, p) = m.get2();
+        let iface = try!(self.get_iface(iname));
+        let prop_name: &str = try!(p.ok_or_else(|| MethodErr::invalid_arg(&1)));
+        let prop: &Property<M> = try!(iface.properties.get(&String::from(prop_name))
+            .ok_or_else(|| MethodErr::no_property(&prop_name)));
+        let r = try!(prop.remote_get(m));
+        Ok(vec!(m.method_return().append1(arg::Variant(r))))
+    }
+
+    fn prop_get_all(&self, m: &Message) -> MethodResult {
+        let iface = try!(self.get_iface(m.get1()));
+        let mut q = vec!();
+        for v in iface.properties.values() {
+            q.push((&**v.name, arg::Variant(try!(v.remote_get(m)))));
+        }
+        Ok(vec!(m.method_return().append1(arg::Dict::new(q))))
+    }
+
+    fn add_property_handler(&mut self) {
+        let ifname = IfaceName::from("org.freedesktop.DBus.Properties");
+        if self.ifaces.contains_key(&ifname) { return };
+        let f: Factory<M> = Factory(PhantomData);
+
+        let i = Interface::<M>::new(ifname)
+            .add_m(f.method_sync("Get", |m,o,_| o.prop_get(m) )
+                .inarg::<&str,_>("interface_name")
+                .inarg::<&str,_>("property_name")
+                .outarg::<arg::Variant<()>,_>("value"))
+            .add_m(f.method_sync("GetAll", |m,o,_| o.prop_get_all(m))
+                .inarg::<&str,_>("interface_name")
+                .outarg::<arg::Dict<&str, arg::Variant<()>, ()>,_>("props"))
+            .add_m(f.method_sync("Set", |m,o,t| o.prop_set(m, o, t))
+                .inarg::<&str,_>("interface_name")
+                .inarg::<&str,_>("property_name")
+                .inarg::<arg::Variant<()>,_>("value"));
+        self.ifaces.insert(i.name.clone(), Arc::new(i));
+    }
+
+    /// Add an Interface to this Object Path.
+    pub fn add(mut self, p: Interface<M>) -> Self {
+        use std::mem;
+        for s in p.signals.values() {
+            let n = Some((self.name.clone(), p.name.clone()));
+            let o = mem::replace(&mut *s.owner.lock().unwrap(), n);
+            assert!(o.is_none(), "Signal {} already added to object path", s.name);
+        };
+        for s in p.properties.values() {
+            let n = Some((self.name.clone(), p.name.clone()));
+            let o = mem::replace(&mut *s.owner.lock().unwrap(), n);
+            assert!(o.is_none(), "Property {} already added to object path", s.name);
+        };
+        if !p.properties.is_empty() { self.add_property_handler(); }
+        self.ifaces.insert(p.name.clone(), Arc::new(p));
+        self
+    }
+
+    /// Adds introspection support for this object path.
+    pub fn introspectable(self) -> Self {
+        let ifname: IfaceName = "org.freedesktop.DBus.Introspectable".into();
+        if self.ifaces.contains_key(&ifname) { return self };
+        let f: Factory<M> = Factory(PhantomData);
+        self.add(Interface::<M>::new(ifname)
+            .add_m(f.method_sync("Introspect",
+                |m,o,t| Ok(vec!(m.method_return().append(o.introspect(t)))))
+                .out_arg(("xml_data", "s"))))
+    }
+
+    fn handle(&self, m: &Message, t: &Tree<M>) -> MethodResult {
+        let i = try!(m.interface().and_then(|i| self.ifaces.get(&i)).ok_or(
+            ("org.freedesktop.DBus.Error.UnknownInterface", "Unknown interface")));
+        let me = try!(m.member().and_then(|me| i.methods.get(&me)).ok_or(
+            ("org.freedesktop.DBus.Error.UnknownMethod", "Unknown method")));
+        me.call(m, &self, t)
+    }
+
+    fn introspect(&self, tree: &Tree<M>) -> String {
+        let ifacestr = introspect_map(&self.ifaces, "interface", "  ", |iv|
+            (format!(""), format!("{}{}{}{}",
+                introspect_map(&iv.methods, "method", "    ", |m| (format!(""), format!("{}{}{}",
+                    Argument::introspect_all(&m.i_args, "      ", " direction=\"in\""),
+                    Argument::introspect_all(&m.o_args, "      ", " direction=\"out\""),
+                    m.anns.introspect("      ")
+                ))),
+                introspect_map(&iv.properties, "property", "    ", |p| (
+                    format!(" type=\"{}\" access=\"{}\"", p.get_value().type_sig(), p.rw.introspect()),
+                    p.anns.introspect("      ")
+                )),
+                introspect_map(&iv.signals, "signal", "    ", |s| (format!(""), format!("{}{}",
+                    Argument::introspect_all(&s.arguments, "      ", ""),
+                    s.anns.introspect("      ")
+                ))),
+                iv.anns.introspect("    ")
+            ))
+        );
+        let olen = self.name.len()+1;
+        let childstr = tree.children(&self, true).iter().fold("".to_string(), |na, n|
+            format!("{}  <node name=\"{}\"/>\n", na, &n.name[olen..])
+        );
+
+        let nodestr = format!(r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="{}">
+{}{}</node>"##, self.name, ifacestr, childstr);
+        nodestr
+    }
+
+    fn get_managed_objects(&self, t: &Tree<M>) -> MessageItem {
+        let mut paths = t.children(&self, false);
+        paths.push(&self);
+        MessageItem::Array(
+            paths.iter().map(|p| ((&*p.name).clone().into(), MessageItem::Array(
+                p.ifaces.values().map(|i| ((&**i.name).into(), MessageItem::Array(
+                    i.properties.values().map(|pp| ((&**pp.name).into(), Box::new(pp.get_value()
+                    ).into()).into()).collect(), "{sv}".into()
+                )).into()).collect(), "{sa{sv}}".into()
+            )).into()).collect(), "{oa{sa{sv}}}".into()
+        )
+    }
+
+    /// Adds ObjectManager support for this object path.
+    ///
+    /// It is not possible to add/remove interfaces while the object path belongs to a tree,
+    /// hence no InterfacesAdded / InterfacesRemoved signals are sent.
+    pub fn object_manager(self) -> Self {
+        let ifname: IfaceName = "org.freedesktop.DBus.ObjectManager".into();
+        if self.ifaces.contains_key(&ifname) { return self };
+        let f: Factory<M> = Factory(PhantomData);
+        self.add(Interface::<M>::new(ifname)
+            .add_m(f.method_sync("GetManagedObjects",
+                |m,o,t| Ok(vec!(m.method_return().append(o.get_managed_objects(t)))))
+                .out_arg("a{oa{sa{sv}}}")))
+    }
+}
+
+/// An iterator adapter that handles incoming method calls.
+///
+/// Method calls that match an object path in the tree are handled and consumed by this
+/// iterator. Other messages are passed through.
+pub struct TreeServer<'a, I, M: 'a> {
+    iter: I,
+    conn: &'a Connection,
+    tree: &'a Tree<M>,
+}
+
+impl<'a, I: Iterator<Item=ConnectionItem>, M: 'a + MethodType> Iterator for TreeServer<'a, I, M> {
+    type Item = ConnectionItem;
+
+    fn next(&mut self) -> Option<ConnectionItem> {
+        loop {
+            let n = self.iter.next();
+            if let &Some(ConnectionItem::MethodCall(ref msg)) = &n {
+                if let Some(v) = self.tree.handle(&msg) {
+                    // Probably the wisest is to ignore any send errors here -
+                    // maybe the remote has disconnected during our processing.
+                    for m in v { let _ = self.conn.send(m); };
+                    continue;
+                }
+            }
+            return n;
+        }
+    }
+}
+
+/// A collection of object paths.
+#[derive(Debug)]
+pub struct Tree<M> {
+    paths: ArcMap<Path<'static>, ObjectPath<M>>
+}
+
+impl<M: MethodType> Tree<M> {
+
+    fn children(&self, o: &ObjectPath<M>, direct_only: bool) -> Vec<&ObjectPath<M>> {
+        let parent: &str = &o.name;
+        let plen = parent.len()+1;
+        self.paths.values().filter_map(|v| {
+            let k: &str = &v.name;
+            if !k.starts_with(parent) || k.len() <= plen || &k[plen-1..plen] != "/" {None} else {
+                let child = &k[plen..];
+                if direct_only && child.contains("/") {None} else {Some(&**v)}
+            }
+        }).collect()
+    }
+
+    /// Add an Object Path to this Tree.
+    ///
+    /// Note: This does not unregister a path with the connection, so if the tree is currently registered,
+    /// you might want to call Connection::register_object_path to add the path manually.
+    pub fn add(mut self, p: ObjectPath<M>) -> Self {
+        self.paths.insert(p.name.clone(), Arc::new(p));
+        self
+    }
+
+    /// Adds an ObjectPath to this Tree. Returns a reference to the ObjectPath.
+    /// The note for add() also applies here.
+    pub fn add_o_ref(&mut self, p: ObjectPath<M>) -> Arc<ObjectPath<M>> {
+        let name = p.name.clone();
+        let o = Arc::new(p);
+        self.paths.insert(name, o.clone());
+        o
+    }
+
+    /// Remove a object path from the Tree. Returns the object path removed, or None if not found.
+    ///
+    /// Note: This does not unregister a path with the connection, so if the tree is currently registered,
+    /// you might want to call Connection::unregister_object_path to remove the path manually.
+    pub fn remove(&mut self, p: &Path<'static>) -> Option<Arc<ObjectPath<M>>> {
+        // There is no real reason p needs to have a static lifetime; but
+        // the borrow checker doesn't agree. :-(
+        self.paths.remove(p)
+    }
+
+    /// Registers or unregisters all object paths in the tree.
+    pub fn set_registered(&self, c: &Connection, b: bool) -> Result<(), Error> {
+        let mut regd_paths = Vec::new();
+        for p in self.paths.keys() {
+            if b {
+                match c.register_object_path(p) {
+                    Ok(()) => regd_paths.push(p.clone()),
+                    Err(e) => {
+                        while let Some(rp) = regd_paths.pop() {
+                            c.unregister_object_path(&rp);
+                        }
+                        return Err(e)
+                    }
+                }
+            } else {
+                c.unregister_object_path(p);
+            }
+        }
+        Ok(())
+    }
+
+    /// Handles a message. Will return None in case the object path was not
+    /// found, or otherwise a list of messages to be sent back.
+    pub fn handle(&self, m: &Message) -> Option<Vec<Message>> {
+        if m.msg_type() != MessageType::MethodCall { None }
+        else { m.path().and_then(|p| self.paths.get(&p).map(|s| s.handle(m, &self)
+            .unwrap_or_else(|e| vec!(m.error(&e.0, &CString::new(e.1).unwrap()))))) }
+    }
+
+    /// This method takes an `ConnectionItem` iterator (you get it from `Connection::iter()`)
+    /// and handles all matching items. Non-matching items (e g signals) are passed through.
+    pub fn run<'a, I: Iterator<Item=ConnectionItem>>(&'a self, c: &'a Connection, i: I) -> TreeServer<'a, I, M> {
+        TreeServer { iter: i, tree: &self, conn: c }
+    }
+}
+
+/// The factory is used to create object paths, interfaces, methods etc.
+///
+/// There are three factories:
+///
+///  **Fn** - all methods are `Fn()`.
+///
+///  **FnMut** - all methods are `FnMut()`. This means they can mutate their environment,
+///  which has the side effect that if you call it recursively, it will RefCell panic.
+///
+///  **Sync** - all methods are `Fn() + Send + Sync + 'static`. This means that the methods
+///  can be called from different threads in parallel.
+#[derive(Debug, Copy, Clone)]
+pub struct Factory<M>(PhantomData<M>);
+
+impl<'a> Factory<MethodFn<'a>> {
+
+    /// Creates a new factory for single-thread use.
+    pub fn new_fn() -> Self { Factory(PhantomData) }
+
+    /// Creates a new method for single-thread use.
+    pub fn method<'b, H: 'b, T>(&self, t: T, handler: H) -> Method<MethodFn<'b>>
+    where H: Fn(&Message, &ObjectPath<MethodFn<'b>>, &Tree<MethodFn<'b>>) -> MethodResult, T: Into<Member<'static>> {
+        Method::new(t.into(), MethodFn(Box::new(handler)))
+    }
+
+    /// Creates a new property for single-thread use.
+    pub fn property<'b, T: Into<String>, I: Into<MessageItem>>(&self, t: T, i: I) -> Property<MethodFn<'b>> {
+        Property::new(t.into(), i.into())
+    }
+
+    /// Creates a new interface for single-thread use.
+    pub fn interface<'b, T: Into<IfaceName<'static>>>(&self, t: T) -> Interface<MethodFn<'b>> { Interface::new(t.into()) }
+
+    /// Creates a new tree for single-thread use.
+    pub fn tree<'b>(&self) -> Tree<MethodFn<'b>> { Tree { paths: BTreeMap::new() }}
+
+    /// Creates a new object path for single-thread use.
+    pub fn object_path<'b, T: Into<Path<'static>>>(&self, t: T) -> ObjectPath<MethodFn<'b>> { ObjectPath::new(t.into()) }
+}
+
+impl<'a> Factory<MethodFnMut<'a>> {
+
+    /// Creates a new factory for single-thread + mutable fns use.
+    pub fn new_fnmut() -> Self { Factory(PhantomData) }
+
+    /// Creates a new method for single-thread use.
+    /// This method can mutate its environment, so it will panic in case
+    /// it is called recursively.
+    pub fn method<'b, H: 'b, T>(&self, t: T, handler: H) -> Method<MethodFnMut<'b>>
+    where H: FnMut(&Message, &ObjectPath<MethodFnMut<'b>>, &Tree<MethodFnMut<'b>>) -> MethodResult, T: Into<Member<'static>> {
+        Method::new(t.into(), MethodFnMut(Box::new(RefCell::new(handler))))
+    }
+
+    /// Creates a new mutable property for single-thread use.
+    pub fn property<'b, T: Into<String>, I: Into<MessageItem>>(&self, t: T, i: I) -> Property<MethodFnMut<'b>> {
+        Property::new(t.into(), i.into())
+    }
+
+    /// Creates a new mutable interface for single-thread use.
+    pub fn interface<'b, T: Into<IfaceName<'static>>>(&self, t: T) -> Interface<MethodFnMut<'b>> { Interface::new(t.into()) }
+
+    /// Creates a new mutable tree for single-thread use.
+    pub fn tree<'b>(&self) -> Tree<MethodFnMut<'b>> { Tree { paths: BTreeMap::new() }}
+
+    /// Creates a new mutable object path for single-thread use.
+    pub fn object_path<'b, T: Into<Path<'static>>>(&self, t: T) -> ObjectPath<MethodFnMut<'b>> { ObjectPath::new(t.into()) }
+}
+
+impl Factory<MethodSync> {
+
+    /// Creates a new factory for multi-thread use.
+    /// Trees created will be able to Send and Sync, i e,
+    /// it can handle several messages in parallel.
+    pub fn new_sync() -> Self { Factory(PhantomData) }
+
+    /// Creates a new method for multi-thread use.
+    /// This puts bounds on the callback to enable it to be called from several threads
+    /// in parallel.
+    pub fn method<H, T>(&self, t: T, handler: H) -> Method<MethodSync>
+    where H: Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static, T: Into<Member<'static>> {
+        Method::new(t.into(), MethodSync(Box::new(handler)))
+    }
+
+    /// Creates a new property for multi-threaded use.
+    pub fn property<T: Into<String>, I: Into<MessageItem>>(&self, t: T, i: I) -> Property<MethodSync> {
+        Property::new(t.into(), i.into())
+    }
+
+    /// Creates a new interface for multi-threaded use.
+    pub fn interface<T: Into<IfaceName<'static>>>(&self, t: T) -> Interface<MethodSync> { Interface::new(t.into()) }
+
+    /// Creates a new tree for multi-threaded use.
+    pub fn tree(&self) -> Tree<MethodSync> { Tree { paths: BTreeMap::new() }}
+
+    /// Creates a new object path for multi-threaded use.
+    pub fn object_path<T: Into<Path<'static>>>(&self, t: T) -> ObjectPath<MethodSync> { ObjectPath::new(t.into()) }
+}
+
+impl<M> Factory<M> {
+    /// Create a Signal.
+    pub fn signal<T: Into<Member<'static>>>(&self, t: T) -> Signal {
+        Signal { name: Arc::new(t.into()), arguments: vec!(), owner: Mutex::new(None), anns: Annotations::new() }
+    }
+}
+
+impl<M: MethodType> Factory<M> {
+    /// Creates a new method with bounds enough to be used in all trees.
+    pub fn method_sync<H, T>(&self, t: T, handler: H) -> Method<M>
+    where H: Fn(&Message, &ObjectPath<M>, &Tree<M>) -> MethodResult + Send + Sync + 'static, T: Into<Member<'static>> {
+        Method::new(t.into(), M::box_method(handler))
+    }
+}
+
+#[test]
+fn factory_test() {
+    let f = Factory::new_fn();
+    f.interface("com.example.hello").deprecated();
+    let b = 5i32;
+    f.method("GetSomething", |m,_,_| Ok(vec!({ let mut z = m.method_return(); z.append_items(&[b.into()]); z})));
+    let t = f.tree().add(f.object_path("/funghi").add(f.interface("a.b.c").deprecated()));
+    let t = t.add(f.object_path("/ab")).add(f.object_path("/a")).add(f.object_path("/a/b/c")).add(f.object_path("/a/b"));
+    assert_eq!(t.children(t.paths.get(&Path::from("/a")).unwrap(), true).len(), 1);
+}
+
+#[test]
+fn test_sync_prop() {
+    let f = Factory::new_sync();
+    let mut i = f.interface("com.example.echo");
+    let p = i.add_p_ref(f.property("EchoCount", 7i32));
+    let tree1 = Arc::new(f.tree().add(f.object_path("/echo").introspectable().add(i)));
+    let tree2 = tree1.clone();
+    println!("{:#?}", tree2);
+    ::std::thread::spawn(move || {
+        let r = p.set_value(9i32.into()).unwrap();
+        let signal = r.get(0).unwrap();
+        assert_eq!(signal.msg_type(), MessageType::Signal);
+        let mut msg = Message::new_method_call("com.example.echoserver", "/echo", "com.example", "dummy").unwrap();
+        super::message::message_set_serial(&mut msg, 3);
+        tree2.handle(&msg);
+    });
+
+    let mut msg = Message::new_method_call("com.example.echoserver", "/echo", "org.freedesktop.DBus.Properties", "Get").unwrap()
+        .append("com.example.echo").append("EchoCount");
+    super::message::message_set_serial(&mut msg, 4);
+    let r = tree1.handle(&msg).unwrap();
+    let r1 = r.get(0).unwrap();
+    println!("{:?}", r1.get_items());
+    let vv: super::arg::Variant<i32> = r1.get1().unwrap();
+    assert!(vv.0 == 7 || vv.0 == 9);
+}
+
+/* This test case no longer works, for unknown reason, see
+   https://github.com/diwic/dbus-rs/issues/27
+
+#[test]
+fn prop_lifetime_simple() {
+    let count;
+    let f = Factory::new_fnmut();
+    count = Arc::new(f.property("changes", 0i32));
+    let mut i = f.interface("com.example.dbus.rs").add_p_arc(count.clone());
+
+    let _setme = i.add_p_ref(f.property("setme", 0u8).access(Access::ReadWrite).on_set(|_,_,_| {
+        let v: i32 = count.get_value().inner().unwrap();
+        count.set_value((v + 1).into()).unwrap();
+        Ok(vec!())
+    }));
+}
+*/
+
+#[test]
+fn prop_server() {
+    let setme: Arc<RefCell<Option<Arc<Property<_>>>>>; // Yikes!
+    setme = Arc::new(RefCell::new(None));
+    let f = Factory::new_fnmut();
+    let mut i = f.interface("com.example.dbus.rs");
+    let count = i.add_p_ref(f.property("changes", 0i32));
+    let count2 = count.clone();
+    let setme2 = setme.clone();
+    let setme3 = Arc::new(f.property("setme", 0u8).access(Access::ReadWrite).on_set(move |m,_,_| {
+        let ss2 = setme2.borrow();
+        let ss = ss2.as_ref().unwrap();
+        let s = try!(ss.verify_remote_set(m));
+        let r = try!(ss.set_value(s).map_err(|_| MethodErr::ro_property(&ss.name)));
+        let v: i32 = count2.get_value().inner().unwrap();
+        count2.set_value((v + 1).into()).unwrap();
+        Ok(r)
+    }));
+    *setme.borrow_mut() = Some(setme3.clone());
+    let i = i.add_p_arc(setme3);
+
+    let tree = f.tree().add(f.object_path("/example").add(i));
+
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Get").unwrap()
+        .append("com.example.dbus.rs").append("changes");
+    super::message::message_set_serial(&mut msg, 10);
+    let r = tree.handle(&msg).unwrap();
+    let r1 = r.get(0).unwrap();
+    let ii = r1.get_items();
+    let vv: &MessageItem = ii.get(0).unwrap().inner().unwrap();
+    let v: i32 = vv.inner().unwrap();
+    assert_eq!(v, 0);
+
+    // Read-only
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append("com.example.dbus.rs").append("changes").append(5i32);
+    super::message::message_set_serial(&mut msg, 20);
+    let mut r = tree.handle(&msg).unwrap();
+    assert!(r.get_mut(0).unwrap().as_result().is_err());
+
+    // Wrong type
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append("com.example.dbus.rs").append("setme").append(8i32);
+    super::message::message_set_serial(&mut msg, 30);
+    let mut r = tree.handle(&msg).unwrap();
+    assert!(r.get_mut(0).unwrap().as_result().is_err());
+
+    // Correct!
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append("com.example.dbus.rs").append("setme").append(Box::new(9u8.into()));
+    super::message::message_set_serial(&mut msg, 30);
+    let mut r = tree.handle(&msg).unwrap();
+
+    println!("{:?}", r[0].as_result());
+
+    let c: i32 = count.get_value().inner().unwrap();
+    assert_eq!(c, 1);
+
+}
+
+
+#[test]
+fn test_introspection() {
+    let f = Factory::new_sync();
+    let t = f.object_path("/echo").introspectable()
+        .add(f.interface("com.example.echo")
+            .add_m(f.method("Echo", |_,_,_| unimplemented!()).in_arg(("request", "s")).out_arg(("reply", "s")))
+            .add_p(f.property("EchoCount", 7i32))
+            .add_s(f.signal("Echoed").arg(("data", "s")).deprecated())
+    );
+
+    let actual_result = t.introspect(&f.tree().add(f.object_path("/echo/subpath")));
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/echo">
+  <interface name="com.example.echo">
+    <method name="Echo">
+      <arg name="request" type="s" direction="in"/>
+      <arg name="reply" type="s" direction="out"/>
+    </method>
+    <property name="EchoCount" type="i" access="read"/>
+    <signal name="Echoed">
+      <arg name="data" type="s"/>
+      <annotation name="org.freedesktop.DBus.Deprecated" value="true"/>
+    </signal>
+  </interface>
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Properties">
+    <method name="Get">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="property_name" type="s" direction="in"/>
+      <arg name="value" type="v" direction="out"/>
+    </method>
+    <method name="GetAll">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="props" type="a{sv}" direction="out"/>
+    </method>
+    <method name="Set">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="property_name" type="s" direction="in"/>
+      <arg name="value" type="v" direction="in"/>
+    </method>
+  </interface>
+  <node name="subpath"/>
+</node>"##;
+ 
+    assert_eq!(expected_result, actual_result);   
+}
+
rename from third_party/rust/dbus/src/objpath.rs
rename to third_party/rust/dbus-0.6.5/src/objpath.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/prop.rs
@@ -0,0 +1,136 @@
+use super::{Connection, Message, MessageItem, Error, Path, Interface, BusName};
+use std::collections::BTreeMap;
+
+/// Client side properties - get and set properties on a remote application.
+pub struct Props<'a> {
+    name: BusName<'a>,
+    path: Path<'a>,
+    interface: Interface<'a>,
+    timeout_ms: i32,
+    conn: &'a Connection,
+}
+
+impl<'a> Props<'a> {
+    /// Create a new Props.
+    pub fn new<N, P, I>(conn: &'a Connection, name: N, path: P, interface: I, timeout_ms: i32) -> Props<'a>
+    where N: Into<BusName<'a>>, P: Into<Path<'a>>, I: Into<Interface<'a>> {
+        Props {
+            name: name.into(),
+            path: path.into(),
+            interface: interface.into(),
+            timeout_ms: timeout_ms,
+            conn: conn,
+        }
+    }
+
+    /// Get a single property's value.
+    pub fn get(&self, propname: &str) -> Result<MessageItem, Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"Get".into());
+        m.append_items(&[self.interface.to_string().into(), propname.to_string().into()]);
+        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
+        let reply = try!(r.as_result()).get_items();
+        if reply.len() == 1 {
+            if let &MessageItem::Variant(ref v) = &reply[0] {
+                return Ok((**v).clone())
+            }
+       }
+       let f = format!("Invalid reply for property get {}: '{:?}'", propname, reply);
+       return Err(Error::new_custom("InvalidReply", &f));
+    }
+
+    /// Set a single property's value.
+    pub fn set(&self, propname: &str, value: MessageItem) -> Result<(), Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"Set".into());
+        m.append_items(&[self.interface.to_string().into(), propname.to_string().into(), Box::new(value).into()]);
+        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
+        try!(r.as_result());
+        Ok(())
+    }
+
+    /// Get a map of all the properties' names and their values.
+    pub fn get_all(&self) -> Result<BTreeMap<String, MessageItem>, Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"GetAll".into());
+        m.append_items(&[self.interface.to_string().into()]);
+        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
+        let reply = try!(r.as_result()).get_items();
+
+        (|| {
+            if reply.len() != 1 { return Err(()) };
+            let mut t = BTreeMap::new();
+            let a: &[MessageItem] = try!(reply[0].inner());
+            for p in a.iter() {
+                let (k, v) = try!(p.inner());
+                let (k, v): (&String, &MessageItem) = (try!(k.inner()), try!(v.inner()));
+                t.insert(k.clone(), v.clone());
+            }
+            Ok(t)
+        })().map_err(|_| {
+            let f = format!("Invalid reply for property GetAll: '{:?}'", reply);
+            Error::new_custom("InvalidReply", &f)
+        })
+    }
+}
+
+/// Wrapper around Props that keeps a map of fetched properties.
+pub struct PropHandler<'a> {
+    p: Props<'a>,
+    map: BTreeMap<String, MessageItem>,
+}
+
+impl<'a> PropHandler<'a> {
+    /// Create a new PropHandler from a Props.
+    pub fn new(p: Props) -> PropHandler {
+        PropHandler { p: p, map: BTreeMap::new() }
+    }
+
+    /// Get a map of all the properties' names and their values.
+    pub fn get_all(&mut self) -> Result<(), Error> {
+        self.map = try!(self.p.get_all());
+        Ok(())
+    }
+
+    /// Get a mutable reference to the PropHandler's fetched properties.
+    pub fn map_mut(&mut self) -> &mut BTreeMap<String, MessageItem> { &mut self.map }
+
+    /// Get a reference to the PropHandler's fetched properties.
+    pub fn map(&self) -> &BTreeMap<String, MessageItem> { &self.map }
+
+    /// Get a single property's value.
+    pub fn get(&mut self, propname: &str) -> Result<&MessageItem, Error> {
+        let v = try!(self.p.get(propname));
+        self.map.insert(propname.to_string(), v);
+        Ok(self.map.get(propname).unwrap())
+    }
+
+    /// Set a single property's value.
+    pub fn set(&mut self, propname: &str, value: MessageItem) -> Result<(), Error> {
+        try!(self.p.set(propname, value.clone()));
+        self.map.insert(propname.to_string(), value);
+        Ok(())
+    }
+}
+
+
+/* Unfortunately org.freedesktop.DBus has no properties we can use for testing, but PolicyKit should be around on most distros. */
+#[test]
+fn test_get_policykit_version() {
+    use super::BusType;
+    let c = Connection::get_private(BusType::System).unwrap();
+    let p = Props::new(&c, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority",
+        "org.freedesktop.PolicyKit1.Authority", 10000);
+
+    /* Let's use both the get and getall methods and see if we get the same result */
+    let v = p.get("BackendVersion").unwrap();
+    let vall = p.get_all().unwrap();
+    let v2 = vall.get("BackendVersion").unwrap();
+
+    assert_eq!(&v, &*v2);
+    match v {
+        MessageItem::Str(ref s) => { println!("Policykit Backend version is {}", s); }
+        _ => { panic!("Invalid Get: {:?}", v); }
+    };
+}
+
rename from third_party/rust/dbus/src/signalargs.rs
rename to third_party/rust/dbus-0.6.5/src/signalargs.rs
rename from third_party/rust/dbus/src/stdintf.rs
rename to third_party/rust/dbus-0.6.5/src/stdintf.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-0.6.5/src/strings.rs
@@ -0,0 +1,216 @@
+// CString wrappers.
+
+use std::{str, fmt, ops, default, hash};
+use std::ffi::{CStr, CString};
+use std::borrow::{Borrow, Cow};
+use std::os::raw::c_char;
+
+#[cfg(not(feature = "no-string-validation"))]
+use Error;
+#[cfg(not(feature = "no-string-validation"))]
+use ffi;
+
+macro_rules! cstring_wrapper {
+    ($t: ident, $s: ident) => {
+
+impl<'m> $t<'m> {
+    #[cfg(feature = "no-string-validation")]
+    fn check_valid(_: *const c_char) -> Result<(), String> { Ok(()) }
+
+    #[cfg(not(feature = "no-string-validation"))]
+    fn check_valid(c: *const c_char) -> Result<(), String> {
+        let mut e = Error::empty();
+        let b = unsafe { ffi::$s(c, e.get_mut()) };
+        if b != 0 { Ok(()) } else { Err(e.message().unwrap().into()) }
+    }
+
+    /// Creates a new instance of this struct.
+    ///
+    /// Note: If the no-string-validation feature is activated, this string
+    /// will not be checked for conformance with the D-Bus specification.
+    pub fn new<S: Into<Vec<u8>>>(s: S) -> Result<$t<'m>, String> {
+        let c = try!(CString::new(s).map_err(|e| e.to_string()));
+        $t::check_valid(c.as_ptr()).map(|_| $t(Cow::Owned(c)))
+    }
+
+    /// Creates a new instance of this struct. If you end it with \0,
+    /// it can borrow the slice without extra allocation.
+    ///
+    /// Note: If the no-string-validation feature is activated, this string
+    /// will not be checked for conformance with the D-Bus specification.
+    pub fn from_slice(s: &'m [u8]) -> Result<$t<'m>, String> {
+        if s.len() == 0 || s[s.len()-1] != 0 { return $t::new(s) };
+        $t::check_valid(s.as_ptr() as *const c_char).map(|_| {
+            let c = unsafe { CStr::from_ptr(s.as_ptr() as *const c_char) };
+            $t(Cow::Borrowed(c)) 
+        })
+    }
+
+    /// This function creates a new instance of this struct, without checking.
+    /// It's up to you to guarantee that s ends with a \0 and is valid.
+    pub unsafe fn from_slice_unchecked(s: &'m [u8]) -> $t<'m> {
+        debug_assert!(s[s.len()-1] == 0);
+        $t(Cow::Borrowed(CStr::from_ptr(s.as_ptr() as *const c_char)))
+    }
+
+    /// View this struct as a CStr.
+    pub fn as_cstr(&self) -> &CStr { &self.0 }
+
+    /// Makes sure this string does not contain borrows.
+    pub fn into_static(self) -> $t<'static> {
+        $t(Cow::Owned(self.0.into_owned()))
+    }
+
+    /// Converts this struct to a CString.
+    pub fn into_cstring(self) -> CString { self.0.into_owned() }
+}
+
+/*
+/// #Panics
+///
+/// If given string is not valid.
+/// impl<S: Into<Vec<u8>>> From<S> for $t { fn from(s: S) -> $t { $t::new(s).unwrap() } }
+*/
+
+/// #Panics
+///
+/// If given string is not valid.
+impl<'m> From<String> for $t<'m> { fn from(s: String) -> $t<'m> { $t::new(s).unwrap() } }
+
+/// #Panics
+///
+/// If given string is not valid.
+impl<'m> From<&'m String> for $t<'m> { fn from(s: &'m String) -> $t<'m> { $t::from_slice(s.as_bytes()).unwrap() } }
+
+/// #Panics
+///
+/// If given string is not valid.
+impl<'m> From<&'m str> for $t<'m> { fn from(s: &'m str) -> $t<'m> { $t::from_slice(s.as_bytes()).unwrap() } }
+
+impl<'m> From<$t<'m>> for CString { fn from(s: $t<'m>) -> CString { s.0.into_owned() } }
+
+
+/// #Panics
+///
+/// If given string is not valid.
+impl<'m> From<Cow<'m, str>> for $t<'m> {
+    fn from(s: Cow<'m, str>) -> $t<'m> { 
+        match s {
+            Cow::Borrowed(z) => z.into(),
+            Cow::Owned(z) => z.into(),
+        }
+    }
+}
+
+impl<'inner, 'm: 'inner> From<&'m $t<'inner>> for $t<'m> {
+    fn from(borrow: &'m $t<'inner>) -> $t<'m> {
+        $t(Cow::Borrowed(borrow.0.borrow()))
+    }
+}
+
+impl<'m> ops::Deref for $t<'m> {
+    type Target = str;
+    fn deref(&self) -> &str { str::from_utf8(self.0.to_bytes()).unwrap() }
+}
+
+impl<'m> fmt::Display for $t<'m> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        let s: &str = &self;
+        (&s as &fmt::Display).fmt(f)
+    }
+}
+
+impl<'m> AsRef<CStr> for $t<'m> {
+    fn as_ref(&self) -> &CStr { &self.0 }
+}
+
+impl<'m> hash::Hash for $t<'m> {
+    fn hash<H: hash::Hasher>(&self, state: &mut H) {
+        self.0.hash(state);
+    }
+}
+
+}}
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid (single) D-Bus type signature. Supersedes TypeSig.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct Signature<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(Signature, dbus_signature_validate_single);
+
+impl Signature<'static> {
+    /// Makes a D-Bus signature that corresponds to A. 
+    pub fn make<A: super::arg::Arg>() -> Signature<'static> { A::signature() }
+}
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid D-Bus object path.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct Path<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(Path, dbus_validate_path);
+
+// This is needed so one can make arrays of paths easily
+impl<'a> default::Default for Path<'a> {
+    fn default() -> Path<'a> { Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"/\0".as_ptr() as *const c_char)})) }
+}
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid D-Bus member, i e, a signal or method name.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct Member<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(Member, dbus_validate_member);
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid D-Bus interface name.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct Interface<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(Interface, dbus_validate_interface);
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid D-Bus bus name.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct BusName<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(BusName, dbus_validate_bus_name);
+
+/// A wrapper around a string that is guaranteed to be
+/// a valid D-Bus bus name.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
+pub struct ErrorName<'a>(Cow<'a, CStr>);
+
+cstring_wrapper!(ErrorName, dbus_validate_error_name);
+
+#[test]
+fn some_path() {
+    use std::os::raw::c_char;
+    let p1: Path = "/valid".into();
+    let p2 = Path::new("##invalid##");
+    assert_eq!(p1, Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"/valid\0".as_ptr() as *const c_char) })));
+    #[cfg(not(feature = "no-string-validation"))]
+    assert_eq!(p2, Err("Object path was not valid: '##invalid##'".into()));
+    #[cfg(feature = "no-string-validation")]
+    assert_eq!(p2, Ok(Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"##invalid##\0".as_ptr() as *const c_char) }))));
+}
+
+#[test]
+fn reborrow_path() {
+    let p1 = Path::from("/valid");
+    let p2 = p1.clone();
+    {
+        let p2_borrow: &Path = &p2;
+        let p3 = Path::from(p2_borrow);
+        // Check path created from borrow
+        assert_eq!(p2, p3);
+    }
+    // Check path that was previously borrowed
+    assert_eq!(p1, p2);
+}
+
+#[test]
+fn make_sig() {
+    assert_eq!(&*Signature::make::<(&str, u8)>(), "(sy)");
+}
rename from third_party/rust/dbus/src/tree/factory.rs
rename to third_party/rust/dbus-0.6.5/src/tree/factory.rs
rename from third_party/rust/dbus/src/tree/leaves.rs
rename to third_party/rust/dbus-0.6.5/src/tree/leaves.rs
rename from third_party/rust/dbus/src/tree/methodtype.rs
rename to third_party/rust/dbus-0.6.5/src/tree/methodtype.rs
rename from third_party/rust/dbus/src/tree/mod.rs
rename to third_party/rust/dbus-0.6.5/src/tree/mod.rs
rename from third_party/rust/dbus/src/tree/objectpath.rs
rename to third_party/rust/dbus-0.6.5/src/tree/objectpath.rs
rename from third_party/rust/dbus/src/tree/utils.rs
rename to third_party/rust/dbus-0.6.5/src/tree/utils.rs
rename from third_party/rust/dbus/src/watch.rs
rename to third_party/rust/dbus-0.6.5/src/watch.rs
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.lock":"06695ab763cabb30d0bed97e7078a98acaed39cc32fd19da055806ff1d6c9c9e","Cargo.toml":"3976c3e5137c4308ea4ccdc2279f6ade68fc797ce7eaa205ae86fe9e751c2cd1","LICENSE-APACHE":"453745410e3be8cf25d56872ea2aec975a78e6c9f217443d0bf908a5bce7c8ff","LICENSE-MIT":"de3911c2d98c8bd2d701ee721347053d9b55995a11f9a8c955e44d3ca1b376bf","README.md":"d6b26864c1757d503289a08f5b8dcd2af6c0ced9535395382f095610ab976215","data/org.freedesktop.DBus.xml":"145e64b620544c59fded04974c14d4a6a2ce5c524757d04448d4ba25e0e3a3db","data/standard_interfaces.xml":"7afc16cf97cb3637b2800fc9bb2a887997a516b751bf4f8d80d7004a3939e664","examples/adv_server_codegen.rs":"a15cfcdeef3196747cd3f11ed76890735300ec789c7bc723bd21c7c99ef3ee48","src/generate.rs":"2dab91e857befd24ee488445fe8565a535e2283d7f7682a646c19dc3a73d7d6e","src/lib.rs":"65f5ad85ad8818abfbcc67e7307e3dcdf9612b1732813b01537f17c42c2bb6d1","src/main.rs":"cd861363737a5fe2056a2ff03c6a0db22f1d19de03d5b8685d7204d9c5122a28"},"package":"a49da9fdfbe872d4841d56605dc42efa5e6ca3291299b87f44e1cde91a28617c"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/Cargo.lock
@@ -0,0 +1,156 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "ansi_term"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
+
+[[package]]
+name = "clap"
+version = "2.33.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002"
+dependencies = [
+ "ansi_term",
+ "atty",
+ "bitflags",
+ "strsim",
+ "textwrap",
+ "unicode-width",
+ "vec_map",
+]
+
+[[package]]
+name = "dbus"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b1334c0161ddfccd239ac81b188d62015b049c986c5cd0b7f9447cf2c54f4a3"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+]
+
+[[package]]
+name = "dbus-codegen"
+version = "0.9.1"
+dependencies = [
+ "clap",
+ "dbus",
+ "dbus-tree",
+ "xml-rs",
+]
+
+[[package]]
+name = "dbus-tree"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26a1c139b794d571d930124e17fa4cae8a904dc8e916abf551ab763b00e93a63"
+dependencies = [
+ "dbus",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.1.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.81"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc12a3bc971424edbbf7edaf6e5740483444db63aa8e23d3751ff12a30f306f0"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c"
+
+[[package]]
+name = "strsim"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
+
+[[package]]
+name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "unicode-width",
+]
+
+[[package]]
+name = "unicode-width"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
+
+[[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "xml-rs"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b07db065a5cf61a7e4ba64f29e67db906fb1787316516c4e6e5ff0fea1efcd8a"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/Cargo.toml
@@ -0,0 +1,58 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "dbus-codegen"
+version = "0.9.1"
+authors = ["David Henningsson <diwic@ubuntu.com>"]
+description = "Binary crate to generate Rust code from XML introspection data"
+readme = "README.md"
+keywords = ["D-Bus", "DBus"]
+categories = ["os::unix-apis", "api-bindings"]
+license = "Apache-2.0/MIT"
+repository = "https://github.com/diwic/dbus-rs"
+
+[lib]
+path = "src/lib.rs"
+
+[[bin]]
+name = "dbus-codegen-rust"
+path = "src/main.rs"
+
+[[example]]
+name = "adv_server_codegen"
+required-features = ["dbus", "dbus-tree"]
+[dependencies.clap]
+version = "2.20"
+
+[dependencies.dbus]
+version = "0.9"
+optional = true
+
+[dependencies.dbus-tree]
+version = "0.9"
+optional = true
+
+[dependencies.xml-rs]
+version = "0.8.3"
+
+[features]
+default = ["dbus"]
+[badges.is-it-maintained-issue-resolution]
+repository = "diwic/dbus-rs"
+
+[badges.is-it-maintained-open-issues]
+repository = "diwic/dbus-rs"
+
+[badges.travis-ci]
+repository = "diwic/dbus-rs"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/LICENSE-APACHE
@@ -0,0 +1,202 @@
+Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/LICENSE-MIT
@@ -0,0 +1,19 @@
+Copyright (c) 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/README.md
@@ -0,0 +1,172 @@
+# dbus-codegen-rust
+
+This program takes D-Bus XML Introspection data and generates Rust code
+for calling and implementing the interfaces in the introspection data.
+
+## Example
+
+From a D-Bus interface like this:
+
+    <node>
+        <interface name="org.example.test">
+            <method name="Foo">
+                <arg type="i" name="bar" direction="in"/>
+                <arg type="s" name="baz" direction="out"/>
+            </method>
+            <signal name="Laundry">
+                <arg type="b" name="eaten"/>
+            </signal>
+        </interface>
+     </node>
+
+This code will generate a few things.
+
+## Common for client and server sides
+
+ * A trait for calling/implementing the methods of the interfaces, like this:
+
+```rust
+pub trait OrgExampleTest {
+    type Err;
+    fn foo(&self, bar: i32) -> Result<String, Self::Err>;
+}
+```
+
+For properties, `get_xx` and `set_xx` methods will be generated. There is currently no `get_all` method.
+
+ * A struct for each signal, like this:
+
+```rust
+#[derive(Debug, Default)]
+pub struct OrgExampleTestLaundry {
+    pub eaten: bool,
+}
+
+impl dbus::SignalArgs for OrgExampleTestLaundry { /* code here */ }
+```
+
+## Client side
+
+ * The trait will be implemented for `ConnPath`, which makes methods easy to call for a client, like this:
+
+```rust
+use OrgExampleTest;
+let myString = try!(myConnPath.foo(myInteger));
+```
+
+ * To help catch signals emitted from the server, you can use `match_str` and `from_message`, like this:
+
+```rust
+use SignalArgs;
+myConnection.add_match(OrgExampleTestLaundry::match_str(None, None));
+for msg in myConnection.incoming(1000) {
+    if let Some(laundrySignal) = OrgExampleTestLaundry::from_message(&msg) {
+        println!("Laundry was eaten: {:?}", laundrySignal.eaten);
+    }
+}
+```
+
+## Server side
+
+ * A method will be generated, which you can call to get a `tree::Interface`, like this:
+
+```rust
+myInterface = orgexampletest_server(&myFactory, ());
+```
+
+This interface can then be added to a `tree::ObjectPath`, as shown in the [main page](../README.md#server).
+
+
+In addition, you also need to implement the interface's methods, like this:
+
+```rust
+impl OrgExampleTest for MyStruct {
+    type Err = tree::MethodErr;
+    fn foo(&self, bar: i32) -> Result<String, Self::Err> {
+        /* Your code here */
+    }
+}
+```
+
+I've been experimenting with different ways of how to make the generated server function reach the implementing struct,
+this is controlled by the command line parameter `methodaccess`.
+
+ 1. If `methodaccess` is `MethodInfo`, then you need to implement the interface for the `MethodInfo` struct, like this:
+
+```rust
+impl<M: tree::MethodType<D>, D> OrgExampleTest for tree::MethodInfo<M, D> {
+    type Err = tree::MethodErr;
+    fn foo(&self, bar: i32) -> Result<String, Self::Err> {
+        /* Your code here */
+    }
+}
+```
+
+ 2. If `methodaccess` is `RefClosure`, then you need to supply a closure that returns a reference to the implementing struct.
+This is a good option if the struct is stored in tree (this means implementing `tree::DataType`).
+
+```rust
+myInterface = orgexampletest_server(&myFactory, (), |m| m.path.get_data());
+```
+
+ 3. If `methodaccess` is `AsRefClosure`, then you need to supply a closure that returns an object which can reference to the implementing struct.
+The object is dropped after the method is called. This works well with `Arc`/`Rc`, like this:
+
+```rust
+impl AsRef<dyn OrgExampleTest + 'static> for Rc<MyStruct> {
+    fn as_ref(&self) -> &(dyn OrgExampleTest + 'static) { &**self }
+}
+
+let myRc = Rc::new(myStruct);
+myInterface = orgexampletest_server(&myFactory, (), move |_| myRc.clone());
+```
+
+There is also a `methodtype` parameter that controls whether the server function will work well with `MTFn`, `MTFnMut` or `MTSync` trees,
+or all three (called `Generic`). Or not generate a server function at all (`None`).
+
+ * To emit a signal, you can call `SignalArgs::to_emit_message` or `ConnPath::emit` to get a message which can be sent over the connection.
+
+# Usage
+
+This code can be used both as a library and as a binary executable.
+
+## Binary executable
+
+Once you have installed dbus-codegen-rust (`cargo install dbus-codegen`), use the following command to import your XML:
+
+```
+dbus-codegen-rust < mydefinition.xml
+```
+
+This will print the generated Rust code to stdout, so you can pipe it into another file if you want:
+
+```
+dbus-codegen-rust < mydefinition.xml > mod.rs
+```
+
+Dbus-codegen-rust can also fetch the xml definition for you. Here's an example that generates client definitions for PolicyKit:
+
+```
+dbus-codegen-rust -s -d org.freedesktop.PolicyKit1 -p "/org/freedesktop/PolicyKit1/Authority" -m None > policykit.rs
+```
+
+See available options:
+
+```
+dbus-codegen-rust --help
+```
+
+## Library usage
+
+```
+let opts = Default::default();
+let code = dbus_codegen::generate(xml_str, &opts)?;
+```
+
+See [documentation](https://docs.rs/dbus-codegen/) for what options are available.
+
+# Features
+
+The `dbus` feature is enabled by default. If you turn it off (with the `--no-default-features` argument to cargo),
+this program (or library) no longer binds to the D-Bus C development headers, meaning you don't need these to be installed.
+This also means you can no longer fetch the xml definition from other programs when you run the binary.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/data/org.freedesktop.DBus.xml
@@ -0,0 +1,113 @@
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node>
+  <interface name="org.freedesktop.DBus">
+    <method name="Hello">
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="RequestName">
+      <arg direction="in" type="s"/>
+      <arg direction="in" type="u"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="ReleaseName">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="StartServiceByName">
+      <arg direction="in" type="s"/>
+      <arg direction="in" type="u"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="UpdateActivationEnvironment">
+      <arg direction="in" type="a{ss}"/>
+    </method>
+    <method name="NameHasOwner">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="b"/>
+    </method>
+    <method name="ListNames">
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="ListActivatableNames">
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="AddMatch">
+      <arg direction="in" type="s"/>
+    </method>
+    <method name="RemoveMatch">
+      <arg direction="in" type="s"/>
+    </method>
+    <method name="GetNameOwner">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="ListQueuedOwners">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="GetConnectionUnixUser">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="GetConnectionUnixProcessID">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="GetAdtAuditSessionData">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="ay"/>
+    </method>
+    <method name="GetConnectionSELinuxSecurityContext">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="ay"/>
+    </method>
+    <method name="GetConnectionAppArmorSecurityContext">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="ReloadConfig">
+    </method>
+    <method name="GetId">
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="GetConnectionCredentials">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <signal name="NameOwnerChanged">
+      <arg type="s"/>
+      <arg type="s"/>
+      <arg type="s"/>
+    </signal>
+    <signal name="NameLost">
+      <arg type="s"/>
+    </signal>
+    <signal name="NameAcquired">
+      <arg type="s"/>
+    </signal>
+  </interface>
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg direction="out" type="s"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Monitoring">
+    <method name="BecomeMonitor">
+      <arg direction="in" type="as"/>
+      <arg direction="in" type="u"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Debug.Stats">
+    <method name="GetStats">
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <method name="GetConnectionStats">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <method name="GetAllMatchRules">
+      <arg direction="out" type="a{sas}"/>
+    </method>
+  </interface>
+</node>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/data/standard_interfaces.xml
@@ -0,0 +1,49 @@
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
+                      "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node>
+  <interface name="org.freedesktop.DBus.Properties">
+    <method name="Get">
+      <arg type="s" name="interface_name" direction="in"/>
+      <arg type="s" name="property_name" direction="in"/>
+      <arg type="v" name="value" direction="out"/>
+    </method>
+    <method name="GetAll">
+      <arg type="s" name="interface_name" direction="in"/>
+      <arg type="a{sv}" name="properties" direction="out"/>
+    </method>
+    <method name="Set">
+      <arg type="s" name="interface_name" direction="in"/>
+      <arg type="s" name="property_name" direction="in"/>
+      <arg type="v" name="value" direction="in"/>
+    </method>
+    <signal name="PropertiesChanged">
+      <arg type="s" name="interface_name"/>
+      <arg type="a{sv}" name="changed_properties"/>
+      <arg type="as" name="invalidated_properties"/>
+    </signal>
+  </interface>
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg type="s" name="xml_data" direction="out"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Peer">
+    <method name="Ping"/>
+    <method name="GetMachineId">
+      <arg type="s" name="machine_uuid" direction="out"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.ObjectManager">
+    <method name="GetManagedObjects">
+      <arg name="objects" type="a{oa{sa{sv}}}" direction="out"/>
+    </method>
+    <signal name="InterfacesAdded">
+      <arg name="object" type="o"/>
+      <arg name="interfaces" type="a{sa{sv}}"/>
+    </signal>
+    <signal name="InterfacesRemoved">
+      <arg name="object" type="o"/>
+      <arg name="interfaces" type="as"/>
+    </signal>
+  </interface>
+</node>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/examples/adv_server_codegen.rs
@@ -0,0 +1,302 @@
+// This is a modified version of dbus/examples/adv_server.rs that uses code generated from dbus-codegen.
+//
+// Usually you would put imported code in a separate .rs file, but I've just copy-pasted it into
+// a module here, for simplicity.
+
+mod com_example_dbus_rs {
+// === Imported code start ===
+
+// This code was autogenerated with dbus-codegen-rust, see https://github.com/diwic/dbus-rs
+
+#![allow(dead_code)]
+use dbus as dbus;
+use dbus::arg;
+use dbus_tree as tree;
+use dbus::ffidisp;
+
+pub trait Device {
+    type Err;
+    fn check(&self) -> Result<(), Self::Err>;
+    fn get_checking(&self) -> Result<bool, Self::Err>;
+    fn get_description(&self) -> Result<String, Self::Err>;
+    fn get_online(&self) -> Result<bool, Self::Err>;
+    fn set_online(&self, value: bool) -> Result<(), Self::Err>;
+}
+
+impl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> Device for ffidisp::ConnPath<'a, C> {
+    type Err = dbus::Error;
+
+    fn check(&self) -> Result<(), Self::Err> {
+        let mut m = self.method_call_with_args(&"com.example.dbus.rs.device".into(), &"check".into(), |_| {
+        })?;
+        m.as_result()?;
+        Ok(())
+    }
+
+    fn get_checking(&self) -> Result<bool, Self::Err> {
+        <Self as dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties>::get(&self, "com.example.dbus.rs.device", "checking")
+    }
+
+    fn get_description(&self) -> Result<String, Self::Err> {
+        <Self as dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties>::get(&self, "com.example.dbus.rs.device", "description")
+    }
+
+    fn get_online(&self) -> Result<bool, Self::Err> {
+        <Self as dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties>::get(&self, "com.example.dbus.rs.device", "online")
+    }
+
+    fn set_online(&self, value: bool) -> Result<(), Self::Err> {
+        <Self as dbus::ffidisp::stdintf::org_freedesktop_dbus::Properties>::set(&self, "com.example.dbus.rs.device", "online", value)
+    }
+}
+
+pub fn device_server<F, T, D>(factory: &tree::Factory<tree::MTFn<D>, D>, data: D::Interface, f: F) -> tree::Interface<tree::MTFn<D>, D>
+where
+    D: tree::DataType,
+    D::Method: Default,
+    D::Property: Default,
+    D::Signal: Default,
+    T: Device<Err=tree::MethodErr>,
+    F: 'static + for <'z> Fn(& 'z tree::MethodInfo<tree::MTFn<D>, D>) -> & 'z T,
+{
+    let i = factory.interface("com.example.dbus.rs.device", data);
+    let f = ::std::sync::Arc::new(f);
+    let fclone = f.clone();
+    let h = move |minfo: &tree::MethodInfo<tree::MTFn<D>, D>| {
+        let d = fclone(minfo);
+        d.check()?;
+        let rm = minfo.msg.method_return();
+        Ok(vec!(rm))
+    };
+    let m = factory.method("check", Default::default(), h);
+    let i = i.add_m(m);
+
+    let p = factory.property::<bool, _>("checking", Default::default());
+    let p = p.access(tree::Access::Read);
+    let fclone = f.clone();
+    let p = p.on_get(move |a, pinfo| {
+        let minfo = pinfo.to_method_info();
+        let d = fclone(&minfo);
+        a.append(d.get_checking()?);
+        Ok(())
+    });
+    let i = i.add_p(p);
+
+    let p = factory.property::<&str, _>("description", Default::default());
+    let p = p.access(tree::Access::Read);
+    let fclone = f.clone();
+    let p = p.on_get(move |a, pinfo| {
+        let minfo = pinfo.to_method_info();
+        let d = fclone(&minfo);
+        a.append(d.get_description()?);
+        Ok(())
+    });
+    let i = i.add_p(p);
+
+    let p = factory.property::<bool, _>("online", Default::default());
+    let p = p.access(tree::Access::ReadWrite);
+    let fclone = f.clone();
+    let p = p.on_get(move |a, pinfo| {
+        let minfo = pinfo.to_method_info();
+        let d = fclone(&minfo);
+        a.append(d.get_online()?);
+        Ok(())
+    });
+    let fclone = f.clone();
+    let p = p.on_set(move |iter, pinfo| {
+        let minfo = pinfo.to_method_info();
+        let d = fclone(&minfo);
+        d.set_online(iter.read()?)?;
+        Ok(())
+    });
+    let i = i.add_p(p);
+    let s = factory.signal("CheckComplete", Default::default());
+    let i = i.add_s(s);
+    i
+}
+
+#[derive(Debug)]
+pub struct DeviceCheckComplete {
+}
+
+impl arg::AppendAll for DeviceCheckComplete {
+    fn append(&self, _: &mut arg::IterAppend) {
+    }
+}
+
+impl arg::ReadAll for DeviceCheckComplete {
+    fn read(_: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DeviceCheckComplete {
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DeviceCheckComplete {
+    const NAME: &'static str = "CheckComplete";
+    const INTERFACE: &'static str = "com.example.dbus.rs.device";
+}
+
+// === Imported code end ===
+}
+
+use dbus::{ffidisp::Connection, Path};
+use dbus_tree as tree;
+use dbus_tree::{Interface, MTFn, MethodErr};
+
+use std::sync::Arc;
+use std::sync::mpsc;
+use std::cell::Cell;
+use std::thread;
+
+
+// Our storage device
+#[derive(Debug)]
+struct Device {
+    description: String,
+    path: Path<'static>,
+    index: i32,
+    online: Cell<bool>,
+    checking: Cell<bool>,
+    check_complete_sender: mpsc::Sender<i32>,
+}
+
+// Every storage device has its own object path.
+// We therefore create a link from the object path to the Device.
+#[derive(Copy, Clone, Default, Debug)]
+struct TData;
+impl tree::DataType for TData {
+    type Tree = ();
+    type ObjectPath = Arc<Device>;
+    type Property = ();
+    type Interface = ();
+    type Method = ();
+    type Signal = ();
+}
+
+
+impl Device {
+    // Creates a "test" device (not a real one, since this is an example).
+    fn new_bogus(index: i32, s: mpsc::Sender<i32>) -> Device {
+        Device {
+            description: format!("This is device {}, which is {}.", index,
+                ["totally awesome", "really fancy", "still going strong"][(index as usize) % 3]),
+            path: format!("/Device{}", index).into(),
+            index: index,
+            online: Cell::new(index % 2 == 0),
+            checking: Cell::new(false),
+            check_complete_sender: s,
+        }
+    }
+}
+
+// Here's where we implement the code for our interface.
+impl com_example_dbus_rs::Device for Device {
+    type Err = tree::MethodErr;
+    fn check(&self) -> Result<(), Self::Err> {
+        if self.checking.get() {
+            return Err(MethodErr::failed(&"Device currently under check, cannot start another check"))
+        }
+        if self.online.get() {
+            return Err(MethodErr::failed(&"Device is currently online, cannot start check"))
+        }
+        self.checking.set(true);
+
+        // Start some lengthy processing in a separate thread...
+        let devindex = self.index;
+        let ch = self.check_complete_sender.clone();
+        thread::spawn(move || {
+
+            // Bogus check of device
+            use std::time::Duration;
+            thread::sleep(Duration::from_secs(15));
+
+            // Tell main thread that we finished
+            ch.send(devindex).unwrap();
+        });
+        Ok(())
+    }
+    fn get_checking(&self) -> Result<bool, Self::Err> {
+        Ok(self.checking.get())
+    }
+    fn get_description(&self) -> Result<String, Self::Err> {
+        Ok(self.description.clone())
+    }
+    fn get_online(&self) -> Result<bool, Self::Err> {
+        Ok(self.online.get())
+    }
+    fn set_online(&self, value: bool) -> Result<(), Self::Err> {
+        if value && self.checking.get() {
+            Err(MethodErr::failed(&"Device currently under check, cannot bring online")) }
+        else {
+            self.online.set(value);
+            Ok(())
+        }
+    }
+}
+
+fn create_iface() -> Interface<MTFn<TData>, TData> {
+    let f = tree::Factory::new_fn();
+    com_example_dbus_rs::device_server(&f, (), |m| {
+        // Just provide a link from MethodInfo (m) to the &Device
+        // we should call.
+        let a: &Arc<Device> = m.path.get_data();
+        let b: &Device = &a;
+        b
+    })
+}
+
+fn create_tree(devices: &[Arc<Device>], iface: &Arc<Interface<MTFn<TData>, TData>>)
+    -> tree::Tree<MTFn<TData>, TData> {
+
+    let f = tree::Factory::new_fn();
+    let mut tree = f.tree(());
+    for dev in devices {
+        tree = tree.add(f.object_path(dev.path.clone(), dev.clone())
+            .introspectable()
+            .add(iface.clone())
+        );
+    }
+    tree
+}
+
+fn run() -> Result<(), Box<dyn std::error::Error>> {
+    let (check_complete_s, check_complete_r) = mpsc::channel::<i32>();
+
+    // Create our bogus devices
+    let devices: Vec<Arc<Device>> = (0..10).map(|i|
+        Arc::new(Device::new_bogus(i, check_complete_s.clone()))
+    ).collect();
+
+    // Create tree
+    let iface = create_iface();
+    let tree = create_tree(&devices, &Arc::new(iface));
+
+    // Setup DBus connection
+    let c = Connection::new_session()?;
+    c.register_name("com.example.dbus.rs.advancedserverexample", 0)?;
+    tree.set_registered(&c, true)?;
+
+    // ...and serve incoming requests.
+    c.add_handler(tree);
+    loop {
+        // Wait for incoming messages. This will block up to one second.
+        // Discard the result - relevant messages have already been handled.
+        c.incoming(1000).next();
+
+        // Do all other things we need to do in our main loop.
+        if let Ok(idx) = check_complete_r.try_recv() {
+            let dev = &devices[idx as usize];
+            dev.checking.set(false);
+            let sig = com_example_dbus_rs::DeviceCheckComplete {};
+            use dbus::message::SignalArgs;
+            c.send(sig.to_emit_message(&dev.path))
+                .map_err(|_| "Sending DBus signal failed")?;
+        }
+    }
+}
+
+fn main() {
+    if let Err(e) = run() {
+        println!("{}", e);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/src/generate.rs
@@ -0,0 +1,1018 @@
+
+use std::{io, error};
+use std::collections::HashSet;
+use xml;
+
+fn find_attr<'a>(a: &'a Vec<xml::attribute::OwnedAttribute>, n: &str) -> Result<&'a str, Box<dyn error::Error>> {
+    a.into_iter()
+        .find(|q| q.name.prefix.is_none() && q.name.local_name == n)
+        .map(|f| &*f.value)
+        .ok_or_else(|| format!("attribute not found: {:?}", n).into())
+}
+
+struct Arg {
+    name: String,
+    typ: String,
+    idx: i32,
+    is_out: bool,
+}
+
+struct Method {
+    name: String,
+    fn_name: String,
+    iargs: Vec<Arg>,
+    oargs: Vec<Arg>,
+}
+
+struct Prop {
+    name: String,
+    get_fn_name: String,
+    set_fn_name: String,
+    typ: String,
+    access: String,
+}
+
+struct Signal {
+    name: String,
+    args: Vec<Arg>,
+}
+
+struct Intf {
+    origname: String,
+    shortname: String,
+    methods: Vec<Method>,
+    props: Vec<Prop>,
+    signals: Vec<Signal>,
+}
+
+/// Server access code generation option
+#[derive(Copy, Clone, Eq, PartialEq, Debug)]
+pub enum ServerAccess {
+    /// Supply a closure from ref to ref
+    RefClosure,
+    /// Supply a closure from ref to owned object which asrefs
+    AsRefClosure,
+    /// The interface is implemented for MethodInfo
+    MethodInfo
+}
+
+
+#[derive(Copy, Clone, Eq, PartialEq, Debug)]
+pub enum ConnectionType {
+    Ffidisp,
+    Blocking,
+    Nonblock,
+}
+
+/// Code generation options
+#[derive(Clone, Debug)]
+pub struct GenOpts {
+    /// Name of dbus crate (used for import)
+    pub dbuscrate: String,
+    /// MethodType for server tree impl, set to none for client impl only
+    pub methodtype: Option<String>,
+    /// Crossroads server handler type, set to none for client impl only
+    pub crhandler: Option<String>,
+    /// Removes a prefix from interface names
+    pub skipprefix: Option<String>,
+    /// Type of server access (tree)
+    pub serveraccess: ServerAccess,
+    /// Tries to make variants generic instead of Variant<Box<Refarg>>
+    pub genericvariant: bool,
+    /// Generates code to work with async / futures 0.3
+    pub futures: bool,
+    /// Type of connection, for client only
+    pub connectiontype: ConnectionType,
+    /// Generates a struct wrapping PropMap to get properties from it with their expected types.
+    pub propnewtype: bool,
+    /// interface filter. Only matching interface are generated, if non-empty.
+    pub interfaces: Option<HashSet<String>>,
+    /// The command line argument string. This will be inserted into generated source files.
+    pub command_line: String,
+}
+
+impl ::std::default::Default for GenOpts {
+    fn default() -> Self { GenOpts {
+        dbuscrate: "dbus".into(), methodtype: Some("MTFn".into()), skipprefix: None,
+        serveraccess: ServerAccess::RefClosure, genericvariant: false, futures: false,
+        crhandler: None, connectiontype: ConnectionType::Blocking, propnewtype: false,
+        interfaces: None,
+        command_line: String::new()
+    }}
+}
+
+const RUST_KEYWORDS: [&str; 57] = [
+    "as",
+    "break",
+    "const",
+    "continue",
+    "crate",
+    "dyn",
+    "else",
+    "enum",
+    "extern",
+    "false",
+    "fn",
+    "for",
+    "if",
+    "impl",
+    "in",
+    "let",
+    "loop",
+    "match",
+    "mod",
+    "move",
+    "mut",
+    "pub",
+    "ref",
+    "return",
+    "Self",
+    "self",
+    "static",
+    "struct",
+    "super",
+    "trait",
+    "true",
+    "type",
+    "union",
+    "unsafe",
+    "use",
+    "where",
+    "while",
+
+    "abstract",
+    "alignof",
+    "async",
+    "await",
+    "become",
+    "box",
+    "do",
+    "final",
+    "macro",
+    "offsetof",
+    "override",
+    "priv",
+    "proc",
+    "pure",
+    "sizeof",
+    "try",
+    "typeof",
+    "unsized",
+    "virtual",
+    "yield",
+];
+
+
+fn make_camel(s: &str) -> String {
+    let mut ucase = true;
+    let mut r: String = s.chars().filter_map(|c| match c {
+        'a'..='z' | 'A'..='Z' | '0'..='9' => {
+            let cc = if ucase { c.to_uppercase().next() } else { Some(c) };
+            ucase = false;
+            cc
+        }
+        _ => { ucase = true; None }
+    }).collect();
+    if RUST_KEYWORDS.iter().any(|i| i == &r) { r.push('_') };
+    r
+}
+
+
+fn make_snake(s: &str, keyword_check: bool) -> String {
+    let mut lcase = false;
+    let mut r = String::new();
+    for c in s.chars() {
+        match c {
+             'a'..='z' | '0'..='9' => {
+                  r.push(c);
+                  lcase = true;
+             }
+             'A'..='Z' => {
+                  if lcase { r.push('_'); }
+                  lcase = false;
+                  r.push(c.to_lowercase().next().unwrap());
+             }
+             _ => {
+                  if lcase { r.push('_'); }
+                  lcase = false;
+             }
+        }
+    }
+    if r.len() < 2 { r.push('_'); } // Don't interfere with variable names like 'm' and 'i'
+    if keyword_check && RUST_KEYWORDS.iter().any(|i| i == &r) { r.push('_') };
+    r
+}
+
+fn make_fn_name(intf: &Intf, name: &str) -> String {
+    let mut r = make_snake(name, true);
+    loop {
+        if intf.methods.iter().any(|x| x.fn_name == r) ||
+            intf.props.iter().any(|x| x.get_fn_name == r || x.set_fn_name == r) {
+            r.push('_');
+        } else { return r };
+    }
+}
+
+struct GenVars {
+    prefix: String,
+    gen: Vec<String>,
+}
+
+fn xml_to_rust_type(i: &mut &[u8], out: bool, genvars: &mut Option<GenVars>) -> Result<String, Box<dyn error::Error>> {
+    let c = i.get(0).ok_or_else(|| "unexpected end of signature")?;
+    *i = &i[1..];
+    Ok(match (*c as char, out) {
+        ('(', _) => {
+            let mut s: Vec<String> = vec!();
+            while i.get(0) != Some(&b')') {
+                let n = xml_to_rust_type(i, out, genvars)?;
+                s.push(n);
+            };
+            *i = &i[1..];
+            format!("({})", s.join(", "))
+        },
+        ('y', _) => "u8".into(),
+        ('b', _) => "bool".into(),
+        ('n', _) => "i16".into(),
+        ('q', _) => "u16".into(),
+        ('i', _) => "i32".into(),
+        ('u', _) => "u32".into(),
+        ('x', _) => "i64".into(),
+        ('t', _) => "u64".into(),
+        ('d', _) => "f64".into(),
+        ('h', _) => "arg::OwnedFd".into(),
+        ('s', false) => "&str".into(),
+        ('s', true) => "String".into(),
+        ('o', false) => "dbus::Path".into(),
+        ('o', true) => "dbus::Path<'static>".into(),
+        ('g', false) => "dbus::Signature".into(),
+        ('g', true) => "dbus::Signature<'static>".into(),
+        ('v', _) => if let &mut Some(ref mut g) = genvars {
+            let t = format!("{}", g.prefix);
+            // let t = format!("arg::Variant<{}>", g.prefix);
+            g.gen.push(g.prefix.clone());
+            g.prefix = format!("{}X", g.prefix);
+            t
+        } else if out { "arg::Variant<Box<dyn arg::RefArg + 'static>>".into() }
+        else { "arg::Variant<Box<dyn arg::RefArg>>".into() },
+        ('a', _) => if i.get(0) == Some(&b'{') {
+            *i = &i[1..];
+            if &i[..3] == b"sv}" {
+                *i = &i[3..];
+                "arg::PropMap".into()
+            } else {
+                let n1 = xml_to_rust_type(i, out, &mut None)?;
+                let n2 = xml_to_rust_type(i, out, &mut None)?;
+                if i.get(0) != Some(&b'}') { return Err("No end of dict".into()); }
+                *i = &i[1..];
+                format!("::std::collections::HashMap<{}, {}>", n1, n2)
+            }
+        } else {
+            format!("Vec<{}>", xml_to_rust_type(i, out, &mut None)?)
+        },
+        (_, _) => return Err(format!("Unknown character in signature {:?}", c).into()),
+    })
+}
+
+/// Return whether the given type implements `Copy`.
+///
+/// Only implented for types which may be returned by `xml_to_rust_type`.
+fn can_copy_type(rust_type: &str) -> bool {
+    match rust_type {
+        "u8" | "bool" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "f64" => true,
+        _ => false
+    }
+}
+
+fn make_type(s: &str, out: bool, genvars: &mut Option<GenVars>) -> Result<String, Box<dyn error::Error>> {
+    let mut i = s.as_bytes();
+    let r = xml_to_rust_type(&mut i, out, genvars)?;
+    if i.len() > 0 { Err("Expected type to end".into()) }
+    else { Ok(r) }
+}
+
+impl Arg {
+    fn varname(&self) -> String {
+        if self.name != "" {
+           make_snake(&self.name, true)
+        } else { format!("arg{}", self.idx) }
+    }
+    fn can_wrap_variant(&self, genvar: bool) -> bool { genvar && self.typ.starts_with("v") }
+    fn varname_maybewrap(&self, genvar: bool) -> String {
+        if self.can_wrap_variant(genvar) {
+            format!("arg::Variant({})", self.varname())
+        } else { self.varname() }
+    }
+    fn typename(&self, genvar: bool) -> Result<(String, Vec<String>), Box<dyn error::Error>> {
+        let mut g = if genvar { Some(GenVars {
+            prefix: format!("{}{}", if self.is_out { 'R' } else { 'I' }, self.idx),
+            gen: vec!(),
+        }) } else { None };
+        let r = make_type(&self.typ, self.is_out, &mut g)?;
+        Ok((r, g.map(|g| g.gen.iter().map(|s|
+            if self.is_out { format!("{}: for<'b> arg::Get<'b> + 'static", s) } else { format!("{}: arg::Arg + arg::Append", s) }
+        ).collect()).unwrap_or(vec!())))
+    }
+    fn typename_maybewrap(&self, genvar: bool) -> Result<String, Box<dyn error::Error>> {
+        let t = self.typename(genvar)?.0;
+        Ok(if self.can_wrap_variant(genvar) {
+            format!("arg::Variant<{}>", t)
+        } else { t })
+    }
+}
+
+impl Prop {
+    fn can_get(&self) -> bool { self.access != "write" }
+    fn can_set(&self) -> bool { self.access == "write" || self.access == "readwrite" }
+}
+
+fn write_method_decl(s: &mut String, m: &Method, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> {
+    let genvar = opts.genericvariant;
+    let g: Vec<String> = if genvar {
+        let mut g = vec!();
+        for z in m.iargs.iter().chain(m.oargs.iter()) {
+            let (_, mut z) = z.typename(genvar)?;
+            g.append(&mut z);
+        }
+        g
+    } else { vec!() };
+
+
+    *s += &format!("    fn {}{}(&self", m.fn_name,
+        if g.len() > 0 { format!("<{}>", g.join(",")) } else { "".into() }
+    );
+
+    for a in m.iargs.iter() {
+        let t = a.typename(genvar)?.0;
+        *s += &format!(", {}: {}", a.varname(), t);
+    }
+    if let Some(crh) = &opts.crhandler { *s += &format!(", info: &cr::{}Info", crh) };
+
+    let r = match m.oargs.len() {
+        0 => "()".to_string(),
+        1 => m.oargs[0].typename(genvar)?.0,
+        _ => {
+            let v: Result<Vec<String>, _> = m.oargs.iter().map(|z| z.typename(genvar).map(|t| t.0)).collect();
+            format!("({})", v?.join(", "))
+        }
+    };
+    *s += &format!(") -> {}", make_result(&r, opts));
+
+    Ok(())
+}
+
+fn make_result(success: &str, opts: &GenOpts) -> String {
+    if opts.futures {
+        format!("dbusf::MethodReply<{}>", success)
+    } else if opts.crhandler.is_some() {
+        format!("Result<{}, cr::MethodErr>", success)
+    } else if opts.methodtype.is_some() {
+        format!("Result<{}, tree::MethodErr>", success)
+    } else if opts.connectiontype == ConnectionType::Nonblock {
+        format!("nonblock::MethodReply<{}>", success)
+    } else {
+        format!("Result<{}, dbus::Error>", success)
+    }
+}
+
+fn write_prop_decl(s: &mut String, p: &Prop, opts: &GenOpts, set: bool) -> Result<(), Box<dyn error::Error>> {
+    if set {
+        *s += &format!("    fn {}(&self, value: {}) -> {}",
+            p.set_fn_name, make_type(&p.typ, true, &mut None)?, make_result("()", opts));
+    } else {
+        *s += &format!("    fn {}(&self) -> {}",
+            p.get_fn_name, make_result(&make_type(&p.typ, true, &mut None)?, opts));
+    };
+    Ok(())
+}
+
+fn write_intf_name(s: &mut String, i: &Intf) -> Result<(), Box<dyn error::Error>> {
+    let const_name = make_snake(&i.shortname, false).to_uppercase();
+    *s += &format!("\npub const {}_NAME: &str = \"{}\";\n", const_name, i.origname);
+    Ok(())
+}
+
+fn write_intf(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> {
+
+    let iname = make_camel(&i.shortname);
+    *s += &format!("\npub trait {} {{\n", iname);
+    for m in &i.methods {
+        write_method_decl(s, &m, opts)?;
+        *s += ";\n";
+    }
+    for p in &i.props {
+        if p.can_get() {
+            write_prop_decl(s, &p, opts, false)?;
+            *s += ";\n";
+        }
+        if p.can_set() {
+            write_prop_decl(s, &p, opts, true)?;
+            *s += ";\n";
+        }
+    }
+    *s += "}\n";
+    Ok(())
+}
+
+fn write_intf_client(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> {
+    let (module, proxy) = match opts.connectiontype {
+        ConnectionType::Ffidisp => ("ffidisp", "ConnPath"),
+        ConnectionType::Blocking => ("blocking", "Proxy"),
+        ConnectionType::Nonblock => ("nonblock", "Proxy"),
+    };
+
+    if module == "nonblock" {
+        *s += &format!("\nimpl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> {} for {}::{}<'a, C> {{\n",
+            make_camel(&i.shortname), module, proxy);
+    } else if opts.futures {
+        *s += &format!("\nimpl<'a> {} for dbusf::ConnPath<'a> {{\n",
+            make_camel(&i.shortname));
+    } else if module == "blocking" {
+        *s += &format!("\nimpl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> {} for {}::{}<'a, C> {{\n",
+            make_camel(&i.shortname), module, proxy);
+    } else {
+        assert_eq!(module, "ffidisp");
+        *s += &format!("\nimpl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> {} for ffidisp::ConnPath<'a, C> {{\n",
+            make_camel(&i.shortname));
+    }
+    for m in &i.methods {
+        *s += "\n";
+        write_method_decl(s, &m, opts)?;
+        *s += " {\n";
+        *s += &format!("        self.method_call(\"{}\", \"{}\", (", i.origname, m.name);
+        for a in m.iargs.iter() {
+            *s += &a.varname_maybewrap(opts.genericvariant);
+            *s += ", ";
+        }
+        *s += "))\n";
+        let needs_andthen = (m.oargs.len() == 1) || (m.oargs.iter().any(|oa| oa.can_wrap_variant(opts.genericvariant)));
+        if needs_andthen {
+            *s += &"            .and_then(|r: (";
+            for oa in m.oargs.iter() {
+                *s += &oa.typename_maybewrap(opts.genericvariant)?;
+                *s += ", ";
+            }
+            let tuple = m.oargs.len() > 1;
+            *s += &format!(")| Ok({}", if tuple { "(" } else { "" });
+            for idx in 0..m.oargs.len() {
+                *s += &if m.oargs[idx].can_wrap_variant(opts.genericvariant) {
+                    format!("(r.{}).0, ", idx)
+                } else {
+                    format!("r.{}, ", idx)
+                };
+            }
+            *s += &format!("{}))\n", if tuple { ")" } else { "" });
+        }
+        *s += "    }\n";
+    }
+
+    let propintf = format!("{}::stdintf::org_freedesktop_dbus::Properties", module);
+
+    for p in i.props.iter().filter(|p| p.can_get()) {
+        *s += "\n";
+        write_prop_decl(s, &p, opts, false)?;
+        *s += " {\n";
+        *s += &format!("        <Self as {}>::get(&self, \"{}\", \"{}\")\n", propintf, i.origname, p.name);
+        *s += "    }\n";
+    }
+
+    for p in i.props.iter().filter(|p| p.can_set()) {
+        *s += "\n";
+        write_prop_decl(s, &p, opts, true)?;
+        *s += " {\n";
+        *s += &format!("        <Self as {}>::set(&self, \"{}\", \"{}\", value)\n", propintf, i.origname, p.name);
+        *s += "    }\n";
+    }
+
+    *s += "}\n";
+    Ok(())
+
+}
+
+fn write_signal(s: &mut String, i: &Intf, ss: &Signal) -> Result<(), Box<dyn error::Error>> {
+    let structname = format!("{}{}", make_camel(&i.shortname), make_camel(&ss.name));
+    *s += "\n#[derive(Debug)]\n";
+    *s += &format!("pub struct {} {{\n", structname);
+    for a in ss.args.iter() {
+        *s += &format!("    pub {}: {},\n", a.varname(), a.typename(false)?.0);
+    }
+    *s += "}\n\n";
+
+    *s += &format!("impl arg::AppendAll for {} {{\n", structname);
+    *s += &format!("    fn append(&self, {}: &mut arg::IterAppend) {{\n", if ss.args.len() > 0 {"i"} else {"_"});
+    for a in ss.args.iter() {
+        *s += &format!("        arg::RefArg::append(&self.{}, i);\n", a.varname());
+    }
+    *s += "    }\n";
+    *s += "}\n\n";
+
+    *s += &format!("impl arg::ReadAll for {} {{\n", structname);
+    *s += &format!("    fn read({}: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {{\n", if ss.args.len() > 0 {"i"} else {"_"});
+    *s += &format!("        Ok({} {{\n", structname);
+    for a in ss.args.iter() {
+        *s += &format!("            {}: i.read()?,\n", a.varname());
+    }
+    *s += "        })\n";
+    *s += "    }\n";
+    *s += "}\n\n";
+
+    *s += &format!("impl dbus::message::SignalArgs for {} {{\n", structname);
+    *s += &format!("    const NAME: &'static str = \"{}\";\n", ss.name);
+    *s += &format!("    const INTERFACE: &'static str = \"{}\";\n", i.origname);
+    *s += "}\n";
+    Ok(())
+}
+
+fn write_signals(s: &mut String, i: &Intf) -> Result<(), Box<dyn error::Error>> {
+    for ss in i.signals.iter() { write_signal(s, i, ss)?; }
+    Ok(())
+}
+
+fn write_prop_struct(s: &mut String, i: &Intf) -> Result<(), Box<dyn error::Error>> {
+    // No point generating the properties struct if the interface has no gettable properties.
+    if !i.props.iter().any(|property| property.can_get()) {
+        return Ok(())
+    }
+
+    let struct_name = format!("{}Properties", make_camel(&i.shortname));
+    *s += &format!(r#"
+#[derive(Copy, Clone, Debug)]
+pub struct {0}<'a>(pub &'a arg::PropMap);
+
+impl<'a> {0}<'a> {{
+    pub fn from_interfaces(
+        interfaces: &'a ::std::collections::HashMap<String, arg::PropMap>,
+    ) -> Option<Self> {{
+        interfaces.get("{1}").map(Self)
+    }}
+"#, struct_name, i.origname);
+
+    for p in &i.props {
+        if p.can_get() {
+            let rust_type = make_type(&p.typ, true, &mut None)?;
+            if can_copy_type(&rust_type) {
+                *s += &format!(r#"
+    pub fn {}(&self) -> Option<{}> {{
+        arg::prop_cast(self.0, "{}").copied()
+    }}
+"#, p.get_fn_name, rust_type, p.name);
+            } else {
+                *s += &format!(r#"
+    pub fn {}(&self) -> Option<&{}> {{
+        arg::prop_cast(self.0, "{}")
+    }}
+"#, p.get_fn_name, rust_type, p.name);
+            }
+        }
+    }
+    *s += "}\n";
+    Ok(())
+}
+
+fn write_server_access(s: &mut String, i: &Intf, saccess: ServerAccess, minfo_is_ref: bool) {
+    let z = if minfo_is_ref {""} else {"&"};
+    match saccess {
+        ServerAccess::AsRefClosure => {
+            *s += &format!("        let dd = fclone({}minfo);\n", z);
+            *s += "        let d = dd.as_ref();\n";
+        },
+        ServerAccess::RefClosure => *s += &format!("        let d = fclone({}minfo);\n", z),
+        ServerAccess::MethodInfo => *s += &format!("        let d: &dyn {} = {}minfo;\n", make_camel(&i.shortname), z),
+    }
+}
+
+// Should we implement this for
+// 1) MethodInfo? That's the only way receiver can check Sender, etc - ServerAccess::MethodInfo
+// 2) D::ObjectPath?
+// 3) A user supplied struct?
+// 4) Something reachable from minfo - ServerAccess::RefClosure
+
+fn write_intf_tree(s: &mut String, i: &Intf, mtype: &str, saccess: ServerAccess, genvar: bool) -> Result<(), Box<dyn error::Error>> {
+    let hasf = saccess != ServerAccess::MethodInfo;
+    let hasm = mtype == "MethodType";
+
+    let treem: String = if hasm { "M".into() } else { format!("tree::{}<D>", mtype) };
+
+    *s += &format!("\npub fn {}_server<{}{}D>(factory: &tree::Factory<{}, D>, data: D::Interface{}) -> tree::Interface<{}, D>\n",
+        make_snake(&i.shortname, false), if hasf {"F, T, "} else {""}, if hasm {"M, "} else {""}, treem, if hasf {", f: F"} else {""}, treem);
+
+    let mut wheres: Vec<String> = vec!["D: tree::DataType".into(), "D::Method: Default".into()];
+    if i.props.len() > 0 {
+        wheres.push("D::Property: Default".into());
+    };
+    if i.signals.len() > 0 {
+        wheres.push("D::Signal: Default".into());
+    };
+    if hasm {
+        wheres.push("M: MethodType<D>".into());
+    };
+    match saccess {
+        ServerAccess::RefClosure => {
+            wheres.push(format!("T: {}", make_camel(&i.shortname)));
+            wheres.push(format!("F: 'static + for <'z> Fn(& 'z tree::MethodInfo<tree::{}<D>, D>) -> & 'z T", mtype));
+        },
+        ServerAccess::AsRefClosure => {
+            wheres.push(format!("T: AsRef<dyn {}>", make_camel(&i.shortname)));
+            wheres.push(format!("F: 'static + Fn(&tree::MethodInfo<tree::{}<D>, D>) -> T", mtype));
+        },
+        ServerAccess::MethodInfo => {},
+    };
+    if let ServerAccess::RefClosure | ServerAccess::AsRefClosure = saccess {
+        if mtype == "MTSync" {
+            wheres.push("F: Send + Sync".into());
+        }
+    }
+    *s += "where\n";
+    for w in wheres { *s += &format!("    {},\n", w); }
+    *s += "{\n";
+
+    *s += &format!("    let i = factory.interface(\"{}\", data);\n", i.origname);
+    if hasf {
+        *s += "    let f = ::std::sync::Arc::new(f);";
+    }
+    for m in &i.methods {
+        if hasf {
+            *s += "\n    let fclone = f.clone();\n";
+        }
+        *s += &format!("    let h = move |minfo: &tree::MethodInfo<{}, D>| {{\n", treem);
+        if m.iargs.len() > 0 {
+            *s += "        let mut i = minfo.msg.iter_init();\n";
+        }
+        for a in &m.iargs {
+            *s += &format!("        let {}: {} = i.read()?;\n", a.varname(), a.typename(genvar)?.0);
+        }
+        write_server_access(s, i, saccess, true);
+        let argsvar = m.iargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", ");
+        let retargs = match m.oargs.len() {
+            0 => String::new(),
+            1 => format!("let {} = ", m.oargs[0].varname()),
+            _ => format!("let ({}) = ", m.oargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", ")),
+        };
+        *s += &format!("        {}d.{}({})?;\n",
+            retargs, m.fn_name, argsvar);
+        *s += "        let rm = minfo.msg.method_return();\n";
+        for r in &m.oargs {
+            *s += &format!("        let rm = rm.append1({});\n", r.varname());
+        }
+        *s += "        Ok(vec!(rm))\n";
+        *s += "    };\n";
+        *s += &format!("    let m = factory.method{}(\"{}\", Default::default(), h);\n", if hasm {"_sync"} else {""}, m.name);
+        for a in &m.iargs {
+            *s += &format!("    let m = m.in_arg((\"{}\", \"{}\"));\n", a.name, a.typ);
+        }
+        for a in &m.oargs {
+            *s += &format!("    let m = m.out_arg((\"{}\", \"{}\"));\n", a.name, a.typ);
+        }
+        *s +=          "    let i = i.add_m(m);\n";
+    }
+    for p in &i.props {
+        *s += &format!("\n    let p = factory.property::<{}, _>(\"{}\", Default::default());\n", make_type(&p.typ, false, &mut None)?, p.name);
+        *s += &format!("    let p = p.access(tree::Access::{});\n", match &*p.access {
+            "read" => "Read",
+            "readwrite" => "ReadWrite",
+            "write" => "Write",
+            _ => return Err(format!("Unexpected access value {}", p.access).into()),
+        });
+        if p.can_get() {
+            if hasf {
+                *s += "    let fclone = f.clone();\n";
+            }
+            *s += "    let p = p.on_get(move |a, pinfo| {\n";
+            *s += "        let minfo = pinfo.to_method_info();\n";
+            write_server_access(s, i, saccess, false);
+            *s += &format!("        a.append(d.{}()?);\n", &p.get_fn_name);
+            *s += "        Ok(())\n";
+            *s += "    });\n";
+        }
+        if p.can_set() {
+            if hasf {
+                *s += "    let fclone = f.clone();\n";
+            }
+            *s += "    let p = p.on_set(move |iter, pinfo| {\n";
+            *s += "        let minfo = pinfo.to_method_info();\n";
+            write_server_access(s, i, saccess, false);
+            *s += &format!("        d.{}(iter.read()?)?;\n", &p.set_fn_name);
+            *s += "        Ok(())\n";
+            *s += "    });\n";
+        }
+        *s +=          "    let i = i.add_p(p);\n";
+    }
+    for ss in &i.signals {
+        *s += &format!("    let s = factory.signal(\"{}\", Default::default());\n", ss.name);
+        for a in &ss.args {
+            *s += &format!("    let s = s.arg((\"{}\", \"{}\"));\n", a.name, a.typ);
+        }
+        *s += "    let i = i.add_s(s);\n";
+    }
+    *s +=          "    i\n";
+    *s +=          "}\n";
+    Ok(())
+}
+
+fn write_intf_crossroads(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> {
+    let crh = opts.crhandler.as_ref().unwrap();
+    *s += &format!("\npub fn {}_ifaceinfo<I>() -> cr::IfaceInfo<'static, cr::{}>\n",
+        make_snake(&i.shortname, false), crh);
+    *s += &format!("where I: {}{} {{\n",
+        make_camel(&i.shortname), if crh == "Par" { " + Send + Sync + 'static" } else { "" });
+    *s += &format!("    cr::IfaceInfo::new(\"{}\", vec!(\n", i.origname);
+
+    for m in &i.methods {
+        *s += &format!("        MethodInfo::new_{}(\"{}\", |intf: &I, info| {{\n", crh.to_lowercase(), m.name);
+        if m.iargs.len() > 0 {
+            *s += "            let mut i = info.msg().iter_init();\n";
+        }
+        for a in &m.iargs {
+            *s += &format!("            let {}: {} = i.read()?;\n", a.varname(), a.typename(opts.genericvariant)?.0);
+        }
+        let mut argsvar: Vec<_> = m.iargs.iter().map(|q| q.varname()).collect();
+        argsvar.push("info".into());
+        let argsvar = argsvar.join(", ");
+        let retargs = match m.oargs.len() {
+            0 => String::new(),
+            1 => format!("let {} = ", m.oargs[0].varname()),
+            _ => format!("let ({}) = ", m.oargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", ")),
+        };
+        *s += &format!("            {}intf.{}({})?;\n",
+            retargs, m.fn_name, argsvar);
+        *s += "            let rm = info.msg().method_return();\n";
+        for r in &m.oargs {
+            *s += &format!("            let rm = rm.append1({});\n", r.varname());
+        }
+        *s += "            Ok(Some(rm))\n";
+        *s += "        }),\n";
+    }
+
+    *s += "    ), vec!(), vec!())\n"; // TODO: Props, signals
+    *s += "}\n";
+    Ok(())
+}
+
+
+fn write_module_header(s: &mut String, opts: &GenOpts) {
+    *s += &format!("// This code was autogenerated with `dbus-codegen-rust {}`, see https://github.com/diwic/dbus-rs\n", opts.command_line);
+    *s += &format!("use {} as dbus;\n", opts.dbuscrate);
+    *s += "#[allow(unused_imports)]\n";
+    *s += &format!("use {}::arg;\n", opts.dbuscrate);
+    if opts.futures {
+        *s += "use dbus_futures as dbusf;\n";
+    }
+    if opts.methodtype.is_some() { *s += &format!("use {}_tree as tree;\n", opts.dbuscrate) } else {
+        *s += &format!("use {}::{};\n", opts.dbuscrate, match opts.connectiontype {
+            ConnectionType::Ffidisp => "ffidisp",
+            ConnectionType::Blocking => "blocking",
+            ConnectionType::Nonblock => "nonblock",
+        });
+    }
+    if opts.crhandler.is_some() { *s += &format!("use {}::crossroads as cr;\n", opts.dbuscrate) }
+}
+
+/// Generates Rust structs and traits from D-Bus XML introspection data.
+pub fn generate(xmldata: &str, opts: &GenOpts) -> Result<String, Box<dyn error::Error>> {
+    use xml::EventReader;
+    use xml::reader::XmlEvent;
+
+    let mut s = String::new();
+    write_module_header(&mut s, opts);
+    let mut curintf = None;
+    let mut curm = None;
+    let mut cursig = None;
+    let mut curprop = None;
+    let parser = EventReader::new(io::Cursor::new(xmldata));
+    for e in parser {
+        match e? {
+            XmlEvent::StartElement { ref name, .. } if name.prefix.is_some() => (),
+            XmlEvent::EndElement { ref name, .. } if name.prefix.is_some() => (),
+            XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "interface" => {
+                if curm.is_some() { Err("Start of Interface inside method")? };
+                if curintf.is_some() { Err("Start of Interface inside interface")? };
+                let n = find_attr(attributes, "name")?;
+                let mut n2 = n;
+                if let &Some(ref p) = &opts.skipprefix {
+                    if n.len() > p.len() && n.starts_with(p) { n2 = &n[p.len()..]; }
+                }
+                curintf = Some(Intf { origname: n.into(), shortname: n2.into(),
+                    methods: Vec::new(), signals: Vec::new(), props: Vec::new() });
+            }
+            XmlEvent::EndElement { ref name } if &name.local_name == "interface" => {
+                if curm.is_some() { Err("End of Interface inside method")? };
+                if curintf.is_none() { Err("End of Interface outside interface")? };
+                let intf = curintf.take().unwrap();
+                // If filters are set and no filter matches -> Just print a message and continue parsing
+                if let Some(filter) = &opts.interfaces {
+                    if !filter.contains(&intf.shortname) && !filter.contains(&intf.origname) {
+                        eprintln!("Skip filtered interface '{}'", &intf.shortname);
+                        continue;
+                    }
+                }
+                write_intf(&mut s, &intf, opts)?;
+                if opts.crhandler.is_some() {
+                    write_intf_crossroads(&mut s, &intf, opts)?;
+                } else if let Some(ref mt) = opts.methodtype {
+                    write_intf_tree(&mut s, &intf, &mt, opts.serveraccess, opts.genericvariant)?;
+                } else {
+                    write_intf_client(&mut s, &intf, opts)?;
+                }
+                write_signals(&mut s, &intf)?;
+                if opts.propnewtype {
+                    write_intf_name(&mut s, &intf)?;
+                    write_prop_struct(&mut s, &intf)?;
+                }
+            }
+
+            XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "method" => {
+                if curm.is_some() { Err("Start of method inside method")? };
+                if curintf.is_none() { Err("Start of method outside interface")? };
+                let name = find_attr(attributes, "name")?;
+                curm = Some(Method { name: name.into(), fn_name: make_fn_name(curintf.as_ref().unwrap(), name),
+                    iargs: Vec::new(), oargs: Vec::new() });
+            }
+            XmlEvent::EndElement { ref name } if &name.local_name == "method" => {
+                if curm.is_none() { Err("End of method outside method")? };
+                if curintf.is_none() { Err("End of method outside interface")? };
+                curintf.as_mut().unwrap().methods.push(curm.take().unwrap());
+            }
+
+            XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "signal" => {
+                if cursig.is_some() { Err("Start of signal inside signal")? };
+                if curintf.is_none() { Err("Start of signal outside interface")? };
+                cursig = Some(Signal { name: find_attr(attributes, "name")?.into(), args: Vec::new() });
+            }
+            XmlEvent::EndElement { ref name } if &name.local_name == "signal" => {
+                if cursig.is_none() { Err("End of signal outside signal")? };
+                if curintf.is_none() { Err("End of signal outside interface")? };
+                curintf.as_mut().unwrap().signals.push(cursig.take().unwrap());
+            }
+
+            XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "property" => {
+                if curprop.is_some() { Err("Start of property inside property")? };
+                if curintf.is_none() { Err("Start of property outside interface")? };
+                let name = find_attr(attributes, "name")?;
+                let get_fn_name = make_fn_name(curintf.as_ref().unwrap(), name);
+                let set_fn_name = make_fn_name(curintf.as_ref().unwrap(), &format!("Set{}", name));
+                curprop = Some(Prop {
+                    name: name.into(),
+                    typ: find_attr(attributes, "type")?.into(),
+                    access: find_attr(attributes, "access")?.into(),
+                    get_fn_name: get_fn_name,
+                    set_fn_name: set_fn_name,
+                });
+            }
+            XmlEvent::EndElement { ref name } if &name.local_name == "property" => {
+                if curprop.is_none() { Err("End of property outside property")? };
+                if curintf.is_none() { Err("End of property outside interface")? };
+                curintf.as_mut().unwrap().props.push(curprop.take().unwrap());
+            }
+
+
+            XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "arg" => {
+                if curm.is_none() && cursig.is_none() { Err("Start of arg outside method and signal")? };
+                if curintf.is_none() { Err("Start of arg outside interface")? };
+                let typ = find_attr(attributes, "type")?.into();
+                let is_out = if cursig.is_some() { true } else { match find_attr(attributes, "direction") {
+                    Err(_) => false,
+                    Ok("in") => false,
+                    Ok("out") => true,
+                    _ => { Err("Invalid direction")?; unreachable!() }
+                }};
+                let arr = if let Some(ref mut sig) = cursig { &mut sig.args }
+                    else if is_out { &mut curm.as_mut().unwrap().oargs } else { &mut curm.as_mut().unwrap().iargs };
+                let arg = Arg { name: find_attr(attributes, "name").unwrap_or("").into(),
+                    typ: typ, is_out: is_out, idx: arr.len() as i32 };
+                arr.push(arg);
+            }
+            _ => (),
+        }
+    }
+    if curintf.is_some() { Err("Unterminated interface")? }
+    Ok(s)
+}
+
+#[cfg(test)]
+mod tests {
+
+use super::{generate, GenOpts};
+
+static FROM_DBUS: &'static str = r#"
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node>
+  <interface name="org.freedesktop.DBus">
+    <method name="Hello">
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="RequestName">
+      <arg direction="in" type="s"/>
+      <arg direction="in" type="u"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="ReleaseName">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="StartServiceByName">
+      <arg direction="in" type="s"/>
+      <arg direction="in" type="u"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="UpdateActivationEnvironment">
+      <arg direction="in" type="a{ss}"/>
+    </method>
+    <method name="NameHasOwner">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="b"/>
+    </method>
+    <method name="ListNames">
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="ListActivatableNames">
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="AddMatch">
+      <arg direction="in" type="s"/>
+    </method>
+    <method name="RemoveMatch">
+      <arg direction="in" type="s"/>
+    </method>
+    <method name="GetNameOwner">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="ListQueuedOwners">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="as"/>
+    </method>
+    <method name="GetConnectionUnixUser">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="GetConnectionUnixProcessID">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="u"/>
+    </method>
+    <method name="GetAdtAuditSessionData">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="ay"/>
+    </method>
+    <method name="GetConnectionSELinuxSecurityContext">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="ay"/>
+    </method>
+    <method name="GetConnectionAppArmorSecurityContext">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="ReloadConfig">
+    </method>
+    <method name="GetId">
+      <arg direction="out" type="s"/>
+    </method>
+    <method name="GetConnectionCredentials">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <signal name="NameOwnerChanged">
+      <arg type="s"/>
+      <arg type="s"/>
+      <arg type="s"/>
+    </signal>
+    <signal name="NameLost">
+      <arg type="s"/>
+    </signal>
+    <signal name="NameAcquired">
+      <arg type="s"/>
+    </signal>
+  </interface>
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg direction="out" type="s"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Monitoring">
+    <method name="BecomeMonitor">
+      <arg direction="in" type="as"/>
+      <arg direction="in" type="u"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Debug.Stats">
+    <method name="GetStats">
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <method name="GetConnectionStats">
+      <arg direction="in" type="s"/>
+      <arg direction="out" type="a{sv}"/>
+    </method>
+    <method name="GetAllMatchRules">
+      <arg direction="out" type="a{sas}"/>
+    </method>
+  </interface>
+</node>
+"#;
+
+    #[test]
+    fn from_dbus() {
+        let s = generate(FROM_DBUS, &GenOpts { methodtype: Some("MTSync".into()), ..Default::default() }).unwrap();
+        println!("{}", s);
+        //assert_eq!(s, "fdjsf");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/src/lib.rs
@@ -0,0 +1,5 @@
+extern crate xml;
+
+mod generate;
+
+pub use crate::generate::{generate, GenOpts, ServerAccess, ConnectionType};
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-codegen/src/main.rs
@@ -0,0 +1,143 @@
+mod generate;
+
+use crate::generate::{ServerAccess, ConnectionType};
+
+#[cfg(feature = "dbus")]
+mod connect_to_dbus {
+
+    use dbus::blocking;
+
+    // This code was copy-pasted from the output of this program. :-)
+    pub trait OrgFreedesktopDBusIntrospectable {
+        fn introspect(&self) -> Result<String, dbus::Error>;
+    }
+
+    impl<'a, C: ::std::ops::Deref<Target=blocking::Connection>> OrgFreedesktopDBusIntrospectable for blocking::Proxy<'a, C> {
+
+        fn introspect(&self) -> Result<String, dbus::Error> {
+            self.method_call("org.freedesktop.DBus.Introspectable", "Introspect", ())
+                .and_then(|r: (String, )| Ok(r.0, ))
+        }
+    }
+
+    pub fn do_introspect(dest: &str, path: &str, systembus: bool) -> String {
+        let c = if systembus { blocking::Connection::new_system() } else { blocking::Connection::new_session() };
+        let c = c.unwrap();
+        let p = c.with_proxy(dest, path, std::time::Duration::from_secs(10));
+        p.introspect().unwrap()
+    }
+}
+
+// Unwrapping is fine here, this is just a test program.
+
+fn main() {
+    let app = clap::App::new("D-Bus Rust code generator").about("Generates Rust code from xml introspection data")
+        .arg(clap::Arg::with_name("interfaces").short("f").long("interfaces").takes_value(true).value_name("FILTER")
+            .help("Comma separated list of filter strings. Only matching interfaces are generated if set."))
+        .arg(clap::Arg::with_name("genericvariant").short("g").long("generic-variant")
+             .help("If present, will try to make variant arguments generic instead of Variant<Box<dyn RefArg>>. \
+Experimental, does not work with server methods (other than None)."))
+        .arg(clap::Arg::with_name("methodtype").short("m").long("methodtype").takes_value(true).value_name("Fn")
+             .help("Type of server method; valid values are: 'Fn', 'FnMut', 'Sync', 'Generic', and 'None'. Defaults to 'Fn'."))
+        .arg(clap::Arg::with_name("methodaccess").short("a").long("methodaccess").takes_value(true).value_name("RefClosure")
+             .help("Specifies how to access the type implementing the interface (experimental). Valid values are: 'RefClosure', 'AsRefClosure', 'MethodInfo'. \
+Defaults to 'RefClosure'."))
+        .arg(clap::Arg::with_name("dbuscrate").long("dbuscrate").takes_value(true).value_name("dbus")
+             .help("Name of dbus crate, defaults to 'dbus'."))
+        .arg(clap::Arg::with_name("skipprefix").short("i").long("skipprefix").takes_value(true).value_name("PREFIX")
+             .help("If present, skips a specific prefix for interface names, e g 'org.freedesktop.DBus.'."))
+//        .arg(clap::Arg::with_name("futures").short("f").long("futures")
+//             .help("Generates code to use with futures 0.3 (experimental)"))
+        .arg(clap::Arg::with_name("client").short("c").long("client").takes_value(true).value_name("client")
+             .help("Type of client connection. Valid values are: 'blocking', 'nonblock', 'ffidisp'."))
+        .arg(clap::Arg::with_name("propnewtype").short("n").long("prop-newtype")
+             .help("If present, will generate a struct wrapping PropMap to get properties from it with their expected types."))
+        .arg(clap::Arg::with_name("output").short("o").long("output").takes_value(true).value_name("FILE")
+             .help("Write output into the specified file"))
+        .arg(clap::Arg::with_name("file").long("file").required(false).takes_value(true).value_name("FILE")
+            .help("D-Bus XML Introspection file"));
+
+    #[cfg(feature = "dbus")]
+    let app = app
+        .arg(clap::Arg::with_name("destination").short("d").long("destination").takes_value(true).value_name("BUSNAME")
+             .help("If present, connects to the supplied service to get introspection data. Reads from stdin otherwise."))
+        .arg(clap::Arg::with_name("path").short("p").long("path").takes_value(true).value_name("PATH")
+             .help("The path to ask for introspection data. Defaults to '/'. (Ignored if destination is not specified.)"))
+        .arg(clap::Arg::with_name("systembus").short("s").long("system-bus")
+             .help("Connects to system bus, if not specified, the session bus will be used. (Ignored if destination is not specified.)"));
+
+    let matches = app.get_matches();
+
+    let s = match (matches.value_of("destination"), matches.value_of("file")) {
+        (Some(_), Some(_)) => panic!("'destination' and 'file' are mutually exclusive arguments - you can't provide both"),
+        (None, Some(file_path)) => std::fs::read_to_string(file_path.to_string()).unwrap(),
+        #[cfg(feature = "dbus")]
+        (Some(dest), None) => {
+            let path = matches.value_of("path").unwrap_or("/");
+            connect_to_dbus::do_introspect(dest, path, matches.is_present("systembus"))
+        },
+        #[cfg(not(feature = "dbus"))]
+        (Some(_), None) => unreachable!(),
+        (None, None) => {
+            let mut s = String::new();
+            std::io::Read::read_to_string(&mut std::io::stdin(),&mut s).unwrap();
+            s
+        }
+    };
+
+    let dbuscrate = matches.value_of("dbuscrate").unwrap_or("dbus");
+
+    let mtype = matches.value_of("methodtype").map(|s| s.to_lowercase());
+    let (mtype, crhandler) = match mtype.as_ref().map(|s| &**s) {
+        None | Some("fn") => (Some("MTFn"), None),
+        Some("fnmut") => (Some("MTFnMut"), None),
+        Some("sync") => (Some("MTSync"), None),
+        Some("generic") => (Some("MethodType"), None),
+        Some("par") => (None, Some("Par")),
+        Some("none") => (None, None),
+        _ => panic!("Invalid methodtype specified"),
+    };
+
+    let maccess = matches.value_of("methodaccess").map(|s| s.to_lowercase());
+    let maccess = match maccess.as_ref().map(|s| &**s) {
+        None | Some("refclosure") => ServerAccess::RefClosure,
+        Some("asrefclosure") => ServerAccess::AsRefClosure,
+        Some("methodinfo") => ServerAccess::MethodInfo,
+        _ => panic!("Invalid methodaccess specified"),
+    };
+
+    let client = matches.value_of("client").map(|s| s.to_lowercase());
+    let client = match client.as_ref().map(|s| &**s) {
+        None | Some("blocking") => ConnectionType::Blocking,
+        Some("nonblock") => ConnectionType::Nonblock,
+        Some("ffidisp") => ConnectionType::Ffidisp,
+        _ => panic!("Invalid client connection type specified"),
+    };
+
+    let interfaces = matches.value_of("interfaces").map(|s| s.split(",").map(|e| e.trim().to_owned()).collect());
+
+    let opts = generate::GenOpts {
+        methodtype: mtype.map(|x| x.into()),
+        dbuscrate: dbuscrate.into(),
+        skipprefix: matches.value_of("skipprefix").map(|x| x.into()),
+        serveraccess: maccess,
+        genericvariant: matches.is_present("genericvariant"),
+        futures: false,
+        connectiontype: client,
+        propnewtype: matches.is_present("propnewtype"),
+        crhandler: crhandler.map(|x| x.to_string()),
+        interfaces,
+        command_line: std::env::args().skip(1).collect::<Vec<String>>().join(" ")
+    };
+
+    let mut h: Box<dyn std::io::Write> = match matches.value_of("output") {
+        Some(file_path) => Box::new(std::fs::File::create(file_path)
+            .unwrap_or_else(|e| {
+                panic!("Failed to open {}", e);
+            })),
+        None => Box::new(std::io::stdout()),
+    };
+
+    h.write(generate::generate(&s, &opts).unwrap().as_bytes()).unwrap();
+    h.flush().unwrap();
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.lock":"b2cd78411bfc304fa311fa19d0830a296c9976891e159b7b0ac8e1e77bb553ae","Cargo.toml":"756a4b3f9f35275a5832cbff7f6697fe0e312f90e1278e9350acdd1acc4fbe17","LICENSE-APACHE":"453745410e3be8cf25d56872ea2aec975a78e6c9f217443d0bf908a5bce7c8ff","LICENSE-MIT":"de3911c2d98c8bd2d701ee721347053d9b55995a11f9a8c955e44d3ca1b376bf","examples/adv_server.rs":"31d290110ae0f3618e832c674abdef25bc0c81df5043da7154b8826f03aa6b07","examples/server.rs":"4f22e84923ab5ec72a4ec43c97932c7d619eb582e4319b3eed169cabf6d7b4f6","src/factory.rs":"bd1e4728df66b8597f07282ca76998a290deae9b690bd2fcb4407bad14e55f95","src/leaves.rs":"4cd9971b7328d4c17b4de9fda666d4e0980e101b0f465243a42f88ef9395515c","src/lib.rs":"c27c782f798b2846cfd0409456a73e23f9af28758859ff7527cb0582322a2f13","src/methodtype.rs":"8b1550856ad0f9d5c5ce817103e99a3e1774dfe627a7a67d36437cfce6a0baa8","src/objectpath.rs":"99dfcd1369646ffcfc7ba6e18ddfa0280ffceffe6653f2e3a036a11d5fa04301","src/utils.rs":"240b7cc7b4ce175ffbeb96943da53e6764f3b4cf47b20820b66d17acfbeade21"},"package":"f456e698ae8e54575e19ddb1f9b7bce2298568524f215496b248eb9498b4f508"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/Cargo.lock
@@ -0,0 +1,62 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "dbus"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de0a745c25b32caa56b82a3950f5fec7893a960f4c10ca3b02060b0c38d8c2ce"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "winapi",
+]
+
+[[package]]
+name = "dbus-tree"
+version = "0.9.2"
+dependencies = [
+ "dbus",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c185b5b7ad900923ef3a8ff594083d4d9b5aea80bb4f32b8342363138c0d456b"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c9b1041b4387893b91ee6746cddfc28516aff326a3519fb2adf820932c5e6cb"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/Cargo.toml
@@ -0,0 +1,28 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "dbus-tree"
+version = "0.9.2"
+authors = ["David Henningsson <diwic@ubuntu.com>"]
+description = "Framework for writing D-Bus method handlers (legacy)"
+documentation = "http://docs.rs/dbus-tree"
+readme = "../README.md"
+keywords = ["D-Bus", "DBus", "IPC"]
+categories = ["os::unix-apis", "api-bindings"]
+license = "Apache-2.0/MIT"
+repository = "https://github.com/diwic/dbus-rs"
+[dependencies.dbus]
+version = "0.9"
+[badges.maintenance]
+status = "passively-maintained"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/LICENSE-APACHE
@@ -0,0 +1,202 @@
+Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/LICENSE-MIT
@@ -0,0 +1,19 @@
+Copyright (c) 2014-2018 David Henningsson <diwic@ubuntu.com> and other contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/examples/adv_server.rs
@@ -0,0 +1,177 @@
+// More advanced server example.
+
+// This is supposed to look like a D-Bus service that allows the user to manipulate storage devices.
+
+// Note: in the dbus-codegen/example directory, there is a version of this example where dbus-codegen
+// was used to create some boilerplate code - feel free to compare the two examples.
+
+use std::sync::Arc;
+use std::sync::mpsc;
+use std::cell::Cell;
+use std::thread;
+
+use dbus_tree as tree;
+use dbus::Path;
+use dbus_tree::{Interface, Signal, MTFn, Access, MethodErr, EmitsChangedSignal};
+use dbus::ffidisp::Connection;
+
+// Our storage device
+#[derive(Debug)]
+struct Device {
+    description: String,
+    path: Path<'static>,
+    index: i32,
+    online: Cell<bool>,
+    checking: Cell<bool>,
+}
+
+// Every storage device has its own object path.
+// We therefore create a link from the object path to the Device.
+#[derive(Copy, Clone, Default, Debug)]
+struct TData;
+impl tree::DataType for TData {
+    type Tree = ();
+    type ObjectPath = Arc<Device>;
+    type Property = ();
+    type Interface = ();
+    type Method = ();
+    type Signal = ();
+}
+
+
+impl Device {
+    // Creates a "test" device (not a real one, since this is an example).
+    fn new_bogus(index: i32) -> Device {
+        Device {
+            description: format!("This is device {}, which is {}.", index,
+                ["totally awesome", "really fancy", "still going strong"][(index as usize) % 3]),
+            path: format!("/Device{}", index).into(),
+            index: index,
+            online: Cell::new(index % 2 == 0),
+            checking: Cell::new(false),
+        }
+    }
+}
+
+// Here's where we implement the code for our interface.
+fn create_iface(check_complete_s: mpsc::Sender<i32>) -> (Interface<MTFn<TData>, TData>, Arc<Signal<TData>>) {
+    let f = tree::Factory::new_fn();
+
+    let check_complete = Arc::new(f.signal("CheckComplete", ()));
+
+    (f.interface("com.example.dbus.rs.device", ())
+        // The online property can be both set and get
+        .add_p(f.property::<bool,_>("online", ())
+            .access(Access::ReadWrite)
+            .on_get(|i, m| {
+                let dev: &Arc<Device> = m.path.get_data();
+                i.append(dev.online.get());
+                Ok(())
+            })
+            .on_set(|i, m| {
+                let dev: &Arc<Device> = m.path.get_data();
+                let b: bool = i.read()?;
+                if b && dev.checking.get() {
+                    return Err(MethodErr::failed(&"Device currently under check, cannot bring online"))
+                }
+                dev.online.set(b);
+                Ok(())
+            })
+        )
+        // The "checking" property is read only
+        .add_p(f.property::<bool,_>("checking", ())
+            .emits_changed(EmitsChangedSignal::False)
+            .on_get(|i, m| {
+                let dev: &Arc<Device> = m.path.get_data();
+                i.append(dev.checking.get());
+                Ok(())
+            })
+        )
+        // ...and so is the "description" property
+        .add_p(f.property::<&str,_>("description", ())
+            .emits_changed(EmitsChangedSignal::Const)
+            .on_get(|i, m| {
+                let dev: &Arc<Device> = m.path.get_data();
+                i.append(&dev.description);
+                Ok(())
+            })
+        )
+        // ...add a method for starting a device check...
+        .add_m(f.method("check", (), move |m| {
+            let dev: &Arc<Device> = m.path.get_data();
+            if dev.checking.get() {
+                return Err(MethodErr::failed(&"Device currently under check, cannot start another check"))
+            }
+            if dev.online.get() {
+                return Err(MethodErr::failed(&"Device is currently online, cannot start check"))
+            }
+            dev.checking.set(true);
+
+            // Start some lengthy processing in a separate thread...
+            let devindex = dev.index;
+            let ch = check_complete_s.clone();
+            thread::spawn(move || {
+
+                // Bogus check of device
+                use std::time::Duration;
+                thread::sleep(Duration::from_secs(15));
+
+                // Tell main thread that we finished
+                ch.send(devindex).unwrap();
+            });
+            Ok(vec!(m.msg.method_return()))
+        }))
+        // Indicate that we send a special signal once checking has completed.
+        .add_s(check_complete.clone())
+    , check_complete)
+}
+
+fn create_tree(devices: &[Arc<Device>], iface: &Arc<Interface<MTFn<TData>, TData>>)
+    -> tree::Tree<MTFn<TData>, TData> {
+
+    let f = tree::Factory::new_fn();
+    let mut tree = f.tree(());
+    for dev in devices {
+        tree = tree.add(f.object_path(dev.path.clone(), dev.clone())
+            .introspectable()
+            .add(iface.clone())
+        );
+    }
+    tree
+}
+
+fn run() -> Result<(), Box<dyn std::error::Error>> {
+    // Create our bogus devices
+    let devices: Vec<Arc<Device>> = (0..10).map(|i| Arc::new(Device::new_bogus(i))).collect();
+
+    // Create tree
+    let (check_complete_s, check_complete_r) = mpsc::channel::<i32>();
+    let (iface, sig) = create_iface(check_complete_s);
+    let tree = create_tree(&devices, &Arc::new(iface));
+
+    // Setup DBus connection
+    let c = Connection::new_session()?;
+    c.register_name("com.example.dbus.rs.advancedserverexample", 0)?;
+    tree.set_registered(&c, true)?;
+
+    // ...and serve incoming requests.
+    c.add_handler(tree);
+    loop {
+        // Wait for incoming messages. This will block up to one second.
+        // Discard the result - relevant messages have already been handled.
+        c.incoming(1000).next();
+
+        // Do all other things we need to do in our main loop.
+        if let Ok(idx) = check_complete_r.try_recv() {
+            let dev = &devices[idx as usize];
+            dev.checking.set(false);
+            c.send(sig.msg(&dev.path, &"com.example.dbus.rs.device".into())).map_err(|_| "Sending DBus signal failed")?;
+        }
+    }
+}
+
+fn main() {
+    if let Err(e) = run() {
+        println!("{}", e);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/examples/server.rs
@@ -0,0 +1,69 @@
+/* This example creates a D-Bus server with the following functionality:
+   It registers the "com.example.dbustest" name, creates a "/hello" object path,
+   which has an "com.example.dbustest" interface.
+
+   The interface has a "Hello" method (which takes no arguments and returns a string),
+   and a "HelloHappened" signal (with a string argument) which is sent every time
+   someone calls the "Hello" method.
+*/
+
+use std::sync::Arc;
+use dbus::blocking::LocalConnection;
+use dbus_tree::Factory;
+use std::error::Error;
+use std::time::Duration;
+
+fn main() -> Result<(), Box<dyn Error>> {
+    // Let's start by starting up a connection to the session bus and request a name.
+    let c = LocalConnection::new_session()?;
+    c.request_name("com.example.dbustest", false, true, false)?;
+
+    // The choice of factory tells us what type of tree we want,
+    // and if we want any extra data inside. We pick the simplest variant.
+    let f = Factory::new_fn::<()>();
+
+    // We create the signal first, since we'll need it in both inside the method callback
+    // and when creating the tree.
+    let signal = Arc::new(f.signal("HelloHappened", ()).sarg::<&str,_>("sender"));
+    let signal2 = signal.clone();
+
+    // We create a tree with one object path inside and make that path introspectable.
+    let tree = f.tree(()).add(f.object_path("/hello", ()).introspectable().add(
+
+        // We add an interface to the object path...
+        f.interface("com.example.dbustest", ()).add_m(
+
+            // ...and a method inside the interface.
+            f.method("Hello", (), move |m| {
+
+                // This is the callback that will be called when another peer on the bus calls our method.
+                // the callback receives "MethodInfo" struct and can return either an error, or a list of
+                // messages to send back.
+
+                let name: &str = m.msg.read1()?;
+                let s = format!("Hello {}!", name);
+                let mret = m.msg.method_return().append1(s);
+
+                let sig = signal.msg(m.path.get_name(), m.iface.get_name())
+                    .append1(&*name);
+
+                // Two messages will be returned - one is the method return (and should always be there),
+                // and in our case we also have a signal we want to send at the same time.
+                Ok(vec!(mret, sig))
+
+            // Our method has one output argument and one input argument.
+            }).outarg::<&str,_>("reply")
+            .inarg::<&str,_>("name")
+
+        // We also add the signal to the interface. This is mainly for introspection.
+        ).add_s(signal2)
+
+    // Also add the root path, to help introspection from debugging tools.
+    )).add(f.object_path("/", ()).introspectable());
+
+    // We add the tree to the connection so that incoming method calls will be handled.
+    tree.start_receive(&c);
+
+    // Serve clients forever.
+    loop { c.process(Duration::from_millis(1000))?; }
+}
copy from third_party/rust/dbus/src/tree/factory.rs
copy to third_party/rust/dbus-tree/src/factory.rs
--- a/third_party/rust/dbus/src/tree/factory.rs
+++ b/third_party/rust/dbus-tree/src/factory.rs
@@ -1,14 +1,14 @@
 use super::{MethodType, DataType, MTFn, MTFnMut, MTSync, MethodResult, MethodInfo};
 use super::{Tree, ObjectPath, Interface, Property, Signal, Method};
 use super::objectpath::IfaceCache;
 use std::sync::Arc;
-use Interface as IfaceName;
-use {Member, Path, arg};
+use dbus::strings::{Interface as IfaceName, Member};
+use dbus::{Path, arg};
 use std::cell::RefCell;
 
 /// The factory is used to create object paths, interfaces, methods etc.
 ///
 /// There are three factories:
 ///
 ///  **MTFn** - all methods are `Fn()`.
 ///
@@ -29,17 +29,17 @@ impl Factory<MTFn<()>, ()> {
     /// Creates a new factory for single-thread use.
     pub fn new_fn<D: DataType>() -> Factory<MTFn<D>, D> { Factory(IfaceCache::new()) }
 
     /// Creates a new factory for single-thread use, where callbacks can mutate their environment.
     pub fn new_fnmut<D: DataType>() -> Factory<MTFnMut<D>, D> { Factory(IfaceCache::new()) }
 
     /// Creates a new factory for multi-thread use.
     pub fn new_sync<D: DataType>() -> Factory<MTSync<D>, D> { Factory(IfaceCache::new()) }
-   
+
 }
 
 impl<D: DataType> Factory<MTFn<D>, D> {
     /// Creates a new method for single-thread use.
     pub fn method<H, T>(&self, t: T, data: D::Method, handler: H) -> Method<MTFn<D>, D>
         where H: 'static + Fn(&MethodInfo<MTFn<D>, D>) -> MethodResult, T: Into<Member<'static>> {
         super::leaves::new_method(t.into(), data, Box::new(handler) as Box<_>)
     }
@@ -102,17 +102,17 @@ impl<M: MethodType<D>, D: DataType> Fact
 }
 
 
 #[test]
 fn create_fnmut() {
     let f = Factory::new_fnmut::<()>();
     let mut move_me = 5u32;
     let m = f.method("test", (), move |m| {
-        move_me += 1; 
+        move_me += 1;
         Ok(vec!(m.msg.method_return().append1(&move_me)))
     });
     assert_eq!(&**m.get_name(), "test");
 }
 
 
 #[test]
 fn fn_customdata() {
@@ -123,15 +123,15 @@ fn fn_customdata() {
         type ObjectPath = Arc<u8>;
         type Interface = ();
         type Property = ();
         type Method = i32;
         type Signal = ();
     }
 
     let f = Factory::new_fn::<Custom>();
-  
+
     let m = f.method("test", 789, |_| unimplemented!());
     assert_eq!(*m.get_data(), 789);
-   
+
     let o = f.object_path("/test/test", Arc::new(7));
     assert_eq!(**o.get_data(), 7);
 }
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/src/leaves.rs
@@ -0,0 +1,685 @@
+// Methods, signals, properties, and interfaces.
+use super::utils::{Argument, Annotations, Introspect, introspect_args};
+use super::{MethodType, MethodInfo, MethodResult, MethodErr, DataType, PropInfo, MTFn, MTFnMut, MTSync};
+use dbus::strings::{Interface as IfaceName, Member, Signature, Path};
+use dbus::{arg, Message};
+use std::fmt;
+use std::cell::RefCell;
+use dbus::ffidisp::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged;
+
+
+// Workaround for https://github.com/rust-lang/rust/issues/31518
+struct DebugMethod<M: MethodType<D>, D: DataType>(Box<M::Method>);
+impl<M: MethodType<D>, D: DataType> fmt::Debug for DebugMethod<M, D> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Method>") }
+}
+struct DebugGetProp<M: MethodType<D>, D: DataType>(Box<M::GetProp>);
+impl<M: MethodType<D>, D: DataType> fmt::Debug for DebugGetProp<M, D> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GetProp>") }
+}
+struct DebugSetProp<M: MethodType<D>, D: DataType>(Box<M::SetProp>);
+impl<M: MethodType<D>, D: DataType> fmt::Debug for DebugSetProp<M, D> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<SetProp>") }
+}
+
+
+#[derive(Debug)]
+/// A D-Bus Method.
+pub struct Method<M: MethodType<D>, D: DataType> {
+    cb: DebugMethod<M, D>,
+    data: D::Method,
+    name: Member<'static>,
+    i_args: Vec<Argument>,
+    o_args: Vec<Argument>,
+    anns: Annotations,
+}
+
+impl<M: MethodType<D>, D: DataType> Method<M, D> {
+
+    /// Builder method that adds an "in" Argument to this Method.
+    pub fn in_arg<A: Into<Argument>>(mut self, a: A) -> Self { self.i_args.push(a.into()); self }
+    /// Builder method that adds an "in" Argument to this Method.
+    pub fn inarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.i_args.push((s.into(), A::signature()).into()); self }
+    /// Builder method that adds multiple "in" Arguments to this Method.
+    pub fn in_args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.i_args.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Builder method that adds an "out" Argument to this Method.
+    pub fn out_arg<A: Into<Argument>>(mut self, a: A) -> Self { self.o_args.push(a.into()); self }
+    /// Builder method that adds an "out" Argument to this Method.
+    pub fn outarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.o_args.push((s.into(), A::signature()).into()); self }
+    /// Builder method that adds multiple "out" Arguments to this Method.
+    pub fn out_args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.o_args.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Builder method that adds an annotation to the method.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+    /// Builder method that adds an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    /// Call the Method
+    pub fn call(&self, minfo: &MethodInfo<M, D>) -> MethodResult { M::call_method(&self.cb.0, minfo) }
+
+    /// Get method name
+    pub fn get_name(&self) -> &Member<'static> { &self.name }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::Method { &self.data }
+
+}
+
+impl<M: MethodType<D>, D: DataType> Introspect for Method<M, D> {
+    fn xml_name(&self) -> &'static str { "method" }
+    fn xml_params(&self) -> String { String::new() }
+    fn xml_contents(&self) -> String {
+        format!("{}{}{}",
+            introspect_args(&self.i_args, "      ", " direction=\"in\""),
+            introspect_args(&self.o_args, "      ", " direction=\"out\""),
+            self.anns.introspect("      "))
+    }
+}
+
+pub fn new_method<M: MethodType<D>, D: DataType>(n: Member<'static>, data: D::Method, cb: Box<M::Method>) -> Method<M, D> {
+    Method { name: n, i_args: vec!(), o_args: vec!(), anns: Annotations::new(), cb: DebugMethod(cb), data: data }
+}
+
+
+
+#[derive(Debug)]
+/// A D-Bus Signal.
+pub struct Signal<D: DataType> {
+    name: Member<'static>,
+    data: D::Signal,
+    arguments: Vec<Argument>,
+    anns: Annotations,
+}
+
+impl<D: DataType> Signal<D> {
+
+    /// Builder method that adds an Argument to the Signal.
+    pub fn arg<A: Into<Argument>>(mut self, a: A) -> Self { self.arguments.push(a.into()); self }
+
+    /// Builder method that adds an Argument to the Signal.
+    pub fn sarg<A: arg::Arg, S: Into<String>>(mut self, s: S) -> Self { self.arguments.push((s.into(), A::signature()).into()); self }
+
+    /// Builder method that adds multiple Arguments to the Signal.
+    pub fn args<Z: Into<Argument>, A: IntoIterator<Item=Z>>(mut self, a: A) -> Self {
+        self.arguments.extend(a.into_iter().map(|b| b.into())); self
+    }
+
+    /// Add an annotation to this Signal.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+    /// Add an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    /// Get signal name
+    pub fn get_name(&self) -> &Member<'static> { &self.name }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::Signal { &self.data }
+
+    /// Returns a message which emits the signal when sent.
+    ///
+    /// Same as "msg" but also takes a list of arguments to send.
+    pub fn emit<A: arg::Append>(&self, p: &Path<'static>, i: &IfaceName<'static>, items: &[A]) -> Message {
+        let mut m = self.msg(p, i);
+        let mut ia = arg::IterAppend::new(&mut m);
+        for a in items { a.append_by_ref(&mut ia) }
+        m
+    }
+
+    /// Returns a message which emits the signal when sent.
+    ///
+    /// Same as "emit" but does not take an "items" argument.
+    pub fn msg(&self, p: &Path<'static>, i: &IfaceName<'static>) -> Message {
+        Message::signal(p, i, &self.name)
+    }
+
+}
+
+impl<D: DataType> Introspect for Signal<D> {
+    fn xml_name(&self) -> &'static str { "signal" }
+    fn xml_params(&self) -> String { String::new() }
+    fn xml_contents(&self) -> String {
+        format!("{}{}",
+            introspect_args(&self.arguments, "      ", ""),
+            self.anns.introspect("      "))
+    }
+}
+
+pub fn new_signal<D: DataType>(n: Member<'static>, data: D::Signal) -> Signal<D> {
+    Signal { name: n, arguments: vec!(), anns: Annotations::new(), data: data }
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
+/// Enumerates the different signaling behaviors a Property can have
+/// to being changed.
+pub enum EmitsChangedSignal {
+    /// The Property emits a signal that includes the new value.
+    True,
+    /// The Property emits a signal that does not include the new value.
+    Invalidates,
+    /// The Property cannot be changed.
+    Const,
+    /// The Property does not emit a signal when changed.
+    False,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
+/// The possible access characteristics a Property can have.
+pub enum Access {
+    /// The Property can only be read (Get).
+    Read,
+    /// The Property can be read or written.
+    ReadWrite,
+    /// The Property can only be written (Set).
+    Write,
+}
+
+impl Access {
+    fn introspect(self) -> &'static str {
+        match self {
+            Access::Read => "read",
+            Access::ReadWrite => "readwrite",
+            Access::Write => "write",
+        }
+    }
+}
+
+
+pub fn prop_append_dict<'v, M: MethodType<D> + 'v, D: DataType + 'v, I: Iterator<Item=&'v Property<M, D>>>
+    (iter: &mut arg::IterAppend, mut props: I, minfo: &MethodInfo<M, D>) -> Result<(), MethodErr> {
+
+    let mut result = Ok(());
+    iter.append_dict(&Signature::make::<&str>(), &Signature::make::<arg::Variant<bool>>(), |subiter| loop {
+        let p = if let Some(p) = props.next() { p } else { return };
+        if p.can_get().is_err() { continue; }
+        let pinfo = minfo.to_prop_info(minfo.iface, p);
+        subiter.append_dict_entry(|mut entryiter| {
+            entryiter.append(&*p.get_name());
+            result = p.get_as_variant(&mut entryiter, &pinfo);
+        });
+        if result.is_err() { return };
+    });
+    result
+}
+
+
+#[derive(Debug)]
+/// A D-Bus Property.
+pub struct Property<M: MethodType<D>, D: DataType> {
+    name: String,
+    data: D::Property,
+    sig: Signature<'static>,
+    emits: EmitsChangedSignal,
+    auto_emit: bool,
+    rw: Access,
+    get_cb: Option<DebugGetProp<M, D>>,
+    set_cb: Option<DebugSetProp<M, D>>,
+    anns: Annotations,
+}
+
+impl<M: MethodType<D>, D: DataType> Property<M, D> {
+
+    /// Builder method that allows setting the Property's signal
+    /// behavior when changed.
+    ///
+    /// Note: if e is set to const, the property will be read only.
+    pub fn emits_changed(mut self, e: EmitsChangedSignal) -> Self {
+        self.emits = e;
+        if self.emits == EmitsChangedSignal::Const { self.rw = Access::Read };
+        self
+    }
+
+    /// Builder method that determines whether or not setting this property
+    /// will result in an PropertiesChanged signal. Defaults to true.
+    ///
+    /// When set to true (the default), the behaviour is determined by "emits_changed".
+    /// When set to false, no PropertiesChanged signal will be emitted (but the signal
+    /// still shows up in introspection data).
+    /// You can still emit the signal manually by, e g, calling `add_propertieschanged`
+    /// and send the resulting message(s).
+    pub fn auto_emit_on_set(mut self, b: bool) -> Self {
+        self.auto_emit = b;
+        self
+    }
+
+    /// Builder method that allows setting the Property as readable,
+    /// writable, or both.
+    ///
+    /// Note: might modify emits_changed as well, if property is changed to non-readonly and emit is set to "Const".
+    pub fn access(mut self, e: Access) -> Self {
+        self.rw = e;
+        if self.rw != Access::Read && self.emits == EmitsChangedSignal::Const {
+            self.emits = EmitsChangedSignal::False
+        };
+        self
+    }
+
+    /// Builder method that adds an annotation to the method.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+
+    /// Builder method that adds an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    /// Get property name
+    pub fn get_name(&self) -> &str { &self.name }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::Property { &self.data }
+
+    /// Returns Ok if the property is gettable
+    pub fn can_get(&self) -> Result<(), MethodErr> {
+        if self.rw == Access::Write || self.get_cb.is_none() {
+            Err(MethodErr::failed(&format!("Property {} is write only", &self.name)))
+        } else { Ok(()) }
+    }
+
+    /// Calls the on_get function and appends the result as a variant.
+    ///
+    /// Note: Will panic if get_cb is not set.
+    pub fn get_as_variant(&self, i: &mut arg::IterAppend, pinfo: &PropInfo<M, D>) -> Result<(), MethodErr> {
+        let mut r = Ok(());
+        i.append_variant(&self.sig, |subi| {
+            r = M::call_getprop(&*self.get_cb.as_ref().unwrap().0, subi, pinfo);
+        });
+        r
+    }
+
+    /// Returns Ok if the property is settable.
+    ///
+    /// Will verify signature in case iter is not None; iter is supposed to point at the Variant with the item inside.
+    pub fn can_set(&self, i: Option<arg::Iter>) -> Result<(), MethodErr> {
+        use dbus::arg::Arg;
+        if self.rw == Access::Read || self.set_cb.is_none() || self.emits == EmitsChangedSignal::Const {
+            return Err(MethodErr::ro_property(&self.name))
+        }
+        if let Some(mut i) = i {
+            let mut subiter = i.recurse(arg::Variant::<bool>::ARG_TYPE).ok_or_else(|| MethodErr::invalid_arg(&2))?;
+            if *subiter.signature() != *self.sig {
+               return Err(MethodErr::failed(&format!("Property {} cannot change type", &self.name)))
+            }
+        }
+        Ok(())
+    }
+
+    /// Calls the on_set function, which reads from i.
+    ///
+    /// The return value might contain an extra message containing the EmitsChanged signal.
+    /// Note: Will panic if set_cb is not set.
+    pub fn set_as_variant(&self, i: &mut arg::Iter, pinfo: &PropInfo<M, D>) -> Result<Option<Message>, MethodErr> {
+        use dbus::arg::Arg;
+        let mut subiter = i.recurse(arg::Variant::<bool>::ARG_TYPE).ok_or_else(|| MethodErr::invalid_arg(&2))?;
+        M::call_setprop(&*self.set_cb.as_ref().unwrap().0, &mut subiter, pinfo)?;
+        self.get_emits_changed_signal(pinfo)
+    }
+
+    /// Gets the signal (if any) associated with the Property.
+    fn get_signal(&self, p: &PropInfo<M, D>) -> Message {
+        Message::signal(p.path.get_name(), &"org.freedesktop.DBus.Properties".into(), &"PropertiesChanged".into())
+            .append1(&**p.iface.get_name())
+    }
+
+    /// Adds this property to a list of PropertiesChanged signals.
+    ///
+    /// "v" is updated with the signal for this property. "new_value" is only called if self.emits is "true",
+    /// it should return the value of the property.
+    /// If no PropertiesChanged signal should be emitted for this property, "v" is left unchanged.
+    pub fn add_propertieschanged<F: FnOnce() -> Box<dyn arg::RefArg>>(&self, v: &mut Vec<PropertiesPropertiesChanged>, iface: &IfaceName, new_value: F) {
+
+        // Impl note: It is a bit silly that this function cannot be used from e g get_emits_changed_signal below,
+        // but it is due to the fact that we cannot create a RefArg out of an IterAppend; which is what the 'on_get'
+        // handler currently receives.
+
+        if self.emits == EmitsChangedSignal::Const || self.emits == EmitsChangedSignal::False { return; }
+        let vpos = v.iter().position(|vv| *vv.interface_name == **iface);
+        let vpos = vpos.unwrap_or_else(|| {
+            let mut z: PropertiesPropertiesChanged = Default::default();
+            z.interface_name = (&**iface).into();
+            v.push(z);
+            v.len()-1
+        });
+
+        let vv = &mut v[vpos];
+        if self.emits == EmitsChangedSignal::Invalidates {
+            vv.invalidated_properties.push(self.name.clone());
+        } else {
+            vv.changed_properties.insert(self.name.clone(), arg::Variant(new_value()));
+        }
+    }
+
+    fn get_emits_changed_signal(&self, m: &PropInfo<M, D>) -> Result<Option<Message>, MethodErr> {
+        if !self.auto_emit { return Ok(None) }
+        match self.emits {
+            EmitsChangedSignal::False => Ok(None),
+            EmitsChangedSignal::Const => Err(MethodErr::ro_property(&self.name)),
+            EmitsChangedSignal::True => Ok(Some({
+                let mut s = self.get_signal(m);
+                {
+                    let mut iter = arg::IterAppend::new(&mut s);
+                    prop_append_dict(&mut iter, Some(self).into_iter(), &m.to_method_info())?;
+                    iter.append(arg::Array::<&str, _>::new(vec!()));
+                }
+                s
+            })),
+            EmitsChangedSignal::Invalidates => Ok(Some(self.get_signal(m).append2(
+                arg::Dict::<&str, arg::Variant<bool>, _>::new(vec!()),
+                arg::Array::new(Some(&*self.name).into_iter())
+            ))),
+        }
+    }
+}
+
+impl<'a, D: DataType> Property<MTFn<D>, D> {
+    /// Sets the callback for getting a property.
+    ///
+    /// For single-thread use.
+    pub fn on_get<H>(mut self, handler: H) -> Property<MTFn<D>, D>
+        where H: 'static + Fn(&mut arg::IterAppend, &PropInfo<MTFn<D>, D>) -> Result<(), MethodErr> {
+        self.get_cb = Some(DebugGetProp(Box::new(handler) as Box<_>));
+        self
+    }
+
+    /// Sets the callback for setting a property.
+    ///
+    /// For single-thread use.
+    pub fn on_set<H>(mut self, handler: H) -> Property<MTFn<D>, D>
+        where H: 'static + Fn(&mut arg::Iter, &PropInfo<MTFn<D>, D>) -> Result<(), MethodErr> {
+        self.set_cb = Some(DebugSetProp(Box::new(handler) as Box<_>));
+        self
+    }
+}
+
+
+impl<'a, D: DataType> Property<MTFnMut<D>, D> {
+    /// Sets the callback for getting a property.
+    ///
+    /// For single-thread use.
+    pub fn on_get<H>(mut self, handler: H) -> Property<MTFnMut<D>, D>
+        where H: 'static + Fn(&mut arg::IterAppend, &PropInfo<MTFnMut<D>, D>) -> Result<(), MethodErr> {
+        self.get_cb = Some(DebugGetProp(Box::new(RefCell::new(handler)) as Box<_>));
+        self
+    }
+
+    /// Sets the callback for setting a property.
+    ///
+    /// For single-thread use.
+    pub fn on_set<H>(mut self, handler: H) -> Property<MTFnMut<D>, D>
+        where H: 'static + Fn(&mut arg::Iter, &PropInfo<MTFnMut<D>, D>) -> Result<(), MethodErr> {
+        self.set_cb = Some(DebugSetProp(Box::new(RefCell::new(handler)) as Box<_>));
+        self
+    }
+}
+
+impl<D: DataType> Property<MTSync<D>, D> {
+    /// Sets the callback for getting a property.
+    ///
+    /// For multi-thread use.
+    pub fn on_get<H>(mut self, handler: H) -> Property<MTSync<D>, D>
+        where H: Fn(&mut arg::IterAppend, &PropInfo<MTSync<D>, D>) -> Result<(), MethodErr> + Send + Sync + 'static {
+        self.get_cb = Some(DebugGetProp(Box::new(handler) as Box<_>));
+        self
+    }
+
+    /// Sets the callback for setting a property.
+    ///
+    /// For single-thread use.
+    pub fn on_set<H>(mut self, handler: H) -> Property<MTSync<D>, D>
+        where H: Fn(&mut arg::Iter, &PropInfo<MTSync<D>, D>) -> Result<(), MethodErr> + Send + Sync + 'static {
+        self.set_cb = Some(DebugSetProp(Box::new(handler) as Box<_>));
+        self
+    }
+}
+
+
+impl<M: MethodType<D>, D: DataType> Property<M, D> where D::Property: arg::Append + Clone {
+    /// Adds a "standard" get handler.
+    pub fn default_get(mut self) -> Self {
+        let g = |i: &mut arg::IterAppend, p: &PropInfo<M, D>| { i.append(p.prop.get_data()); Ok(()) };
+        self.get_cb = Some(DebugGetProp(M::make_getprop(g)));
+        self
+    }
+}
+
+
+impl<M: MethodType<D>, D: DataType> Property<M, D> where D::Property: arg::RefArg {
+    /// Adds a "standard" get handler (for RefArgs).
+    pub fn default_get_refarg(mut self) -> Self {
+        let g = |i: &mut arg::IterAppend, p: &PropInfo<M, D>| { arg::RefArg::append(p.prop.get_data(),i); Ok(()) };
+        self.get_cb = Some(DebugGetProp(M::make_getprop(g)));
+        self
+    }
+}
+
+impl<M: MethodType<D>, D: DataType> Introspect for Property<M, D> {
+    fn xml_name(&self) -> &'static str { "property" }
+    fn xml_params(&self) -> String { format!(" type=\"{}\" access=\"{}\"", self.sig, self.rw.introspect()) }
+    fn xml_contents(&self) -> String {
+        let s = match self.emits {
+             EmitsChangedSignal::True => return self.anns.introspect("      "),
+             EmitsChangedSignal::False => "false",
+             EmitsChangedSignal::Const => "const",
+             EmitsChangedSignal::Invalidates => "invalidates",
+        };
+        let mut tempanns = self.anns.clone();
+        tempanns.insert("org.freedesktop.DBus.Property.EmitsChangedSignal", s);
+        tempanns.introspect("      ")
+    }
+}
+
+pub fn new_property<M: MethodType<D>, D: DataType>
+    (n: String, sig: Signature<'static>, data: D::Property) -> Property<M, D> {
+    Property {
+        name: n, emits: EmitsChangedSignal::True, auto_emit: true, rw: Access::Read,
+        sig: sig, anns: Annotations::new(), set_cb: None, get_cb: None, data: data
+    }
+}
+
+#[test]
+fn test_prop_handlers() {
+    use crate::Factory;
+    use std::collections::BTreeMap;
+    use dbus::arg::{Dict, Variant};
+
+    #[derive(Default, Debug)]
+    struct Custom;
+    impl DataType for Custom {
+        type Tree = ();
+        type ObjectPath = ();
+        type Interface = ();
+        type Property = i32;
+        type Method = ();
+        type Signal = ();
+    }
+
+    let f = Factory::new_fn::<Custom>();
+    let tree = f.tree(()).add(f.object_path("/test", ()).introspectable().object_manager()
+        .add(f.interface("com.example.test", ())
+            .add_p(f.property::<i32,_>("Value1", 5i32).default_get())
+            .add_p(f.property::<i32,_>("Value2", 9i32).default_get())
+        )
+    );
+
+    let mut msg = Message::new_method_call("com.example.test", "/test", "org.freedesktop.DBus.Properties", "Get").unwrap()
+        .append2("com.example.test", "Value1");
+    msg.set_serial(4);
+    let res = tree.handle(&msg).unwrap();
+    assert_eq!(res[0].get1(), Some(arg::Variant(5i32)));
+
+    let mut msg = Message::new_method_call("com.example.test", "/test", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append3("com.example.test", "Value1", arg::Variant(3i32));
+    msg.set_serial(4);
+    let mut res = tree.handle(&msg).unwrap();
+    assert!(res[0].as_result().is_err());
+
+    let mut msg = Message::new_method_call("com.example.test", "/test", "org.freedesktop.DBus.Properties", "GetAll").unwrap()
+        .append1("com.example.test");
+    msg.set_serial(4);
+    let res = tree.handle(&msg).unwrap();
+    let d: Dict<&str, Variant<i32>, _> = res[0].get1().unwrap();
+    let z2: BTreeMap<_, _> = d.collect();
+    assert_eq!(z2.get("Value1"), Some(&arg::Variant(5i32)));
+    assert_eq!(z2.get("Value2"), Some(&arg::Variant(9i32)));
+    assert_eq!(z2.get("Mooh"), None);
+}
+
+#[test]
+fn test_get_managed_objects() {
+    use std::collections::BTreeMap;
+
+    use crate::Factory;
+    use dbus::arg::{Dict, Variant};
+
+    #[derive(Default, Debug)]
+    struct Custom;
+    impl DataType for Custom {
+        type Tree = ();
+        type ObjectPath = ();
+        type Interface = ();
+        type Property = i32;
+        type Method = ();
+        type Signal = ();
+    }
+
+    let f = Factory::new_fn::<Custom>();
+    let tree = f.tree(()).add(f.object_path("/test", ()).introspectable().object_manager()
+        .add(f.interface("com.example.test", ())
+            .add_p(f.property::<i32,_>("Value1", 5i32).default_get())
+            .add_p(f.property::<i32,_>("Value2", 9i32).default_get())
+        )
+    ).add(f.object_path("/test/subtest", ()).introspectable()
+        .add(f.interface("com.example.subtest", ())
+            .add_p(f.property::<i32, _>("Value3", 7i32).default_get())
+        )
+    );
+
+    let mut msg = Message::new_method_call("com.example.test", "/test", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects").unwrap();
+    msg.set_serial(4);
+    let res = tree.handle(&msg).unwrap();
+    let pdict: arg::Dict<Path, Dict<&str, Dict<&str, Variant<i32>, _>, _>, _> = res[0].get1().unwrap();
+    let pmap: BTreeMap<_, _> = pdict.collect();
+
+    assert!(pmap.get(&Path::from("/test")).is_none());
+
+    let idict = pmap.get(&Path::from("/test/subtest")).unwrap();
+    let imap: BTreeMap<_, _> = idict.collect();
+    let propdict = imap.get("com.example.subtest").unwrap();
+    let propmap: BTreeMap<_, _> = propdict.collect();
+    assert_eq!(propmap.get("Value3"), Some(&arg::Variant(7i32)));
+}
+
+#[test]
+fn test_set_prop() {
+    use crate::{Factory, Access};
+    use std::cell::{Cell, RefCell};
+    use std::collections::BTreeMap;
+    use std::rc::Rc;
+
+    let changes = Rc::new(Cell::new(0i32));
+    let (changes1, changes2) = (changes.clone(), changes.clone());
+    let setme = Rc::new(RefCell::new("I have not been set yet!".to_owned()));
+    let (setme1, setme2) = (setme.clone(), setme.clone());
+
+    let f = Factory::new_fn::<()>();
+    let tree = f.tree(()).add(f.object_path("/example", ()).introspectable()
+        .add(f.interface("com.example.dbus.rs", ())
+            .add_p(f.property::<i32,_>("changes", ())
+                .on_get(move |i, _| { i.append(changes1.get()); Ok(()) }))
+            .add_p(f.property::<String,_>("setme", ())
+                .access(Access::ReadWrite)
+                .on_get(move |i, _| { i.append(&*setme1.borrow()); Ok(()) })
+                .on_set(move |i, _| {
+                    *setme2.borrow_mut() = i.get().unwrap();
+                    changes2.set(changes2.get() + 1);
+                    Ok(())
+                }))
+        )
+    );
+
+    // Read-only
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append3("com.example.dbus.rs", "changes", arg::Variant(5i32));
+    msg.set_serial(20);
+    let mut r = tree.handle(&msg).unwrap();
+    assert!(r.get_mut(0).unwrap().as_result().is_err());
+
+    // Wrong type
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append3("com.example.dbus.rs", "setme", arg::Variant(8i32));
+    msg.set_serial(30);
+    let mut r = tree.handle(&msg).unwrap();
+    assert!(r.get_mut(0).unwrap().as_result().is_err());
+
+    // Correct!
+    let mut msg = Message::new_method_call("com.example.dbus.rs", "/example", "org.freedesktop.DBus.Properties", "Set").unwrap()
+        .append3("com.example.dbus.rs", "setme", arg::Variant("Correct"));
+    msg.set_serial(30);
+    let r = tree.handle(&msg).unwrap();
+
+    assert_eq!(changes.get(), 1);
+    assert_eq!(&**setme.borrow(), "Correct");
+
+    println!("{:?}", r);
+    assert_eq!(r.len(), 2);
+    assert_eq!(&*r[0].member().unwrap(), "PropertiesChanged");
+    let (s, d): (Option<&str>, Option<arg::Dict<&str, arg::Variant<_>, _>>) = r[0].get2();
+    assert_eq!(s, Some("com.example.dbus.rs"));
+    let z2: BTreeMap<_, _> = d.unwrap().collect();
+    assert_eq!(z2.get("setme"), Some(&arg::Variant("Correct")));
+
+}
+
+
+#[test]
+fn test_sync_prop() {
+    use std::sync::atomic::{AtomicUsize, Ordering};
+    use std::sync::Arc;
+    use crate::{Factory, Access, EmitsChangedSignal};
+
+    let f = Factory::new_sync::<()>();
+
+    let count = Arc::new(AtomicUsize::new(3));
+    let (cget, cset) = (count.clone(), count.clone());
+
+    let tree1 = Arc::new(f.tree(()).add(f.object_path("/syncprop", ()).introspectable()
+        .add(f.interface("com.example.syncprop", ())
+            .add_p(f.property::<u32,_>("syncprop", ())
+                .access(Access::ReadWrite)
+                .emits_changed(EmitsChangedSignal::False)
+                .on_get(move |i,_| { i.append(cget.load(Ordering::SeqCst) as u32); Ok(()) })
+                .on_set(move |i,_| { cset.store(i.get::<u32>().unwrap() as usize, Ordering::SeqCst); Ok(()) })
+            )
+        )
+    ));
+
+    let tree2 = tree1.clone();
+    println!("{:#?}", tree2);
+
+    ::std::thread::spawn(move || {
+        let mut msg = Message::new_method_call("com.example.syncprop", "/syncprop", "org.freedesktop.DBus.Properties", "Set").unwrap()
+            .append3("com.example.syncprop", "syncprop", arg::Variant(5u32));
+         msg.set_serial(30);
+         let mut r = tree2.handle(&msg).unwrap();
+         assert!(r[0].as_result().is_ok());
+    });
+
+    loop {
+        let mut msg = Message::new_method_call("com.example.echoserver", "/syncprop", "org.freedesktop.DBus.Properties", "Get").unwrap()
+            .append1("com.example.syncprop").append1("syncprop");
+        msg.set_serial(4);
+        let mut r = tree1.handle(&msg).unwrap();
+        let r = r[0].as_result().unwrap();
+        let z: arg::Variant<u32> = r.get1().unwrap();
+        if z.0 == 5 { break; }
+        assert_eq!(z.0, 3);
+   }
+   assert_eq!(count.load(Ordering::SeqCst), 5);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/src/lib.rs
@@ -0,0 +1,38 @@
+//! Contains functionality for dispatching methods on a D-Bus "server".
+//!
+//! # Example
+//! ```rust,no_run
+//! use dbus_tree::Factory;
+//! use dbus::ffidisp::Connection;
+//! let f = Factory::new_fn::<()>();
+//! /* Add a method returning "Thanks!" on interface "com.example.dbus.rs"
+//!    on object path "/example". */
+//! let t = f.tree(()).add(f.object_path("/example", ()).introspectable()
+//!     .add(f.interface("com.example.dbus.rs", ())
+//!         .add_m(f.method("CallMe", (), |m| {
+//!             Ok(vec!(m.msg.method_return().append1("Thanks!"))) }
+//!         ).out_arg("s"))
+//! ));
+//!
+//! let c = Connection::new_session().unwrap();
+//! t.set_registered(&c, true).unwrap();
+//! c.add_handler(t);
+//! /* Run forever */
+//! loop { c.incoming(1000).next(); }
+//! ```
+//!
+//! See `examples/server.rs` and `examples/adv_server.rs` for more thorough examples.
+
+mod utils;
+mod methodtype;
+mod leaves;
+mod objectpath;
+mod factory;
+
+pub use dbus::MethodErr;
+
+pub use self::utils::{Argument, Iter};
+pub use self::methodtype::{MethodInfo, PropInfo, MethodResult, MethodType, DataType, MTFn, MTFnMut, MTSync};
+pub use self::leaves::{Method, Signal, Property, Access, EmitsChangedSignal};
+pub use self::objectpath::{Interface, ObjectPath, Tree, TreeServer};
+pub use self::factory::Factory;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/src/methodtype.rs
@@ -0,0 +1,209 @@
+// Methods and method types. Glue to make stuff generic over MFn, MFnMut and MSync
+
+use std::fmt;
+use dbus::Message;
+use dbus::ffidisp::stdintf;
+use dbus::arg::{Iter, IterAppend};
+use std::marker::PhantomData;
+use super::{Method, Interface, Property, ObjectPath, Tree};
+use std::cell::RefCell;
+use dbus::MethodErr;
+
+/// Result containing the Messages returned from the Method, or a MethodErr.
+pub type MethodResult = Result<Vec<Message>, MethodErr>;
+
+/// Associated data for different objects in a tree.
+///
+/// These currently require a debug bound, due to https://github.com/rust-lang/rust/issues/31518
+pub trait DataType: Sized + Default {
+    /// Type of associated data on the Tree.
+    type Tree: fmt::Debug;
+    /// Type of associated data on every ObjectPath.
+    type ObjectPath: fmt::Debug;
+    /// Type of associated data on every Property.
+    type Property: fmt::Debug;
+    /// Type of associated data on every Interface.
+    type Interface: fmt::Debug;
+    /// Type of associated data on every Method.
+    type Method: fmt::Debug;
+    /// Type of associated data on every Signal.
+    type Signal: fmt::Debug;
+}
+
+/// No associated data for the tree.
+impl DataType for () {
+    type Tree = ();
+    type ObjectPath = ();
+    type Interface = ();
+    type Property = ();
+    type Method = ();
+    type Signal = ();
+}
+
+/// A helper trait used internally to make the tree generic over MTFn, MTFnMut and MTSync.
+///
+/// You should not need to call these methods directly, it's primarily for internal use.
+pub trait MethodType<D: DataType>: Sized + Default {
+    /// For internal use.
+    type Method: ?Sized;
+    /// For internal use.
+    type GetProp: ?Sized;
+    /// For internal use.
+    type SetProp: ?Sized;
+
+    /// For internal use.
+    fn call_getprop(_: &Self::GetProp, _: &mut IterAppend, _: &PropInfo<Self, D>) -> Result<(), MethodErr>;
+    /// For internal use.
+    fn call_setprop(_: &Self::SetProp, _: &mut Iter, _: &PropInfo<Self, D>) -> Result<(), MethodErr>;
+    /// For internal use.
+    fn call_method(_: &Self::Method, _: &MethodInfo<Self, D>) -> MethodResult;
+
+    /// For internal use.
+    fn make_getprop<H>(h: H) -> Box<Self::GetProp>
+    where H: Fn(&mut IterAppend, &PropInfo<Self,D>) -> Result<(), MethodErr> + Send + Sync + 'static;
+    /// For internal use.
+    fn make_method<H>(h: H) -> Box<Self::Method>
+    where H: Fn(&MethodInfo<Self,D>) -> MethodResult + Send + Sync + 'static;
+}
+
+
+/// An abstract type to represent Fn functions.
+#[derive(Default, Debug, Copy, Clone)]
+pub struct MTFn<D=()>(PhantomData<*const D>);
+
+impl<D: DataType> MethodType<D> for MTFn<D> {
+    type GetProp = dyn Fn(&mut IterAppend, &PropInfo<Self, D>) -> Result<(), MethodErr>;
+    type SetProp = dyn Fn(&mut Iter, &PropInfo<Self, D>) -> Result<(), MethodErr>;
+    type Method = dyn Fn(&MethodInfo<Self, D>) -> MethodResult;
+
+    fn call_getprop(p: &Self::GetProp, i: &mut IterAppend, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { p(i, pinfo) }
+    fn call_setprop(p: &Self::SetProp, i: &mut Iter, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { p(i, pinfo) }
+    fn call_method(p: &Self::Method, minfo: &MethodInfo<Self, D>)
+        -> MethodResult { p(minfo) }
+
+    fn make_getprop<H>(h: H) -> Box<Self::GetProp>
+    where H: Fn(&mut IterAppend, &PropInfo<Self,D>) -> Result<(), MethodErr> + Send + Sync + 'static { Box::new(h) }
+    fn make_method<H>(h: H) -> Box<Self::Method>
+    where H: Fn(&MethodInfo<Self,D>) -> MethodResult + Send + Sync + 'static { Box::new(h) }
+}
+
+/// An abstract type to represent FnMut functions.
+#[derive(Default, Debug, Copy, Clone)]
+pub struct MTFnMut<D=()>(PhantomData<*const D>);
+
+impl<D: DataType> MethodType<D> for MTFnMut<D> {
+    type GetProp = RefCell<dyn FnMut(&mut IterAppend, &PropInfo<Self, D>) -> Result<(), MethodErr>>;
+    type SetProp = RefCell<dyn FnMut(&mut Iter, &PropInfo<Self, D>) -> Result<(), MethodErr>>;
+    type Method = RefCell<dyn FnMut(&MethodInfo<Self, D>) -> MethodResult>;
+
+    fn call_getprop(p: &Self::GetProp, i: &mut IterAppend, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { (&mut *p.borrow_mut())(i, pinfo) }
+    fn call_setprop(p: &Self::SetProp, i: &mut Iter, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { (&mut *p.borrow_mut())(i, pinfo) }
+    fn call_method(p: &Self::Method, minfo: &MethodInfo<Self, D>)
+        -> MethodResult { (&mut *p.borrow_mut())(minfo) }
+
+    fn make_getprop<H>(h: H) -> Box<Self::GetProp>
+    where H: Fn(&mut IterAppend, &PropInfo<Self,D>) -> Result<(), MethodErr> + Send + Sync + 'static { Box::new(RefCell::new(h)) }
+    fn make_method<H>(h: H) -> Box<Self::Method>
+    where H: Fn(&MethodInfo<Self,D>) -> MethodResult + Send + Sync + 'static { Box::new(RefCell::new(h)) }
+
+}
+
+/// An abstract type to represent Fn + Send + Sync functions (that can be called from several threads in parallel).
+#[derive(Default, Debug, Copy, Clone)]
+pub struct MTSync<D=()>(PhantomData<*const D>);
+
+impl<D: DataType> MethodType<D> for MTSync<D> {
+    type GetProp = dyn Fn(&mut IterAppend, &PropInfo<Self, D>) -> Result<(), MethodErr> + Send + Sync + 'static;
+    type SetProp = dyn Fn(&mut Iter, &PropInfo<Self, D>) -> Result<(), MethodErr> + Send + Sync + 'static;
+    type Method = dyn Fn(&MethodInfo<Self, D>) -> MethodResult + Send + Sync + 'static;
+
+    fn call_getprop(p: &Self::GetProp, i: &mut IterAppend, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { p(i, pinfo) }
+    fn call_setprop(p: &Self::SetProp, i: &mut Iter, pinfo: &PropInfo<Self, D>)
+        -> Result<(), MethodErr> { p(i, pinfo) }
+    fn call_method(p: &Self::Method, minfo: &MethodInfo<Self, D>)
+        -> MethodResult { p(minfo) }
+
+    fn make_getprop<H>(h: H) -> Box<Self::GetProp>
+    where H: Fn(&mut IterAppend, &PropInfo<Self,D>) -> Result<(), MethodErr> + Send + Sync + 'static  { Box::new(h) }
+    fn make_method<H>(h: H) -> Box<Self::Method>
+    where H: Fn(&MethodInfo<Self,D>) -> MethodResult + Send + Sync + 'static { Box::new(h) }
+}
+
+
+
+#[derive(Debug, Copy, Clone)]
+/// Contains information about the incoming method call.
+pub struct MethodInfo<'a, M: 'a + MethodType<D>, D: 'a + DataType> {
+    /// Message
+    pub msg: &'a Message,
+    /// The method to be called
+    pub method: &'a Method<M, D>,
+    /// Interface
+    pub iface: &'a Interface<M, D>,
+    /// Object path
+    pub path: &'a ObjectPath<M, D>,
+    /// Tree
+    pub tree: &'a Tree<M, D>,
+}
+
+impl<'a, M: 'a + MethodType<D>, D: 'a + DataType> MethodInfo<'a, M, D> {
+    /// MethodInfo to PropInfo conversion
+    pub fn to_prop_info(&self, iface: &'a Interface<M, D>, prop: &'a Property<M, D>) -> PropInfo<'a, M, D> {
+        PropInfo { msg: self.msg, method: self.method, iface: iface, prop: prop, path: self.path, tree: self.tree }
+    }
+}
+
+
+impl<'a, M: 'a + MethodType<D>, D: 'a + DataType> stdintf::OrgFreedesktopDBusIntrospectable for MethodInfo<'a, M, D> {
+    type Err = MethodErr;
+    fn introspect(&self) -> Result<String, Self::Err> { Ok(self.path.introspect(self.tree)) }
+}
+
+// Mostly autogenerated by dbus-codegen
+pub fn org_freedesktop_dbus_introspectable_server<M, D>(factory: &super::Factory<M, D>, data: D::Interface) -> super::Interface<M, D>
+where
+    D: super::DataType,
+    D::Method: Default,
+    M: MethodType<D>,
+{
+    let i = factory.interface("org.freedesktop.DBus.Introspectable", data);
+    let h = move |minfo: &super::MethodInfo<M, D>| {
+        let d: &dyn stdintf::OrgFreedesktopDBusIntrospectable<Err=super::MethodErr> = minfo;
+        let arg0 = d.introspect()?;
+        let rm = minfo.msg.method_return();
+        let rm = rm.append1(arg0);
+        Ok(vec!(rm))
+    };
+    let m = factory.method_sync("Introspect", Default::default(), h);
+    let m = m.out_arg(("xml_data", "s"));
+    i.add_m(m)
+}
+
+#[derive(Debug, Copy, Clone)]
+/// Contains information about the incoming property get/set request.
+pub struct PropInfo<'a, M: 'a + MethodType<D>, D: 'a + DataType> {
+    /// Message
+    pub msg: &'a Message,
+    /// Get, Set or GetAll
+    pub method: &'a Method<M, D>,
+    /// The property to be set/get
+    pub prop: &'a Property<M, D>,
+    /// The interface the property belongs to
+    pub iface: &'a Interface<M, D>,
+    /// Object path
+    pub path: &'a ObjectPath<M, D>,
+    /// Tree
+    pub tree: &'a Tree<M, D>,
+}
+
+impl<'a, M: 'a + MethodType<D>, D: 'a + DataType> PropInfo<'a, M, D> {
+    /// PropInfo to MethodInfo conversion.
+    pub fn to_method_info(&self) -> MethodInfo<'a, M, D> {
+        MethodInfo { msg: self.msg, method: self.method, iface: self.iface, path: self.path, tree: self.tree }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/src/objectpath.rs
@@ -0,0 +1,720 @@
+use super::utils::{ArcMap, Iter, IterE, Annotations, Introspect};
+use super::{Factory, MethodType, MethodInfo, MethodResult, MethodErr, DataType, Property, Method, Signal, methodtype};
+use std::sync::{Arc, Mutex};
+use dbus::{Message, MessageType, Error, arg, message, channel};
+use dbus::strings::{Member, Path, Signature, Interface as IfaceName};
+use dbus::ffidisp::{ConnectionItem, MsgHandler, Connection, MsgHandlerType, MsgHandlerResult};
+use std::fmt;
+use super::leaves::prop_append_dict;
+use dbus::channel::Channel;
+use std::time::Duration;
+
+fn introspect_map<I: fmt::Display, T: Introspect>
+    (h: &ArcMap<I, T>, indent: &str) -> String {
+
+    h.iter().fold("".into(), |a, (k, v)| {
+        let (name, params, contents) = (v.xml_name(), v.xml_params(), v.xml_contents());
+        format!("{}{}<{} name=\"{}\"{}{}>\n",
+            a, indent, name, &*k, params, if !contents.is_empty() {
+                format!(">\n{}{}</{}", contents, indent, name)
+            }
+            else { "/".to_string() }
+        )
+    })
+}
+
+#[derive(Debug)]
+/// Represents a D-Bus interface.
+pub struct Interface<M: MethodType<D>, D: DataType> {
+    name: Arc<IfaceName<'static>>,
+    methods: ArcMap<Member<'static>, Method<M, D>>,
+    signals: ArcMap<Member<'static>, Signal<D>>,
+    properties: ArcMap<String, Property<M, D>>,
+    anns: Annotations,
+    data: D::Interface,
+}
+
+impl<M: MethodType<D>, D: DataType> Interface<M, D> {
+    /// Builder function that adds a method to the interface.
+    pub fn add_m<I: Into<Arc<Method<M, D>>>>(mut self, m: I) -> Self {
+        let m = m.into();
+        self.methods.insert(m.get_name().clone(), m);
+        self
+    }
+
+    /// Builder function that adds a signal to the interface.
+    pub fn add_s<I: Into<Arc<Signal<D>>>>(mut self, s: I) -> Self {
+        let m = s.into();
+        self.signals.insert(m.get_name().clone(), m);
+        self
+    }
+
+    /// Builder function that adds a property to the interface.
+    pub fn add_p<I: Into<Arc<Property<M, D>>>>(mut self, p: I) -> Self {
+        let m = p.into();
+        self.properties.insert(m.get_name().to_owned(), m);
+        self
+    }
+
+    /// Builder function that adds an annotation to this interface.
+    pub fn annotate<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
+        self.anns.insert(name, value); self
+    }
+
+    /// Builder function that adds an annotation that this entity is deprecated.
+    pub fn deprecated(self) -> Self { self.annotate("org.freedesktop.DBus.Deprecated", "true") }
+
+    /// Get interface name
+    pub fn get_name(&self) -> &IfaceName<'static> { &self.name }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::Interface { &self.data }
+
+    /// Iterates over methods implemented by this interface.
+    pub fn iter_m<'a>(&'a self) -> Iter<'a, Method<M, D>> { IterE::Member(self.methods.values()).into() }
+
+    /// Iterates over signals implemented by this interface.
+    pub fn iter_s<'a>(&'a self) -> Iter<'a, Signal<D>> { IterE::Member(self.signals.values()).into() }
+
+    /// Iterates over properties implemented by this interface.
+    pub fn iter_p<'a>(&'a self) -> Iter<'a, Property<M, D>> { IterE::String(self.properties.values()).into() }
+}
+
+impl<M: MethodType<D>, D: DataType> Introspect for Interface<M, D> {
+    fn xml_name(&self) -> &'static str { "interface" }
+    fn xml_params(&self) -> String { String::new() }
+    fn xml_contents(&self) -> String {
+        format!("{}{}{}{}",
+            introspect_map(&self.methods, "    "),
+            introspect_map(&self.properties, "    "),
+            introspect_map(&self.signals, "    "),
+            self.anns.introspect("    "))
+    }
+}
+
+
+pub fn new_interface<M: MethodType<D>, D: DataType>(t: IfaceName<'static>, d: D::Interface) -> Interface<M, D> {
+    Interface { name: Arc::new(t), methods: ArcMap::new(), signals: ArcMap::new(),
+        properties: ArcMap::new(), anns: Annotations::new(), data: d
+    }
+}
+
+
+#[derive(Debug)]
+/// Cache of built-in interfaces, in order to save memory when many object paths implement the same interface(s).
+pub struct IfaceCache<M: MethodType<D>, D: DataType>(Mutex<ArcMap<IfaceName<'static>, Interface<M, D>>>);
+
+impl<M: MethodType<D>, D: DataType> IfaceCache<M, D>
+where D::Interface: Default {
+    pub fn get<S: Into<IfaceName<'static>> + Clone, F>(&self, s: S, f: F) -> Arc<Interface<M, D>>
+        where F: FnOnce(Interface<M, D>) -> Interface<M, D> {
+        let s2 = s.clone().into();
+        let mut m = self.0.lock().unwrap();
+        m.entry(s2).or_insert_with(|| {
+            let i = new_interface(s.into(), Default::default());
+            Arc::new(f(i))
+        }).clone()
+    }
+}
+
+impl<M: MethodType<D>, D: DataType> IfaceCache<M, D> {
+    pub fn get_factory<S: Into<IfaceName<'static>> + Clone, F>(&self, s: S, f: F) -> Arc<Interface<M, D>>
+        where F: FnOnce() -> Interface<M, D> {
+        let s2 = s.clone().into();
+        let mut m = self.0.lock().unwrap();
+        m.entry(s2).or_insert_with(|| {
+            Arc::new(f())
+        }).clone()
+    }
+
+
+    pub fn new() -> Arc<Self> { Arc::new(IfaceCache(Mutex::new(ArcMap::new()))) }
+}
+
+#[derive(Debug)]
+/// A D-Bus Object Path.
+pub struct ObjectPath<M: MethodType<D>, D: DataType> {
+    name: Arc<Path<'static>>,
+    default_iface: Option<IfaceName<'static>>,
+    ifaces: ArcMap<Arc<IfaceName<'static>>, Interface<M, D>>,
+    ifacecache: Arc<IfaceCache<M, D>>,
+    data: D::ObjectPath,
+}
+
+impl<M: MethodType<D>, D: DataType> ObjectPath<M, D> {
+
+    /// Get property name
+    pub fn get_name(&self) -> &Path<'static> { &self.name }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::ObjectPath { &self.data }
+
+    /// Iterates over interfaces implemented by this object path.
+    pub fn iter<'a>(&'a self) -> Iter<'a, Interface<M, D>> { IterE::Iface(self.ifaces.values()).into() }
+
+    pub(super) fn introspect(&self, tree: &Tree<M, D>) -> String {
+        let ifacestr = introspect_map(&self.ifaces, "  ");
+        let olen = if &**self.name == "/" { 1 } else { self.name.len()+1 };
+        let childstr = tree.children(self, true).iter().fold("".to_string(), |na, n|
+            format!("{}  <node name=\"{}\"/>\n", na, &n.name[olen..])
+        );
+
+        let nodestr = format!(r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="{}">
+{}{}</node>"##, self.name, ifacestr, childstr);
+        nodestr
+    }
+
+    fn get_iface<'a>(&'a self, iface_name: &'a str) -> Result<&Arc<Interface<M, D>>, MethodErr> {
+        let j = IfaceName::from_slice(iface_name).map_err(|e| MethodErr::invalid_arg(&e))?;
+        self.ifaces.get(&j).ok_or_else(|| MethodErr::no_interface(&j))
+    }
+
+    fn prop_get(&self, m: &MethodInfo<M, D>) -> MethodResult {
+        let (iname, prop_name): (&str, &str) = m.msg.read2()?;
+        let iface = self.get_iface(iname)?;
+        let prop: &Property<M, D> = iface.properties.get(&String::from(prop_name))
+            .ok_or_else(|| MethodErr::no_property(&prop_name))?;
+        prop.can_get()?;
+        let mut mret = m.msg.method_return();
+        {
+            let mut iter = arg::IterAppend::new(&mut mret);
+            let pinfo = m.to_prop_info(iface, prop);
+            prop.get_as_variant(&mut iter, &pinfo)?;
+        }
+        Ok(vec!(mret))
+    }
+
+    fn prop_get_all(&self, m: &MethodInfo<M, D>) -> MethodResult {
+        let iface = self.get_iface(m.msg.read1()?)?;
+        let mut mret = m.msg.method_return();
+        prop_append_dict(&mut arg::IterAppend::new(&mut mret),
+            iface.properties.values().map(|v| &**v), m)?;
+        Ok(vec!(mret))
+    }
+
+
+    fn prop_set(&self, m: &MethodInfo<M, D>) -> MethodResult {
+        let (iname, prop_name): (&str, &str) = m.msg.read2()?;
+        let iface = self.get_iface(iname)?;
+        let prop: &Property<M, D> = iface.properties.get(&String::from(prop_name))
+            .ok_or_else(|| MethodErr::no_property(&prop_name))?;
+
+        let mut iter = arg::Iter::new(m.msg);
+        iter.next(); iter.next();
+        let mut iter2 = iter;
+        prop.can_set(Some(iter))?;
+
+        let pinfo = m.to_prop_info(iface, prop);
+        let mut r: Vec<Message> = prop.set_as_variant(&mut iter2, &pinfo)?.into_iter().collect();
+        r.push(m.msg.method_return());
+        Ok(r)
+
+    }
+
+    fn get_managed_objects(&self, m: &MethodInfo<M, D>) -> MethodResult {
+        use dbus::arg::{Dict, Variant};
+        let paths = m.tree.children(&self, false);
+        let mut result = Ok(());
+        let mut r = m.msg.method_return();
+        {
+            let mut i = arg::IterAppend::new(&mut r);
+            i.append_dict(&Signature::make::<Path>(), &Signature::make::<Dict<&str,Dict<&str,Variant<()>,()>,()>>(), |ii| {
+                for p in paths {
+                    ii.append_dict_entry(|pi| {
+                        pi.append(&*p.name);
+                        pi.append_dict(&Signature::make::<&str>(), &Signature::make::<Dict<&str,Variant<()>,()>>(), |pii| {
+                            for ifaces in p.ifaces.values() {
+                                let m2 = MethodInfo { msg: m.msg, path: p, iface: ifaces, tree: m.tree, method: m.method };
+                                pii.append_dict_entry(|ppii| {
+                                    ppii.append(&**ifaces.name);
+                                    result = prop_append_dict(ppii, ifaces.properties.values().map(|v| &**v), &m2);
+                                });
+                                if result.is_err() { break; }
+                            }
+                        });
+                    });
+                    if result.is_err() { break; }
+                }
+            });
+        }
+        result?;
+        Ok(vec!(r))
+    }
+
+    fn handle(&self, m: &Message, t: &Tree<M, D>) -> MethodResult {
+        let iname = m.interface().or_else(|| { self.default_iface.clone() });
+        let i = iname.and_then(|i| self.ifaces.get(&i)).ok_or_else(|| MethodErr::no_interface(&""))?;
+        let me = m.member().and_then(|me| i.methods.get(&me)).ok_or_else(|| MethodErr::no_method(&""))?;
+        let minfo = MethodInfo { msg: m, tree: t, path: self, iface: i, method: me };
+        me.call(&minfo)
+    }
+
+}
+
+impl<M: MethodType<D>, D: DataType> ObjectPath<M, D>
+where <D as DataType>::Interface: Default,
+      <D as DataType>::Method: Default,
+      <D as DataType>::Signal: Default
+{
+    /// Adds introspection support for this object path.
+    pub fn introspectable(self) -> Self {
+        let z = self.ifacecache.get_factory("org.freedesktop.DBus.Introspectable", || {
+            let f = Factory::from(self.ifacecache.clone());
+            methodtype::org_freedesktop_dbus_introspectable_server(&f, Default::default())
+        });
+        self.add(z)
+    }
+
+    /// Builder function that adds a interface to the object path.
+    pub fn add<I: Into<Arc<Interface<M, D>>>>(mut self, s: I) -> Self {
+        let m = s.into();
+        if !m.properties.is_empty() { self.add_property_handler(); }
+        self.ifaces.insert(m.name.clone(), m);
+        self
+    }
+
+    /// Builder function that sets what interface should be dispatched on an incoming
+    /// method call without interface.
+    pub fn default_interface(mut self, i: IfaceName<'static>) -> Self {
+        self.default_iface = Some(i);
+        self
+    }
+
+    /// Adds ObjectManager support for this object path.
+    ///
+    /// It is not possible to add/remove interfaces while the object path belongs to a tree,
+    /// hence no InterfacesAdded / InterfacesRemoved signals are sent.
+    pub fn object_manager(mut self) -> Self {
+        use dbus::arg::{Variant, Dict};
+        let ifname = IfaceName::from("org.freedesktop.DBus.ObjectManager");
+        if self.ifaces.contains_key(&ifname) { return self };
+        let z = self.ifacecache.get(ifname, |i| {
+            i.add_m(super::leaves::new_method("GetManagedObjects".into(), Default::default(),
+                M::make_method(|m| m.path.get_managed_objects(m)))
+                .outarg::<Dict<Path,Dict<&str,Dict<&str,Variant<()>,()>,()>,()>,_>("objpath_interfaces_and_properties"))
+        });
+        self.ifaces.insert(z.name.clone(), z);
+        self
+    }
+
+    fn add_property_handler(&mut self) {
+        use dbus::arg::{Variant, Dict};
+        let ifname = IfaceName::from("org.freedesktop.DBus.Properties");
+        if self.ifaces.contains_key(&ifname) { return };
+        let z = self.ifacecache.get(ifname, |i| {
+            i.add_m(super::leaves::new_method("Get".into(), Default::default(),
+                M::make_method(|m| m.path.prop_get(m)))
+                .inarg::<&str,_>("interface_name")
+                .inarg::<&str,_>("property_name")
+                .outarg::<Variant<()>,_>("value"))
+            .add_m(super::leaves::new_method("GetAll".into(), Default::default(),
+                M::make_method(|m| m.path.prop_get_all(m)))
+                .inarg::<&str,_>("interface_name")
+                .outarg::<Dict<&str, Variant<()>, ()>,_>("props"))
+            .add_m(super::leaves::new_method("Set".into(), Default::default(),
+                M::make_method(|m| m.path.prop_set(m)))
+                .inarg::<&str,_>("interface_name")
+                .inarg::<&str,_>("property_name")
+                .inarg::<Variant<bool>,_>("value"))
+            .add_s(super::leaves::new_signal("PropertiesChanged".into(), Default::default())
+                .sarg::<&str, _>("interface_name")
+                .sarg::<Dict<&str, Variant<()>, ()>, _>("changed_properties")
+                .sarg::<Vec<&str>, _>("invalidated_properties"))
+        });
+        self.ifaces.insert(z.name.clone(), z);
+    }
+}
+
+pub fn new_objectpath<M: MethodType<D>, D: DataType>(n: Path<'static>, d: D::ObjectPath, cache: Arc<IfaceCache<M, D>>)
+    -> ObjectPath<M, D> {
+    ObjectPath { name: Arc::new(n), data: d, ifaces: ArcMap::new(), ifacecache: cache, default_iface: None }
+}
+
+
+/// A collection of object paths.
+#[derive(Debug, Default)]
+pub struct Tree<M: MethodType<D>, D: DataType> {
+    paths: ArcMap<Arc<Path<'static>>, ObjectPath<M, D>>,
+    data: D::Tree,
+}
+
+impl<M: MethodType<D>, D: DataType> Tree<M, D> {
+    /// Builder function that adds an object path to this tree.
+    pub fn add<I: Into<Arc<ObjectPath<M, D>>>>(mut self, s: I) -> Self {
+        self.insert(s);
+        self
+    }
+
+    /// Get a reference to an object path from the tree.
+    pub fn get(&self, p: &Path<'static>) -> Option<&Arc<ObjectPath<M, D>>> {
+        self.paths.get(p)
+    }
+
+    /// Iterates over object paths in this tree.
+    pub fn iter<'a>(&'a self) -> Iter<'a, ObjectPath<M, D>> { IterE::Path(self.paths.values()).into() }
+
+    /// Non-builder function that adds an object path to this tree.
+    pub fn insert<I: Into<Arc<ObjectPath<M, D>>>>(&mut self, s: I) {
+        let m = s.into();
+        self.paths.insert(m.name.clone(), m);
+    }
+
+
+    /// Remove a object path from the Tree. Returns the object path removed, or None if not found.
+    pub fn remove(&mut self, p: &Path<'static>) -> Option<Arc<ObjectPath<M, D>>> {
+        // There is no real reason p needs to have a static lifetime; but
+        // the borrow checker doesn't agree. :-(
+        self.paths.remove(p)
+    }
+
+    /// Registers or unregisters all object paths in the tree to a ffidisp::Connection.
+    pub fn set_registered(&self, c: &Connection, b: bool) -> Result<(), Error> {
+        let mut regd_paths = Vec::new();
+        for p in self.paths.keys() {
+            if b {
+                match c.register_object_path(p) {
+                    Ok(()) => regd_paths.push(p.clone()),
+                    Err(e) => {
+                        while let Some(rp) = regd_paths.pop() {
+                            c.unregister_object_path(&rp);
+                        }
+                        return Err(e)
+                    }
+                }
+            } else {
+                c.unregister_object_path(p);
+            }
+        }
+        Ok(())
+    }
+
+    /// This method takes an `ConnectionItem` iterator (you get it from `Connection::iter()`)
+    /// and handles all matching items. Non-matching items (e g signals) are passed through.
+    pub fn run<'a, I: Iterator<Item=ConnectionItem>>(&'a self, c: &'a Connection, i: I) -> TreeServer<'a, I, M, D> {
+        TreeServer { iter: i, tree: &self, conn: c }
+    }
+
+    /// Handles a message.
+    ///
+    /// Will return None in case the object path was not
+    /// found in this tree, or otherwise a list of messages to be sent back.
+    pub fn handle(&self, m: &Message) -> Option<Vec<Message>> {
+        if m.msg_type() != MessageType::MethodCall { None }
+        else { m.path().and_then(|p| self.paths.get(&p).map(|s| s.handle(m, &self)
+            .unwrap_or_else(|e| vec!(e.to_message(m))))) }
+    }
+
+    /// Tries to handle an incoming message from the provided channel if there is one. If there isn't one,
+    /// it will wait up to timeout
+    pub fn process_channel(&self, channel: &Channel, timeout: Duration) -> Result<bool, Error> {
+        if let Some(msg) = channel.blocking_pop_message(timeout)? {
+            if let Some(replies) = self.handle(&msg) {
+                for r in replies {
+                    let _ = channel.send(r);
+                }
+            } else if let Some(reply) = dbus::channel::default_reply(&msg) {
+                let _ = channel.send(reply);
+            }
+
+            Ok(true)
+        } else {
+            Ok(false)
+        }
+    }
+
+
+    fn children(&self, o: &ObjectPath<M, D>, direct_only: bool) -> Vec<&ObjectPath<M, D>> {
+        let parent: &str = &o.name;
+        let plen = if parent == "/" { 1 } else { parent.len()+1 };
+        let mut r: Vec<&ObjectPath<M, D>> = self.paths.values().filter_map(|v| {
+            let k: &str = &v.name;
+            if !k.starts_with(parent) || k.len() <= plen || &k[plen-1..plen] != "/" {None} else {
+                Some(&**v)
+            }
+        }).collect();
+        if direct_only {
+            r.sort_by_key(|v| &**v.name);
+            // println!("DEBUG before: {:?}", r.iter().map(|v| &**v.name).collect::<Vec<_>>());
+            let mut prev: Option<&ObjectPath<M, D>> = None;
+            r.retain(|v| {
+                let a = prev.map(|prev|
+                     !(v.name.starts_with(&**prev.name) && v.name.as_bytes().get(prev.name.len()) == Some(&b'/'))
+                 ).unwrap_or(true);
+                if a { prev = Some(v); }
+                a
+            });
+        }
+        r
+    }
+
+    /// Get associated data
+    pub fn get_data(&self) -> &D::Tree { &self.data }
+}
+
+impl<M: MethodType<D> + 'static, D: DataType + 'static> Tree<M, D> {
+    /// Connects a SyncConnection with a Tree so that incoming method calls are handled.
+    ///
+    /// The tree needs to be of type MTSync.
+    pub fn start_receive_sync<C>(self, connection: &C)
+    where
+        C: channel::MatchingReceiver<F=Box<dyn FnMut(Message, &C) -> bool + Send + Sync>> + channel::Sender,
+        D::Tree: Send + Sync, D::ObjectPath: Send + Sync, D::Interface: Send + Sync,
+        D::Property: Send + Sync, D::Method: Send + Sync, D::Signal: Send + Sync,
+        M::Method: Send + Sync, M::GetProp: Send + Sync, M::SetProp: Send + Sync,
+    {
+        connection.start_receive(message::MatchRule::new_method_call(), Box::new(move |msg, c| {
+            if let Some(replies) = self.handle(&msg) {
+                for r in replies { let _ = c.send(r); }
+            }
+            true
+        }));
+    }
+
+    /// Connects a Connection with a Tree so that incoming method calls are handled.
+    ///
+    /// The tree needs to be of type MTSync.
+    pub fn start_receive_send<C>(self, connection: &C)
+    where
+        C: channel::MatchingReceiver<F=Box<dyn FnMut(Message, &C) -> bool + Send>> + channel::Sender,
+        D::Tree: Send + Sync, D::ObjectPath: Send + Sync, D::Interface: Send + Sync,
+        D::Property: Send + Sync, D::Method: Send + Sync, D::Signal: Send + Sync,
+        M::Method: Send + Sync, M::GetProp: Send + Sync, M::SetProp: Send + Sync,
+    {
+        connection.start_receive(message::MatchRule::new_method_call(), Box::new(move |msg, c| {
+            if let Some(replies) = self.handle(&msg) {
+                for r in replies { let _ = c.send(r); }
+            }
+            true
+        }));
+    }
+
+
+    /// Connects a LocalConnection with a Tree so that incoming method calls are handled.
+    pub fn start_receive<C>(self, connection: &C)
+    where
+        C: channel::MatchingReceiver<F=Box<dyn FnMut(Message, &C) -> bool>> + channel::Sender
+    {
+        connection.start_receive(message::MatchRule::new_method_call(), Box::new(move |msg, c| {
+            if let Some(replies) = self.handle(&msg) {
+                for r in replies { let _ = c.send(r); }
+            }
+            true
+        }));
+    }
+
+}
+
+pub fn new_tree<M: MethodType<D>, D: DataType>(d: D::Tree) -> Tree<M, D> {
+    Tree { paths: ArcMap::new(), data: d }
+}
+
+impl<M: MethodType<D>, D: DataType> MsgHandler for Tree<M, D> {
+    fn handle_msg(&mut self, msg: &Message) -> Option<MsgHandlerResult> {
+        self.handle(msg).map(|v| MsgHandlerResult { handled: true, done: false, reply: v })
+    }
+    fn handler_type(&self) -> MsgHandlerType { MsgHandlerType::MsgType(MessageType::MethodCall) }
+}
+/*
+impl<M: MethodType<D>, D: DataType> MsgHandler for Arc<Tree<M, D>> {
+    fn handle_msg(&mut self, msg: &Message) -> Option<MsgHandlerResult> {
+        self.handle(msg).map(|v| MsgHandlerResult { handled: true, done: false, reply: v })
+    }
+    fn handler_type(&self) -> MsgHandlerType { MsgHandlerType::MsgType(MessageType::MethodCall) }
+}
+*/
+/// An iterator adapter that handles incoming method calls.
+///
+/// Method calls that match an object path in the tree are handled and consumed by this
+/// iterator. Other messages are passed through.
+pub struct TreeServer<'a, I, M: MethodType<D> + 'a, D: DataType + 'a> {
+    iter: I,
+    conn: &'a Connection,
+    tree: &'a Tree<M, D>,
+}
+
+impl<'a, I: Iterator<Item=ConnectionItem>, M: 'a + MethodType<D>, D: DataType + 'a> Iterator for TreeServer<'a, I, M, D> {
+    type Item = ConnectionItem;
+
+    fn next(&mut self) -> Option<ConnectionItem> {
+        loop {
+            let n = self.iter.next();
+            if let Some(ConnectionItem::MethodCall(ref msg)) = n {
+                if let Some(v) = self.tree.handle(&msg) {
+                    // Probably the wisest is to ignore any send errors here -
+                    // maybe the remote has disconnected during our processing.
+                    for m in v { let _ = self.conn.send(m); };
+                    continue;
+                }
+            }
+            return n;
+        }
+    }
+}
+
+
+#[test]
+fn test_iter() {
+    let f = super::Factory::new_fn::<()>();
+    let t = f.tree(())
+    .add(f.object_path("/echo", ()).introspectable()
+        .add(f.interface("com.example.echo", ())
+            .add_m(f.method("Echo", (), |_| unimplemented!()).in_arg(("request", "s")).out_arg(("reply", "s")))
+            .add_p(f.property::<i32,_>("EchoCount", ()))
+            .add_s(f.signal("Echoed", ()).arg(("data", "s")).deprecated()
+        )
+    )).add(f.object_path("/echo/subpath", ()));
+
+    let paths: Vec<_> = t.iter().collect();
+    assert_eq!(paths.len(), 2);
+}
+
+#[test]
+fn test_set_default_interface() {
+    let iface_name: IfaceName<'_> = "com.example.echo".into();
+    let f = super::Factory::new_fn::<()>();
+    let t = f.object_path("/echo", ()).default_interface(iface_name.clone());
+    assert_eq!(t.default_iface, Some(iface_name));
+}
+
+
+#[test]
+fn test_introspection() {
+    let f = super::Factory::new_fn::<()>();
+    let t = f.object_path("/echo", ()).introspectable()
+        .add(f.interface("com.example.echo", ())
+            .add_m(f.method("Echo", (), |_| unimplemented!()).in_arg(("request", "s")).out_arg(("reply", "s")))
+            .add_p(f.property::<i32,_>("EchoCount", ()))
+            .add_s(f.signal("Echoed", ()).arg(("data", "s")).deprecated())
+    );
+
+    let actual_result = t.introspect(&f.tree(()).add(f.object_path("/echo/subpath2", ())).add(f.object_path("/echo/subpath", ())));
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/echo">
+  <interface name="com.example.echo">
+    <method name="Echo">
+      <arg name="request" type="s" direction="in"/>
+      <arg name="reply" type="s" direction="out"/>
+    </method>
+    <property name="EchoCount" type="i" access="read"/>
+    <signal name="Echoed">
+      <arg name="data" type="s"/>
+      <annotation name="org.freedesktop.DBus.Deprecated" value="true"/>
+    </signal>
+  </interface>
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <interface name="org.freedesktop.DBus.Properties">
+    <method name="Get">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="property_name" type="s" direction="in"/>
+      <arg name="value" type="v" direction="out"/>
+    </method>
+    <method name="GetAll">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="props" type="a{sv}" direction="out"/>
+    </method>
+    <method name="Set">
+      <arg name="interface_name" type="s" direction="in"/>
+      <arg name="property_name" type="s" direction="in"/>
+      <arg name="value" type="v" direction="in"/>
+    </method>
+    <signal name="PropertiesChanged">
+      <arg name="interface_name" type="s"/>
+      <arg name="changed_properties" type="a{sv}"/>
+      <arg name="invalidated_properties" type="as"/>
+    </signal>
+  </interface>
+  <node name="subpath"/>
+  <node name="subpath2"/>
+</node>"##;
+
+    assert_eq!(expected_result, actual_result);
+}
+
+#[test]
+fn test_introspection_dynamic() {
+    let f = super::Factory::new_fn::<()>();
+    let tree = f
+        .tree(())
+        .add(f.object_path("/", ()).introspectable())
+        .add(f.object_path("/foo/bar", ()).introspectable())
+        .add(f.object_path("/foo/bar/item1", ()).introspectable());
+
+    // For / only node /foo/bar is listed.
+    let o = f.object_path("/", ()).introspectable();
+    let actual_result = o.introspect(&tree);
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/">
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <node name="foo/bar"/>
+</node>"##;
+
+    assert_eq!(expected_result, actual_result);
+
+    // For /foo/bar node /foo/bar/item1 is listed.
+    let o = f.object_path("/foo/bar", ()).introspectable();
+    let actual_result = o.introspect(&tree);
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/foo/bar">
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <node name="item1"/>
+</node>"##;
+
+    assert_eq!(expected_result, actual_result);
+
+    // Dynamically add an object /foo/bar/item2.
+    let tree = tree.add(f.object_path("/foo/bar/item2", ()).introspectable());
+
+    // Now, for / still only node /foo/bar is listed.
+    let o = f.object_path("/", ()).introspectable();
+    let actual_result = o.introspect(&tree);
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/">
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <node name="foo/bar"/>
+</node>"##;
+
+    assert_eq!(expected_result, actual_result);
+
+    // And for /foo/bar node /foo/bar/item2 is now listed too.
+    let o = f.object_path("/foo/bar", ()).introspectable();
+    let actual_result = o.introspect(&tree);
+    println!("\n=== Introspection XML start ===\n{}\n=== Introspection XML end ===", actual_result);
+
+    let expected_result = r##"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node name="/foo/bar">
+  <interface name="org.freedesktop.DBus.Introspectable">
+    <method name="Introspect">
+      <arg name="xml_data" type="s" direction="out"/>
+    </method>
+  </interface>
+  <node name="item1"/>
+  <node name="item2"/>
+</node>"##;
+
+    assert_eq!(expected_result, actual_result);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus-tree/src/utils.rs
@@ -0,0 +1,99 @@
+// Small structs that don't have their own unit.
+
+use dbus::strings::{Signature, Member, Path, Interface as IfaceName};
+use std::collections::{BTreeMap, btree_map};
+use std::sync::Arc;
+
+pub type ArcMap<K, V> = BTreeMap<K, Arc<V>>;
+
+#[derive(Clone, Debug)]
+pub enum IterE<'a, V: 'a> {
+    Path(btree_map::Values<'a, Arc<Path<'static>>, Arc<V>>),
+    Iface(btree_map::Values<'a, Arc<IfaceName<'static>>, Arc<V>>),
+    Member(btree_map::Values<'a, Member<'static>, Arc<V>>),
+    String(btree_map::Values<'a, String, Arc<V>>),
+}
+
+#[derive(Clone, Debug)]
+/// Iterator struct, returned from iterator methods on Tree, Objectpath and Interface.
+pub struct Iter<'a, V: 'a>(IterE<'a, V>);
+
+impl<'a, V: 'a> From<IterE<'a, V>> for Iter<'a, V> { fn from(x: IterE<'a, V>) -> Iter<'a, V> { Iter(x) }}
+
+impl<'a, V: 'a> Iterator for Iter<'a, V> {
+    type Item = &'a Arc<V>;
+    fn next(&mut self) -> Option<Self::Item> {
+        match self.0 {
+            IterE::Path(ref mut x) => x.next(),
+            IterE::Iface(ref mut x) => x.next(),
+            IterE::Member(ref mut x) => x.next(),
+            IterE::String(ref mut x) => x.next(),
+        }
+    }
+}
+
+#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
+/// A D-Bus Argument.
+pub struct Argument(Option<String>, Signature<'static>);
+
+impl Argument {
+    /// Create a new Argument.
+    pub fn new(name: Option<String>, sig: Signature<'static>) -> Argument { Argument(name, sig) }
+
+    /// Descriptive name (if any).
+    pub fn name(&self) -> Option<&str> { self.0.as_ref().map(|s| &**s) }
+
+    /// Type signature of argument.
+    pub fn signature(&self) -> &Signature<'static> { &self.1 }
+
+    fn introspect(&self, indent: &str, dir: &str) -> String {
+        let n = self.0.as_ref().map(|n| format!("name=\"{}\" ", n)).unwrap_or_default();
+        format!("{}<arg {}type=\"{}\"{}/>\n", indent, n, self.1, dir)
+    }
+
+}
+
+pub fn introspect_args(args: &[Argument], indent: &str, dir: &str) -> String {
+    args.iter().fold("".to_string(), |aa, az| format!("{}{}", aa, az.introspect(indent, dir)))
+}
+
+// Small helper struct to reduce memory somewhat for objects without annotations
+#[derive(Clone, Debug, Default)]
+pub struct Annotations(Option<BTreeMap<String, String>>);
+
+impl Annotations {
+    pub fn new() -> Annotations { Annotations(None) }
+
+    pub fn insert<N: Into<String>, V: Into<String>>(&mut self, n: N, v: V) {
+       if self.0.is_none() { self.0 = Some(BTreeMap::new()) }
+        self.0.as_mut().unwrap().insert(n.into(), v.into());
+    }
+
+    pub fn introspect(&self, indent: &str) -> String {
+        self.0.as_ref().map(|s| s.iter().fold("".into(), |aa, (ak, av)| {
+            format!("{}{}<annotation name=\"{}\" value=\"{}\"/>\n", aa, indent, ak, av)
+        })).unwrap_or_default()
+    }
+}
+
+// Doesn't work, conflicting impls
+// impl<S: Into<Signature>> From<S> for Argument
+
+impl From<Signature<'static>> for Argument {
+    fn from(t: Signature<'static>) -> Argument { Argument(None, t) }
+}
+
+impl<'a> From<&'a str> for Argument {
+    fn from(t: &'a str) -> Argument { Argument(None, String::from(t).into()) }
+}
+
+impl<N: Into<String>, S: Into<Signature<'static>>> From<(N, S)> for Argument {
+    fn from((n, s): (N, S)) -> Argument { Argument(Some(n.into()), s.into()) }
+}
+
+pub trait Introspect {
+    // At some point we might want to switch to fmt::Write / fmt::Formatter for performance...
+    fn xml_name(&self) -> &'static str;
+    fn xml_params(&self) -> String;
+    fn xml_contents(&self) -> String;
+}
--- a/third_party/rust/dbus/.cargo-checksum.json
+++ b/third_party/rust/dbus/.cargo-checksum.json
@@ -1,1 +1,1 @@
-{"files":{"Cargo.toml":"ff5bac5ffe795109feabd656a03c823b02fcad9186f6e6a957c2fb7201cd1bd8","LICENSE-APACHE":"453745410e3be8cf25d56872ea2aec975a78e6c9f217443d0bf908a5bce7c8ff","LICENSE-MIT":"de3911c2d98c8bd2d701ee721347053d9b55995a11f9a8c955e44d3ca1b376bf","examples/adv_server.rs":"45526c1ebeabad80e5dd5e8ecf071ea7a5e4870c58e47fad194f849fa347ef3a","examples/argument_guide.md":"b9824fc2b20c6478b3d42195f7d2486d11401aa9f72267e81ec3878bd6882e95","examples/client.rs":"56579c1a4fc3386ca41ddb350d9283d270e31cdf117fb815c84b6b0dd6548335","examples/properties.rs":"dac7eef86e17af1bc4b8d37f431686d3cc1f5890214ea880894c7cbd04ba2ad7","examples/properties_msgitem.rs":"b51e2cd87dc38696e8f0f98bac974d802ba00d69e0aff1102460fdfbf4448ffc","examples/rtkit.rs":"20b46aecac84aa90f0daa423dd9e2c118f1195ac777732bc4cedf9a0d85c4861","examples/server.rs":"9c286b26e45990cab5a7300bb5dd20048dd4dde6366d0e1cb6cdc85b7bf76eb6","examples/unity_focused_window.rs":"f1098e4ebce0feda47af862c6f3e755d6d74f78928731a75f15416bd76577fe1","src/arg/array_impl.rs":"bd18d93fe37a8053c0eb6e4e2d29cfc619adec69ba5ee3411cf03f6ad01fa0c0","src/arg/basic_impl.rs":"7c596da14de18220eb2258c80bc6eb0db9a7cd72bc85ba8d60da78cbf0232454","src/arg/mod.rs":"63274e49ed6f6dd632349e336504e0508d191f35403a7eec2ea20fee7e4ed4a2","src/arg/msgarg.rs":"1df0674603ef7d3e6d3fc1674aa7ffe6a048c3631ea76b533757b9daed958a7b","src/arg/variantstruct_impl.rs":"d9ddc73c44f1e57b67a7a73e8204f6915b51365cd47b1caf68573eb802b93a01","src/connection.rs":"8178688223b392ba5c29bb66b7e89ab642a129da7c777e34014ff9fb6a0daae8","src/connection2.rs":"ef0ba9ace17c8465bf25f3b8d97666e4ab1a6db048653cde408f946206592dcf","src/crossroads/crossroads.rs":"a1f17a5359bb38a54c89553f08c41b2268265fcd195f757c8f409c4ea1b43272","src/crossroads/handlers.rs":"21fbc36bb79aeeb02ac05b11f02ababd544b019d3ec258d73894344fc742c58a","src/crossroads/info.rs":"88a1648d367d0b8a4870bf2fc276c576ad60a23976e2f67f6d784f2dc0c3bc28","src/crossroads/mod.rs":"3e7e03ace37f0a18422d4a724b9db166c114216b2e6d1991ca9453380aa42dff","src/crossroads/stdimpl.rs":"1ded85e9efa18e55d3e65a8cc253b0544869093723157a99b8f7bdd7c3d3149f","src/dispatcher.rs":"b98c29a2063d6e9b263854256487dedf644d3fdb9071623f1e30e7132abedc7a","src/lib.rs":"2fad04e6f162e8121a72c0bad95b77ceabf4bc1c4a86c648602a929983272dc4","src/matchrule.rs":"502fc71bfb5c8bec2b3f0b92d95679513e656b0aa89094164223042fac26435b","src/message.rs":"d07db0c6208f5057961e904e5da8aa12352d0a1d1917c07d0ab0d18a981637aa","src/methoddisp.rs":"57d5b0e7eef7b76393dfd80e2e5125b266521f3252edbc402b893f12791b933e","src/objpath.rs":"e9f662d6cc81ea0717553787773261e7fb3221b36fab1799fb281f21de961b72","src/prop.rs":"60541e569ff06f503d889a7b62dd0aa980d39be60cde01f917503a80e0b7b27f","src/signalargs.rs":"7f0a380d51788208d153e2b51a1759d43a9e4bc41b38b3268a31cd9d681b0cce","src/stdintf.rs":"29027f8cffde7354fc432b306a3ade149bc12440f08fe86d1a72074d514d7101","src/strings.rs":"49635568c8e7f5993e67bfc72941f4ef9407671c63d57c37489620386fbed724","src/tree/factory.rs":"77bfdfa9074e653b43e9c51b3e0b2dcfc9bc02948b7f9eb8e2fc0fe1a9009d14","src/tree/leaves.rs":"9c8b07925c07424a3977b8effa154e63d32addcbab1f59331025039592705bc1","src/tree/methodtype.rs":"6e77276ad1ca4040cd4bea320f525e49165e1d21df89281de4d9b1913129e0e2","src/tree/mod.rs":"471ff6e4bbd9c360326ed92867744b78235d769ba4483e0a8c20137153ab1e82","src/tree/objectpath.rs":"727fa86029f3ebd1d5de183e8f105deb1b3a273f1f89d0e02a5b227c6b1ff515","src/tree/utils.rs":"d15e64ed288ffa7477c2c35532d7f61feafb50ef6068606014101622bcd36caa","src/watch.rs":"9f323ea92206c77e184169e4b7f2a01f2014bf761d3aa5228431109283a1a4fe"},"package":"48b5f0f36f1eebe901b0e6bee369a77ed3396334bf3f09abd46454a576f71819"}
\ No newline at end of file
+{"files":{"Cargo.lock":"41e39602eacfad80042b88c266f823f188527155a56ef38806c7bde54d30238d","Cargo.toml":"d5dbcb8661c738fcabec684c05eea244b9b09bb18105e94748cc7794f6d97d55","LICENSE-APACHE":"453745410e3be8cf25d56872ea2aec975a78e6c9f217443d0bf908a5bce7c8ff","LICENSE-MIT":"de3911c2d98c8bd2d701ee721347053d9b55995a11f9a8c955e44d3ca1b376bf","README.md":"558baa49cdba9310372b1dda45e01a06e332d7b3cecd9deedb1072d6689f9b62","changes-in-0.7.md":"c3ba661492c7040456f162def04b4a30916762792c92aaa934b1372541212ab2","examples/argument_guide.md":"f88171a15b8fa5afd6c2c6094d124e51ed82d1fcb34e61c7f73eeb0661796240","examples/client.rs":"9fd16152c32a7b10b918e46e924952bcc5562b81ec1eb1539207342b757d311c","examples/match_signal.rs":"602b8b5da5df2ea08b904644d714231ffbb6913c76f976afdd4990002c30e2f0","examples/monitor.rs":"719a75a803e10b4b10ac4128be3f9329260fdb3a8e7af9df2eb84d8276bb15d3","examples/properties.rs":"0879c05d5844a0282d60531b0419a82b8202a3a19e1f325d89a57153b7f97fc7","examples/properties_msgitem.rs":"1bebb5b3f7ef10ca609dd61a43f16f7501a8f737748abe3e0565b0769f5445d8","examples/rtkit.rs":"eaf43f9303f03bbb3c5a00156e465a6f89d8959f14bec0d72c96ec81376cb8d8","examples/unity_focused_window.rs":"8246d07397fa4ada314bc18a9f257064897e0f1e68148b94b8b65ebe6556f19e","src/arg/array_impl.rs":"903e0e01eefb31da51b02fff84436621b10c4ac5df173f32b4aeb5031b166725","src/arg/basic_impl.rs":"6190b3a7c509cf32159f0b66457254641283a0b323342fb04deb0b63ecc0290d","src/arg/messageitem.rs":"4a3963dfe967d2c4e0c02ba4bbbe6ab1d5b612c7ca8448e8a0d0a1d1b3f9b698","src/arg/mod.rs":"8768a13d9805836c647b674704741d8d73aec01d7550a3c633c1e70bec039acd","src/arg/msgarg.rs":"2f3ab4313bdcbb82b0250ddce41e1d6db47baccefe4b6815dec199919ea56c44","src/arg/variantstruct_impl.rs":"3d6837840436e953941a087b23b837269415d9505869fc5e76213407f3f40ced","src/blocking.rs":"c9f708432e9fb04bd8f231512ecce9b32df772fdd2513134f5f38f0d57223e92","src/blocking/generated_org_freedesktop_dbus.rs":"35a5678a4d9e0eb08c788ff1f0d7c18540132776c51c84d99e1508d4662d2c6e","src/blocking/generated_org_freedesktop_standard_interfaces.rs":"0e7cc6977f5f32b7c96d34eacb30ee3d59411656f29ada43f5db852a30dd4e48","src/channel.rs":"2d1c2efe74472c99baeed969b86c3f9c68f24079e4fc7773813abcfd9c01e4d9","src/channel/ffichannel.rs":"5b932418cd5763fcc30acf1f88bb85f0fb51b6c4c1cf99a3fe67c796f67ed4c1","src/channel/nativechannel.rs":"16b2eae180b28d9bdea711daa740e9193775f670fb12360c840e3c785f43bd6c","src/error.rs":"104bd4f4bb3dda37c5211b281db0a615a386a830c8576aa6575db8549048b54a","src/ffidisp.rs":"56b782358f98ecd44c0bed27020ae8fcf7ac5defab5809fbcb04229c00e99881","src/ffidisp/connection.rs":"e96d8c1931f5981a81cb3a64e411b9449a07c26d803d421c7c42c16de25ca75b","src/ffidisp/stdintf.rs":"3b1bd23cbe1a5c046a4a2117af7678e411f3a8eb5e0c1c8615558b244490db93","src/ffidisp/watch.rs":"931c255f7bd1ab797b209613c5b7e7d6be0268600ed9553db33ca8e4e80f8ab2","src/filters.rs":"cf2a565d8eb38fcccc34d72e442517cccd138042c078032f89606594f2cca364","src/lib.rs":"d2b1c91324426b2c84b212ddc0cb1bf1e2554e8dda8b5154f72b827f04422803","src/message.rs":"98ee2fc261bd5596cf5faadbe13f136bb76d3e749cb75857860be003ba57ad1e","src/message/matchrule.rs":"b0aa95d82fed34518d9ec5d69d22e5f085044e411d1e296d4113113704b2ca49","src/message/parser.rs":"e937660213a99dccc57477e5a4dc6bdcc8e68ffb35a711890272dfb2b28ee7a2","src/message/signalargs.rs":"0493e439e0337d4d7d97f336d8ae7ab08dd87af99b8617e74f08470cec8f6b89","src/methoddisp.rs":"85dbfee533624ccb7f040db7b9107bf142c2eb3408f01a0aef5a42c8b4c57b5d","src/nonblock.rs":"46e7101e3e8fbb5461ca8762b2bdc603c4f2ce13af6ebdd95d67fa767abc3264","src/nonblock/generated_org_freedesktop_dbus.rs":"a6ab2d60e1679fc57b9968fc8e4fa607bfe2fe7cff6282b11252ccac0c3a68d9","src/nonblock/generated_org_freedesktop_standard_interfaces.rs":"2dfad17a2545cd1104839268590e31ebde74940632c4fc988821861a24e56d40","src/prop.rs":"83097787e4afc5de39600ca75bcf1b09990016f415a488acbd04ca4ef4e4942f","src/strings.rs":"2ba17e03e0737fe9c36af2837047754ba2bf41e574fc3fbc426c9e5f9a9bad61"},"package":"6f8bcdd56d2e5c4ed26a529c5a9029f5db8290d433497506f958eae3be148eb6"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/Cargo.lock
@@ -0,0 +1,184 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "dbus"
+version = "0.9.6"
+dependencies = [
+ "futures-channel",
+ "futures-executor",
+ "futures-util",
+ "libc",
+ "libdbus-sys",
+ "tempfile",
+ "winapi",
+]
+
+[[package]]
+name = "fastrand"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf"
+dependencies = [
+ "instant",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-task"
+version = "0.3.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a"
+
+[[package]]
+name = "futures-util"
+version = "0.3.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "instant"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.126"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c185b5b7ad900923ef3a8ff594083d4d9b5aea80bb4f32b8342363138c0d456b"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae"
+
+[[package]]
+name = "redox_syscall"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "remove_dir_all"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32"
+
+[[package]]
+name = "tempfile"
+version = "3.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"
+dependencies = [
+ "cfg-if",
+ "fastrand",
+ "libc",
+ "redox_syscall",
+ "remove_dir_all",
+ "winapi",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
--- a/third_party/rust/dbus/Cargo.toml
+++ b/third_party/rust/dbus/Cargo.toml
@@ -1,38 +1,69 @@
 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
 #
 # When uploading crates to the registry Cargo will automatically
 # "normalize" Cargo.toml files for maximal compatibility
 # with all versions of Cargo and also rewrite `path` dependencies
-# to registry (e.g., crates.io) dependencies
+# to registry (e.g., crates.io) dependencies.
 #
-# If you believe there's an error in this file please file an
-# issue against the rust-lang/cargo repository. If you're
-# editing this file be aware that the upstream Cargo.toml
-# will likely look very different (and much more reasonable)
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
 
 [package]
+edition = "2018"
 name = "dbus"
-version = "0.6.5"
+version = "0.9.6"
 authors = ["David Henningsson <diwic@ubuntu.com>"]
 description = "Bindings to D-Bus, which is a bus commonly used on Linux for inter-process communication."
 documentation = "http://docs.rs/dbus"
-readme = "../README.md"
-keywords = ["D-Bus", "DBus", "IPC"]
-categories = ["os::unix-apis", "api-bindings"]
+readme = "README.md"
+keywords = [
+    "D-Bus",
+    "DBus",
+    "IPC",
+]
+categories = [
+    "os::unix-apis",
+    "api-bindings",
+]
 license = "Apache-2.0/MIT"
 repository = "https://github.com/diwic/dbus-rs"
+
+[package.metadata.docs.rs]
+features = ["futures"]
+
+[dependencies.futures-channel]
+version = "0.3"
+optional = true
+
+[dependencies.futures-executor]
+version = "0.3"
+optional = true
+
+[dependencies.futures-util]
+version = "0.3"
+optional = true
+default-features = false
+
 [dependencies.libc]
-version = "0.2.7"
+version = "0.2.66"
 
 [dependencies.libdbus-sys]
-version = "0.2"
-[dev-dependencies.tempdir]
-version = "0.3"
+version = "0.2.2"
+
+[dev-dependencies.tempfile]
+version = "3"
 
 [features]
+futures = [
+    "futures-util",
+    "futures-channel",
+]
 no-string-validation = []
-[badges.is-it-maintained-issue-resolution]
-repository = "diwic/dbus-rs"
 
-[badges.is-it-maintained-open-issues]
-repository = "diwic/dbus-rs"
+[target."cfg(windows)".dependencies.winapi]
+version = "0.3.0"
+features = ["winsock2"]
+
+[badges.maintenance]
+status = "actively-developed"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/README.md
@@ -0,0 +1,162 @@
+D-Bus bindings for Rust
+=======================
+
+[![crates.io](https://img.shields.io/crates/v/dbus.svg)](https://crates.io/crates/dbus)
+[![API documentation](https://docs.rs/dbus/badge.svg)](https://docs.rs/dbus)
+[![license](https://img.shields.io/crates/l/dbus.svg)](https://crates.io/crates/dbus)
+[![Github CI](https://github.com/diwic/dbus-rs/actions/workflows/dbus-rs-github-ci.yml/badge.svg)](https://github.com/diwic/dbus-rs/actions/workflows/dbus-rs-github-ci.yml/badge.svg)
+
+ * Use `blocking::Connection` to connect to the session or system bus. (Or `SyncConnection` / `LocalConnection`)
+ * Use `Message` to send and receive messages. Get and append arguments of all types, see the [argument guide](dbus/examples/argument_guide.md) for details.
+ * Build method dispatching servers using the `dbus-crossroads` or `dbus-tree` crates.
+   Standard D-Bus interfaces (introspection, properties, object manager) are supported.
+
+Breaking changes
+----------------
+
+The main dbus crate is fairly mature and the features you need should be all there. Breaking changes can still happen, but not often.
+
+ * In 0.9, the `dbus::tree` module moved to the `dbus-tree` crate (but consider migrating to `dbus-crossroads` instead).
+ * If you're currently using 0.6.x of dbus and want to upgrade to later versions, you can read [changes in dbus-rs 0.7](dbus/changes-in-0.7.md).
+
+
+Additional crates
+-----------------
+
+ * [dbus-crossroads](http://crates.io/crates/dbus-crossroads/) for easy building of method
+    dispatching servers. [![API documentation](https://docs.rs/dbus-crossroads/badge.svg)](https://docs.rs/dbus-crossroads)
+ * [dbus-tokio](http://crates.io/crates/dbus-tokio/) integrates D-Bus with [Tokio](http://tokio.rs). [![API documentation](https://docs.rs/dbus-tokio/badge.svg)](https://docs.rs/dbus-tokio)
+ * [dbus-codegen](http://crates.io/crates/dbus-codegen/) installs a binary tool which generates Rust code from D-Bus XML introspection data. The [readme](https://github.com/diwic/dbus-rs/tree/master/dbus-codegen) contains an introduction to how to use it.
+ * [libdbus-sys](http://crates.io/crates/libdbus-sys/) contains the raw FFI bindings to libdbus.
+ * [dbus-tree](http://crates.io/crates/dbus-tree/) facitilates easy building of method
+    dispatching servers (legacy design). [![API documentation](https://docs.rs/dbus-tree/badge.svg)](https://docs.rs/dbus-tree)
+
+Invitation
+----------
+
+You are hereby invited to participate in the development of these crates:
+
+ * If you have discovered what you believe is a bug, [file an issue](https://github.com/diwic/dbus-rs/issues).
+ * If you have questions or comments that the documentation cannot answer in an easy way, [start a discussion](https://github.com/diwic/dbus-rs/discussions).
+ * If you have smaller improvements to code, documentation, examples etc, go ahead and [submit a pull request](https://github.com/diwic/dbus-rs/pulls).
+   Larger pieces of work are better off discussed first.
+
+The code is Apache 2.0 / MIT dual licensed. Any code submitted in Pull Requests, discussions or issues is assumed to have this license,
+unless explicitly stated otherwise.
+
+
+Examples
+========
+
+Client
+------
+
+This example opens a connection to the session bus and asks for a list of all names currently present.
+
+```rust
+use dbus::blocking::Connection;
+use std::time::Duration;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    // First open up a connection to the session bus.
+    let conn = Connection::new_session()?;
+
+    // Second, create a wrapper struct around the connection that makes it easy
+    // to send method calls to a specific destination and path.
+    let proxy = conn.with_proxy("org.freedesktop.DBus", "/", Duration::from_millis(5000));
+
+    // Now make the method call. The ListNames method call takes zero input parameters and
+    // one output parameter which is an array of strings.
+    // Therefore the input is a zero tuple "()", and the output is a single tuple "(names,)".
+    let (names,): (Vec<String>,) = proxy.method_call("org.freedesktop.DBus", "ListNames", ())?;
+
+    // Let's print all the names to stdout.
+    for name in names { println!("{}", name); }
+
+    Ok(())
+}
+```
+
+Examples of client code in the examples directory:
+
+ * [client.rs](https://github.com/diwic/dbus-rs/tree/master/dbus/examples/client.rs) (same as the above)
+ * [properties.rs](https://github.com/diwic/dbus-rs/tree/master/dbus/examples/properties.rs)
+ * [match_signal.rs](https://github.com/diwic/dbus-rs/tree/master/dbus/examples/match_signal.rs)
+ * [rtkit.rs](https://github.com/diwic/dbus-rs/tree/master/dbus/examples/rtkit.rs)
+ * [monitor.rs](https://github.com/diwic/dbus-rs/tree/master/dbus/examples/monitor.rs)
+
+Server
+------
+
+This example grabs the `com.example.dbustest` bus name, adds the `/hello` path
+which implements the `com.example.dbustest` interface, and specifies that this
+interface has a `Hello` method.
+It then listens for incoming D-Bus method calls on this path and handles them accordingly.
+
+**dbus-crossroads**:
+
+```rust
+let c = Connection::new_session()?;
+c.request_name("com.example.dbustest", false, true, false)?;
+let mut cr = Crossroads::new();
+let token = cr.register("com.example.dbustest", |b| {
+    b.method("Hello", ("name",), ("reply",), |_, _, (name,): (String,)| {
+        Ok(format!("Hello {}!", name))
+    });
+});
+cr.insert("/hello", &[token], ());
+cr.serve(&c)?;
+```
+
+Examples of server code using `dbus-crossroads` in the examples directory:
+
+ * [server_cr.rs](https://github.com/diwic/dbus-rs/blob/master/dbus-crossroads/examples/server_cr.rs)
+ * [tokio_server_cr.rs](https://github.com/diwic/dbus-rs/blob/master/dbus-tokio/examples/tokio_server_cr.rs)
+ * [tokio_adv_server_cr.rs](https://github.com/diwic/dbus-rs/blob/master/dbus-tokio/examples/tokio_adv_server_cr.rs)
+
+**dbus-tree**:
+
+```rust
+let c = Connection::new_session()?;
+c.request_name("com.example.dbustest", false, true, false)?;
+let f = Factory::new_fn::<()>();
+let tree = f.tree(())
+    .add(f.object_path("/hello", ()).introspectable()
+        .add(f.interface("com.example.dbustest", ())
+            .add_m(f.method("Hello", (), |m| {
+                let n: &str = m.msg.read1()?;
+                let s = format!("Hello {}!", n);
+                Ok(vec!(m.msg.method_return().append1(s)))
+            }).inarg::<&str,_>("name")
+              .outarg::<&str,_>("reply")
+        )
+    ).add(f.object_path("/", ()).introspectable());
+tree.start_receive(&c);
+loop { c.process(Duration::from_millis(1000))?; }
+```
+
+Examples of server code using `dbus-tree` in the examples directory:
+
+ * [server.rs](https://github.com/diwic/dbus-rs/tree/master/dbus-tree/examples/server.rs)
+ * [adv_server.rs](https://github.com/diwic/dbus-rs/tree/master/dbus-tree/examples/adv_server.rs)
+
+Features
+========
+
+The `futures` feature makes `dbus` depend on the `futures` crate. This enables the `nonblock` module (used by the `dbus-tokio` crate).
+
+The `no-string-validation` feature skips an extra check that a specific string (e g a `Path`, `ErrorName` etc) conforms to the D-Bus specification, which might also make things a tiny bit faster. But - if you do so, and then actually send invalid strings to the D-Bus library, you might get a panic instead of a proper error.
+
+Requirements
+============
+
+[Libdbus](https://dbus.freedesktop.org/releases/dbus/) 1.6 or higher, and latest stable release of [Rust](https://www.rust-lang.org/). If you run Ubuntu (any maintained version should be okay), this means having the `libdbus-1-dev` and `pkg-config` packages installed while building, and the `libdbus-1-3` package installed while running.
+
+Cross compiling libdbus might be tricky because it binds to a C library, there are some notes [here](https://github.com/diwic/dbus-rs/blob/master/libdbus-sys/cross_compile.md).
+
+Alternatives
+============
+
+[zbus](https://gitlab.freedesktop.org/dbus/zbus) and [rustbus](https://github.com/KillingSpark/rustbus) (stalled?) are D-Bus crates
+written completely in Rust (i e, no bindings to C libraries).
+Some more alternatives are listed [here](https://github.com/KillingSpark/rust-dbus-comparisons), but I'm not sure how usable they are.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/changes-in-0.7.md
@@ -0,0 +1,45 @@
+D-Bus crate 0.7 overview
+========================
+
+In 0.7 the `Connection` struct has been rewritten (but the old one is still there). The new struct(s) have the following advantages:
+
+ * It makes it possible to make a connection `Send`/`Sync`, see `blocking::SyncConnection`.
+ * The call to `dbus_connection_dispatch` has been removed and what it did has been rewritten in Rust. This means better performance and panic safety.
+ * The two-layer design (with `Channel` as a low-level connection) makes it easier to write a custom `Connection`, should that be necessary.
+ * Preparation for a first class async/non-blocking `Connection`. A `nonblock` module is in the works.
+ * Some preparations for interfacing the `dbus` crate with a native backend instead of relying on `libdbus`, should someone want to write such a backend. There is a lot more to do before that becomes a reality though.
+
+Things that have moved
+======================
+
+If you want the quickest upgrade experience, then you can just update your imports:
+
+ * The old `Connection` is now at `ffidisp::Connection`, likewise for `ConnPath`, `BusType` and many others. Have a look at the `ffidisp` module to see if your struct has moved there.
+ * The `stdintf` module is at `ffidisp::stdintf`.
+ * The old `MessageItem`, should you still need it, is now under `arg::messageitem`. But do use the generic functions instead of `MessageItem` whenever possible. `MessageItem::DictEntry` has changed to `MessageItem::Dict` (which contains the entire dict, not just one entry) to make it less error prone.
+
+Migrating / upgrading
+=====================
+
+On a long term, consider migrating / upgrading to `blocking::Connection` or `blocking::SyncConnection`. You would need to make the following adjustments:
+
+ * Create and connect your connection easily with just `Connection::new_session()` or `Connection::new_system()`.
+ * Instead of `ConnPath`, use a `Proxy`. It works approximately the same way.
+ * `blocking::stdintf` can be helpful to make standard method calls, such as getting and setting properties on a remote peer.
+ * `Connection::register_name` has been renamed to `request_name`. (This was just a misnaming.)
+ * Instead of `incoming()` to process incoming messages, use `process()` (which takes a std `Duration`). This will not hand out any messages though, instead register callbacks using (in order from most convenient to most generic): `Proxy::match_signal`, `Proxy::match_start` or `channel::MatchingReceiver::start_receive`.
+ * For `tree`s, you must now make sure the root path (`/`) is always part of your tree. 
+ * For `tree`s, call `Tree::start_receive()` to attach the tree and the connection, then call `Connection::process()` to process incoming messages.
+
+Have a look at the `client`, `server` and `match_signal` examples to get started.
+
+ReadAll / AppendAll
+===================
+
+The `ReadAll` and `AppendAll` traits were present in later 0.6.x versions as well, but are worthy a mention because they can make code more ergonomic in many cases. They are implemented for tuples: the empty tuple `()`, the single-tuple `(TYPE,)`, and usual tuples `(TYPE1, TYPE2)` up to 11. So if you have a method call that takes `STRING arg1, INT32 arg2` and returns a `BOOLEAN`, you can call it like this:
+
+```
+let (r,): (bool,) = myProxy.method_call(interface, name, (arg1, arg2))?;
+```
+
+...where `arg1` is a `&str` and `arg2` is a `i32`. 
--- a/third_party/rust/dbus/examples/argument_guide.md
+++ b/third_party/rust/dbus/examples/argument_guide.md
@@ -1,14 +1,15 @@
 Preamble
 --------
 
 The different ways you can append and get message arguments can be a bit bewildering. I've iterated a few times on the design and didn't want to lose backwards compatibility.
 
 This guide is to help you on your way. In addition, many of the examples in the examples directory append and read arguments.
+There is also a reference at the end of this document.
 
 Code generation
 ---------------
 
 First - if you can get D-Bus introspection data, you can use the the `dbus-codegen` tool to generate some boilerplate code for you. E g, if you want to talk to NetworkManager:
 
 ```rust
 cargo install dbus-codegen
@@ -19,51 +20,51 @@ You would then use this code like:
 
 ```rust
 // main.rs
 mod networkmanager;
 
 /* ... */
 
 // Start a connection to the system bus.
-let c = Connection::get_private(BusType::System)?;
+let c = Connection::new_system()?;
 
 // Make a "ConnPath" struct that just contains a Connection, a destination and a path.
-let p = c.with_path("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", 5000);
+let p = c.with_proxy("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", Duration::new(5, 0));
 
 // Bring our generated code into scope.
 use networkmanager::OrgFreedesktopNetworkManager;
 
 // Now we can call methods on our connpath from the "org.freedesktop.NetworkManager" interface.
-let devices = c.get_all_devices()?;
+let devices = p.get_all_devices()?;
 ```
 
 There is also pre-generated code for standard D-Bus interfaces in the `stdintf` module. A similar example:
 
 ```rust
-let c = Connection::get_private(BusType::Session)?;
+let c = Connection::new_session()?;
 
 // Make a "ConnPath" struct that just contains a Connection, a destination and a path.
-let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000);
+let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", Duration::new(5, 0));
 
 // The ConnPath struct implements many traits, e g `org.freedesktop.DBus.Properties`. Bring the trait into scope.
 use stdintf::org_freedesktop_dbus::Properties;
 
 // Now we can call org.freedesktop.DBus.Properties.Get just like an ordinary method and get the result back.
 let metadata = p.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
 ```
 
 For more details, see `dbus-codegen-rust --help` and the `README.md` in the dbus-codegen directory.
 
 Now, if you want to make a service yourself, the generated code is more complex. And for some use cases, codegen isn't really an option, so let's move on:
 
 Append / get basic types
 ------------------------
 
-If you just want to get/append simple types, just use `append1` / `append2` / `append3`, and 
+If you just want to get/append simple types, just use `append1` / `append2` / `append3`, and
 `read1` / `read2` / `read3`. The imaginary method below takes one byte parameter and one string parameter, and returns one string parameter and one int parameter.
 
 ```rust
 let m = Message::new_method_call(dest, path, intf, member)?.append2(5u8, "Foo");
 let r = c.send_with_reply_and_block(m, 2000)?;
 let (data1, data2): (&str, i32) = c.read2()?;
 ```
 
@@ -101,65 +102,136 @@ let v = Variant("This is a variant conta
 let m = Message::new_method_call(dest, path, intf, member)?.append1(v);
 let r = c.send_with_reply_and_block(m, 2000)?;
 let z: Variant<i32> = r.read1()?;
 println!("Method returned {}", z.0);
 ```
 
 The `Variant` struct is just a wrapper with a public interior, so you can easily both read from it and write to it with the `.0` accessor.
 
-Sometimes you don't know the type beforehand. We can solve this in two ways (choose whichever is more appropriate for your use case), either through the trait object `Box<RefArg>` or through `Iter` / `IterAppend` (see later sections).
+Sometimes you don't know the type beforehand. We can solve this in two ways (choose whichever is more appropriate for your use case), either through the trait object `Box<dyn RefArg>` or through `Iter` / `IterAppend` (see later sections).
 
 Through trait objects:
 
 ```rust
-let x = Box::new(5000i32) as Box<RefArg>;
+let x = Box::new(5000i32) as Box<dyn RefArg>;
 let m = Message::new_method_call(dest, path, intf, member)?.append1(Variant(x));
 let r = c.send_with_reply_and_block(m, 2000)?;
-let z: Variant<Box<RefArg>> = r.read1()?;
+let z: Variant<Box<dyn RefArg>> = r.read1()?;
 ```
 
-Ok, so we retrieved our `Box<RefArg>`. We now need to use the `RefArg` methods to probe it, to see what's inside. Easiest is to use `as_i64` or `as_str` if you want to test for integer or string types. Use `as_iter` if the variant contains a complex type you need to iterate over.
-For floating point values, use `arg::cast` (this requires that the RefArg is `static` though, due to Rust type system limitations).
-Match over `arg_type` if you need to know the exact type. 
+Ok, so we retrieved our `Box<dyn RefArg>`. We now need to use the `RefArg` methods to probe it, to see what's inside.
+You can use `as_i64`, `as_u64`, `as_f64` or `as_str` if you want to test for number or string types.
+Second easiest is to use `arg::cast` to downcast to the specific type inside (see reference section below
+for what type you need to cast to).
 
+This works for most types, but in some advanced cases, this is not possible, either because the `RefArg` is not `'static`
+(work around this with the `box_clone` method if necessary), or because the internal representation is not specified.
+In this case, try to use `as_static_inner` or `as_iter` to iterate through the interior of the complex type.
 
 ```rust
-let z: Variant<Box<RefArg + 'static>> = r.read1()?;
+let z: Variant<Box<dyn RefArg + 'static>> = r.read1()?;
 let value = &z.0;
 
 if let Some(s) = value.as_str() { println!("It's a string: {}", s); }
 else if let Some(i) = value.as_i64() { println!("It's an integer: {}", i); }
 else if let Some(f) = arg::cast::<f64>(value) { println!("It's a float: {}", f); }
 else { println!("Don't know how to handle a {:?}", value.arg_type()) }
 ```
 
-Dicts and variants are sometimes combined, e g, you might need to read a D-Bus dictionary of String to Variants. You can then read these as `HashMap<String, Variant<Box<RefArg>>>`.
+Dicts and variants are sometimes combined, e g, you might need to read a D-Bus dictionary of String to Variants.
+You can read these as `PropMap` (which is a type alias for `HashMap<String, Variant<Box<dyn RefArg>>>`) and use
+`prop_cast` to retrieve a value.
 
 Structs
 -------
 
 D-Bus structs are implemented as Rust tuples. You can append and get tuples like you do with other types of arguments.
+You can also use `VecDeque<Box<dyn RefArg>>` for when the types of the struct cannot be statically typed.
 
-TODO: Example
+For an example of the latter, the [Desktop Notifications Specification](https://specifications.freedesktop.org/notification-spec/notification-spec-latest.html#idm46059356295632) specifies that the `notify()` method sends a dictionary of optional [hints](https://specifications.freedesktop.org/notification-spec/notification-spec-latest.html#hints), one of which is `"image-data"` hint, which contains a struct.  Here's how you might retrieve that `"image-data"` hint and cast it into a rust struct.
+
+Implementing the `notify()` method in Rust -- trait generated by [`dbus-codegen-rust`](https://github.com/diwic/dbus-rs/tree/master/dbus-codegen):
+```rust
+// impl OrgFreedesktopNotifications {
+fn notify(
+    &mut self,
+    app_name: String,
+    replaces_id: u32,
+    app_icon: String,
+    summary: String,
+    body: String,
+    actions: Vec<String>,
+    hints: arg::PropMap,
+    expire_timeout: i32
+) -> Result<u32, dbus::MethodErr> {
+    use dbus::arg::prop_cast;
+
+    // Retrieving a property from a PropMap of type byte (`u8`).
+    let urgency: Option<&u8> = prop_cast(&hints, "urgency");
+
+    // Retrieving a property from a PropMap of type struct (`Image`, in this case).
+    struct Image {
+        width: i32,
+        height: i32,
+        rowstride: i32,
+        one_point_two_bit_alpha: bool,
+        bits_per_sample: i32,
+        channels: i32,
+        data: Vec<u8>,
+    }
+
+    // Structs are represented internally as `VecDeque<Box<RefArg>>`.
+    let image_data: Option<&VecDeque<Box<dyn RefArg>>> = prop_cast(&hints, "image-data");
+    let image = if let Some(img) = image_data {
+        use dbus::arg::cast;
+        // NOTE: It's possible that someone sent the "image-data" hint but didn't fill it correctly, which will
+        // panic with this code!  You should make sure that the length of the `Vec` is correct and handle the
+        // `cast` `Option` instead of just unwrapping.
+        let width = *cast::<i32>(&img[0]).unwrap();
+        let height = *cast::<i32>(&img[1]).unwrap();
+        let rowstride = *cast::<i32>(&img[2]).unwrap();
+        let one_point_two_bit_alpha = *cast::<bool>(&img[3]).unwrap();
+        let bits_per_sample = *cast::<i32>(&img[4]).unwrap();
+        let channels = *cast::<i32>(&img[5]).unwrap();
+        let data = cast::<Vec<u8>>(&img[6]).unwrap().clone();
+        Some(Image { width, height, rowstride, one_point_two_bit_alpha, bits_per_sample, channels, data })
+    } else {
+        None
+    }
+
+    // Do something with image / urgency.
+
+    Ok(0)
+}
+```
+
+TODO: tuple example
 
 Declare method arguments
 ------------------------
 
-When you make a `Tree`, you want to declare what input and output arguments your method expects - so that correct D-Bus introspection data can be generated. You'll use the same types as you learned earlier in this guide:
+For `dbus-crossroads`, the method argument types are automatically deduced from your method closure, but the names have to repeated. Method arguments - both in and out - are always tuples, so if you have a single argument, it needs to be wrapped into a "one element tuple" (so a variable or type `x` becomes `(x,)`). Like this:
+
+```rust
+b.method("Hello", ("request",), ("reply",), |_, _, (request,): (HashMap<i32, Vec<(i32, bool, String)>>,)| {
+  // Returns a Result<String>
+});
+```
+
+For `dbus-tree`, you want to declare what input and output arguments your method expects - so that correct D-Bus introspection data can be generated. You'll use the same types as you learned earlier in this guide:
 
 ```rust
 factory.method( /* ... */ )
 .inarg::<HashMap<i32, Vec<(i32, bool, String)>>,_>("request")
 .outarg::<&str,_>("reply")
 ```
 
 The types are just for generating a correct signature, they are never instantiated. Many different types can generate the same signature - e g, `Array<u8, _>`, `Vec<u8>` and `&[u8]` will all generate the same signature. `Variant` will generate the same type signature regardless of what's inside, so just write `Variant<()>` for simplicity.
 
-
 Iter / IterAppend
 -----------------
 
 Iter and IterAppend are more low-level, direct methods to get and append arguments. They can, e g, come handy if you have more than five arguments to read.
 
 E g, for appending a variant with IterAppend you can use `IterAppend::new(&msg).append_variant(|i| i.append(5000i32))` to append what you need to your variant inside the closure.
 To read a variant you can use `let i = msg.read1::<Variant<Iter>>::()?` and then examine the methods on `i.0` to probe the variant.
 
@@ -176,18 +248,50 @@ let z: Dict<i32, &str, _> = r.read1()?;
 for (key, value) in z { /* do something */ }
 ```
 
 An edge case where this is necessary is having floating point keys in a dictionary - this is supported in D-Bus but not in Rust's `HashMap`. I have never seen this in practice, though.
 
 Unusual types
 -------------
 
-The types `Path`, `Signature` and `OwnedFd` are not often used, but they can be appended and read as other argument types. `Path` and `Signature` will return strings with a borrowed lifetime - use `.into_static()` if you want to untie that lifetime.
+The types `Path` and `Signature` are not often used, but they can be appended and read as other argument types. `Path` and `Signature` will return strings with a borrowed lifetime - use `.into_static()` if you want to untie that lifetime.
 
-For `OwnedFd`, which a wrapper around a file descriptor, remember that the file descriptor will be closed when it goes out of scope.
+You can also append and get a `std::fs::File`, this will send or receive a file descriptor. `OwnedFd` is an earlier design which was used for the same thing.
 
 MessageItem
 -----------
 
 MessageItem was the first design - an enum representing a D-Bus argument. It still works, but I doubt you'll ever need to use it. Newer methods provide better type safety, speed, and ergonomics.
 
+Reference
+=========
 
+This is a translation table between D-Bus types and Rust types. Both the RefArg type
+and the other types can be used in most cases, e g `append`, `get` and/or `read`, as
+well as function arguments for `dbus-crossroads`. In addition, `&T`, `Box<T>`, `Rc<T>` and
+`Arc<T>` can (in general) be used instead of `T`, where `T` is a Rust type.
+
+If you want to to use `cast` or `prop_cast` on a `&RefArg` however, you need to use
+the RefArg type.
+
+| D-Bus type | Signature | RefArg type | Other types |
+| ---------- | --------- | ----------- | ----------- |
+| BYTE | `y` | `u8` | |
+| BOOLEAN | `b` | `bool` | |
+| INT16	| `n` | `i16` | |
+| UINT16 | `q` | `u16` | |
+| INT32 | `i` | `i32` | |
+| UINT32 | `u` | `u32` | |
+| INT64 | `x` | `i64` | |
+| UINT64 | `t` | `u64` | |
+| DOUBLE | `d` | `f64` | |
+| STRING | `s` | `String` | `&str`, `&CStr` |
+| UNIX_FD | `h` | `File` | `OwnedFd` |
+| OBJECT_PATH | `o` | `Path<'static>` | `Path<'a>` |
+| SIGNATURE	| `g` | `Signature<'static>` | `Signature<'a>` |
+| VARIANT | `v` | `Variant<Box<RefArg>>` | `Variant<T>`, `Variant<Iter>` |
+| STRUCT | `(`...`)` | `VecDeque<Box<RefArg>>` | tuples: `(T,)`, `(T1,T2)` etc |
+| DICT<STRING, VARIANT> | `a{sv}` | `PropMap` | |
+| DICT<_, _> | `a{`...`}` | N/A | `HashMap<K, V>`, `Dict<K, V, _>`, `BTreeMap<K, V>` |
+| ARRAY<ARRAY<_>> | `aa`... | N/A | `Vec<Vec<T>>`, `&[&[T]]`, `Array<Array<T>>` |
+| ARRAY<STRUCT<_>> | `a(`...`)` | N/A | `Vec<VecDeque<Box<RefArg>>>`, `Vec<`tuple`>` |
+| ARRAY<_> (all else) | `a`... | `Vec<T>` | `&[T]` `Array<T, _>` |
--- a/third_party/rust/dbus/examples/client.rs
+++ b/third_party/rust/dbus/examples/client.rs
@@ -1,14 +1,22 @@
-extern crate dbus;
+use dbus::blocking::Connection;
+use std::time::Duration;
 
-use dbus::{Connection, BusType, Message};
-use dbus::arg::Array;
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    // First open up a connection to the session bus.
+    let conn = Connection::new_session()?;
 
-fn main() {
-    let c = Connection::get_private(BusType::Session).unwrap();
-    let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
-    let r = c.send_with_reply_and_block(m, 2000).unwrap();
-    // ListNames returns one argument, which is an array of strings.
-    let arr: Array<&str, _>  = r.get1().unwrap();
-    for name in arr { println!("{}", name); }
+    // Second, create a wrapper struct around the connection that makes it easy
+    // to send method calls to a specific destination and path.
+    let proxy = conn.with_proxy("org.freedesktop.DBus", "/", Duration::from_millis(5000));
+
+    // Now make the method call. The ListNames method call takes zero input parameters and 
+    // one output parameter which is an array of strings.
+    // Therefore the input is a zero tuple "()", and the output is a single tuple "(names,)".
+    let (names,): (Vec<String>,) = proxy.method_call("org.freedesktop.DBus", "ListNames", ())?;
+
+    // Let's print all the names to stdout.
+    for name in names { println!("{}", name); }
+
+    Ok(())
 }
 
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/examples/match_signal.rs
@@ -0,0 +1,61 @@
+/// Connects to the "server" example. Have the server example running when you're running this example.
+
+use dbus::arg;
+
+// First, let's autogenerate some code using the dbus-codegen-rust tool.
+// With the server example running, the below was (part of) the output when running:
+// `dbus-codegen-rust -d com.example.dbustest -p /hello -m None`
+
+#[derive(Debug)]
+pub struct ComExampleDbustestHelloHappened {
+    pub sender: String,
+}
+
+impl arg::AppendAll for ComExampleDbustestHelloHappened {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.sender, i);
+    }
+}
+
+impl arg::ReadAll for ComExampleDbustestHelloHappened {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ComExampleDbustestHelloHappened {
+            sender: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for ComExampleDbustestHelloHappened {
+    const NAME: &'static str = "HelloHappened";
+    const INTERFACE: &'static str = "com.example.dbustest";
+}
+
+// Autogenerated code ends here.
+
+use dbus::blocking::Connection;
+use dbus::Message;
+use std::error::Error;
+use std::time::Duration;
+
+
+fn main() -> Result<(), Box<dyn Error>> {
+    // Let's start by starting up a connection to the session bus.
+    let c = Connection::new_session()?;
+
+    {
+        let proxy = c.with_proxy("com.example.dbustest", "/hello", Duration::from_millis(5000));
+
+        // Let's start listening to signals.
+        let _id = proxy.match_signal(|h: ComExampleDbustestHelloHappened, _: &Connection, _: &Message| {
+            println!("Hello happened from sender: {}", h.sender);
+            true
+        });
+
+        // Say hello to the server example, so we get a signal.
+        let (s,): (String,) = proxy.method_call("com.example.dbustest", "Hello", ("match_signal example",))?;
+        println!("{}", s);
+    }
+
+    // Listen to incoming signals forever.
+    loop { c.process(Duration::from_millis(1000))?; }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/examples/monitor.rs
@@ -0,0 +1,43 @@
+use std::time::Duration;
+
+use dbus::blocking::Connection;
+use dbus::channel::MatchingReceiver;
+use dbus::Message;
+use dbus::message::MatchRule;
+
+// This programs implements the equivalent of running the "dbus-monitor" tool
+fn main() {
+    // First open up a connection to the session bus.
+    let conn = Connection::new_session().expect("D-Bus connection failed");
+
+    // Second create a rule to match messages we want to receive; in this example we add no
+    // further requirements, so all messages will match
+    let mut rule = MatchRule::new();
+
+    // Try matching using new scheme
+    let proxy = conn.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", Duration::from_millis(5000));
+    let result: Result<(), dbus::Error> = proxy.method_call("org.freedesktop.DBus.Monitoring", "BecomeMonitor", (vec!(rule.match_str()), 0u32));
+
+    if result.is_ok() {
+        // Start matching using new scheme
+        conn.start_receive(rule, Box::new(|msg, _| {
+            handle_message(&msg);
+            true
+        }));
+    } else {
+        // Start matching using old scheme
+        rule.eavesdrop = true; // this lets us eavesdrop on *all* session messages, not just ours
+        conn.add_match(rule, |_: (), _, msg| {
+            handle_message(&msg);
+            true
+        }).expect("add_match failed");
+    }
+
+    // Loop and print out all messages received (using handle_message()) as they come.
+    // Some can be quite large, e.g. if they contain embedded images..
+    loop { conn.process(Duration::from_millis(1000)).unwrap(); };
+}
+
+fn handle_message(msg: &Message) {
+    println!("Got message: {:?}", msg);
+}
--- a/third_party/rust/dbus/examples/properties.rs
+++ b/third_party/rust/dbus/examples/properties.rs
@@ -1,50 +1,56 @@
-extern crate dbus;
+use dbus::{blocking::Connection, arg};
+use std::time::Duration;
 
-use dbus::{Connection, BusType, stdintf, arg};
-use std::collections::HashMap;
-
-fn print_refarg(value: &arg::RefArg) {
+fn print_refarg(value: &dyn arg::RefArg) {
     // We don't know what type the value is. We'll try a few and fall back to
     // debug printing if the value is more complex than that.
     if let Some(s) = value.as_str() { println!("{}", s); }
     else if let Some(i) = value.as_i64() { println!("{}", i); }
     else { println!("{:?}", value); }
 }
 
-fn main() {
-    // Connect to server and create a ConnPath. A ConnPath implements several interfaces,
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    // Connect to server and create a proxy object. A proxy implements several interfaces,
     // in this case we'll use OrgFreedesktopDBusProperties, which allows us to call "get".
-    let c = Connection::get_private(BusType::Session).unwrap();
-    let p = c.with_path("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", 5000);
-    use stdintf::org_freedesktop_dbus::Properties;
+    let c = Connection::new_session()?;
+    let p = c.with_proxy("org.mpris.MediaPlayer2.rhythmbox", "/org/mpris/MediaPlayer2", Duration::from_millis(5000));
+    use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
 
-    // The Metadata property is a Dict<String, Variant>. 
+    // The Metadata property is a Dict<String, Variant>.
 
     // Option 1: we can get the dict straight into a hashmap, like this:
 
-    let metadata: HashMap<String, arg::Variant<Box<arg::RefArg>>> = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap();
+    let metadata: arg::PropMap = p.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
 
     println!("Option 1:");
 
     // We now iterate over the hashmap.
     for (key, value) in metadata.iter() {
         print!("  {}: ", key);
         print_refarg(&value);
     }
 
+    // As an alternative, if we just want a specific property and know the type of it, we can use
+    // prop_cast:
+    let title: Option<&String> = arg::prop_cast(&metadata, "xesam:title");
+    if let Some(title) = title {
+        println!("The title is: {}", title);
+    }
 
     // Option 2: we can get the entire dict as a RefArg and get the values out by iterating over it.
 
-    let metadata: Box<arg::RefArg> = p.get("org.mpris.MediaPlayer2.Player", "Metadata").unwrap();
+    let metadata: Box<dyn arg::RefArg> = p.get("org.mpris.MediaPlayer2.Player", "Metadata")?;
 
     // When using "as_iter()" for a dict, we'll get one key, it's value, next key, it's value, etc.
     let mut iter = metadata.as_iter().unwrap();
 
     println!("Option 2:");
     while let Some(key) = iter.next() {
         // Printing the key is easy, since we know it's a String.
         print!("  {}: ", key.as_str().unwrap());
         let value = iter.next().unwrap();
         print_refarg(&value);
     }
+
+    Ok(())
 }
--- a/third_party/rust/dbus/examples/properties_msgitem.rs
+++ b/third_party/rust/dbus/examples/properties_msgitem.rs
@@ -1,10 +1,9 @@
-extern crate dbus;
-
-use dbus::{Connection, BusType, Props};
+use dbus::ffidisp::Connection;
+use dbus::arg::messageitem::Props;
 
 fn main() {
-    let c = Connection::get_private(BusType::System).unwrap();
+    let c = Connection::new_system().unwrap();
     let p = Props::new(&c, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority",
         "org.freedesktop.PolicyKit1.Authority", 10000);
     println!("BackendVersion: {:?}", p.get("BackendVersion").unwrap())
 }
--- a/third_party/rust/dbus/examples/rtkit.rs
+++ b/third_party/rust/dbus/examples/rtkit.rs
@@ -1,65 +1,46 @@
 /* This example asks the rtkit service to make our thread realtime priority.
    Rtkit puts a few limitations on us to let us become realtime, such as setting
    RLIMIT_RTTIME correctly, hence the syscalls. */
 
-extern crate dbus;
-extern crate libc;
-
 use std::cmp;
-
-use dbus::{Connection, BusType, Props, MessageItem, Message};
+use std::time::Duration;
 
-fn item_as_i64(i: MessageItem) -> Result<i64, Box<std::error::Error>> {
-    match i {
-        MessageItem::Int32(i) => Ok(i as i64),
-        MessageItem::Int64(i) => Ok(i),
-        _ => Err(Box::from(&*format!("Property is not integer ({:?})", i)))
-    }
-}
+fn make_realtime(prio: u32) -> Result<u32, Box<dyn std::error::Error>> {
+    let c = dbus::blocking::Connection::new_system()?;
 
-fn rtkit_set_realtime(c: &Connection, thread: u64, prio: u32) -> Result<(), ::dbus::Error> {
-    let mut m = Message::new_method_call("org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
-        "org.freedesktop.RealtimeKit1", "MakeThreadRealtime").unwrap();
-    m.append_items(&[thread.into(), prio.into()]);
-    let mut r = try!(c.send_with_reply_and_block(m, 10000));
-    r.as_result().map(|_| ())
-}
-
-fn make_realtime(prio: u32) -> Result<u32, Box<std::error::Error>> {
-    let c = try!(Connection::get_private(BusType::System));
-
-    let p = Props::new(&c, "org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
-        "org.freedesktop.RealtimeKit1", 10000);
+    let proxy = c.with_proxy("org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
+        Duration::from_millis(10000));
+    use dbus::blocking::stdintf::org_freedesktop_dbus::Properties;
 
     // Make sure we don't fail by wanting too much
-    let max_prio = try!(item_as_i64(try!(p.get("MaxRealtimePriority")))) as u32;
-    let prio = cmp::min(prio, max_prio);
+    let max_prio: i32 = proxy.get("org.freedesktop.RealtimeKit1", "MaxRealtimePriority")?;
+    let prio = cmp::min(prio, max_prio as u32);
 
     // Enforce RLIMIT_RTPRIO, also a must before asking rtkit for rtprio
-    let max_rttime = try!(item_as_i64(try!(p.get("RTTimeUSecMax")))) as u64;
-    let new_limit = libc::rlimit64 { rlim_cur: max_rttime, rlim_max: max_rttime };
+    let max_rttime: i64 = proxy.get("org.freedesktop.RealtimeKit1", "RTTimeUSecMax")?;
+    let new_limit = libc::rlimit64 { rlim_cur: max_rttime as u64, rlim_max: max_rttime as u64 };
     let mut old_limit = new_limit;
     if unsafe { libc::getrlimit64(libc::RLIMIT_RTTIME, &mut old_limit) } < 0 {
         return Err(Box::from("getrlimit failed"));
     }
     if unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &new_limit) } < 0 {
         return Err(Box::from("setrlimit failed"));
     }
 
     // Finally, let's ask rtkit to make us realtime
     let thread_id = unsafe { libc::syscall(libc::SYS_gettid) };
-    let r = rtkit_set_realtime(&c, thread_id as u64, prio);
+    let r = proxy.method_call("org.freedesktop.RealtimeKit1", "MakeThreadRealtime", (thread_id as u64, prio));
 
     if r.is_err() {
         unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &old_limit) };
     }
 
-    try!(r);
+    r?;
     Ok(prio)
 }
 
 
 fn main() {
     match make_realtime(5) {
         Ok(n) => println!("Got rtprio, level {}", n),
         Err(e) => println!("No rtprio: {}", e),
--- a/third_party/rust/dbus/examples/unity_focused_window.rs
+++ b/third_party/rust/dbus/examples/unity_focused_window.rs
@@ -1,25 +1,28 @@
 extern crate dbus;
 
 // Tracks currently focused window under the Unity desktop by listening to the
 // FocusedWindowChanged signal. The signal contains "window_id", "app_id" and "stage",
-// we print only "app_id". 
+// we print only "app_id".
 
-use dbus::{Connection, BusType, ConnectionItem};
+use dbus::{ffidisp::Connection, Message, MessageType};
 
-fn focus_msg(ci: &ConnectionItem) -> Option<&str> {
-    let m = if let &ConnectionItem::Signal(ref s) = ci { s } else { return None };
-    if &*m.interface().unwrap() != "com.canonical.Unity.WindowStack" { return None };
-    if &*m.member().unwrap() != "FocusedWindowChanged" { return None };
-    let (_, app) = m.get2::<u32, &str>();
+fn focus_msg(msg: &Message) -> Option<&str> {
+    if msg.msg_type() != MessageType::Signal { return None };
+    if &*msg.interface().unwrap() != "com.canonical.Unity.WindowStack" { return None };
+    if &*msg.member().unwrap() != "FocusedWindowChanged" { return None };
+    let (_, app) = msg.get2::<u32, &str>();
     app
 }
 
 fn main() {
-    let c = Connection::get_private(BusType::Session).unwrap();
+    let c = Connection::new_session().unwrap();
     c.add_match("interface='com.canonical.Unity.WindowStack',member='FocusedWindowChanged'").unwrap();
 
-    for i in c.iter(1000) {
-        if let Some(app) = focus_msg(&i) { println!("{} has now focus.", app) };
+    loop {
+        if let Some(msg) = c.incoming(1000).next() {
+            if let Some(app) = focus_msg(&msg) {
+                println!("{} has now focus.", app);
+            }
+        }
     }
 }
-
--- a/third_party/rust/dbus/src/arg/array_impl.rs
+++ b/third_party/rust/dbus/src/arg/array_impl.rs
@@ -1,25 +1,26 @@
 use super::*;
-use {Signature, Path, Message, ffi, OwnedFd};
+use crate::{Message, ffi};
+use crate::strings::{Signature, Path};
 use std::marker::PhantomData;
 use std::{ptr, mem, any, fmt};
 use super::check;
 use std::ffi::{CString};
 use std::os::raw::{c_void, c_int};
-use std::collections::HashMap;
-use std::hash::Hash;
+use std::collections::{HashMap, BTreeMap};
+use std::hash::{Hash, BuildHasher};
 
 // Map DBus-Type -> Alignment. Copied from _dbus_marshal_write_fixed_multi in
 // http://dbus.freedesktop.org/doc/api/html/dbus-marshal-basic_8c_source.html#l01020
 // Note that Rust booleans are one byte, dbus booleans are four bytes!
 const FIXED_ARRAY_ALIGNMENTS: [(ArgType, usize); 9] = [
     (ArgType::Byte, 1),
     (ArgType::Int16, 2),
-    (ArgType::UInt16, 2),	
+    (ArgType::UInt16, 2),
     (ArgType::UInt32, 4),
     (ArgType::Int32, 4),
     (ArgType::Boolean, 4),
     (ArgType::Int64, 8),
     (ArgType::UInt64, 8),
     (ArgType::Double, 8)
 ];
 
@@ -42,70 +43,80 @@ fn array_append<T: Arg, F: FnMut(&T, &mu
             ffi::dbus_message_iter_append_fixed_array(&mut s.0, a.0 as c_int, &zptr as *const _ as *const c_void, zlen)) }}
         else { for arg in z { f(arg, s); }}
     );
 }
 
 /// Appends a D-Bus array. Note: In case you have a large array of a type that implements FixedArray,
 /// using this method will be more efficient than using an Array.
 impl<'a, T: Arg + Append + Clone> Append for &'a [T] {
-    fn append(self, i: &mut IterAppend) {
+    fn append_by_ref(&self, i: &mut IterAppend) {
         array_append(self, i, |arg, s| arg.clone().append(s));
     }
 }
 
 impl<'a, T: Arg + RefArg> RefArg for &'a [T] {
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
     fn append(&self, i: &mut IterAppend) {
-        array_append(self, i, |arg, s| (arg as &RefArg).append(s));
+        array_append(self, i, |arg, s| RefArg::append(arg,s));
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        self.get(index).map(|x| x as &dyn RefArg)
+    }
 
-    fn box_clone(&self) -> Box<RefArg + 'static> {
-        Box::new(InternalArray {
-            inner_sig: <T as Arg>::signature(),
-            data: self.iter().map(|x| x.box_clone()).collect(),
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
+        T::array_clone(self).unwrap_or_else(|| {
+            Box::new(InternalArray {
+                inner_sig: <T as Arg>::signature(),
+                data: self.iter().map(|x| x.box_clone()).collect(),
+            })
         })
     }
 }
 
 impl<T: Arg + RefArg> RefArg for Vec<T> {
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
     fn append(&self, i: &mut IterAppend) {
-        array_append(&self, i, |arg, s| (arg as &RefArg).append(s));
+        array_append(&self, i, |arg, s| RefArg::append(arg,s));
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
-        Some(Box::new(self.iter().map(|b| b as &RefArg)))
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> {
+        Some(Box::new(self.iter().map(|b| b as &dyn RefArg)))
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        self.get(index).map(|x| x as &dyn RefArg)
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { (&**self).box_clone() }
 }
 
 
 impl<'a, T: FixedArray> Get<'a> for &'a [T] {
     fn get(i: &mut Iter<'a>) -> Option<&'a [T]> {
         debug_assert!(FIXED_ARRAY_ALIGNMENTS.iter().any(|&v| v == (T::ARG_TYPE, mem::size_of::<T>())));
         i.recurse(Self::ARG_TYPE).and_then(|mut si| unsafe {
             let etype = ffi::dbus_message_iter_get_element_type(&mut i.0);
 
             if etype != T::ARG_TYPE as c_int { return None };
 
-            let mut v = ptr::null_mut();
+            let mut v: *mut T = ptr::null_mut();
             let mut i = 0;
             ffi::dbus_message_iter_get_fixed_array(&mut si.0, &mut v as *mut _ as *mut c_void, &mut i);
-            if v == ptr::null_mut() {
+            if v.is_null() {
                 assert_eq!(i, 0);
                 Some(&[][..])
             } else {
                 Some(::std::slice::from_raw_parts(v, i as usize))
             }
         })
     }
 }
@@ -113,37 +124,37 @@ impl<'a, T: FixedArray> Get<'a> for &'a 
 
 #[derive(Copy, Clone, Debug)]
 /// Append a D-Bus dict type (i e, an array of dict entries).
 ///
 /// See the argument guide and module level documentation for details and alternatives.
 pub struct Dict<'a, K: DictKey, V: Arg, I>(I, PhantomData<(&'a Message, *const K, *const V)>);
 
 impl<'a, K: DictKey, V: Arg, I> Dict<'a, K, V, I> {
-    fn entry_sig() -> String { format!("{{{}{}}}", K::signature(), V::signature()) } 
+    fn entry_sig() -> String { format!("{{{}{}}}", K::signature(), V::signature()) }
 }
 
 impl<'a, K: 'a + DictKey, V: 'a + Append + Arg, I: Iterator<Item=(K, V)>> Dict<'a, K, V, I> {
-    /// Creates a new Dict from an iterator. The iterator is consumed when appended.
+    /// Creates a new Dict from an iterator.
     pub fn new<J: IntoIterator<IntoIter=I, Item=(K, V)>>(j: J) -> Dict<'a, K, V, I> { Dict(j.into_iter(), PhantomData) }
 }
 
 impl<'a, K: DictKey, V: Arg, I> Arg for Dict<'a, K, V, I> {
     const ARG_TYPE: ArgType = ArgType::Array;
     fn signature() -> Signature<'static> {
         Signature::from(format!("a{}", Self::entry_sig())) }
 }
 
-impl<'a, K: 'a + DictKey + Append, V: 'a + Append + Arg, I: Iterator<Item=(K, V)>> Append for Dict<'a, K, V, I> {
-    fn append(self, i: &mut IterAppend) {
-        let z = self.0;
+impl<'a, K: 'a + DictKey + Append, V: 'a + Append + Arg, I: Iterator<Item=(K, V)> + Clone> Append for Dict<'a, K, V, I> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        let z = self.0.clone();
         i.append_container(Self::ARG_TYPE, Some(&CString::new(Self::entry_sig()).unwrap()), |s| for (k, v) in z {
             s.append_container(ArgType::DictEntry, None, |ss| {
-                k.append(ss);
-                v.append(ss);
+                k.append_by_ref(ss);
+                v.append_by_ref(ss);
             })
         });
     }
 }
 
 
 impl<'a, K: DictKey + Get<'a>, V: Arg + Get<'a>> Get<'a> for Dict<'a, K, V, Iter<'a>> {
     fn get(i: &mut Iter<'a>) -> Option<Self> {
@@ -154,110 +165,157 @@ impl<'a, K: DictKey + Get<'a>, V: Arg + 
 
 impl<'a, K: DictKey + Get<'a>, V: Arg + Get<'a>> Iterator for Dict<'a, K, V, Iter<'a>> {
     type Item = (K, V);
     fn next(&mut self) -> Option<(K, V)> {
         let i = self.0.recurse(ArgType::DictEntry).and_then(|mut si| {
             let k = si.get();
             if k.is_none() { return None };
             assert!(si.next());
-            let v = si.get(); 
+            let v = si.get();
             if v.is_none() { return None };
             Some((k.unwrap(), v.unwrap()))
         });
         self.0.next();
         i
     }
 }
 
-impl<K: DictKey, V: Arg> Arg for HashMap<K, V> {
+impl<K: DictKey, V: Arg, S: BuildHasher> Arg for HashMap<K, V, S> {
     const ARG_TYPE: ArgType = ArgType::Array;
     fn signature() -> Signature<'static> {
         Signature::from(format!("a{{{}{}}}", K::signature(), V::signature())) }
 }
 
-impl<K: DictKey + Append + Eq + Hash, V: Arg + Append> Append for HashMap<K, V> {
-    fn append(self, i: &mut IterAppend) {
-        Dict::new(self.into_iter()).append(i);
+impl<K: DictKey + Append + Eq + Hash, V: Arg + Append, S: BuildHasher> Append for HashMap<K, V, S> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        Dict::new(self.iter()).append_by_ref(i);
     }
 }
 
-impl<'a, K: DictKey + Get<'a> + Eq + Hash, V: Arg + Get<'a>> Get<'a> for HashMap<K, V> {
+impl<'a, K: DictKey + Get<'a> + Eq + Hash, V: Arg + Get<'a>, S: BuildHasher + Default> Get<'a> for HashMap<K, V, S> {
     fn get(i: &mut Iter<'a>) -> Option<Self> {
         // TODO: Full element signature is not verified.
-        Dict::get(i).map(|d| d.into_iter().collect())
+        Dict::get(i).map(|d| d.collect())
     }
 }
 
-impl<K: DictKey + RefArg + Eq + Hash, V: RefArg + Arg> RefArg for HashMap<K, V> {
+impl<K: DictKey + RefArg + Eq + Hash, V: RefArg + Arg, S: BuildHasher + Send + Sync> RefArg for HashMap<K, V, S> {
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { format!("a{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature()).into() }
     fn append(&self, i: &mut IterAppend) {
         let sig = CString::new(format!("{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature())).unwrap();
         i.append_container(ArgType::Array, Some(&sig), |s| for (k, v) in self {
             s.append_container(ArgType::DictEntry, None, |ss| {
                 k.append(ss);
                 v.append(ss);
             })
         });
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
-        Some(Box::new(self.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<dyn Iterator<Item=&'b dyn RefArg> + 'b>> {
+        Some(Box::new(self.iter().flat_map(|(k, v)| vec![k as &dyn RefArg, v as &dyn RefArg].into_iter())))
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
         Box::new(InternalDict {
             outer_sig: self.signature(),
             data: self.iter().map(|(k, v)| (k.box_clone(), v.box_clone())).collect(),
         })
     }
 }
 
+impl<K: DictKey, V: Arg> Arg for BTreeMap<K, V> {
+    const ARG_TYPE: ArgType = ArgType::Array;
+    fn signature() -> Signature<'static> {
+        Signature::from(format!("a{{{}{}}}", K::signature(), V::signature())) }
+}
+
+impl<K: DictKey + Append + Eq + Ord, V: Arg + Append> Append for BTreeMap<K, V> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        Dict::new(self.iter()).append_by_ref(i);
+    }
+}
+
+impl<'a, K: DictKey + Get<'a> + Eq + Ord, V: Arg + Get<'a>> Get<'a> for BTreeMap<K, V> {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        // TODO: Full element signature is not verified.
+        Dict::get(i).map(|d| d.collect())
+    }
+}
+
+impl<K: DictKey + RefArg + Eq + Ord, V: RefArg + Arg> RefArg for BTreeMap<K, V> {
+    fn arg_type(&self) -> ArgType { ArgType::Array }
+    fn signature(&self) -> Signature<'static> { format!("a{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature()).into() }
+    fn append(&self, i: &mut IterAppend) {
+        let sig = CString::new(format!("{{{}{}}}", <K as Arg>::signature(), <V as Arg>::signature())).unwrap();
+        i.append_container(ArgType::Array, Some(&sig), |s| for (k, v) in self {
+            s.append_container(ArgType::DictEntry, None, |ss| {
+                k.append(ss);
+                v.append(ss);
+            })
+        });
+    }
+    #[inline]
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<dyn Iterator<Item=&'b dyn RefArg> + 'b>> {
+        Some(Box::new(self.iter().flat_map(|(k, v)| vec![k as &dyn RefArg, v as &dyn RefArg].into_iter())))
+    }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
+        Box::new(InternalDict {
+            outer_sig: self.signature(),
+            data: self.iter().map(|(k, v)| (k.box_clone(), v.box_clone())).collect(),
+        })
+    }
+}
+
+
 impl<T: Arg> Arg for Vec<T> {
     const ARG_TYPE: ArgType = ArgType::Array;
     fn signature() -> Signature<'static> { Signature::from(format!("a{}", T::signature())) }
 }
 
 impl<T: Arg + Append> Append for Vec<T> {
-    fn append(self, i: &mut IterAppend) {
-        Array::new(self).append(i);
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        Array::new(self).append_by_ref(i);
     }
 }
 
 impl<'a, T: Arg + Get<'a>> Get<'a> for Vec<T> {
     fn get(i: &mut Iter<'a>) -> Option<Self> {
         <Array<T, Iter<'a>>>::get(i).map(|a| a.collect())
     }
 }
 
 
 #[derive(Copy, Clone, Debug)]
-/// Represents a D-Bus Array. Maximum flexibility (wraps an iterator of items to append). 
+/// Represents a D-Bus Array. Maximum flexibility (wraps an iterator of items to append).
 ///
 /// See the argument guide and module level documentation for details and alternatives.
-pub struct Array<'a, T, I>(I, PhantomData<(*const T, &'a Message)>);
+pub struct Array<'a, T, I>(I, PhantomData<(fn() -> T, &'a ())>);
 
 impl<'a, T: 'a, I: Iterator<Item=T>> Array<'a, T, I> {
-    /// Creates a new Array from an iterator. The iterator is consumed when appending.
+    /// Creates a new Array from an iterator.
     pub fn new<J: IntoIterator<IntoIter=I, Item=T>>(j: J) -> Array<'a, T, I> { Array(j.into_iter(), PhantomData) }
 }
 
 impl<'a, T: Arg, I> Arg for Array<'a, T, I> {
     const ARG_TYPE: ArgType = ArgType::Array;
     fn signature() -> Signature<'static> { Signature::from(format!("a{}", T::signature())) }
 }
 
-impl<'a, T: 'a + Arg + Append, I: Iterator<Item=T>> Append for Array<'a, T, I> {
-    fn append(self, i: &mut IterAppend) {
-        let z = self.0;
-        i.append_container(ArgType::Array, Some(T::signature().as_cstr()), |s| for arg in z { arg.append(s) });
+impl<'a, T: 'a + Arg + Append, I: Iterator<Item=T> + Clone> Append for Array<'a, T, I> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        let z = self.0.clone();
+        i.append_container(ArgType::Array, Some(T::signature().as_cstr()), |s| for arg in z { arg.append_by_ref(s) });
     }
 }
 
 impl<'a, T: Arg + Get<'a>> Get<'a> for Array<'a, T, Iter<'a>> {
     fn get(i: &mut Iter<'a>) -> Option<Array<'a, T, Iter<'a>>> {
         i.recurse(Self::ARG_TYPE).map(|si| Array(si, PhantomData))
         // TODO: Verify full element signature?
     }
@@ -269,97 +327,127 @@ impl<'a, T: Get<'a>> Iterator for Array<
         let i = self.0.get();
         self.0.next();
         i
     }
 }
 
 // Due to the strong typing here; RefArg is implemented only for T's that are both Arg and RefArg.
 // We need Arg for this to work for empty arrays (we can't get signature from first element if there is no elements).
-// We need RefArg for non-consuming append.
-impl<'a, T: 'a + Arg + fmt::Debug + RefArg, I: fmt::Debug + Clone + Iterator<Item=&'a T>> RefArg for Array<'static, T, I> {
+// We need RefArg for box_clone.
+impl<'a, T, I> RefArg for Array<'static, T, I>
+where
+    T: 'a + Arg + RefArg,
+    I: fmt::Debug + Clone + Send + Sync + Iterator<Item=&'a T>
+{
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", <T as Arg>::signature())) }
     fn append(&self, i: &mut IterAppend) {
         let z = self.0.clone();
         i.append_container(ArgType::Array, Some(<T as Arg>::signature().as_cstr()), |s|
-            for arg in z { (arg as &RefArg).append(s) }
+            for arg in z { RefArg::append(arg, s); }
         );
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
 
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
         Box::new(InternalArray {
             inner_sig: <T as Arg>::signature(),
             data: self.0.clone().map(|x| x.box_clone()).collect(),
         })
     }
 }
 
-fn get_fixed_array_refarg<'a, T: FixedArray + Clone + RefArg>(i: &mut Iter<'a>) -> Box<RefArg> {
+fn get_fixed_array_refarg<T: FixedArray + Clone + RefArg>(i: &mut Iter) -> Box<dyn RefArg> {
     let s = <&[T]>::get(i).unwrap();
     Box::new(s.to_vec())
 }
 
 fn get_var_array_refarg<'a, T: 'static + RefArg + Arg, F: FnMut(&mut Iter<'a>) -> Option<T>>
-    (i: &mut Iter<'a>, mut f: F) -> Box<RefArg> {
+    (i: &mut Iter<'a>, mut f: F) -> Box<dyn RefArg> {
     let mut v: Vec<T> = vec!(); // dbus_message_iter_get_element_count might be O(n), better not use it
     let mut si = i.recurse(ArgType::Array).unwrap();
     while let Some(q) = f(&mut si) { v.push(q); si.next(); }
     Box::new(v)
 }
 
+fn get_dict_refarg<'a, K, V, KF, VF>(i: &mut Iter<'a>, mut kf: KF, mut vf: VF) -> Box<dyn RefArg>
+where
+    K: DictKey + 'static + RefArg + Clone + Eq + Hash,
+    V: RefArg + Arg + 'static,
+    KF: FnMut(&mut Iter<'a>) -> Option<K>,
+    VF: FnMut(&mut Iter<'a>) -> Option<V>,
+{
+    let mut data: HashMap<K, V> = HashMap::new();
+    let mut si = i.recurse(ArgType::Array).unwrap();
+    while let Some(mut d) = si.recurse(ArgType::DictEntry) {
+        let k = kf(&mut d).unwrap();
+        d.next();
+        let v = vf(&mut d).unwrap();
+        data.insert(k, v);
+        si.next();
+    }
+    Box::new(data)
+}
 
 #[derive(Debug)]
 struct InternalDict<K> {
-   data: Vec<(K, Box<RefArg>)>,
+   data: Vec<(K, Box<dyn RefArg>)>,
    outer_sig: Signature<'static>,
 }
 
-fn get_dict_refarg<'a, K, F: FnMut(&mut Iter<'a>) -> Option<K>>(i: &mut Iter<'a>, mut f: F) -> Box<RefArg>
-    where K: DictKey + 'static + RefArg + Clone
- {
-    let mut data = vec!();
+fn get_internal_dict_refarg<'a, K, F: FnMut(&mut Iter<'a>) -> Option<K>>(
+    i: &mut Iter<'a>,
+    mut f: F,
+) -> Box<dyn RefArg>
+where
+    K: DictKey + 'static + RefArg + Clone,
+{
+    let mut data = vec![];
     let outer_sig = i.signature();
     let mut si = i.recurse(ArgType::Array).unwrap();
     while let Some(mut d) = si.recurse(ArgType::DictEntry) {
         let k = f(&mut d).unwrap();
         d.next();
         data.push((k, d.get_refarg().unwrap()));
         si.next();
     }
     Box::new(InternalDict { data, outer_sig })
 }
 
 // This only happens from box_clone
-impl RefArg for InternalDict<Box<RefArg>> {
+impl RefArg for InternalDict<Box<dyn RefArg>> {
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { self.outer_sig.clone() }
     fn append(&self, i: &mut IterAppend) {
         let inner_sig = &self.outer_sig.as_cstr().to_bytes_with_nul()[1..];
         let inner_sig = CStr::from_bytes_with_nul(inner_sig).unwrap();
         i.append_container(ArgType::Array, Some(inner_sig), |s| for (k, v) in &self.data {
             s.append_container(ArgType::DictEntry, None, |ss| {
                 k.append(ss);
                 v.append(ss);
             })
         });
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
-        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<dyn Iterator<Item=&'b dyn RefArg> + 'b>> {
+        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &dyn RefArg, v as &dyn RefArg].into_iter())))
+    }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        let (k, v) = self.data.get(index / 2)?;
+        Some(if index & 1 != 0 { v } else { k })
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
         Box::new(InternalDict {
             data: self.data.iter().map(|(k, v)| (k.box_clone(), v.box_clone())).collect(),
             outer_sig: self.outer_sig.clone(),
         })
     }
 }
 
 
@@ -372,112 +460,162 @@ impl<K: DictKey + RefArg + Clone + 'stat
         i.append_container(ArgType::Array, Some(inner_sig), |s| for (k, v) in &self.data {
             s.append_container(ArgType::DictEntry, None, |ss| {
                 k.append(ss);
                 v.append(ss);
             })
         });
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> {
-        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &RefArg, v as &RefArg].into_iter())))
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'b>(&'b self) -> Option<Box<dyn Iterator<Item=&'b dyn RefArg> + 'b>> {
+        Some(Box::new(self.data.iter().flat_map(|(k, v)| vec![k as &dyn RefArg, v as &dyn RefArg].into_iter())))
+    }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        let (k, v) = self.data.get(index / 2)?;
+        Some(if index & 1 != 0 { v } else { k })
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
         Box::new(InternalDict {
             data: self.data.iter().map(|(k, v)| (k.clone(), v.box_clone())).collect(),
             outer_sig: self.outer_sig.clone(),
         })
     }
-} 
+}
 
 
 // Fallback for Arrays of Arrays and Arrays of Structs.
 // We store the signature manually here and promise that it is correct for all elements
 // has that signature.
 #[derive(Debug)]
 struct InternalArray {
-   data: Vec<Box<RefArg>>,
+   data: Vec<Box<dyn RefArg>>,
    inner_sig: Signature<'static>,
 }
 
-fn get_internal_array<'a>(i: &mut Iter<'a>) -> Box<RefArg> {
+fn get_internal_array(i: &mut Iter) -> Box<dyn RefArg> {
     let mut si = i.recurse(ArgType::Array).unwrap();
     let inner_sig = si.signature();
     let data = si.collect::<Vec<_>>();
     Box::new(InternalArray { data, inner_sig })
 }
 
 impl RefArg for InternalArray {
     fn arg_type(&self) -> ArgType { ArgType::Array }
     fn signature(&self) -> Signature<'static> { Signature::from(format!("a{}", self.inner_sig)) }
     fn append(&self, i: &mut IterAppend) {
         i.append_container(ArgType::Array, Some(self.inner_sig.as_cstr()), |s|
-            for arg in &self.data { (arg as &RefArg).append(s) }
+            for arg in &self.data { RefArg::append(arg,s) }
         );
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
-        Some(Box::new(self.data.iter().map(|b| b as &RefArg)))
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> {
+        Some(Box::new(self.data.iter().map(|b| b as &dyn RefArg)))
+    }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        self.data.get(index).map(|x| x as &dyn RefArg)
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
         Box::new(InternalArray {
             data: self.data.iter().map(|x| x.box_clone()).collect(),
             inner_sig: self.inner_sig.clone(),
         })
     }
 }
 
-pub fn get_array_refarg<'a>(i: &mut Iter<'a>) -> Box<RefArg> {
+fn get_dict_refarg_for_value_type<'a, K, KF>(
+    value_type: ArgType,
+    i: &mut Iter<'a>,
+    kf: KF,
+) -> Box<dyn RefArg>
+where
+    K: DictKey + 'static + RefArg + Clone + Eq + Hash,
+    KF: FnMut(&mut Iter<'a>) -> Option<K>,
+{
+    match value_type {
+        ArgType::Variant => {
+            get_dict_refarg::<K, Variant<Box<dyn RefArg>>, KF, _>(i, kf, Variant::new_refarg)
+        }
+        // Most of the following could also use get_dict_refarg to convert to a typed HashMap, but
+        // doing so results in a large binary size increase due to all the generic instances being
+        // instantiated.
+        ArgType::Byte
+        | ArgType::Int16
+        | ArgType::UInt16
+        | ArgType::Int32
+        | ArgType::UInt32
+        | ArgType::Int64
+        | ArgType::UInt64
+        | ArgType::Double
+        | ArgType::String
+        | ArgType::ObjectPath
+        | ArgType::Signature
+        | ArgType::Boolean
+        | ArgType::UnixFd
+        | ArgType::Array
+        | ArgType::Struct => get_internal_dict_refarg::<K, KF>(i, kf),
+        ArgType::DictEntry => panic!("Can't have DictEntry as value for dictionary"),
+        ArgType::Invalid => panic!("Array with invalid dictvalue"),
+    }
+}
+
+pub fn get_array_refarg(i: &mut Iter) -> Box<dyn RefArg> {
     debug_assert!(i.arg_type() == ArgType::Array);
     let etype = ArgType::from_i32(unsafe { ffi::dbus_message_iter_get_element_type(&mut i.0) } as i32).unwrap();
 
     let x = match etype {
         ArgType::Byte => get_fixed_array_refarg::<u8>(i),
         ArgType::Int16 => get_fixed_array_refarg::<i16>(i),
         ArgType::UInt16 => get_fixed_array_refarg::<u16>(i),
         ArgType::Int32 => get_fixed_array_refarg::<i32>(i),
         ArgType::UInt32 => get_fixed_array_refarg::<u32>(i),
         ArgType::Int64 => get_fixed_array_refarg::<i64>(i),
         ArgType::UInt64 => get_fixed_array_refarg::<u64>(i),
         ArgType::Double => get_fixed_array_refarg::<f64>(i),
-	ArgType::String => get_var_array_refarg::<String, _>(i, |si| si.get()),
-	ArgType::ObjectPath => get_var_array_refarg::<Path<'static>, _>(i, |si| si.get::<Path>().map(|s| s.into_static())),
-	ArgType::Signature => get_var_array_refarg::<Signature<'static>, _>(i, |si| si.get::<Signature>().map(|s| s.into_static())),
-	ArgType::Variant => get_var_array_refarg::<Variant<Box<RefArg>>, _>(i, |si| Variant::new_refarg(si)),
-	ArgType::Boolean => get_var_array_refarg::<bool, _>(i, |si| si.get()),
-	ArgType::Invalid => panic!("Array with Invalid ArgType"),
+        ArgType::String => get_var_array_refarg::<String, _>(i, |si| si.get()),
+        ArgType::ObjectPath => get_var_array_refarg::<Path<'static>, _>(i, |si| si.get::<Path>().map(|s| s.into_static())),
+        ArgType::Signature => get_var_array_refarg::<Signature<'static>, _>(i, |si| si.get::<Signature>().map(|s| s.into_static())),
+        ArgType::Variant => get_var_array_refarg::<Variant<Box<dyn RefArg>>, _>(i, |si| Variant::new_refarg(si)),
+        ArgType::Boolean => get_var_array_refarg::<bool, _>(i, |si| si.get()),
+        ArgType::Invalid => panic!("Array with Invalid ArgType"),
         ArgType::Array => get_internal_array(i),
         ArgType::DictEntry => {
             let key = ArgType::from_i32(i.signature().as_bytes()[2] as i32).unwrap(); // The third character, after "a{", is our key.
+            let value = ArgType::from_i32(i.signature().as_bytes()[3] as i32).unwrap(); // The fourth character, after "a{", is our value.
             match key {
-                ArgType::Byte => get_dict_refarg::<u8, _>(i, |si| si.get()),
-                ArgType::Int16 => get_dict_refarg::<i16, _>(i, |si| si.get()),
-                ArgType::UInt16 => get_dict_refarg::<u16, _>(i, |si| si.get()),
-                ArgType::Int32 => get_dict_refarg::<i32, _>(i, |si| si.get()),
-                ArgType::UInt32 => get_dict_refarg::<u32, _>(i, |si| si.get()),
-                ArgType::Int64 => get_dict_refarg::<i64, _>(i, |si| si.get()),
-                ArgType::UInt64 => get_dict_refarg::<u64, _>(i, |si| si.get()),
-                ArgType::Double => get_dict_refarg::<f64, _>(i, |si| si.get()),
-                ArgType::Boolean => get_dict_refarg::<bool, _>(i, |si| si.get()),
-                // ArgType::UnixFd => get_dict_refarg::<OwnedFd, _>(i, |si| si.get()),
-                ArgType::String => get_dict_refarg::<String, _>(i, |si| si.get()),
-                ArgType::ObjectPath => get_dict_refarg::<Path<'static>, _>(i, |si| si.get::<Path>().map(|s| s.into_static())),
-                ArgType::Signature => get_dict_refarg::<Signature<'static>, _>(i, |si| si.get::<Signature>().map(|s| s.into_static())),
+                ArgType::Byte => get_dict_refarg_for_value_type::<u8, _>(value, i, Iter::get),
+                ArgType::Int16 => get_dict_refarg_for_value_type::<i16, _>(value, i, Iter::get),
+                ArgType::UInt16 => get_dict_refarg_for_value_type::<u16, _>(value, i, Iter::get),
+                ArgType::Int32 => get_dict_refarg_for_value_type::<i32, _>(value, i, Iter::get),
+                ArgType::UInt32 => get_dict_refarg_for_value_type::<u32, _>(value, i, Iter::get),
+                ArgType::Int64 => get_dict_refarg_for_value_type::<i64, _>(value, i, Iter::get),
+                ArgType::UInt64 => get_dict_refarg_for_value_type::<u64, _>(value, i, Iter::get),
+                ArgType::Double => get_internal_dict_refarg::<f64, _>(i, Iter::get),
+                ArgType::Boolean => get_dict_refarg_for_value_type::<bool, _>(value, i, Iter::get),
+                // ArgType::UnixFd => get_dict_refarg::<OwnedFd, _>(i),
+                ArgType::String => get_dict_refarg_for_value_type::<String, _>(value, i, Iter::get),
+                ArgType::ObjectPath => {
+                    get_dict_refarg_for_value_type::<Path<'static>, _>(value, i, |si| {
+                        si.get::<Path>().map(|s| s.into_static())
+                    })
+                }
+                ArgType::Signature => {
+                    get_dict_refarg_for_value_type::<Signature<'static>, _>(value, i, |si| {
+                        si.get::<Signature>().map(|s| s.into_static())
+                    })
+                }
                 _ => panic!("Array with invalid dictkey ({:?})", key),
             }
         }
         ArgType::UnixFd => get_var_array_refarg::<OwnedFd, _>(i, |si| si.get()),
         ArgType::Struct => get_internal_array(i),
     };
 
     debug_assert_eq!(i.signature(), x.signature());
     x
 }
-
-
--- a/third_party/rust/dbus/src/arg/basic_impl.rs
+++ b/third_party/rust/dbus/src/arg/basic_impl.rs
@@ -1,49 +1,34 @@
-use ffi;
+use crate::ffi;
 use super::*;
 use super::check;
-use {Signature, Path, OwnedFd};
+use crate::strings::{Signature, Path, Member, ErrorName, Interface};
 use std::{ptr, any, mem};
 use std::ffi::CStr;
 use std::os::raw::{c_void, c_char, c_int};
+use std::fs::File;
 
 
 fn arg_append_basic<T>(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: T) {
     let p = &v as *const _ as *const c_void;
     unsafe {
         check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, p));
     };
 }
 
 fn arg_get_basic<T>(i: *mut ffi::DBusMessageIter, arg_type: ArgType) -> Option<T> {
     unsafe {
-        let mut c: T = mem::zeroed();
         if ffi::dbus_message_iter_get_arg_type(i) != arg_type as c_int { return None };
+        let mut c = mem::MaybeUninit::uninit();
         ffi::dbus_message_iter_get_basic(i, &mut c as *mut _ as *mut c_void);
-        Some(c)
+        Some(c.assume_init())
     }
 }
 
-fn arg_append_f64(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: f64) {
-    let p = &v as *const _ as *const c_void;
-    unsafe {
-        check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, p));
-    };
-}
-
-fn arg_get_f64(i: *mut ffi::DBusMessageIter, arg_type: ArgType) -> Option<f64> {
-    let mut c = 0f64;
-    unsafe {
-        if ffi::dbus_message_iter_get_arg_type(i) != arg_type as c_int { return None };
-        ffi::dbus_message_iter_get_basic(i, &mut c as *mut _ as *mut c_void);
-    }
-    Some(c)
-}
-
 fn arg_append_str(i: *mut ffi::DBusMessageIter, arg_type: ArgType, v: &CStr) {
     let p = v.as_ptr();
     let q = &p as *const _ as *const c_void;
     unsafe {
         check("dbus_message_iter_append_basic", ffi::dbus_message_iter_append_basic(i, arg_type as c_int, q));
     };
 }
 
@@ -64,128 +49,131 @@ macro_rules! integer_impl {
 
 impl Arg for $t {
     const ARG_TYPE: ArgType = ArgType::$s;
     #[inline]
     fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
 }
 
 impl Append for $t {
-    fn append(self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::$s, self) }
+    fn append_by_ref(&self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::$s, *self) }
 }
 
 impl<'a> Get<'a> for $t {
     fn get(i: &mut Iter) -> Option<Self> { arg_get_basic(&mut i.0, ArgType::$s) }
 }
 
 impl RefArg for $t {
     #[inline]
     fn arg_type(&self) -> ArgType { ArgType::$s }
     #[inline]
     fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
     #[inline]
     fn append(&self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::$s, *self) }
     #[inline]
-    fn as_any(&self) -> &any::Any { self }
+    fn as_any(&self) -> &dyn any::Any { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any { self }
     #[inline]
     fn as_i64(&self) -> Option<i64> { let $i = *self; $ii }
     #[inline]
     fn as_u64(&self) -> Option<u64> { let $u = *self; $uu }
     #[inline]
     fn as_f64(&self) -> Option<f64> { let $fff = *self; $ff }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { Box::new(self.clone()) }
+    fn array_clone(v: &[Self]) -> Option<Box<dyn RefArg + 'static>> where Self: Sized { Some(Box::new(v.to_vec())) }
 }
 
 impl DictKey for $t {}
 unsafe impl FixedArray for $t {}
 
 }} // End of macro_rules
 
-integer_impl!(u8, Byte, b"y\0", i, Some(i as i64),    u, Some(u as u64), f, Some(f as f64));
-integer_impl!(i16, Int16, b"n\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
-integer_impl!(u16, UInt16, b"q\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
-integer_impl!(i32, Int32, b"i\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
-integer_impl!(u32, UInt32, b"u\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
-integer_impl!(i64, Int64, b"x\0", i, Some(i),         _u, None,          _f, None);
-integer_impl!(u64, UInt64, b"t\0", _i, None,          u, Some(u as u64), _f, None);
+integer_impl!(u8, Byte, "y\0", i, Some(i as i64),    u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i16, Int16, "n\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
+integer_impl!(u16, UInt16, "q\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i32, Int32, "i\0", i, Some(i as i64),  _u, None,          f, Some(f as f64));
+integer_impl!(u32, UInt32, "u\0", i, Some(i as i64), u, Some(u as u64), f, Some(f as f64));
+integer_impl!(i64, Int64, "x\0", i, Some(i),         _u, None,          _f, None);
+integer_impl!(u64, UInt64, "t\0", _i, None,          u, Some(u as u64), _f, None);
 
 
 macro_rules! refarg_impl {
     ($t: ty, $i: ident, $ii: expr, $ss: expr, $uu: expr, $ff: expr) => {
 
 impl RefArg for $t {
     #[inline]
     fn arg_type(&self) -> ArgType { <$t as Arg>::ARG_TYPE }
     #[inline]
     fn signature(&self) -> Signature<'static> { <$t as Arg>::signature() }
     #[inline]
-    fn append(&self, i: &mut IterAppend) { <$t as Append>::append(self.clone(), i) }
+    fn append(&self, i: &mut IterAppend) { <$t as Append>::append_by_ref(self, i) }
     #[inline]
-    fn as_any(&self) -> &any::Any { self }
+    fn as_any(&self) -> &dyn any::Any { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any { self }
     #[inline]
     fn as_i64(&self) -> Option<i64> { let $i = self; $ii }
     #[inline]
     fn as_u64(&self) -> Option<u64> { let $i = self; $uu }
     #[inline]
     fn as_f64(&self) -> Option<f64> { let $i = self; $ff }
     #[inline]
     fn as_str(&self) -> Option<&str> { let $i = self; $ss }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { Box::new(self.clone()) }
+    fn array_clone(v: &[Self]) -> Option<Box<dyn RefArg + 'static>> where Self: Sized { Some(Box::new(v.to_vec())) }
+
 }
 
     }
 }
 
 
 impl Arg for bool {
     const ARG_TYPE: ArgType = ArgType::Boolean;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"b\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("b\0") } }
 }
 impl Append for bool {
-    fn append(self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::Boolean, if self {1} else {0}) }
+    fn append_by_ref(&self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::Boolean, if *self {1} else {0}) }
 }
 impl DictKey for bool {}
 impl<'a> Get<'a> for bool {
     fn get(i: &mut Iter) -> Option<Self> { arg_get_basic::<u32>(&mut i.0, ArgType::Boolean).map(|q| q != 0) }
 }
 
 refarg_impl!(bool, _i, Some(if *_i { 1 } else { 0 }), None, Some(if *_i { 1 as u64 } else { 0 as u64 }), Some(if *_i { 1 as f64 } else { 0 as f64 }));
 
 impl Arg for f64 {
     const ARG_TYPE: ArgType = ArgType::Double;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"d\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("d\0") } }
 }
 impl Append for f64 {
-    fn append(self, i: &mut IterAppend) { arg_append_f64(&mut i.0, ArgType::Double, self) }
+    fn append_by_ref(&self, i: &mut IterAppend) { arg_append_basic(&mut i.0, ArgType::Double, *self) }
 }
 impl DictKey for f64 {}
 impl<'a> Get<'a> for f64 {
-    fn get(i: &mut Iter) -> Option<Self> { arg_get_f64(&mut i.0, ArgType::Double) }
+    fn get(i: &mut Iter) -> Option<Self> { arg_get_basic(&mut i.0, ArgType::Double) }
 }
 unsafe impl FixedArray for f64 {}
 
 refarg_impl!(f64, _i, None, None, None, Some(*_i));
 
 /// Represents a D-Bus string.
 impl<'a> Arg for &'a str {
     const ARG_TYPE: ArgType = ArgType::String;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("s\0") } }
 }
 
 impl<'a> Append for &'a str {
-    fn append(self, i: &mut IterAppend) {
+    fn append_by_ref(&self, i: &mut IterAppend) {
         use std::borrow::Cow;
         let b: &[u8] = self.as_bytes();
-        let v: Cow<[u8]> = if b.len() > 0 && b[b.len()-1] == 0 { Cow::Borrowed(b) }
+        let v: Cow<[u8]> = if !b.is_empty() && b[b.len()-1] == 0 { Cow::Borrowed(b) }
         else {
             let mut bb: Vec<u8> = b.into();
             bb.push(0);
             Cow::Owned(bb)
         };
         let z = unsafe { CStr::from_ptr(v.as_ptr() as *const c_char) };
         arg_append_str(&mut i.0, ArgType::String, &z)
     }
@@ -193,36 +181,39 @@ impl<'a> Append for &'a str {
 impl<'a> DictKey for &'a str {}
 impl<'a> Get<'a> for &'a str {
     fn get(i: &mut Iter<'a>) -> Option<&'a str> { unsafe { arg_get_str(&mut i.0, ArgType::String) }
         .and_then(|s| s.to_str().ok()) }
 }
 
 impl<'a> Arg for String {
     const ARG_TYPE: ArgType = ArgType::String;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("s\0") } }
 }
 impl<'a> Append for String {
     fn append(mut self, i: &mut IterAppend) {
         self.push_str("\0");
         let s: &str = &self;
         s.append(i)
     }
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        (&**self).append_by_ref(i)
+    }
 }
 impl<'a> DictKey for String {}
 impl<'a> Get<'a> for String {
-    fn get(i: &mut Iter<'a>) -> Option<String> { <&str>::get(i).map(|s| String::from(s)) }
+    fn get(i: &mut Iter<'a>) -> Option<String> { <&str>::get(i).map(String::from) }
 }
 
 refarg_impl!(String, _i, None, Some(&_i), None, None);
 
 /// Represents a D-Bus string.
 impl<'a> Arg for &'a CStr {
     const ARG_TYPE: ArgType = ArgType::String;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"s\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("s\0") } }
 }
 
 /*
 /// Note: Will give D-Bus errors in case the CStr is not valid UTF-8.
 impl<'a> Append for &'a CStr {
     fn append(self, i: &mut IterAppend) {
         arg_append_str(&mut i.0, Self::arg_type(), &self)
     }
@@ -231,78 +222,141 @@ impl<'a> Append for &'a CStr {
 
 impl<'a> DictKey for &'a CStr {}
 impl<'a> Get<'a> for &'a CStr {
     fn get(i: &mut Iter<'a>) -> Option<&'a CStr> { unsafe { arg_get_str(&mut i.0, Self::ARG_TYPE) }}
 }
 
 impl Arg for OwnedFd {
     const ARG_TYPE: ArgType = ArgType::UnixFd;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"h\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("h\0") } }
 }
 impl Append for OwnedFd {
-    fn append(self, i: &mut IterAppend) {
-        use std::os::unix::io::AsRawFd;
+    #[cfg(unix)]
+    fn append_by_ref(&self, i: &mut IterAppend) {
         arg_append_basic(&mut i.0, ArgType::UnixFd, self.as_raw_fd())
     }
+    #[cfg(windows)]
+    fn append_by_ref(&self, _i: &mut IterAppend) {
+        panic!("File descriptor passing not available on Windows");
+    }
 }
 impl DictKey for OwnedFd {}
 impl<'a> Get<'a> for OwnedFd {
+    #[cfg(unix)]
     fn get(i: &mut Iter) -> Option<Self> {
-        arg_get_basic(&mut i.0, ArgType::UnixFd).map(|q| OwnedFd::new(q)) 
+        arg_get_basic(&mut i.0, ArgType::UnixFd).map(|fd| unsafe { OwnedFd::new(fd) })
+    }
+    #[cfg(windows)]
+    fn get(_i: &mut Iter) -> Option<Self> {
+        None
     }
 }
 
+#[cfg(unix)]
 refarg_impl!(OwnedFd, _i, { use std::os::unix::io::AsRawFd; Some(_i.as_raw_fd() as i64) }, None, None, None);
 
+#[cfg(windows)]
+refarg_impl!(OwnedFd, _i, None, None, None, None);
+
+impl Arg for File {
+    const ARG_TYPE: ArgType = ArgType::UnixFd;
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("h\0") } }
+}
+impl Append for File {
+    #[cfg(unix)]
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        arg_append_basic(&mut i.0, ArgType::UnixFd, self.as_raw_fd())
+    }
+    #[cfg(windows)]
+    fn append_by_ref(&self, _i: &mut IterAppend) {
+        panic!("File descriptor passing not available on Windows");
+    }
+}
+impl DictKey for File {}
+impl<'a> Get<'a> for File {
+    #[cfg(unix)]
+    fn get(i: &mut Iter) -> Option<Self> {
+        arg_get_basic(&mut i.0, ArgType::UnixFd).map(|fd| unsafe { File::from_raw_fd(fd) })
+    }
+    #[cfg(windows)]
+    fn get(_i: &mut Iter) -> Option<Self> {
+        None
+    }
+}
+
+impl RefArg for File {
+    #[inline]
+    fn arg_type(&self) -> ArgType { <File as Arg>::ARG_TYPE }
+    #[inline]
+    fn signature(&self) -> Signature<'static> { <File as Arg>::signature() }
+    #[inline]
+    fn append(&self, i: &mut IterAppend) { <File as Append>::append_by_ref(self, i) }
+    #[inline]
+    fn as_any(&self) -> &dyn any::Any { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut dyn any::Any { self }
+    #[cfg(unix)]
+    #[inline]
+    fn as_i64(&self) -> Option<i64> { Some(self.as_raw_fd() as i64) }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { Box::new(self.try_clone().unwrap()) }
+}
+
+
 macro_rules! string_impl {
     ($t: ident, $s: ident, $f: expr) => {
 
 impl<'a> Arg for $t<'a> {
     const ARG_TYPE: ArgType = ArgType::$s;
     fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
 }
 
 impl RefArg for $t<'static> {
     fn arg_type(&self) -> ArgType { ArgType::$s }
     fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked($f) } }
     fn append(&self, i: &mut IterAppend) { arg_append_str(&mut i.0, ArgType::$s, self.as_cstr()) }
     #[inline]
-    fn as_any(&self) -> &any::Any { self }
+    fn as_any(&self) -> &dyn any::Any { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any { self }
     #[inline]
     fn as_str(&self) -> Option<&str> { Some(self) }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone().into_static()) }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { Box::new(self.clone().into_static()) }
+    fn array_clone(v: &[Self]) -> Option<Box<dyn RefArg + 'static>> where Self: Sized { Some(Box::new(v.to_vec())) }
 }
 
 impl<'a> DictKey for $t<'a> {}
 
 impl<'a> Append for $t<'a> {
-    fn append(self, i: &mut IterAppend) {
+    fn append_by_ref(&self, i: &mut IterAppend) {
         arg_append_str(&mut i.0, ArgType::$s, self.as_cstr())
     }
 }
 
 /*
 
 Unfortunately, this does not work because it conflicts with getting a $t<'static>.
 
 impl<'a> Get<'a> for $t<'a> {
     fn get(i: &mut Iter<'a>) -> Option<$t<'a>> { unsafe { arg_get_str(&mut i.0, ArgType::$s) }
         .map(|s| unsafe { $t::from_slice_unchecked(s.to_bytes_with_nul()) } ) }
 }
 */
 
 impl<'a> Get<'a> for $t<'static> {
     fn get(i: &mut Iter<'a>) -> Option<$t<'static>> { unsafe {
-        arg_get_str(&mut i.0, ArgType::$s).map(|s| $t::from_slice_unchecked(s.to_bytes_with_nul()).into_static())
+        let c = arg_get_str(&mut i.0, ArgType::$s)?;
+        let s = std::str::from_utf8(c.to_bytes_with_nul()).ok()?;
+        Some($t::from_slice_unchecked(s).into_static())
     }}
 }
 
 
     }
 }
 
-string_impl!(Path, ObjectPath, b"o\0");
-string_impl!(Signature, Signature, b"g\0");
-
+string_impl!(Interface, String, "s\0");
+string_impl!(ErrorName, String, "s\0");
+string_impl!(Member, String, "s\0");
+string_impl!(Path, ObjectPath, "o\0");
+string_impl!(Signature, Signature, "g\0");
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/arg/messageitem.rs
@@ -0,0 +1,974 @@
+//! MessageItem - old, enum design that is used as parameters and return values from
+//! method calls, or as data added to a signal.
+//!
+//! Note that the newer generic design (see `arg` module) is, in general, both faster
+//! and smaller than MessageItem, and should be your first hand choice
+//! whenever applicable. There is also a trait object design called `RefArg` in
+//! case the generic design is too inflexible.
+
+use crate::strings::{Signature, Path, Interface, BusName};
+
+use crate::arg;
+use crate::arg::{Iter, IterAppend, Arg, ArgType};
+use crate::arg::OwnedFd;
+use std::ffi::CStr;
+use std::{ops, any};
+
+use crate::{ffidisp::Connection, Message, Error};
+use std::collections::BTreeMap;
+use std::convert::TryFrom;
+
+#[derive(Debug,Copy,Clone)]
+/// Errors that can happen when creating a MessageItem::Array.
+pub enum ArrayError {
+    /// The array is empty.
+    EmptyArray,
+    /// The array is composed of different element types.
+    DifferentElementTypes,
+    /// The supplied signature is not a valid array signature
+    InvalidSignature,
+}
+
+
+#[derive(Debug, Clone, PartialEq, PartialOrd)]
+/// An array of MessageItem where every MessageItem is of the same type.
+pub struct MessageItemArray {
+    v: Vec<MessageItem>,
+    // signature includes the "a"!
+    sig: Signature<'static>,
+}
+
+impl MessageItemArray {
+    /// Creates a new array where every element has the supplied signature.
+    ///
+    /// Signature is the full array signature, not the signature of the element.
+    pub fn new(v: Vec<MessageItem>, sig: Signature<'static>) -> Result<MessageItemArray, ArrayError> {
+        let a = MessageItemArray {v: v, sig: sig };
+        if a.sig.as_bytes()[0] != ffi::DBUS_TYPE_ARRAY as u8 { return Err(ArrayError::InvalidSignature) }
+        {
+            let esig = a.element_signature();
+            for i in &a.v {
+                if i.signature().as_cstr() != esig { return Err(ArrayError::DifferentElementTypes) }
+            }
+        }
+        Ok(a)
+    }
+
+    fn element_signature(&self) -> &CStr {
+        let z = &self.sig.as_cstr().to_bytes_with_nul()[1..];
+        unsafe { CStr::from_bytes_with_nul_unchecked(z) }
+    }
+
+    fn make_sig(m: &MessageItem) -> Signature<'static> {
+        Signature::new(format!("a{}", m.signature())).unwrap()
+    }
+
+    /// Signature of array (full array signature)
+    pub fn signature(&self) -> &Signature<'static> { &self.sig }
+
+    /// Consumes the MessageItemArray in order to allow you to modify the individual items of the array.
+    pub fn into_vec(self) -> Vec<MessageItem> { self.v }
+}
+
+impl ops::Deref for MessageItemArray {
+    type Target = [MessageItem];
+    fn deref(&self) -> &Self::Target { &self.v }
+}
+
+impl arg::Append for MessageItemArray {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        i.append_container(ArgType::Array, Some(self.element_signature()), |s| {
+            for a in &self.v { a.append_by_ref(s) }
+        });
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, PartialOrd)]
+/// An array of MessageItem where every MessageItem is of the same type.
+pub struct MessageItemDict {
+    v: Vec<(MessageItem, MessageItem)>,
+    // signature includes the "a"!
+    sig: Signature<'static>,
+}
+
+impl MessageItemDict {
+    /// Creates a new dict where every key and value elements have the supplied signature.
+    pub fn new(v: Vec<(MessageItem, MessageItem)>, keysig: Signature<'static>, valuesig: Signature<'static>) -> Result<MessageItemDict, ArrayError> {
+        let sig = Signature::from(format!("a{{{}{}}}", keysig, valuesig));
+        let a = MessageItemDict {v: v, sig: sig };
+        for (k, v) in &a.v {
+            if keysig != k.signature() || valuesig != v.signature() {
+                return Err(ArrayError::DifferentElementTypes);
+            }
+        }
+        Ok(a)
+    }
+
+    fn element_signature(&self) -> &CStr {
+        let z = &self.sig.as_cstr().to_bytes_with_nul()[1..];
+        unsafe { CStr::from_bytes_with_nul_unchecked(z) }
+    }
+
+    /// Signature of array (full array signature)
+    pub fn signature(&self) -> &Signature<'static> { &self.sig }
+
+    /// Consumes the MessageItemDict in order to allow you to modify the individual items of the dict.
+    pub fn into_vec(self) -> Vec<(MessageItem, MessageItem)> { self.v }
+}
+
+impl ops::Deref for MessageItemDict {
+    type Target = [(MessageItem, MessageItem)];
+    fn deref(&self) -> &Self::Target { &self.v }
+}
+
+impl arg::Append for MessageItemDict {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        i.append_container(ArgType::Array, Some(self.element_signature()), |s| {
+            for (k, v) in &self.v {
+                s.append_container(ArgType::DictEntry, None, |ss| {
+                    k.append_by_ref(ss);
+                    v.append_by_ref(ss);
+                });
+            }
+        });
+    }
+}
+
+/// MessageItem - used as parameters and return values from
+/// method calls, or as data added to a signal (old, enum version).
+///
+/// Note that the newer generic design (see `arg` module) is both faster
+/// and less error prone than MessageItem, and should be your first hand choice
+/// whenever applicable.
+#[derive(Debug, PartialEq, PartialOrd, Clone)]
+pub enum MessageItem {
+    /// A D-Bus array requires all elements to be of the same type.
+    /// All elements must match the Signature.
+    Array(MessageItemArray),
+    /// A D-Bus struct allows for values of different types.
+    Struct(Vec<MessageItem>),
+    /// A D-Bus variant is a wrapper around another `MessageItem`, which
+    /// can be of any type.
+    Variant(Box<MessageItem>),
+    /// A D-Bus dictionary. All keys and values are required to be of the same type.
+    /// Not all types can be dictionary keys, but all can be dictionary values.
+    Dict(MessageItemDict),
+    /// A D-Bus objectpath requires its content to be a valid objectpath,
+    /// so this cannot be any string.
+    ObjectPath(Path<'static>),
+    /// A D-Bus signature requires its content to be a valid type signature,
+    /// so this cannot be any string.
+    Signature(Signature<'static>),
+    /// A D-Bus String is zero terminated, so no \0 s in the String, please.
+    /// (D-Bus strings are also - like Rust strings - required to be valid UTF-8.)
+    Str(String),
+    /// A D-Bus boolean type.
+    Bool(bool),
+    /// A D-Bus unsigned 8 bit type.
+    Byte(u8),
+    /// A D-Bus signed 16 bit type.
+    Int16(i16),
+    /// A D-Bus signed 32 bit type.
+    Int32(i32),
+    /// A D-Bus signed 64 bit type.
+    Int64(i64),
+    /// A D-Bus unsigned 16 bit type.
+    UInt16(u16),
+    /// A D-Bus unsigned 32 bit type.
+    UInt32(u32),
+    /// A D-Bus unsigned 64 bit type.
+    UInt64(u64),
+    /// A D-Bus IEEE-754 double-precision floating point type.
+    Double(f64),
+    /// D-Bus allows for sending file descriptors, which can be used to
+    /// set up SHM, unix pipes, or other communication channels.
+    UnixFd(OwnedFd),
+}
+
+impl MessageItem {
+    /// Get the D-Bus Signature for this MessageItem.
+    pub fn signature(&self) -> Signature<'static> {
+        use crate::arg::Variant;
+        match self {
+            MessageItem::Str(_) => <String as Arg>::signature(),
+            MessageItem::Bool(_) => <bool as Arg>::signature(),
+            MessageItem::Byte(_) => <u8 as Arg>::signature(),
+            MessageItem::Int16(_) => <i16 as Arg>::signature(),
+            MessageItem::Int32(_) => <i32 as Arg>::signature(),
+            MessageItem::Int64(_) => <i64 as Arg>::signature(),
+            MessageItem::UInt16(_) => <u16 as Arg>::signature(),
+            MessageItem::UInt32(_) => <u32 as Arg>::signature(),
+            MessageItem::UInt64(_) => <u64 as Arg>::signature(),
+            MessageItem::Double(_) => <f64 as Arg>::signature(),
+            MessageItem::Array(ref a) => a.sig.clone(),
+            MessageItem::Struct(ref s) => Signature::new(format!("({})", s.iter().fold(String::new(), |s, i| s + &*i.signature()))).unwrap(),
+            MessageItem::Variant(_) => <Variant<u8> as Arg>::signature(),
+            MessageItem::Dict(ref a) => a.sig.clone(),
+            MessageItem::ObjectPath(_) => <Path as Arg>::signature(),
+            MessageItem::Signature(_) => <Signature as Arg>::signature(),
+            MessageItem::UnixFd(_) => <std::fs::File as Arg>::signature(),
+        }
+    }
+
+    /// Get the arg type of this MessageItem.
+    pub fn arg_type(&self) -> arg::ArgType {
+        match self {
+            MessageItem::Str(_) => ArgType::String,
+            MessageItem::Bool(_) => ArgType::Boolean,
+            MessageItem::Byte(_) => ArgType::Byte,
+            MessageItem::Int16(_) => ArgType::Int16,
+            MessageItem::Int32(_) => ArgType::Int32,
+            MessageItem::Int64(_) => ArgType::Int64,
+            MessageItem::UInt16(_) => ArgType::UInt16,
+            MessageItem::UInt32(_) => ArgType::UInt32,
+            MessageItem::UInt64(_) => ArgType::UInt64,
+            MessageItem::Double(_) => ArgType::Double,
+            MessageItem::Array(_) => ArgType::Array,
+            MessageItem::Struct(_) => ArgType::Struct,
+            MessageItem::Variant(_) => ArgType::Variant,
+            MessageItem::Dict(_) => ArgType::Array,
+            MessageItem::ObjectPath(_) => ArgType::ObjectPath,
+            MessageItem::Signature(_) => ArgType::Signature,
+            MessageItem::UnixFd(_) => ArgType::UnixFd,
+        }
+    }
+
+    /// Creates a (String, Variant) dictionary from an iterator with Result passthrough (an Err will abort and return that Err)
+    pub fn from_dict<E, I: Iterator<Item=Result<(String, MessageItem),E>>>(i: I) -> Result<MessageItem, E> {
+        let mut v = Vec::new();
+        for r in i {
+            let (s, vv) = r?;
+            v.push((s.into(), Box::new(vv).into()));
+        }
+        Ok(MessageItem::Dict(MessageItemDict::new(v, Signature::new("s").unwrap(), Signature::new("v").unwrap()).unwrap()))
+    }
+
+    /// Creates an MessageItem::Array from a list of MessageItems.
+    ///
+    /// Note: This requires `v` to be non-empty. See also
+    /// `MessageItem::from(&[T])`, which can handle empty arrays as well.
+    pub fn new_array(v: Vec<MessageItem>) -> Result<MessageItem, ArrayError> {
+        if v.is_empty() {
+            return Err(ArrayError::EmptyArray);
+        }
+        let s = MessageItemArray::make_sig(&v[0]);
+        Ok(MessageItem::Array(MessageItemArray::new(v, s)?))
+    }
+
+    /// Creates an MessageItem::Dict from a list of MessageItem pairs.
+    ///
+    /// Note: This requires `v` to be non-empty. See also
+    /// `MessageItem::from(&[(T1, T2)])`, which can handle empty arrays as well.
+    pub fn new_dict(v: Vec<(MessageItem, MessageItem)>) -> Result<MessageItem, ArrayError> {
+        if v.is_empty() {
+            return Err(ArrayError::EmptyArray);
+        }
+        let (s1, s2) = (v[0].0.signature(), v[0].1.signature());
+        Ok(MessageItem::Dict(MessageItemDict::new(v, s1, s2)?))
+    }
+
+    /// Get the inner value of a `MessageItem`
+    ///
+    /// # Example
+    /// ```
+    /// use dbus::arg::messageitem::MessageItem;
+    /// let m: MessageItem = 5i64.into();
+    /// let s: i64 = m.inner().unwrap();
+    /// assert_eq!(s, 5i64);
+    /// ```
+    pub fn inner<'a, T: TryFrom<&'a MessageItem>>(&'a self) -> Result<T, T::Error> {
+        T::try_from(self)
+    }
+
+    /// Get the underlying `MessageItem` of a `MessageItem::Variant`
+    ///
+    /// Nested `MessageItem::Variant`s are unwrapped recursively until a
+    /// non-`Variant` is found.
+    ///
+    /// # Example
+    /// ```
+    /// use dbus::arg::messageitem::MessageItem;
+    /// let nested = MessageItem::Variant(Box::new(6i64.into()));
+    /// let flat: MessageItem = 6i64.into();
+    /// assert_ne!(&nested, &flat);
+    /// assert_eq!(nested.peel(), &flat);
+    /// ```
+    pub fn peel(&self) -> &Self {
+        let mut current = self;
+
+        while let MessageItem::Variant(b) = current {
+            current = &*b;
+        }
+
+        current
+    }
+
+    fn new_array2<D, I>(i: I) -> MessageItem
+    where D: Into<MessageItem>, D: Default, I: Iterator<Item=D> {
+        let v: Vec<MessageItem> = i.map(|ii| ii.into()).collect();
+        let s = {
+            let d;
+            let t = if v.is_empty() { d = D::default().into(); &d } else { &v[0] };
+            MessageItemArray::make_sig(t)
+        };
+        MessageItem::Array(MessageItemArray::new(v, s).unwrap())
+    }
+
+    fn new_dict2<K, V, I>(i: I) -> MessageItem
+    where K: Into<MessageItem> + Default, V: Into<MessageItem> + Default, I: Iterator<Item=(K, V)> {
+        let v: Vec<(MessageItem, MessageItem)> = i.map(|(k, v)| (k.into(), v.into())).collect();
+        let (kt, vt) = if v.is_empty() {
+            let kd = K::default().into();
+            let vd = V::default().into();
+            (kd.signature(), vd.signature())
+        } else { (v[0].0.signature(), v[0].1.signature()) };
+        MessageItem::Dict(MessageItemDict::new(v, kt, vt).unwrap())
+    }
+}
+
+macro_rules! msgitem_convert {
+    ($t: ty, $s: ident) => {
+        impl From<$t> for MessageItem { fn from(i: $t) -> MessageItem { MessageItem::$s(i) } }
+
+        impl<'a> TryFrom<&'a MessageItem> for $t {
+            type Error = ();
+            fn try_from(i: &'a MessageItem) -> Result<$t,()> {
+                if let MessageItem::$s(b) = i.peel() { Ok(*b) } else { Err(()) }
+            }
+        }
+    }
+}
+
+msgitem_convert!(u8, Byte);
+msgitem_convert!(u64, UInt64);
+msgitem_convert!(u32, UInt32);
+msgitem_convert!(u16, UInt16);
+msgitem_convert!(i16, Int16);
+msgitem_convert!(i32, Int32);
+msgitem_convert!(i64, Int64);
+msgitem_convert!(f64, Double);
+msgitem_convert!(bool, Bool);
+
+
+
+/// Create a `MessageItem::Array`.
+impl<'a, T> From<&'a [T]> for MessageItem
+where T: Into<MessageItem> + Clone + Default {
+    fn from(i: &'a [T]) -> MessageItem {
+        MessageItem::new_array2(i.iter().cloned())
+    }
+}
+
+/// Create a `MessageItem::Dict`.
+impl<'a, T1, T2> From<&'a [(T1, T2)]> for MessageItem
+where T1: Into<MessageItem> + Clone + Default, T2: Into<MessageItem> + Clone + Default {
+    fn from(i: &'a [(T1, T2)]) -> MessageItem {
+        MessageItem::new_dict2(i.iter().cloned())
+    }
+}
+
+impl<'a> From<&'a str> for MessageItem { fn from(i: &str) -> MessageItem { MessageItem::Str(i.to_string()) } }
+
+impl From<String> for MessageItem { fn from(i: String) -> MessageItem { MessageItem::Str(i) } }
+
+impl From<Path<'static>> for MessageItem { fn from(i: Path<'static>) -> MessageItem { MessageItem::ObjectPath(i) } }
+
+impl From<Signature<'static>> for MessageItem { fn from(i: Signature<'static>) -> MessageItem { MessageItem::Signature(i) } }
+
+impl From<OwnedFd> for MessageItem { fn from(i: OwnedFd) -> MessageItem { MessageItem::UnixFd(i) } }
+
+/// Create a `MessageItem::Variant`
+impl From<Box<MessageItem>> for MessageItem {
+    fn from(i: Box<MessageItem>) -> MessageItem { MessageItem::Variant(i) }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a str {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a str, Self::Error> {
+        match i.peel() {
+            MessageItem::Str(ref b) => Ok(b),
+            MessageItem::ObjectPath(ref b) => Ok(b),
+            MessageItem::Signature(ref b) => Ok(b),
+            _ => Err(()),
+        }
+    }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a String {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a String,()> { if let MessageItem::Str(b) = i.peel() { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a Path<'static> {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a Path<'static>,()> { if let MessageItem::ObjectPath(b) = i.peel() { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a Signature<'static> {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a Signature<'static>,()> { if let MessageItem::Signature(b) = i.peel() { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a Box<MessageItem> {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a Box<MessageItem>,()> { if let MessageItem::Variant(b) = i { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a Vec<MessageItem> {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a Vec<MessageItem>,()> {
+        match i.peel() {
+            MessageItem::Array(b) => Ok(&b.v),
+            MessageItem::Struct(b) => Ok(b),
+            _ => Err(()),
+        }
+    }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a [MessageItem] {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a [MessageItem],()> { i.inner::<&Vec<MessageItem>>().map(|s| &**s) }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a OwnedFd {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a OwnedFd,()> { if let MessageItem::UnixFd(ref b) = i { Ok(b) } else { Err(()) } }
+}
+
+impl<'a> TryFrom<&'a MessageItem> for &'a [(MessageItem, MessageItem)] {
+    type Error = ();
+    fn try_from(i: &'a MessageItem) -> Result<&'a [(MessageItem, MessageItem)],()> {
+        if let MessageItem::Dict(ref d) = i { Ok(&*d.v) } else { Err(()) }
+    }
+}
+
+
+impl arg::Append for MessageItem {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        match self {
+            MessageItem::Str(a) => a.append_by_ref(i),
+            MessageItem::Bool(a) => a.append_by_ref(i),
+            MessageItem::Byte(a) => a.append_by_ref(i),
+            MessageItem::Int16(a) => a.append_by_ref(i),
+            MessageItem::Int32(a) => a.append_by_ref(i),
+            MessageItem::Int64(a) => a.append_by_ref(i),
+            MessageItem::UInt16(a) => a.append_by_ref(i),
+            MessageItem::UInt32(a) => a.append_by_ref(i),
+            MessageItem::UInt64(a) => a.append_by_ref(i),
+            MessageItem::Double(a) => a.append_by_ref(i),
+            MessageItem::Array(a) => a.append_by_ref(i),
+            MessageItem::Struct(a) => i.append_container(ArgType::Struct, None, |s| {
+                for v in a { v.append_by_ref(s); }
+            }),
+            MessageItem::Variant(a) => {
+                i.append_container(ArgType::Variant, Some(a.signature().as_cstr()), |s| a.append_by_ref(s))
+            },
+            MessageItem::Dict(a) => a.append_by_ref(i),
+            MessageItem::ObjectPath(a) => a.append_by_ref(i),
+            MessageItem::Signature(a) => a.append_by_ref(i),
+            MessageItem::UnixFd(a) => a.append_by_ref(i),
+        }
+    }
+}
+
+impl<'a> arg::Get<'a> for MessageItem {
+    fn get(i: &mut Iter<'a>) -> Option<Self> {
+        Some(match i.arg_type() {
+            ArgType::Array => {
+                let mut s = i.recurse(ArgType::Array).unwrap();
+                if i.signature().as_bytes()[1] == b'{' { // Dict
+                    let mut v = vec!();
+                    while s.arg_type() == ArgType::DictEntry {
+                        let mut ss = s.recurse(ArgType::DictEntry).unwrap();
+                        let kk = MessageItem::get(&mut ss).unwrap();
+                        ss.next();
+                        let vv = MessageItem::get(&mut ss).unwrap();
+                        v.push((kk, vv));
+                        s.next();
+                    };
+                    MessageItem::Dict(MessageItemDict { v: v, sig:  i.signature() })
+                } else {
+                    let mut v = vec!();
+                    while let Some(mi) = MessageItem::get(&mut s) { v.push(mi); s.next(); };
+                    MessageItem::Array(MessageItemArray { v: v, sig: i.signature() })
+                }
+            },
+            ArgType::Variant => MessageItem::Variant({
+                let mut s = i.recurse(ArgType::Variant).unwrap();
+                Box::new(MessageItem::get(&mut s).unwrap())
+            }),
+            ArgType::Boolean => MessageItem::Bool(i.get::<bool>().unwrap()),
+            ArgType::Invalid => return None,
+            ArgType::String => MessageItem::Str(i.get::<String>().unwrap()),
+            ArgType::DictEntry => return None,
+            ArgType::Byte => MessageItem::Byte(i.get::<u8>().unwrap()),
+            ArgType::Int16 => MessageItem::Int16(i.get::<i16>().unwrap()),
+            ArgType::UInt16 => MessageItem::UInt16(i.get::<u16>().unwrap()),
+            ArgType::Int32 => MessageItem::Int32(i.get::<i32>().unwrap()),
+            ArgType::UInt32 => MessageItem::UInt32(i.get::<u32>().unwrap()),
+            ArgType::Int64 => MessageItem::Int64(i.get::<i64>().unwrap()),
+            ArgType::UInt64 => MessageItem::UInt64(i.get::<u64>().unwrap()),
+            ArgType::Double => MessageItem::Double(i.get::<f64>().unwrap()),
+            ArgType::UnixFd => MessageItem::UnixFd(i.get::<OwnedFd>().unwrap()),
+            ArgType::Struct => MessageItem::Struct({
+                let mut s = i.recurse(ArgType::Struct).unwrap();
+                let mut v = vec!();
+                while let Some(mi) = MessageItem::get(&mut s) { v.push(mi); s.next(); };
+                v
+            }),
+            ArgType::ObjectPath => MessageItem::ObjectPath(i.get::<Path>().unwrap().into_static()),
+            ArgType::Signature => MessageItem::Signature(i.get::<Signature>().unwrap().into_static()),
+        })
+    }
+}
+
+impl arg::RefArg for MessageItem {
+    fn arg_type(&self) -> ArgType { MessageItem::arg_type(&self) }
+    fn signature(&self) -> Signature<'static> { MessageItem::signature(&self) }
+    fn append(&self, i: &mut IterAppend) { arg::Append::append_by_ref(self, i) }
+    #[inline]
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
+    #[inline]
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn arg::RefArg + 'static> { Box::new(self.clone()) }
+}
+
+
+impl arg::Append for arg::Variant<MessageItem> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        let z = &self.0;
+        let asig = z.signature();
+        let sig = asig.as_cstr();
+        i.append_container(ArgType::Variant, Some(&sig), |s| z.append_by_ref(s));
+    }
+}
+
+
+/// Client side properties - get and set properties on a remote application.
+pub struct Props<'a> {
+    name: BusName<'a>,
+    path: Path<'a>,
+    interface: Interface<'a>,
+    timeout_ms: i32,
+    conn: &'a Connection,
+}
+
+impl<'a> Props<'a> {
+    /// Create a new Props.
+    pub fn new<N, P, I>(conn: &'a Connection, name: N, path: P, interface: I, timeout_ms: i32) -> Props<'a>
+    where N: Into<BusName<'a>>, P: Into<Path<'a>>, I: Into<Interface<'a>> {
+        Props {
+            name: name.into(),
+            path: path.into(),
+            interface: interface.into(),
+            timeout_ms: timeout_ms,
+            conn: conn,
+        }
+    }
+
+    /// Get a single property's value.
+    pub fn get(&self, propname: &str) -> Result<MessageItem, Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"Get".into());
+        m.append_items(&[self.interface.to_string().into(), propname.to_string().into()]);
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        let reply = r.as_result()?.get_items();
+        if reply.len() == 1 {
+            if let MessageItem::Variant(ref v) = reply[0] {
+                return Ok((**v).clone())
+            }
+       }
+       let f = format!("Invalid reply for property get {}: '{:?}'", propname, reply);
+       Err(Error::new_custom("InvalidReply", &f))
+    }
+
+    /// Set a single property's value.
+    pub fn set(&self, propname: &str, value: MessageItem) -> Result<(), Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"Set".into());
+        m.append_items(&[self.interface.to_string().into(), propname.to_string().into(), Box::new(value).into()]);
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        r.as_result()?;
+        Ok(())
+    }
+
+    /// Get a map of all the properties' names and their values.
+    pub fn get_all(&self) -> Result<BTreeMap<String, MessageItem>, Error> {
+        let mut m = Message::method_call(&self.name, &self.path,
+            &"org.freedesktop.DBus.Properties".into(), &"GetAll".into());
+        m.append_items(&[self.interface.to_string().into()]);
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        let reply = r.as_result()?.get_items();
+
+        (|| {
+            if reply.len() != 1 { return Err(()) };
+            let mut tree = BTreeMap::new();
+            let a: &[(MessageItem, MessageItem)] = reply[0].inner()?;
+            for (k, v) in a.iter() {
+                let (k, v): (&String, &Box<MessageItem>) = (k.inner()?, v.inner()?);
+                tree.insert(k.clone(), *v.clone());
+            }
+            Ok(tree)
+        })().map_err(|_| {
+            let f = format!("Invalid reply for property GetAll: '{:?}'", reply);
+            Error::new_custom("InvalidReply", &f)
+        })
+    }
+}
+
+/// Wrapper around Props that keeps a map of fetched properties.
+pub struct PropHandler<'a> {
+    p: Props<'a>,
+    map: BTreeMap<String, MessageItem>,
+}
+
+impl<'a> PropHandler<'a> {
+    /// Create a new PropHandler from a Props.
+    pub fn new(p: Props) -> PropHandler {
+        PropHandler { p: p, map: BTreeMap::new() }
+    }
+
+    /// Get a map of all the properties' names and their values.
+    pub fn get_all(&mut self) -> Result<(), Error> {
+        self.map = self.p.get_all()?;
+        Ok(())
+    }
+
+    /// Get a mutable reference to the PropHandler's fetched properties.
+    pub fn map_mut(&mut self) -> &mut BTreeMap<String, MessageItem> { &mut self.map }
+
+    /// Get a reference to the PropHandler's fetched properties.
+    pub fn map(&self) -> &BTreeMap<String, MessageItem> { &self.map }
+
+    /// Get a single property's value.
+    pub fn get(&mut self, propname: &str) -> Result<&MessageItem, Error> {
+        let v = self.p.get(propname)?;
+        self.map.insert(propname.to_string(), v);
+        Ok(self.map.get(propname).unwrap())
+    }
+
+    /// Set a single property's value.
+    pub fn set(&mut self, propname: &str, value: MessageItem) -> Result<(), Error> {
+        self.p.set(propname, value.clone())?;
+        self.map.insert(propname.to_string(), value);
+        Ok(())
+    }
+}
+
+
+#[cfg(test)]
+mod test {
+    extern crate tempfile;
+
+    use crate::{Message, MessageType, Path, Signature};
+    #[cfg(unix)]
+    use libc;
+    use crate::arg::messageitem::MessageItem;
+    #[cfg(unix)]
+    use crate::arg::OwnedFd;
+    use crate::ffidisp::{Connection, BusType};
+
+    #[test]
+    fn unix_fd() {
+        use std::io::prelude::*;
+        use std::io::SeekFrom;
+        use std::fs::OpenOptions;
+        #[cfg(unix)]
+        use std::os::unix::io::{IntoRawFd, AsRawFd};
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        let tempdir = tempfile::Builder::new().prefix("dbus-rs-test").tempdir().unwrap();
+        let mut filename = tempdir.path().to_path_buf();
+        filename.push("test");
+        println!("Creating file {:?}", filename);
+        let mut file = OpenOptions::new().create(true).read(true).write(true).open(&filename).unwrap();
+        file.write_all(b"z").unwrap();
+        file.seek(SeekFrom::Start(0)).unwrap();
+        #[cfg(unix)]
+        {
+            let ofd = unsafe { OwnedFd::new(file.into_raw_fd()) };
+            m.append_items(&[MessageItem::UnixFd(ofd.clone())]);
+        }
+        println!("Sending {:?}", m.get_items());
+        c.send(m).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                #[cfg(unix)]
+                {
+                    let z: OwnedFd = n.read1().unwrap();
+                    println!("Got {:?}", z);
+                    let mut q: libc::c_char = 100;
+                    assert_eq!(1, unsafe { libc::read(z.as_raw_fd(), &mut q as *mut _ as *mut libc::c_void, 1) });
+                    assert_eq!(q, 'z' as libc::c_char);
+                }
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        }}
+    }
+
+    #[test]
+    fn message_types() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        m.append_items(&[
+            2000u16.into(),
+            MessageItem::new_array(vec!(129u8.into())).unwrap(),
+            ["Hello", "world"][..].into(),
+            987654321u64.into(),
+            (-1i32).into(),
+            format!("Hello world").into(),
+            (-3.14f64).into(),
+            MessageItem::Struct(vec!(256i16.into())),
+            Path::new("/some/path").unwrap().into(),
+            MessageItem::new_dict(vec!((123543u32.into(), true.into()).into())).unwrap()
+        ]);
+        let sending = format!("{:?}", m.get_items());
+        println!("Sending {}", sending);
+        c.send(m).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                let receiving = format!("{:?}", n.get_items());
+                println!("Receiving {}", receiving);
+                assert_eq!(sending, receiving);
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        }}
+    }
+
+    #[test]
+    fn dict_of_dicts() {
+        use std::collections::BTreeMap;
+
+        let officeactions: BTreeMap<&'static str, MessageItem> = BTreeMap::new();
+        let mut officethings = BTreeMap::new();
+        officethings.insert("pencil", 2u16.into());
+        officethings.insert("paper", 5u16.into());
+        let mut homethings = BTreeMap::new();
+        homethings.insert("apple", 11u16.into());
+        let mut homeifaces = BTreeMap::new();
+        homeifaces.insert("getThings", homethings);
+        let mut officeifaces = BTreeMap::new();
+        officeifaces.insert("getThings", officethings);
+        officeifaces.insert("getActions", officeactions);
+        let mut paths = BTreeMap::new();
+        paths.insert("/hello/office", officeifaces);
+        paths.insert("/hello/home", homeifaces);
+
+        println!("Original treemap: {:?}", paths);
+        let m = MessageItem::new_dict(paths.iter().map(
+            |(path, ifaces)| (MessageItem::ObjectPath(Path::new(*path).unwrap()),
+                MessageItem::new_dict(ifaces.iter().map(
+                    |(iface, props)| (iface.to_string().into(),
+                        MessageItem::from_dict::<(),_>(props.iter().map(
+                            |(name, value)| Ok((name.to_string(), value.clone()))
+                        )).unwrap()
+                    ).into()
+                ).collect()).unwrap()
+            ).into()
+        ).collect()).unwrap();
+        println!("As MessageItem: {:?}", m);
+        assert_eq!(&*m.signature(), "a{oa{sa{sv}}}");
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/hello").unwrap();
+        let mut msg = Message::new_method_call(&c.unique_name(), "/hello", "org.freedesktop.DBusObjectManager", "GetManagedObjects").unwrap();
+        msg.append_items(&[m]);
+        let sending = format!("{:?}", msg.get_items());
+        println!("Sending {}", sending);
+        c.send(msg).unwrap();
+
+        loop { for n in c.incoming(1000) {
+            if n.msg_type() == MessageType::MethodCall {
+                let receiving = format!("{:?}", n.get_items());
+                println!("Receiving {}", receiving);
+                assert_eq!(sending, receiving);
+                return;
+            } else {
+                println!("Got {:?}", n);
+            }
+        } }
+    }
+
+    #[test]
+    fn issue24() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let mut m = Message::new_method_call("org.test.rust", "/", "org.test.rust", "Test").unwrap();
+
+        let a = MessageItem::from("test".to_string());
+        let b = MessageItem::from("test".to_string());
+        let foo = MessageItem::Struct(vec!(a, b));
+        let bar = foo.clone();
+
+        let args = [MessageItem::new_array(vec!(foo, bar)).unwrap()];
+        println!("{:?}", args);
+
+        m.append_items(&args);
+        c.send(m).unwrap();
+    }
+
+    /* Unfortunately org.freedesktop.DBus has no properties we can use for testing, but hostname1 should be around on most distros. */
+    #[cfg(unix)]
+    #[test]
+    fn test_get_hostname1_prop() {
+        use super::Props;
+
+        let c = Connection::new_system().unwrap();
+        let p = Props::new(&c, "org.freedesktop.hostname1", "/org/freedesktop/hostname1",
+            "org.freedesktop.hostname1", 10000);
+
+        /* Let's use both the get and getall methods and see if we get the same result */
+        let v = p.get("StaticHostname").unwrap();
+        let vall = p.get_all().unwrap();
+        let v2 = vall.get("StaticHostname").unwrap();
+
+        assert_eq!(&v, &*v2);
+        match v {
+            MessageItem::Str(ref s) => { println!("StaticHostname is {}", s); }
+            _ => { panic!("Invalid Get: {:?}", v); }
+        };
+    }
+
+    #[test]
+    fn message_listnames() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let m = Message::method_call(&"org.freedesktop.DBus".into(), &"/".into(),
+            &"org.freedesktop.DBus".into(), &"ListNames".into());
+        let r = c.send_with_reply_and_block(m, 2000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+    }
+
+    #[test]
+    fn message_namehasowner() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
+        m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
+        let r = c.send_with_reply_and_block(m, 2000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+        assert_eq!(reply, vec!(MessageItem::Bool(true)));
+    }
+
+    #[test]
+    fn message_inner_str() {
+        let ob = MessageItem::ObjectPath("/path".into());
+        assert_eq!("/path", ob.inner::<&str>().unwrap());
+
+        let ob = MessageItem::ObjectPath("/path".into());
+        assert_ne!("/path/another", ob.inner::<&str>().unwrap());
+
+        let ob = MessageItem::Str("String".into());
+        assert_eq!("String", ob.inner::<&str>().unwrap());
+
+        let ob = MessageItem::Str("String".into());
+        assert_ne!("StringDiff", ob.inner::<&str>().unwrap());
+
+        let ob = MessageItem::Signature(Signature::make::<i32>());
+        assert_eq!("i", ob.inner::<&str>().unwrap());
+
+        let ob = MessageItem::Signature(Signature::make::<u32>());
+        assert_ne!("i", ob.inner::<&str>().unwrap());
+
+    }
+
+    #[test]
+    fn message_peel() {
+        let flat_str = MessageItem::Str("foobar".into());
+        assert_eq!(flat_str.peel(), &flat_str);
+
+        let flat_path = MessageItem::ObjectPath("/path".into());
+        assert_eq!(flat_path.peel(), &flat_path);
+
+        let flat_sig = MessageItem::Signature(Signature::make::<i32>());
+        assert_eq!(flat_sig.peel(), &flat_sig);
+
+        let flat_int = MessageItem::Int32(1234);
+        assert_eq!(flat_int.peel(), &flat_int);
+
+        let layered_str = MessageItem::Variant(Box::new(flat_str));
+        assert_eq!(layered_str.peel(), &MessageItem::Str("foobar".into()));
+
+        let layered_path = MessageItem::Variant(Box::new(flat_path));
+        assert_eq!(layered_path.peel(), &MessageItem::ObjectPath("/path".into()));
+
+        let layered_sig = MessageItem::Variant(Box::new(flat_sig));
+        assert_eq!(layered_sig.peel(), &MessageItem::Signature(Signature::make::<i32>()));
+
+        let layered_int = MessageItem::Variant(Box::new(flat_int));
+        assert_eq!(layered_int.peel(), &MessageItem::Int32(1234));
+
+        let very_deep =
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Variant(Box::new(
+            MessageItem::Int32(1234)
+            ))))))))))))))))))));
+
+        assert_eq!(very_deep.peel(), &MessageItem::Int32(1234));
+
+    }
+
+    #[test]
+    fn inner_from_variant() {
+        let msg_u8 = MessageItem::Variant(Box::new(3u8.into()));
+        assert_eq!(msg_u8.inner::<u8>().unwrap(), 3u8);
+
+        let msg_u16 = MessageItem::Variant(Box::new(4u16.into()));
+        assert_eq!(msg_u16.inner::<u16>().unwrap(), 4u16);
+
+        let msg_u32 = MessageItem::Variant(Box::new(5u32.into()));
+        assert_eq!(msg_u32.inner::<u32>().unwrap(), 5u32);
+
+        let msg_u64 = MessageItem::Variant(Box::new(6u64.into()));
+        assert_eq!(msg_u64.inner::<u64>().unwrap(), 6u64);
+
+        let msg_i16 = MessageItem::Variant(Box::new(4i16.into()));
+        assert_eq!(msg_i16.inner::<i16>().unwrap(), 4i16);
+
+        let msg_i32 = MessageItem::Variant(Box::new(5i32.into()));
+        assert_eq!(msg_i32.inner::<i32>().unwrap(), 5i32);
+
+        let msg_i64 = MessageItem::Variant(Box::new(6i64.into()));
+        assert_eq!(msg_i64.inner::<i64>().unwrap(), 6i64);
+
+        let msg_f64 = MessageItem::Variant(Box::new(6.5f64.into()));
+        assert_eq!(msg_f64.inner::<f64>().unwrap(), 6.5f64);
+
+        let msg_bool = MessageItem::Variant(Box::new(false.into()));
+        assert_eq!(msg_bool.inner::<bool>().unwrap(), false);
+
+        let msg_string = MessageItem::Variant(Box::new("asdf".to_string().into()));
+        assert_eq!(msg_string.inner::<&String>().unwrap(), "asdf");
+
+        let path: Path = "/path".into();
+        let msg_path = MessageItem::Variant(Box::new(MessageItem::ObjectPath(path.clone())));
+        assert_eq!(msg_path.inner::<&Path>().unwrap(), &path);
+
+        let sig: Signature = "a{si}".into();
+        let msg_sig = MessageItem::Variant(Box::new(MessageItem::Signature(sig.clone())));
+        assert_eq!(msg_sig.inner::<&Signature>().unwrap(), &sig);
+
+        assert_eq!(msg_string.inner::<&str>().unwrap(), "asdf");
+        assert_eq!(msg_path.inner::<&str>().unwrap(), "/path");
+        assert_eq!(msg_sig.inner::<&str>().unwrap(), "a{si}");
+
+    }
+
+}
--- a/third_party/rust/dbus/src/arg/mod.rs
+++ b/third_party/rust/dbus/src/arg/mod.rs
@@ -1,94 +1,117 @@
 //! Types and traits for easily getting a message's arguments, or appening a message with arguments.
 //!
-//! Also see the arguments guide (in the examples directory).
-//!
-//! A message has `read1`, `read2` etc, and `append1`, `append2` etc, which is your
-//! starting point into this module's types. 
-//!
-//! **Append a**:
-//!
-//! `bool, u8, u16, u32, u64, i16, i32, i64, f64` - the corresponding D-Bus basic type
-//!
-//! `&str` - a D-Bus string. D-Bus strings do not allow null characters, so 
-//! if the string contains null characters, it will be cropped
-//! to only include the data before the null character. (Tip: This allows for skipping an
-//! allocation by writing a string literal which ends with a null character.)
-//!
-//! `&[T] where T: Append` - a D-Bus array. Note: can use an efficient fast-path in case of 
-//! T being an FixedArray type.
-//!
-//! `Array<T, I> where T: Append, I: Iterator<Item=T>` - a D-Bus array, maximum flexibility.
-//!
-//! `Variant<T> where T: Append` - a D-Bus variant.
-//!
-//! `(T1, T2) where T1: Append, T2: Append` - tuples are D-Bus structs. Implemented up to 12.
-//!
-//! `Dict<K, V, I> where K: Append + DictKey, V: Append, I: Iterator<Item=(&K, &V)>` - A D-Bus dict (array of dict entries).
-//!
-//! `Path` - a D-Bus object path.
-//!
-//! `Signature` - a D-Bus signature.
+//! Also see the argument's guide (in the examples directory) for details about which Rust
+//! types correspond to which D-Bus types.
 //!
-//! `OwnedFd` - shares the file descriptor with the remote side.
-//!
-//! **Get / read a**:
-//!
-//! `bool, u8, u16, u32, u64, i16, i32, i64, f64` - the corresponding D-Bus basic type
-//!
-//! `&str`, `&CStr` - a D-Bus string. D-Bus strings are always UTF-8 and do not contain null characters.
-//!
-//! `&[T] where T: FixedArray` - a D-Bus array of integers or f64.
-//!
-//! `Array<T, Iter> where T: Get` - a D-Bus array, maximum flexibility. Implements Iterator so you can easily
-//! collect it into, e g, a `Vec`.
-//!
-//! `Variant<T> where T: Get` - a D-Bus variant. Use this type of Variant if you know the inner type.
-//!
-//! `Variant<Iter>` - a D-Bus variant. This type of Variant allows you to examine the inner type.
-//!
-//! `(T1, T2) where T1: Get, T2: Get` - tuples are D-Bus structs. Implemented up to 12.
-//!
-//! `Dict<K, V, Iter> where K: Get + DictKey, V: Get` - A D-Bus dict (array of dict entries). Implements Iterator so you can easily
-//! collect it into, e g, a `HashMap`.
-//!
-//! `Path` - a D-Bus object path.
-//!
-//! `Signature` - a D-Bus signature.
-//!
-//! `OwnedFd` - a file descriptor sent from the remote side.
-//!
+//! A message has `read1`, `read2` etc, and `append1`, `append2` etc, which is one
+//! starting point into this module's types.
+
 
 mod msgarg;
 mod basic_impl;
 mod variantstruct_impl;
 mod array_impl;
 
-pub use self::msgarg::{Arg, FixedArray, Get, DictKey, Append, RefArg, AppendAll, ReadAll, cast, cast_mut};
+pub mod messageitem;
+
+pub use self::msgarg::{Arg, FixedArray, Get, DictKey, Append, RefArg, AppendAll, ReadAll, ArgAll,
+    cast, cast_mut, prop_cast, PropMap};
 pub use self::array_impl::{Array, Dict};
 pub use self::variantstruct_impl::Variant;
 
 use std::{fmt, mem, ptr, error};
-use {ffi, Message, Signature, Path, OwnedFd};
+use crate::{ffi, Message, Signature, Path};
 use std::ffi::{CStr, CString};
 use std::os::raw::{c_void, c_int};
+#[cfg(unix)]
+use std::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd};
+use std::collections::VecDeque;
 
+fn check(f: &str, i: u32) { if i == 0 { panic!("D-Bus error: '{}' failed", f) }}
+
+fn ffi_iter() -> ffi::DBusMessageIter {
+    // Safe because DBusMessageIter contains only fields that are allowed to be zeroed (i e no references or similar)
+    unsafe { mem::zeroed() }
+}
+
+/// An RAII wrapper around Fd to ensure that file descriptor is closed
+/// when the scope ends.
+#[derive(Debug, PartialEq, PartialOrd)]
+pub struct OwnedFd {
+    #[cfg(unix)]
+    fd: RawFd
+}
+
+#[cfg(unix)]
+impl OwnedFd {
+    /// Create a new OwnedFd from a RawFd.
+    ///
+    /// This function is unsafe, because you could potentially send in an invalid file descriptor,
+    /// or close it during the lifetime of this struct. This could potentially be unsound.
+    pub unsafe fn new(fd: RawFd) -> OwnedFd {
+        OwnedFd { fd: fd }
+    }
+
+    /// Convert an OwnedFD back into a RawFd.
+    pub fn into_fd(self) -> RawFd {
+        let s = self.fd;
+        ::std::mem::forget(self);
+        s
+    }
+}
 
-fn check(f: &str, i: u32) { if i == 0 { panic!("D-Bus error: '{}' failed", f) }} 
+#[cfg(unix)]
+impl Drop for OwnedFd {
+    fn drop(&mut self) {
+        unsafe { libc::close(self.fd); }
+    }
+}
+
+impl Clone for OwnedFd {
+    #[cfg(unix)]
+    fn clone(&self) -> OwnedFd {
+        let x = unsafe { libc::dup(self.fd) };
+        if x == -1 { panic!("Duplicating file descriptor failed") }
+        unsafe { OwnedFd::new(x) }
+    }
 
-fn ffi_iter() -> ffi::DBusMessageIter { unsafe { mem::zeroed() }} 
+    #[cfg(windows)]
+    fn clone(&self) -> OwnedFd {
+        OwnedFd {}
+    }
+}
+
+#[cfg(unix)]
+impl AsRawFd for OwnedFd {
+    fn as_raw_fd(&self) -> RawFd {
+        self.fd
+    }
+}
+
+#[cfg(unix)]
+impl IntoRawFd for OwnedFd {
+    fn into_raw_fd(self) -> RawFd {
+        self.into_fd()
+    }
+}
+
+#[cfg(unix)]
+impl FromRawFd for OwnedFd {
+    unsafe fn from_raw_fd(fd: RawFd) -> Self { OwnedFd::new(fd) }
+}
 
 #[derive(Clone, Copy)]
-/// Helper struct for appending one or more arguments to a Message. 
+/// Helper struct for appending one or more arguments to a Message.
 pub struct IterAppend<'a>(ffi::DBusMessageIter, &'a Message);
 
 impl<'a> IterAppend<'a> {
     /// Creates a new IterAppend struct.
-    pub fn new(m: &'a mut Message) -> IterAppend<'a> { 
+    pub fn new(m: &'a mut Message) -> IterAppend<'a> {
         let mut i = ffi_iter();
         unsafe { ffi::dbus_message_iter_init_append(m.ptr(), &mut i) };
         IterAppend(i, m)
     }
 
     /// Appends the argument.
     pub fn append<T: Append>(&mut self, a: T) { a.append(self) }
 
@@ -104,17 +127,17 @@ impl<'a> IterAppend<'a> {
 
     /// Low-level function to append a variant.
     ///
     /// Use in case the `Variant` struct is not flexible enough -
     /// the easier way is to just call e g "append1" on a message and supply a `Variant` parameter.
     ///
     /// In order not to get D-Bus errors: during the call to "f" you need to call "append" on
     /// the supplied `IterAppend` exactly once,
-    /// and with a value which has the same signature as inner_sig.  
+    /// and with a value which has the same signature as inner_sig.
     pub fn append_variant<F: FnOnce(&mut IterAppend<'a>)>(&mut self, inner_sig: &Signature, f: F) {
         self.append_container(ArgType::Variant, Some(inner_sig.as_cstr()), f)
     }
 
     /// Low-level function to append an array.
     ///
     /// Use in case the `Array` struct is not flexible enough -
     /// the easier way is to just call e g "append1" on a message and supply an `Array` parameter.
@@ -160,66 +183,61 @@ impl<'a> IterAppend<'a> {
 
 
 
 #[derive(Clone, Copy)]
 /// Helper struct for retrieve one or more arguments from a Message.
 pub struct Iter<'a>(ffi::DBusMessageIter, &'a Message, u32);
 
 impl<'a> Iter<'a> {
-    /// Creates a new struct for iterating over the arguments of a message, starting with the first argument. 
-    pub fn new(m: &'a Message) -> Iter<'a> { 
+    /// Creates a new struct for iterating over the arguments of a message, starting with the first argument.
+    pub fn new(m: &'a Message) -> Iter<'a> {
         let mut i = ffi_iter();
         unsafe { ffi::dbus_message_iter_init(m.ptr(), &mut i) };
         Iter(i, m, 0)
     }
 
     /// Returns the current argument, if T is the argument type. Otherwise returns None.
     pub fn get<T: Get<'a>>(&mut self) -> Option<T> {
         T::get(self)
     }
 
-    /// Returns the current argument as a trait object (experimental).
+    /// Returns the current argument as a trait object.
     ///
-    /// Note: For the more complex arguments (arrays / dicts / structs, and especially
-    /// combinations thereof), their internal representations are still a bit in flux.
-    /// Instead, use as_iter() to read the values of those.
-    ///
-    /// The rest are unlikely to change - Variants are `Variant<Box<RefArg>>`, strings are `String`,
-    /// paths are `Path<'static>`, signatures are `Signature<'static>`, Int32 are `i32s` and so on.
-    pub fn get_refarg(&mut self) -> Option<Box<RefArg + 'static>> {
+    /// See the argument guide's reference part for information on what types hide inside the RefArg.
+    pub fn get_refarg(&mut self) -> Option<Box<dyn RefArg + 'static>> {
         Some(match self.arg_type() {
-	    ArgType::Array => array_impl::get_array_refarg(self),
-	    ArgType::Variant => Box::new(Variant::new_refarg(self).unwrap()),
-	    ArgType::Boolean => Box::new(self.get::<bool>().unwrap()),
-	    ArgType::Invalid => return None,
-	    ArgType::String => Box::new(self.get::<String>().unwrap()),
-	    ArgType::DictEntry => unimplemented!(),
-	    ArgType::Byte => Box::new(self.get::<u8>().unwrap()),
-	    ArgType::Int16 => Box::new(self.get::<i16>().unwrap()),
-	    ArgType::UInt16 => Box::new(self.get::<u16>().unwrap()),
-	    ArgType::Int32 => Box::new(self.get::<i32>().unwrap()),
-	    ArgType::UInt32 => Box::new(self.get::<u32>().unwrap()),
-	    ArgType::Int64 => Box::new(self.get::<i64>().unwrap()),
-	    ArgType::UInt64 => Box::new(self.get::<u64>().unwrap()),
-	    ArgType::Double => Box::new(self.get::<f64>().unwrap()),
-	    ArgType::UnixFd => Box::new(self.get::<OwnedFd>().unwrap()),
-	    ArgType::Struct => Box::new(self.recurse(ArgType::Struct).unwrap().collect::<Vec<_>>()),
-	    ArgType::ObjectPath => Box::new(self.get::<Path>().unwrap().into_static()),
-	    ArgType::Signature => Box::new(self.get::<Signature>().unwrap().into_static()),
+            ArgType::Array => array_impl::get_array_refarg(self),
+            ArgType::Variant => Box::new(Variant::new_refarg(self).unwrap()),
+            ArgType::Boolean => Box::new(self.get::<bool>().unwrap()),
+            ArgType::Invalid => return None,
+            ArgType::String => Box::new(self.get::<String>().unwrap()),
+            ArgType::DictEntry => unimplemented!(),
+            ArgType::Byte => Box::new(self.get::<u8>().unwrap()),
+            ArgType::Int16 => Box::new(self.get::<i16>().unwrap()),
+            ArgType::UInt16 => Box::new(self.get::<u16>().unwrap()),
+            ArgType::Int32 => Box::new(self.get::<i32>().unwrap()),
+            ArgType::UInt32 => Box::new(self.get::<u32>().unwrap()),
+            ArgType::Int64 => Box::new(self.get::<i64>().unwrap()),
+            ArgType::UInt64 => Box::new(self.get::<u64>().unwrap()),
+            ArgType::Double => Box::new(self.get::<f64>().unwrap()),
+            ArgType::UnixFd => Box::new(self.get::<std::fs::File>().unwrap()),
+            ArgType::Struct => Box::new(self.recurse(ArgType::Struct).unwrap().collect::<VecDeque<_>>()),
+            ArgType::ObjectPath => Box::new(self.get::<Path>().unwrap().into_static()),
+            ArgType::Signature => Box::new(self.get::<Signature>().unwrap().into_static()),
         })
     }
 
     /// Returns the type signature for the current argument.
     pub fn signature(&mut self) -> Signature<'static> {
         unsafe {
             let c = ffi::dbus_message_iter_get_signature(&mut self.0);
             assert!(c != ptr::null_mut());
             let cc = CStr::from_ptr(c);
-            let r = Signature::new(cc.to_bytes());
+            let r = Signature::new(std::str::from_utf8(cc.to_bytes()).unwrap());
             ffi::dbus_free(c as *mut c_void);
             r.unwrap()
         }
     }
 
     /// The raw arg_type for the current item.
     ///
     /// Unlike Arg::arg_type, this requires access to self and is not a static method.
@@ -228,20 +246,20 @@ impl<'a> Iter<'a> {
     pub fn arg_type(&mut self) -> ArgType {
         let s = unsafe { ffi::dbus_message_iter_get_arg_type(&mut self.0) };
         ArgType::from_i32(s as i32).unwrap()
     }
 
     /// Returns false if there are no more items.
     pub fn next(&mut self) -> bool {
         self.2 += 1;
-        unsafe { ffi::dbus_message_iter_next(&mut self.0) != 0 } 
+        unsafe { ffi::dbus_message_iter_next(&mut self.0) != 0 }
     }
 
-    /// Wrapper around `get` and `next`. Calls `get`, and then `next` if `get` succeeded. 
+    /// Wrapper around `get` and `next`. Calls `get`, and then `next` if `get` succeeded.
     ///
     /// Also returns a `Result` rather than an `Option` to give an error if successful.
     ///
     /// # Example
     /// ```ignore
     /// struct ServiceBrowserItemNew {
     ///     interface: i32,
     ///     protocol: i32,
@@ -259,18 +277,18 @@ impl<'a> Iter<'a> {
     ///         name: iter.read()?,
     ///         item_type: iter.read()?,
     ///         domain: iter.read()?,
     ///         flags: iter.read()?,
     ///     })
     /// }
     /// ```
     pub fn read<T: Arg + Get<'a>>(&mut self) -> Result<T, TypeMismatchError> {
-        let r = try!(self.get().ok_or_else(||
-             TypeMismatchError { expected: T::ARG_TYPE, found: self.arg_type(), position: self.2 }));
+        let r = self.get().ok_or_else(||
+             TypeMismatchError { expected: T::ARG_TYPE, found: self.arg_type(), position: self.2 })?;
         self.next();
         Ok(r)
     }
 
     /// If the current argument is a container of the specified arg_type, then a new
     /// Iter is returned which is for iterating over the contents inside the container.
     ///
     /// Primarily for internal use (the "get" function is more ergonomic), but could be
@@ -296,27 +314,27 @@ impl<'a> fmt::Debug for Iter<'a> {
             t.field(&z.arg_type());
             if !z.next() { break }
         }
         t.finish()
     }
 }
 
 impl<'a> Iterator for Iter<'a> {
-    type Item = Box<RefArg + 'static>;
+    type Item = Box<dyn RefArg + 'static>;
     fn next(&mut self) -> Option<Self::Item> {
         let r = self.get_refarg();
         if r.is_some() { self.next(); }
         r
     }
 }
 
 /// Type of Argument
 ///
-/// use this to figure out, e g, which type of argument is at the current position of Iter. 
+/// use this to figure out, e g, which type of argument is at the current position of Iter.
 #[repr(u8)]
 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
 pub enum ArgType {
     /// Dicts are Arrays of dict entries, so Dict types will have Array as ArgType.
     Array = ffi::DBUS_TYPE_ARRAY as u8,
     /// Variant
     Variant = ffi::DBUS_TYPE_VARIANT as u8,
     /// bool
@@ -338,103 +356,107 @@ pub enum ArgType {
     /// u32
     UInt32 = ffi::DBUS_TYPE_UINT32 as u8,
     /// i64
     Int64 = ffi::DBUS_TYPE_INT64 as u8,
     /// u64
     UInt64 = ffi::DBUS_TYPE_UINT64 as u8,
     /// f64
     Double = ffi::DBUS_TYPE_DOUBLE as u8,
-    /// OwnedFd
+    /// File
     UnixFd = ffi::DBUS_TYPE_UNIX_FD as u8,
-    /// Use tuples or Vec<Box<RefArg>> to read/write structs.
+    /// Use tuples or Vec<Box<dyn RefArg>> to read/write structs.
     Struct = ffi::DBUS_TYPE_STRUCT as u8,
     /// Path
     ObjectPath = ffi::DBUS_TYPE_OBJECT_PATH as u8,
     /// Signature
     Signature = ffi::DBUS_TYPE_SIGNATURE as u8,
 }
 
-const ALL_ARG_TYPES: [(ArgType, &'static str); 18] =
+const ALL_ARG_TYPES: [(ArgType, &str); 18] =
     [(ArgType::Variant, "Variant"),
     (ArgType::Array, "Array/Dict"),
     (ArgType::Struct, "Struct"),
     (ArgType::String, "String"),
     (ArgType::DictEntry, "Dict entry"),
     (ArgType::ObjectPath, "Path"),
     (ArgType::Signature, "Signature"),
-    (ArgType::UnixFd, "OwnedFd"),
+    (ArgType::UnixFd, "File"),
     (ArgType::Boolean, "bool"),
     (ArgType::Byte, "u8"),
     (ArgType::Int16, "i16"),
     (ArgType::Int32, "i32"),
     (ArgType::Int64, "i64"),
     (ArgType::UInt16, "u16"),
     (ArgType::UInt32, "u32"),
     (ArgType::UInt64, "u64"),
     (ArgType::Double, "f64"),
     (ArgType::Invalid, "nothing")];
 
 impl ArgType {
-    /// A str corresponding to the name of a Rust type. 
+    /// A str corresponding to the name of a Rust type.
     pub fn as_str(self) -> &'static str {
         ALL_ARG_TYPES.iter().skip_while(|a| a.0 != self).next().unwrap().1
     }
 
+    /// Returns a Vec of all possible argtypes.
+    pub fn all() -> Vec<Self> {
+        ALL_ARG_TYPES.iter().map(|x| x.0).collect()
+    }
+
     /// Converts an i32 to an ArgType (or an error).
     pub fn from_i32(i: i32) -> Result<ArgType, String> {
         for &(a, _) in &ALL_ARG_TYPES {
             if a as i32 == i { return Ok(a); }
         }
         Err(format!("Invalid ArgType {} ({})", i, i as u8 as char))
     }
 }
 
 
 /// Error struct to indicate a D-Bus argument type mismatch.
 ///
-/// Might be returned from `iter::read()`. 
+/// Might be returned from `iter::read()`.
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub struct TypeMismatchError {
     expected: ArgType,
     found: ArgType,
     position: u32,
 }
 
 impl TypeMismatchError {
     /// The ArgType we were trying to read, but failed
     pub fn expected_arg_type(&self) -> ArgType { self.expected }
 
-    /// The ArgType we should have been trying to read, if we wanted the read to succeed 
+    /// The ArgType we should have been trying to read, if we wanted the read to succeed
     pub fn found_arg_type(&self) -> ArgType { self.found }
 
     /// At what argument was the error found?
     ///
     /// Returns 0 for first argument, 1 for second argument, etc.
     pub fn pos(&self) -> u32 { self.position }
 }
 
 impl error::Error for TypeMismatchError {
     fn description(&self) -> &str { "D-Bus argument type mismatch" }
-    fn cause(&self) -> Option<&error::Error> { None }
+    fn cause(&self) -> Option<&dyn error::Error> { None }
 }
 
 impl fmt::Display for TypeMismatchError {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        write!(f, "{} at position {}: expected {}, found {}",
-            (self as &error::Error).description(),
+        write!(f, "D-Bus argument type mismatch at position {}: expected {}, found {}",
             self.position, self.expected.as_str(),
             if self.expected == self.found { "same but still different somehow" } else { self.found.as_str() }
         )
     }
 }
 
 
 #[allow(dead_code)]
 fn test_compile() {
-    let mut q = IterAppend::new(unsafe { mem::transmute(0usize) });
+    let mut msg = Message::new_signal("/", "a.b", "C").unwrap();
+    let mut q = IterAppend::new(&mut msg);
 
     q.append(5u8);
     q.append(Array::new(&[5u8, 6, 7]));
     q.append((8u8, &[9u8, 6, 7][..]));
     q.append(Variant((6u8, 7u8)));
 }
-
--- a/third_party/rust/dbus/src/arg/msgarg.rs
+++ b/third_party/rust/dbus/src/arg/msgarg.rs
@@ -1,79 +1,84 @@
 #![allow(dead_code)]
 
-use {Signature, Message, arg::TypeMismatchError};
+use crate::{Signature, arg::TypeMismatchError, arg::Variant};
 use std::{fmt, any};
 use std::sync::Arc;
-use std::rc::Rc;
+// use std::rc::Rc;
+use std::collections::HashMap;
 
 use super::{Iter, IterAppend, ArgType};
 
 /// Types that can represent a D-Bus message argument implement this trait.
 ///
-/// Types should also implement either Append or Get to be useful. 
+/// Types should also implement either Append or Get to be useful.
 pub trait Arg {
-    /// The corresponding D-Bus argument type code. 
+    /// The corresponding D-Bus argument type code.
     const ARG_TYPE: ArgType;
-    /// The corresponding D-Bus argument type code; just returns ARG_TYPE. 
-    ///
-    /// For backwards compatibility.
-    #[deprecated(note = "Use associated constant ARG_TYPE instead")]
-    fn arg_type() -> ArgType { return Self::ARG_TYPE; }
-    /// The corresponding D-Bus type signature for this type. 
+    /// The corresponding D-Bus type signature for this type.
     fn signature() -> Signature<'static>;
 }
 
+/// Helper trait to introspect many arguments.
+pub trait ArgAll {
+    /// A tuple of &static str. Used for introspection.
+    #[allow(non_camel_case_types)] // Note: This should be changed for 0.9 - but for now, don't break backwards compatibility
+    type strs;
+    /// Enumerates all arguments with their signatures (introspection helper method).
+    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(a: Self::strs, f: F);
+}
+
 /// Types that can be appended to a message as arguments implement this trait.
-pub trait Append: Sized {
-    /// Performs the append operation.
-    fn append(self, &mut IterAppend);
+pub trait Append {
+    /// Performs the append operation by consuming self.
+    fn append(self, ia: &mut IterAppend) where Self: Sized { self.append_by_ref(ia) }
+
+    /// Performs the append operation by borrowing self.
+    fn append_by_ref(&self, _: &mut IterAppend);
 }
 
 /// Helper trait to append many arguments to a message.
-pub trait AppendAll: Sized {
-    /// Performs the append operation.
-    fn append(self, &mut IterAppend);
+pub trait AppendAll {
+    /// Performs the append operation by borrowing self.
+    fn append(&self, _: &mut IterAppend);
 }
 
 /// Types that can be retrieved from a message as arguments implement this trait.
 pub trait Get<'a>: Sized {
     /// Performs the get operation.
     fn get(i: &mut Iter<'a>) -> Option<Self>;
 }
 
 /// Helper trait to read all arguments from a message.
 pub trait ReadAll: Sized {
     /// Performs the read operation.
     fn read(i: &mut Iter) -> Result<Self, TypeMismatchError>;
 }
 
 
 /// Object safe version of Arg + Append + Get.
-pub trait RefArg: fmt::Debug {
+pub trait RefArg: fmt::Debug + Send + Sync {
     /// The corresponding D-Bus argument type code.
     fn arg_type(&self) -> ArgType;
-    /// The corresponding D-Bus type signature for this type. 
+    /// The corresponding D-Bus type signature for this type.
     fn signature(&self) -> Signature<'static>;
     /// Performs the append operation.
-    fn append(&self, &mut IterAppend);
+    fn append(&self, _: &mut IterAppend);
     /// Transforms this argument to Any (which can be downcasted to read the current value).
     ///
-    /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
-    /// and as_any should not be relied upon for these types. Use as_iter instead.
-    fn as_any(&self) -> &any::Any where Self: 'static;
+    /// See the argument guide's reference section for which types you can cast to.
+    fn as_any(&self) -> &dyn any::Any where Self: 'static;
     /// Transforms this argument to Any (which can be downcasted to read the current value).
-    ///
-    /// Note: The internal representation of complex types (Array, Dict, Struct) is unstable
-    /// and as_any should not be relied upon for these types. Use as_iter instead.
-    ///
+	///
+    /// See the argument guide's reference section for which types you can cast to.
     /// # Panic
     /// Will panic if the interior cannot be made mutable, e g, if encapsulated
     /// inside a Rc with a reference count > 1.
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static;
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static;
     /// Try to read the argument as an i64.
     ///
     /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, Int64, UnixFd.
     #[inline]
     fn as_i64(&self) -> Option<i64> { None }
     /// Try to read the argument as an u64.
     ///
     /// Works for: Boolean, Byte, Int16, UInt16, Int32, UInt32, UInt64.
@@ -87,256 +92,282 @@ pub trait RefArg: fmt::Debug {
     /// Try to read the argument as a str.
     ///
     /// Works for: String, ObjectPath, Signature.
     #[inline]
     fn as_str(&self) -> Option<&str> { None }
     /// Try to read the argument as an iterator.
     ///
     /// Works for: Array/Dict, Struct, Variant.
+    /// For Dicts, keys and values are interleaved.
     #[inline]
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { None }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> { None }
+    /// Try to read the inner of an argument, as another argument, specifying an index.
+    ///
+    /// Works for: Variant, Array, Struct, Dict.
+    /// For Dicts, even indices gets a key, odd indices gets a value.
+    #[inline]
+    fn as_static_inner(&self, _index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static { None }
     /// Deep clone of the RefArg, causing the result to be 'static.
     ///
     /// Usable as an escape hatch in case of lifetime problems with RefArg.
     ///
     /// In case of complex types (Array, Dict, Struct), the clone is not guaranteed
     /// to have the same internal representation as the original.
-    fn box_clone(&self) -> Box<RefArg + 'static> { unimplemented!() /* Needed for backwards comp */ }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static>;
+
+    /// Deep clone of an array.
+    ///
+    /// This method is used internally by box_clone.
+    fn array_clone(_arg: &[Self]) -> Option<Box<dyn RefArg + 'static>> where Self: Sized { None }
 }
 
-impl<'a> Get<'a> for Box<RefArg> {
+impl<'a> Get<'a> for Box<dyn RefArg> {
     fn get(i: &mut Iter<'a>) -> Option<Self> { i.get_refarg() }
 }
 
 /// Cast a RefArg as a specific type (shortcut for any + downcast)
+///
+/// See the argument guide's reference section for which types you can cast to.
 #[inline]
-pub fn cast<'a, T: 'static>(a: &'a (RefArg + 'static)) -> Option<&'a T> { a.as_any().downcast_ref() }
+pub fn cast<'a, T: 'static>(a: &'a (dyn RefArg + 'static)) -> Option<&'a T> { a.as_any().downcast_ref() }
 
 /// Cast a RefArg as a specific type (shortcut for any_mut + downcast_mut)
 ///
+/// See the argument guide's reference section for which types you can cast to.
+///
 /// # Panic
 /// Will panic if the interior cannot be made mutable, e g, if encapsulated
 /// inside a Rc with a reference count > 1.
 #[inline]
-pub fn cast_mut<'a, T: 'static>(a: &'a mut (RefArg + 'static)) -> Option<&'a mut T> { a.as_any_mut().downcast_mut() }
+pub fn cast_mut<'a, T: 'static>(a: &'a mut (dyn RefArg + 'static)) -> Option<&'a mut T> { a.as_any_mut().downcast_mut() }
+
+/// The type typically used for a dictionary of properties.
+pub type PropMap = HashMap<String, Variant<Box<dyn RefArg + 'static>>>;
+
+
+/// Descend into a hashmap returned by e g "Properties::get_all" to retrieve the value of a property.
+///
+/// Shortcut for get + cast. Returns None both if the property does not exist, or if it was of a different type.
+/// See the argument guide's reference section for which types you can cast to.
+pub fn prop_cast<'a, T: 'static>(map: &'a PropMap, key: &str) -> Option<&'a T> {
+    map.get(key).and_then(|v| cast(&v.0))
+}
 
 /// If a type implements this trait, it means the size and alignment is the same
 /// as in D-Bus. This means that you can quickly append and get slices of this type.
 ///
 /// Note: Booleans do not implement this trait because D-Bus booleans are 4 bytes and Rust booleans are 1 byte.
 pub unsafe trait FixedArray: Arg + 'static + Clone + Copy {}
 
-/// Types that can be used as keys in a dict type implement this trait. 
+/// Types that can be used as keys in a dict type implement this trait.
 pub trait DictKey: Arg {}
 
 
 
 /// Simple lift over reference to value - this makes some iterators more ergonomic to use
 impl<'a, T: Arg> Arg for &'a T {
     const ARG_TYPE: ArgType = T::ARG_TYPE;
     fn signature() -> Signature<'static> { T::signature() }
 }
-impl<'a, T: Append + Clone> Append for &'a T {
-    fn append(self, i: &mut IterAppend) { self.clone().append(i) }
+impl<'a, T: Append> Append for &'a T {
+    fn append_by_ref(&self, i: &mut IterAppend) { (&**self).append_by_ref(i) }
 }
 impl<'a, T: DictKey> DictKey for &'a T {}
 
 impl<'a, T: RefArg + ?Sized> RefArg for &'a T {
     #[inline]
     fn arg_type(&self) -> ArgType { (&**self).arg_type() }
     #[inline]
     fn signature(&self) -> Signature<'static> { (&**self).signature() }
     #[inline]
     fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
     #[inline]
-    fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
+    fn as_any(&self) -> &dyn any::Any where T: 'static { (&**self).as_any() }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where T: 'static { unreachable!() }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where T: 'static { unreachable!() }
     #[inline]
     fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
     #[inline]
     fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
     #[inline]
     fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
     #[inline]
     fn as_str(&self) -> Option<&str> { (&**self).as_str() }
     #[inline]
-    fn as_iter<'b>(&'b self) -> Option<Box<Iterator<Item=&'b RefArg> + 'b>> { (&**self).as_iter() }
+    fn as_iter<'b>(&'b self) -> Option<Box<dyn Iterator<Item=&'b dyn RefArg> + 'b>> { (&**self).as_iter() }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static { (&**self).as_static_inner(index) }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { (&**self).box_clone() }
 }
 
 
 
 macro_rules! deref_impl {
     ($t: ident, $ss: ident, $make_mut: expr) => {
 
 impl<T: RefArg + ?Sized> RefArg for $t<T> {
     #[inline]
     fn arg_type(&self) -> ArgType { (&**self).arg_type() }
     #[inline]
     fn signature(&self) -> Signature<'static> { (&**self).signature() }
     #[inline]
     fn append(&self, i: &mut IterAppend) { (&**self).append(i) }
     #[inline]
-    fn as_any(&self) -> &any::Any where T: 'static { (&**self).as_any() }
+    fn as_any(&self) -> &dyn any::Any where T: 'static { (&**self).as_any() }
     #[inline]
-    fn as_any_mut<'a>(&'a mut $ss) -> &'a mut any::Any where T: 'static { $make_mut.as_any_mut() }
+    fn as_any_mut(&mut $ss) -> &mut dyn any::Any where T: 'static { $make_mut.as_any_mut() }
     #[inline]
     fn as_i64(&self) -> Option<i64> { (&**self).as_i64() }
     #[inline]
     fn as_u64(&self) -> Option<u64> { (&**self).as_u64() }
     #[inline]
     fn as_f64(&self) -> Option<f64> { (&**self).as_f64() }
     #[inline]
     fn as_str(&self) -> Option<&str> { (&**self).as_str() }
     #[inline]
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> { (&**self).as_iter() }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> { (&**self).as_iter() }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { (&**self).box_clone() }
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static { (&**self).as_static_inner(index) }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { (&**self).box_clone() }
 }
 impl<T: DictKey> DictKey for $t<T> {}
 
 impl<T: Arg> Arg for $t<T> {
     const ARG_TYPE: ArgType = T::ARG_TYPE;
     fn signature() -> Signature<'static> { T::signature() }
 }
 impl<'a, T: Get<'a>> Get<'a> for $t<T> {
-    fn get(i: &mut Iter<'a>) -> Option<Self> { T::get(i).map(|v| $t::new(v)) }
+    fn get(i: &mut Iter<'a>) -> Option<Self> { T::get(i).map($t::new) }
 }
 
     }
 }
 
 impl<T: Append> Append for Box<T> {
-    fn append(self, i: &mut IterAppend) { let q: T = *self; q.append(i) }
+    fn append_by_ref(&self, i: &mut IterAppend) { (&**self).append_by_ref(i) }
 }
 
 deref_impl!(Box, self, &mut **self );
-deref_impl!(Rc, self, Rc::get_mut(self).unwrap());
+// deref_impl!(Rc, self, Rc::get_mut(self).unwrap());
 deref_impl!(Arc, self, Arc::get_mut(self).unwrap());
 
-/// Internal trait to help generics. Implemented for (), (A1), (A1, A2) and so on (where A1: Arg, A2: Arg etc).
-///
-/// You would probably not use this trait directly, instead use generic functions which
-/// take ArgBuilder as an argument. It helps reading and appending multiple arguments
-/// to/from a message in one go.
-pub trait ArgBuilder: Sized {
-    /// A tuple of &static str. Used for introspection.
-    type strs;
-    /// Low-level introspection helper method.
-    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(a: Self::strs, f: F);
-    /// Low-level method to read arguments from a message.
-    fn read(msg: &Message) -> Result<Self, TypeMismatchError>;
-    /// Low-level method to append arguments to a message.
-    fn append(self, msg: &mut Message);
-}
-
-impl ArgBuilder for () {
-    type strs = ();
-    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(_: Self::strs, _: F) {}
-    fn read(_: &Message) -> Result<Self, TypeMismatchError> { Ok(()) }
-    fn append(self, _: &mut Message) {}
-}
-
-macro_rules! argbuilder_impl {
+macro_rules! argall_impl {
     ($($n: ident $t: ident $s: ty,)+) => {
 
-impl<$($t: Arg + Append + for<'z> Get<'z>),*> ArgBuilder for ($($t,)*) {
-    type strs = ($(&'static $s,)*); 
+impl<$($t: Arg),*> ArgAll for ($($t,)*) {
+    type strs = ($(&'static $s,)*);
     fn strs_sig<Q: FnMut(&'static str, Signature<'static>)>(z: Self::strs, mut q: Q) {
         let ( $($n,)*) = z;
         $( q($n, $t::signature()); )*
     }
-
-    fn read(msg: &Message) -> Result<Self, TypeMismatchError> {
-        let mut ii = msg.iter_init();
-        $( let $n = ii.read()?; )*
-        Ok(($( $n, )* ))
-    }
-
-    fn append(self, msg: &mut Message) {
-        let ( $($n,)*) = self;
-        let mut ia = IterAppend::new(msg);
-        $( ia.append($n); )*
-    }
 }
 
 impl<$($t: Append),*> AppendAll for ($($t,)*) {
-    fn append(self, ia: &mut IterAppend) {
+    fn append(&self, ia: &mut IterAppend) {
         let ( $($n,)*) = self;
         $( ia.append($n); )*
     }
 }
 
 impl<$($t: Arg + for<'z> Get<'z>),*> ReadAll for ($($t,)*) {
     fn read(ii: &mut Iter) -> Result<Self, TypeMismatchError> {
         $( let $n = ii.read()?; )*
         Ok(($( $n, )* ))
     }
 }
 
 
     }
 }
 
-argbuilder_impl!(a A str,);
-argbuilder_impl!(a A str, b B str,);
-argbuilder_impl!(a A str, b B str, c C str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str,);
-argbuilder_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str,);
+impl ArgAll for () {
+    type strs = ();
+    fn strs_sig<F: FnMut(&'static str, Signature<'static>)>(_: Self::strs, _: F) {}
+}
+
+impl AppendAll for () {
+    fn append(&self, _: &mut IterAppend) {}
+}
+
+impl ReadAll for () {
+    fn read(_: &mut Iter) -> Result<Self, TypeMismatchError> {
+        Ok(())
+    }
+}
 
+argall_impl!(a A str,);
+argall_impl!(a A str, b B str,);
+argall_impl!(a A str, b B str, c C str,);
+argall_impl!(a A str, b B str, c C str, d D str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str, v V str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str, v V str, w W str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str, v V str, w W str, x X str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str, v V str, w W str, x X str, y Y str,);
+argall_impl!(a A str, b B str, c C str, d D str, e E str, f F str, g G str, h H str, i I str, j J str, k K str, l L str, m M str, n N str, o O str, p P str, r R str, s S str, t T str, u U str, v V str, w W str, x X str, y Y str, z Z str,);
 
 
 #[cfg(test)]
 mod test {
-    extern crate tempdir;
-
-    use {Connection, ConnectionItem, Message, BusType, Path, Signature};
-    use arg::{Array, Variant, Dict, Iter, ArgType, TypeMismatchError, RefArg, cast};
+    use crate::{channel::{Channel, BusType}, Message, Path, Signature};
+    use crate::message::MessageType;
+    use crate::arg::{Array, Variant, Dict, Iter, ArgType, TypeMismatchError, RefArg, cast};
 
     use std::collections::HashMap;
 
     #[test]
     fn refarg() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        c.register_object_path("/mooh").unwrap();
-        let m = Message::new_method_call(&c.unique_name(), "/mooh", "com.example.hello", "Hello").unwrap();
+        let c = Channel::get_private(BusType::Session).unwrap();
+        let m = Message::new_method_call(c.unique_name().unwrap(), "/mooh", "com.example.hello", "Hello").unwrap();
 
-        let mut vv: Vec<Variant<Box<RefArg>>> = vec!();
+        let mut vv: Vec<Variant<Box<dyn RefArg>>> = vec!();
         vv.push(Variant(Box::new(5i32)));
         vv.push(Variant(Box::new(String::from("Hello world"))));
         let m = m.append_ref(&vv);
 
         let (f1, f2) = (false, 7u64);
-        let mut v: Vec<&RefArg> = vec!();
+        let mut v: Vec<&dyn RefArg> = vec!();
         v.push(&f1);
         v.push(&f2);
         let m = m.append_ref(&v);
         let vi32 = vec![7i32, 9i32];
         let vstr: Vec<String> = ["This", "is", "dbus", "rs"].iter().map(|&s| s.into()).collect();
-        let m = m.append_ref(&[&vi32 as &RefArg, &vstr as &RefArg]);
+        let m = m.append_ref(&[&vi32 as &dyn RefArg, &vstr as &dyn RefArg]);
         let mut map = HashMap::new();
         map.insert(true, String::from("Yes"));
         map.insert(false, String::from("No"));
-        let m = m.append_ref(&[&map as &RefArg, &1.5f64 as &RefArg]);
+        let m = m.append_ref(&[&map as &dyn RefArg, &1.5f64 as &dyn RefArg]);
 
         c.send(m).unwrap();
 
-        for n in c.iter(1000) {
-            if let ConnectionItem::MethodCall(m) = n {
-                let rv: Vec<Box<RefArg + 'static>> = m.iter_init().collect();
+        loop {
+            if let Some(m) = c.blocking_pop_message(std::time::Duration::from_millis(1000)).unwrap() {
+                if m.msg_type() != MessageType::MethodCall { continue; }
+
+                let rv: Vec<Box<dyn RefArg + 'static>> = m.iter_init().collect();
                 println!("Receiving {:?}", rv);
-                let rv0: &Variant<Box<RefArg>> = cast(&rv[0]).unwrap(); 
+                let rv0: &Variant<Box<dyn RefArg>> = cast(&rv[0]).unwrap();
                 let rv00: &i32 = cast(&rv0.0).unwrap();
                 assert_eq!(rv00, &5i32);
                 assert_eq!(Some(&false), rv[2].as_any().downcast_ref::<bool>());
                 assert_eq!(Some(&vi32), rv[4].as_any().downcast_ref::<Vec<i32>>());
                 assert_eq!(Some(&vstr), rv[5].as_any().downcast_ref::<Vec<String>>());
                 let mut diter = rv[6].as_iter().unwrap();
                 {
                     let mut mmap: HashMap<bool, String> = HashMap::new();
@@ -356,71 +387,212 @@ mod test {
                 assert!(rv[7].as_f64().unwrap() < 2.0);
                 break;
             }
         }
     }
 
     #[test]
     fn message_types() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        c.register_object_path("/hello").unwrap();
-        let m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
+        let c = Channel::get_private(BusType::Session).unwrap();
+
+        let m = Message::new_method_call(c.unique_name().unwrap(), "/hello", "com.example.hello", "Hello").unwrap();
         let m = m.append1(2000u16);
-        let m = m.append1(Array::new(&vec![129u8, 5, 254]));
+        let m = m.append1(&Array::new(&vec![129u8, 5, 254]));
         let m = m.append2(Variant(&["Hello", "world"][..]), &[32768u16, 16u16, 12u16][..]);
         let m = m.append3(-1i32, &*format!("Hello world"), -3.14f64);
         let m = m.append1((256i16, Variant(18_446_744_073_709_551_615u64)));
-        let m = m.append2(Path::new("/a/valid/path").unwrap(), Signature::new("a{sv}").unwrap());
+        let m = m.append2(Path::new("/a/valid/path").unwrap(), &Signature::new("a{sv}").unwrap());
         let mut z = HashMap::new();
         z.insert(123543u32, true);
         z.insert(0u32, false);
         let m = m.append1(Dict::new(&z));
         let sending = format!("{:?}", m.iter_init());
         println!("Sending {}", sending);
         c.send(m).unwrap();
 
-        for n in c.iter(1000) {
-            match n {
-                ConnectionItem::MethodCall(m) => {
-                    use super::Arg;
-                    let receiving = format!("{:?}", m.iter_init());
-                    println!("Receiving {}", receiving);
-                    assert_eq!(sending, receiving);
+        loop {
+            if let Some(m) = c.blocking_pop_message(std::time::Duration::from_millis(1000)).unwrap() {
+                if m.msg_type() != MessageType::MethodCall { continue; }
+                use super::Arg;
+                let receiving = format!("{:?}", m.iter_init());
+                println!("Receiving {}", receiving);
+                assert_eq!(sending, receiving);
+
+                assert_eq!(2000u16, m.get1().unwrap());
+                assert_eq!(m.get2(), (Some(2000u16), Some(&[129u8, 5, 254][..])));
+                assert_eq!(m.read2::<u16, bool>().unwrap_err(),
+                    TypeMismatchError { position: 1, found: ArgType::Array, expected: ArgType::Boolean });
+
+                let mut g = m.iter_init();
+                let e = g.read::<u32>().unwrap_err();
+                assert_eq!(e.pos(), 0);
+                assert_eq!(e.expected_arg_type(), ArgType::UInt32);
+                assert_eq!(e.found_arg_type(), ArgType::UInt16);
+
+                assert!(g.next() && g.next());
+                let v: Variant<Iter> = g.get().unwrap();
+                let mut viter = v.0;
+                assert_eq!(viter.arg_type(), Array::<&str,()>::ARG_TYPE);
+                let a: Array<&str, _> = viter.get().unwrap();
+                assert_eq!(a.collect::<Vec<&str>>(), vec!["Hello", "world"]);
+
+                assert!(g.next());
+                assert_eq!(g.get::<u16>(), None); // It's an array, not a single u16
+                assert!(g.next() && g.next() && g.next() && g.next());
 
-                    assert_eq!(2000u16, m.get1().unwrap());
-                    assert_eq!(m.get2(), (Some(2000u16), Some(&[129u8, 5, 254][..])));
-                    assert_eq!(m.read2::<u16, bool>().unwrap_err(),
-                        TypeMismatchError { position: 1, found: ArgType::Array, expected: ArgType::Boolean });
+                assert_eq!(g.get(), Some((256i16, Variant(18_446_744_073_709_551_615u64))));
+                assert!(g.next());
+                assert_eq!(g.get(), Some(Path::new("/a/valid/path").unwrap()));
+                assert!(g.next());
+                assert_eq!(g.get(), Some(Signature::new("a{sv}").unwrap()));
+                assert!(g.next());
+                let d: Dict<u32, bool, _> = g.get().unwrap();
+                let z2: HashMap<_, _> = d.collect();
+                assert_eq!(z, z2);
+                break;
+            }
+        }
+    }
+
+    #[test]
+    fn cast_vecs() {
+        let c = Channel::get_private(BusType::Session).unwrap();
 
-                    let mut g = m.iter_init();
-                    let e = g.read::<u32>().unwrap_err();
-                    assert_eq!(e.pos(), 0);
-                    assert_eq!(e.expected_arg_type(), ArgType::UInt32);
-                    assert_eq!(e.found_arg_type(), ArgType::UInt16);
+        let m = Message::new_method_call(c.unique_name().unwrap(), "/hello", "com.example.hello", "Hello").unwrap();
+        macro_rules! append_array {
+            ($m:expr, $t:ty) => {
+                $m.append1(Variant(&Array::<&$t, _>::new(&vec![Default::default()])))
+            };
+        }
+        let m = append_array!(m, bool);
+        let m = append_array!(m, u8);
+        let m = append_array!(m, u16);
+        let m = append_array!(m, i16);
+        let m = append_array!(m, u32);
+        let m = append_array!(m, i32);
+        let m = append_array!(m, f64);
+        let m = append_array!(m, String);
+        c.send(m).unwrap();
+        loop {
+            if let Some(m) = c.blocking_pop_message(std::time::Duration::from_millis(1000)).unwrap() {
+                if m.msg_type() != MessageType::MethodCall {
+                    continue;
+                }
+                let mut i = m.iter_init();
+                let mut i2 = m.iter_init();
 
-                    assert!(g.next() && g.next());
-                    let v: Variant<Iter> = g.get().unwrap();
-                    let mut viter = v.0;
-                    assert_eq!(viter.arg_type(), Array::<&str,()>::ARG_TYPE);
-                    let a: Array<&str, _> = viter.get().unwrap();
-                    assert_eq!(a.collect::<Vec<&str>>(), vec!["Hello", "world"]);
+                macro_rules! check_array {
+                    ($t:ty) => {
+                        let array: Variant<Box<dyn RefArg>> = i.read().unwrap();
+                        assert_eq!(
+                            cast::<Vec<$t>>(&(array.0)),
+                            Some(&vec![Default::default()]),
+                            "a variant containing an array of {0} should be castable to a Vec<{0}>",
+                            std::any::type_name::<$t>()
+                        );
+                        let refarg = i2.get_refarg().unwrap();
+                        println!("refarg {:?}", refarg);
+                        let cloned = refarg.box_clone();
+                        println!("cloned: {:?}", cloned);
+                        let st_inner = refarg.as_static_inner(0).unwrap();
+                        println!("st_inner {:?}", st_inner);
+                        i2.next();
+                        assert_eq!(cast::<Vec<$t>>(st_inner), Some(&vec![Default::default()]));
+                        let cl_inner = refarg.as_static_inner(0).unwrap();
+                        assert_eq!(cast::<Vec<$t>>(cl_inner), Some(&vec![Default::default()]));
+                    };
+                }
+                check_array!(bool);
+                check_array!(u8);
+                check_array!(u16);
+                check_array!(i16);
+                check_array!(u32);
+                check_array!(i32);
+                check_array!(f64);
+                check_array!(String);
+                break;
+            }
+        }
+    }
 
-                    assert!(g.next());
-                    assert_eq!(g.get::<u16>(), None); // It's an array, not a single u16
-                    assert!(g.next() && g.next() && g.next() && g.next());
+    #[test]
+    fn cast_dicts() {
+        let c = Channel::get_private(BusType::Session).unwrap();
 
-                    assert_eq!(g.get(), Some((256i16, Variant(18_446_744_073_709_551_615u64))));
-                    assert!(g.next());
-                    assert_eq!(g.get(), Some(Path::new("/a/valid/path").unwrap()));
-                    assert!(g.next());
-                    assert_eq!(g.get(), Some(Signature::new("a{sv}").unwrap()));
-                    assert!(g.next());
-                    let d: Dict<u32, bool, _> = g.get().unwrap();
-                    let z2: HashMap<_, _> = d.collect();
-                    assert_eq!(z, z2);
-                    break;
+        let m = Message::new_method_call(
+            c.unique_name().unwrap(),
+            "/hello",
+            "com.example.hello",
+            "Hello",
+        )
+        .unwrap();
+        macro_rules! append_dict_variant {
+            ($m:expr, $k:ty, $v:ty) => {{
+                let mut map: HashMap<$k, Variant<Box<dyn RefArg>>> = HashMap::new();
+                map.insert(Default::default(), Variant(Box::new(<$v>::default())));
+                $m.append1(Variant(&map))
+            }};
+        }
+        let m = append_dict_variant!(m, bool, bool);
+        let m = append_dict_variant!(m, u8, u8);
+        let m = append_dict_variant!(m, u16, u16);
+        let m = append_dict_variant!(m, i16, i16);
+        let m = append_dict_variant!(m, u32, u32);
+        let m = append_dict_variant!(m, i32, i32);
+        let m = append_dict_variant!(m, u64, u64);
+        let m = append_dict_variant!(m, i64, i64);
+        let m = append_dict_variant!(m, u8, f64);
+        let m = append_dict_variant!(m, String, String);
+        c.send(m).unwrap();
+        loop {
+            if let Some(m) = c
+                .blocking_pop_message(std::time::Duration::from_millis(1000))
+                .unwrap()
+            {
+                if m.msg_type() != MessageType::MethodCall {
+                    continue;
                 }
-                _ => println!("Got {:?}", n),
+                let mut i = m.iter_init();
+                let mut i2 = m.iter_init();
+
+                macro_rules! check_dict_variant {
+                    ($k:ty, $v:ty) => {
+                        let map: Variant<Box<dyn RefArg>> = i.read().unwrap();
+                        let expected_key: $k = Default::default();
+                        let expected_value: $v = Default::default();
+                        let cast_map = cast::<HashMap<$k, Variant<Box<dyn RefArg>>>>(&map.0);
+                        assert!(cast_map.is_some(),
+                            "a variant containing a dict of {0} to Variant({1}) should be castable to a HashMap<{0}, Variant<Box<dyn RefArg>>>",
+                            std::any::type_name::<$k>(),
+                            std::any::type_name::<$v>()
+                        );
+                        let cast_map_value = cast_map.unwrap().get(&expected_key).unwrap();
+                        assert_eq!(
+                            cast::<$v>(&cast_map_value.0),
+                            Some(&expected_value),
+                            "a variant {0:?} containing a {1} should be castable to {1}",
+                            cast_map_value,
+                            std::any::type_name::<$v>()
+                        );
+                        let refarg = i2.get_refarg().unwrap();
+                        println!("refarg {:?}", refarg);
+                        let st_inner = refarg.as_static_inner(0).unwrap();
+                        println!("st_inner {:?}", st_inner);
+                        i2.next();
+                        assert!(cast::<HashMap<$k, Variant<Box<dyn RefArg>>>>(st_inner).is_some());
+                    };
+                }
+                check_dict_variant!(bool, bool);
+                check_dict_variant!(u8, u8);
+                check_dict_variant!(u16, u16);
+                check_dict_variant!(i16, i16);
+                check_dict_variant!(u32, u32);
+                check_dict_variant!(i32, i32);
+                check_dict_variant!(u64, u64);
+                check_dict_variant!(i64, i64);
+                check_dict_variant!(u8, f64);
+                check_dict_variant!(String, String);
+                break;
             }
         }
     }
 }
--- a/third_party/rust/dbus/src/arg/variantstruct_impl.rs
+++ b/third_party/rust/dbus/src/arg/variantstruct_impl.rs
@@ -1,131 +1,119 @@
 use super::*;
-use {message, Signature};
+use crate::Signature;
 use std::any;
+use std::collections::VecDeque;
 
 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
 /// A simple wrapper to specify a D-Bus variant.
 ///
 /// See the argument guide and module level documentation for details and examples.
 pub struct Variant<T>(pub T);
 
-impl Variant<Box<RefArg>> {
+impl Variant<Box<dyn RefArg>> {
     /// Creates a new refarg from an Iter. Mainly for internal use.
     pub fn new_refarg<'a>(i: &mut Iter<'a>) -> Option<Self> {
-        i.recurse(ArgType::Variant).and_then(|mut si| si.get_refarg()).map(|v| Variant(v))
+        i.recurse(ArgType::Variant).and_then(|mut si| si.get_refarg()).map(Variant)
     }
 }
 
-impl Default for Variant<Box<RefArg>> {
-    // This is a bit silly, because there is no such thing as a default argument.
-    // Unfortunately due to a design mistake while making the SignalArgs trait, we'll
-    // have to work around that by adding a default implementation here.
-    // https://github.com/diwic/dbus-rs/issues/136
-    fn default() -> Self { Variant(Box::new(0u8) as Box<RefArg>) }
-}
-
 impl<T:Default> Default for Variant<T> {
     fn default() -> Self { Variant(T::default()) }
 }
 
 
 impl<T> Arg for Variant<T> {
     const ARG_TYPE: ArgType = ArgType::Variant;
-    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"v\0") } }
+    fn signature() -> Signature<'static> { unsafe { Signature::from_slice_unchecked("v\0") } }
 }
 
 impl<T: Arg + Append> Append for Variant<T> {
-    fn append(self, i: &mut IterAppend) {
-        let z = self.0;
-        i.append_container(ArgType::Variant, Some(T::signature().as_cstr()), |s| z.append(s));
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        let z = &self.0;
+        i.append_container(ArgType::Variant, Some(T::signature().as_cstr()), |s| z.append_by_ref(s));
     }
 }
 
-impl Append for Variant<message::MessageItem> {
-    fn append(self, i: &mut IterAppend) {
-        let z = self.0;
-        let asig = z.signature();
-        let sig = asig.as_cstr();
-        i.append_container(ArgType::Variant, Some(&sig), |s| z.append(s));
-    }
-}
-
-impl Append for Variant<Box<RefArg>> {
-    fn append(self, i: &mut IterAppend) {
-        let z = self.0;
+impl Append for Variant<Box<dyn RefArg>> {
+    fn append_by_ref(&self, i: &mut IterAppend) {
+        let z = &self.0;
         i.append_container(ArgType::Variant, Some(z.signature().as_cstr()), |s| z.append(s));
     }
 }
 
 impl<'a, T: Get<'a>> Get<'a> for Variant<T> {
     fn get(i: &mut Iter<'a>) -> Option<Variant<T>> {
-        i.recurse(ArgType::Variant).and_then(|mut si| si.get().map(|v| Variant(v)))
+        i.recurse(ArgType::Variant).and_then(|mut si| si.get().map(Variant))
     }
 }
 
 impl<'a> Get<'a> for Variant<Iter<'a>> {
     fn get(i: &mut Iter<'a>) -> Option<Variant<Iter<'a>>> {
-        i.recurse(ArgType::Variant).map(|v| Variant(v))
+        i.recurse(ArgType::Variant).map(Variant)
     }
 }
 /*
-impl<'a> Get<'a> for Variant<Box<RefArg>> {
-    fn get(i: &mut Iter<'a>) -> Option<Variant<Box<RefArg>>> {
+impl<'a> Get<'a> for Variant<Box<dyn RefArg>> {
+    fn get(i: &mut Iter<'a>) -> Option<Variant<Box<dyn RefArg>>> {
         i.recurse(ArgType::Variant).and_then(|mut si| si.get_refarg().map(|v| Variant(v)))
     }
 }
 */
 impl<T: RefArg> RefArg for Variant<T> {
-    fn arg_type(&self) -> ArgType { ArgType::Variant } 
-    fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked(b"v\0") } }
+    fn arg_type(&self) -> ArgType { ArgType::Variant }
+    fn signature(&self) -> Signature<'static> { unsafe { Signature::from_slice_unchecked("v\0") } }
     fn append(&self, i: &mut IterAppend) {
         let z = &self.0;
         i.append_container(ArgType::Variant, Some(z.signature().as_cstr()), |s| z.append(s));
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where T: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where T: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where T: 'static { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where T: 'static { self }
     #[inline]
     fn as_i64(&self) -> Option<i64> { self.0.as_i64() }
     #[inline]
     fn as_u64(&self) -> Option<u64> { self.0.as_u64() }
     #[inline]
     fn as_f64(&self) -> Option<f64> { self.0.as_f64() }
     #[inline]
     fn as_str(&self) -> Option<&str> { self.0.as_str() }
     #[inline]
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> {
         use std::iter;
-        let z: &RefArg = &self.0;
+        let z: &dyn RefArg = &self.0;
         Some(Box::new(iter::once(z)))
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(Variant(self.0.box_clone())) }
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> { Box::new(Variant(self.0.box_clone())) }
+    #[inline]
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        if index == 0 { Some(&self.0) } else { None }
+    }
 }
 
 macro_rules! struct_impl {
     ( $($n: ident $t: ident,)+ ) => {
 
-/// Tuples are represented as D-Bus structs. 
+/// Tuples are represented as D-Bus structs.
 impl<$($t: Arg),*> Arg for ($($t,)*) {
     const ARG_TYPE: ArgType = ArgType::Struct;
     fn signature() -> Signature<'static> {
         let mut s = String::from("(");
         $( s.push_str(&$t::signature()); )*
         s.push_str(")");
         Signature::from(s)
     }
 }
 
 impl<$($t: Append),*> Append for ($($t,)*) {
-    fn append(self, i: &mut IterAppend) {
+    fn append_by_ref(&self, i: &mut IterAppend) {
         let ( $($n,)*) = self;
-        i.append_container(ArgType::Struct, None, |s| { $( $n.append(s); )* });
+        i.append_container(ArgType::Struct, None, |s| { $( $n.append_by_ref(s); )* });
     }
 }
 
 impl<'a, $($t: Get<'a>),*> Get<'a> for ($($t,)*) {
     fn get(i: &mut Iter<'a>) -> Option<Self> {
         let si = i.recurse(ArgType::Struct);
         if si.is_none() { return None; }
         let mut si = si.unwrap();
@@ -148,30 +136,35 @@ impl<$($t: RefArg),*> RefArg for ($($t,)
         $( s.push_str(&$n.signature()); )*
         s.push_str(")");
         Signature::from(s)
     }
     fn append(&self, i: &mut IterAppend) {
         let &( $(ref $n,)*) = self;
         i.append_container(ArgType::Struct, None, |s| { $( $n.append(s); )* });
     }
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> {
         let &( $(ref $n,)*) = self;
         let v = vec!(
-        $( $n as &RefArg, )*
+        $( $n as &dyn RefArg, )*
         );
         Some(Box::new(v.into_iter()))
     }
-    #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
         let &( $(ref $n,)*) = self;
-        let mut z = vec!();
-        $( z.push($n.box_clone()); )*
+        let arr = [ $($n as &dyn RefArg,)*];
+        arr.get(index).map(|x| *x)
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
+        let &( $(ref $n,)*) = self;
+        let mut z = VecDeque::new();
+        $( z.push_back($n.box_clone()); )*
         Box::new(z)
     }
 }
 
 
 }} // macro_rules end
 
 struct_impl!(a A,);
@@ -182,61 +175,40 @@ struct_impl!(a A, b B, c C, d D, e E,);
 struct_impl!(a A, b B, c C, d D, e E, f F,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K,);
 struct_impl!(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K, l L,);
 
-impl RefArg for Vec<Box<RefArg>> {
+impl RefArg for VecDeque<Box<dyn RefArg>> {
     fn arg_type(&self) -> ArgType { ArgType::Struct }
     fn signature(&self) -> Signature<'static> {
         let mut s = String::from("(");
         for z in self {
             s.push_str(&z.signature());
         }
         s.push_str(")");
         Signature::from(s)
     }
     fn append(&self, i: &mut IterAppend) {
         i.append_container(ArgType::Struct, None, |s| {
             for z in self { z.append(s); }
         });
     }
     #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
+    fn as_any(&self) -> &dyn any::Any where Self: 'static { self }
     #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    fn as_iter<'a>(&'a self) -> Option<Box<Iterator<Item=&'a RefArg> + 'a>> {
+    fn as_any_mut(&mut self) -> &mut dyn any::Any where Self: 'static { self }
+    fn as_iter<'a>(&'a self) -> Option<Box<dyn Iterator<Item=&'a dyn RefArg> + 'a>> {
         Some(Box::new(self.iter().map(|b| &**b)))
     }
     #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> {
-        let t: Vec<Box<RefArg + 'static>> = self.iter().map(|x| x.box_clone()).collect();
+    fn as_static_inner(&self, index: usize) -> Option<&(dyn RefArg + 'static)> where Self: 'static {
+        self.get(index).map(|x| x as &dyn RefArg)
+    }
+    #[inline]
+    fn box_clone(&self) -> Box<dyn RefArg + 'static> {
+        let t: VecDeque<Box<dyn RefArg + 'static>> = self.iter().map(|x| x.box_clone()).collect();
         Box::new(t)
     }
 }
-
-impl Append for message::MessageItem {
-    fn append(self, i: &mut IterAppend) {
-        message::append_messageitem(&mut i.0, &self)
-    }
-}
-
-impl<'a> Get<'a> for message::MessageItem {
-    fn get(i: &mut Iter<'a>) -> Option<Self> {
-        message::get_messageitem(&mut i.0)
-    }
-}
-
-impl RefArg for message::MessageItem {
-    fn arg_type(&self) -> ArgType { ArgType::from_i32(self.array_type()).unwrap() }
-    fn signature(&self) -> Signature<'static> { message::MessageItem::signature(&self) }
-    fn append(&self, i: &mut IterAppend) { message::append_messageitem(&mut i.0, self) }
-    #[inline]
-    fn as_any(&self) -> &any::Any where Self: 'static { self }
-    #[inline]
-    fn as_any_mut(&mut self) -> &mut any::Any where Self: 'static { self }
-    #[inline]
-    fn box_clone(&self) -> Box<RefArg + 'static> { Box::new(self.clone()) }
-}
-
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/blocking.rs
@@ -0,0 +1,515 @@
+//! Connections and proxies that make blocking method calls.
+
+
+use crate::strings::{BusName, Path, Interface, Member};
+use crate::arg::{AppendAll, ReadAll, IterAppend};
+use crate::{channel, Error, Message};
+use crate::message::{MatchRule, SignalArgs, MessageType};
+use crate::channel::{Channel, BusType, Token};
+use std::{cell::RefCell, time::Duration, sync::Mutex};
+use std::sync::atomic::{AtomicBool, Ordering};
+use crate::filters::Filters;
+
+#[allow(missing_docs)]
+mod generated_org_freedesktop_standard_interfaces;
+mod generated_org_freedesktop_dbus;
+
+/// This module contains some standard interfaces and an easy way to call them.
+///
+/// See the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces) for more information about these standard interfaces.
+///
+/// The code was created by dbus-codegen.
+pub mod stdintf {
+    #[allow(missing_docs)]
+    pub mod org_freedesktop_dbus {
+        pub use super::super::generated_org_freedesktop_standard_interfaces::*;
+
+        #[derive(Debug, PartialEq, Eq, Copy, Clone)]
+        pub enum RequestNameReply {
+            PrimaryOwner = 1,
+            InQueue = 2,
+            Exists = 3,
+            AlreadyOwner = 4,
+        }
+
+        #[derive(Debug, PartialEq, Eq, Copy, Clone)]
+        pub enum ReleaseNameReply {
+            Released = 1,
+            NonExistent = 2,
+            NotOwner = 3,
+        }
+
+        #[derive(Debug, PartialEq, Eq, Copy, Clone)]
+        pub enum EmitsChangedSignal {
+            True,
+            Invalidates,
+            Const,
+            False,
+        }
+
+        pub (crate) fn request_name<S: crate::blocking::BlockingSender>(s: &S, name: &str, allow_replacement: bool, replace_existing: bool, do_not_queue: bool)
+            -> Result<RequestNameReply, crate::Error> {
+            let flags: u32 =
+                if allow_replacement { 1 } else { 0 } +
+                if replace_existing { 2 } else { 0 } +
+                if do_not_queue { 4 } else { 0 };
+            let proxy = super::proxy(s);
+            use super::org_freedesktop::DBus;
+            let r = proxy.request_name(name, flags)?;
+            use RequestNameReply::*;
+            let all = [PrimaryOwner, InQueue, Exists, AlreadyOwner];
+            all.iter().find(|x| **x as u32 == r).copied().ok_or_else(||
+                crate::Error::new_failed("Invalid reply from DBus server")
+            )
+        }
+
+        pub (crate) fn release_name<S: crate::blocking::BlockingSender>(s: &S, name: &str)
+            -> Result<ReleaseNameReply, crate::Error> {
+
+            let proxy = super::proxy(s);
+            use super::org_freedesktop::DBus;
+            let r = proxy.release_name(name)?;
+            use ReleaseNameReply::*;
+            let all = [Released, NonExistent, NotOwner];
+            all.iter().find(|x| **x as u32 == r).copied().ok_or_else(||
+                crate::Error::new_failed("Invalid reply from DBus server")
+            )
+        }
+
+        use crate::arg;
+        impl PropertiesPropertiesChanged {
+            pub fn add_prop<F: FnOnce() -> Box<dyn arg::RefArg>>(&mut self, prop_name: &str, emits: EmitsChangedSignal, f: F) -> bool {
+                match emits {
+                    EmitsChangedSignal::False => { false },
+                    EmitsChangedSignal::Invalidates => {
+                        if !self.invalidated_properties.iter().any(|x| x == prop_name) {
+                            self.invalidated_properties.push(prop_name.into())
+                        }
+                        true
+                    }
+                    EmitsChangedSignal::True => {
+                        let val = f();
+                        self.changed_properties.insert(prop_name.into(), arg::Variant(val));
+                        true
+                    }
+                    EmitsChangedSignal::Const => panic!("Called add_prop with EmitsChangedSignal::Const")
+                }
+            }
+        }
+    }
+
+    // Not public yet, because of lack of named arguments
+    pub (super) mod org_freedesktop {
+        pub(crate) use super::super::generated_org_freedesktop_dbus::*;
+    }
+
+    pub (crate) fn proxy<C>(c: C) -> crate::blocking::Proxy<'static, C> {
+        super::Proxy::new("org.freedesktop.DBus", "/org/freedesktop/DBus", std::time::Duration::from_millis(5000), c)
+    }
+}
+
+/// A connection to D-Bus, thread local + non-async version
+pub struct LocalConnection {
+    channel: Channel,
+    filters: RefCell<Filters<LocalFilterCb>>,
+    all_signal_matches: AtomicBool,
+}
+
+/// A connection to D-Bus, non-async version where callbacks are Send but not Sync.
+pub struct Connection {
+    channel: Channel,
+    filters: RefCell<Filters<FilterCb>>,
+    all_signal_matches: AtomicBool,
+}
+
+/// A connection to D-Bus, Send + Sync + non-async version
+pub struct SyncConnection {
+    channel: Channel,
+    filters: Mutex<Filters<SyncFilterCb>>,
+    all_signal_matches: AtomicBool,
+}
+
+use crate::blocking::stdintf::org_freedesktop_dbus;
+
+macro_rules! connimpl {
+     ($c: ident, $cb: ident $(, $ss:tt)*) =>  {
+
+type
+    $cb = Box<dyn FnMut(Message, &$c) -> bool $(+ $ss)* + 'static>;
+
+
+impl $c {
+
+    /// Create a new connection to the session bus.
+    pub fn new_session() -> Result<Self, Error> {
+        Channel::get_private(BusType::Session).map(From::from)
+    }
+
+    /// Create a new connection to the system-wide bus.
+    pub fn new_system() -> Result<Self, Error> {
+        Channel::get_private(BusType::System).map(From::from)
+    }
+
+    /// Get the connection's unique name.
+    ///
+    /// It's usually something like ":1.54"
+    pub fn unique_name(&self) -> BusName { self.channel.unique_name().unwrap().into() }
+
+    /// Create a convenience struct for easier calling of many methods on the same destination and path.
+    pub fn with_proxy<'a, 'b, D: Into<BusName<'a>>, P: Into<Path<'a>>>(&'b self, dest: D, path: P, timeout: Duration) ->
+    Proxy<'a, &'b Self> {
+        Proxy { connection: self, destination: dest.into(), path: path.into(), timeout }
+    }
+
+
+    /// Request a name on the D-Bus.
+    ///
+    /// For detailed information on the flags and return values, see the libdbus documentation.
+    pub fn request_name<'a, N: Into<BusName<'a>>>(&self, name: N, allow_replacement: bool, replace_existing: bool, do_not_queue: bool)
+    -> Result<org_freedesktop_dbus::RequestNameReply, Error> {
+        org_freedesktop_dbus::request_name(&self.channel, &name.into(), allow_replacement, replace_existing, do_not_queue)
+    }
+
+    /// Release a previously requested name on the D-Bus.
+    pub fn release_name<'a, N: Into<BusName<'a>>>(&self, name: N) -> Result<org_freedesktop_dbus::ReleaseNameReply, Error> {
+        org_freedesktop_dbus::release_name(&self.channel, &name.into())
+    }
+
+    /// Adds a new match to the connection, and sets up a callback when this message arrives.
+    ///
+    /// If multiple [`MatchRule`]s match the same message, then by default only the first match will
+	/// get the callback. This behaviour can be changed for signal messages by calling
+	/// [`set_signal_match_mode`](Self::set_signal_match_mode).
+    ///
+    /// The returned value can be used to remove the match. The match is also removed if the callback
+    /// returns "false".
+    pub fn add_match<S: ReadAll, F>(&self, match_rule: MatchRule<'static>, f: F) -> Result<Token, Error>
+    where F: FnMut(S, &Self, &Message) -> bool $(+ $ss)* + 'static {
+        let m = match_rule.match_str();
+        self.add_match_no_cb(&m)?;
+        use channel::MatchingReceiver;
+        Ok(self.start_receive(match_rule, MakeSignal::make(f, m)))
+    }
+
+    /// Adds a new match to the connection, without setting up a callback when this message arrives.
+    pub fn add_match_no_cb(&self, match_str: &str) -> Result<(), Error> {
+        use crate::blocking::stdintf::org_freedesktop::DBus;
+        let proxy = stdintf::proxy(self);
+        proxy.add_match(match_str)
+    }
+
+    /// Removes a match from the connection, without removing any callbacks.
+    pub fn remove_match_no_cb(&self, match_str: &str) -> Result<(), Error> {
+        use crate::blocking::stdintf::org_freedesktop::DBus;
+        let proxy = stdintf::proxy(self);
+        proxy.remove_match(match_str)
+    }
+
+    /// Removes a previously added match and callback from the connection.
+    pub fn remove_match(&self, id: Token) -> Result<(), Error> {
+        use channel::MatchingReceiver;
+        let (mr, _) = self.stop_receive(id).ok_or_else(|| Error::new_failed("No match with that id found"))?;
+        self.remove_match_no_cb(&mr.match_str())
+    }
+
+    /// If true, configures the connection to send signal messages to all matching [`MatchRule`]
+    /// filters added with [`add_match`](Self::add_match) rather than just the first one. This comes
+    /// with the following gotchas:
+    ///
+    ///  * The messages might be duplicated, so the message serial might be lost (this is
+    ///    generally not a problem for signals).
+    ///  * Panicking inside a match callback might mess with other callbacks, causing them
+    ///    to be permanently dropped.
+    ///  * Removing other matches from inside a match callback is not supported.
+    ///
+    /// This is false by default, for a newly-created connection.
+    pub fn set_signal_match_mode(&self, match_all: bool) {
+        self.all_signal_matches.store(match_all, Ordering::Release);
+    }
+
+    /// Tries to handle an incoming message if there is one. If there isn't one,
+    /// it will wait up to timeout
+    ///
+    /// This method only takes "&self" instead of "&mut self", but it is a logic error to call
+    /// it recursively and might lead to panics or deadlocks.
+    ///
+    /// For `SyncConnection`: It is also a logic error to call this method from one thread, while
+    /// calling this or other methods from other threads. This can lead to messages being lost.
+    pub fn process(&self, timeout: Duration) -> Result<bool, Error> {
+        if let Some(msg) = self.channel.blocking_pop_message(timeout)? {
+            if self.all_signal_matches.load(Ordering::Acquire) && msg.msg_type() == MessageType::Signal {
+                // If it's a signal and the mode is enabled, send a copy of the message to all
+                // matching filters.
+                let matching_filters = self.filters_mut().remove_all_matching(&msg);
+                // `matching_filters` needs to be a separate variable and not inlined here, because
+                // if it's inline then the `MutexGuard` will live too long and we'll get a deadlock
+                // on the next call to `filters_mut()` below.
+                for mut ff in matching_filters {
+                    if let Ok(copy) = msg.duplicate() {
+                        if ff.2(copy, self) {
+                            self.filters_mut().insert(ff);
+                        }
+                    } else {
+                        // Silently drop the message, but add the filter back.
+                        self.filters_mut().insert(ff);
+                    }
+                }
+            } else {
+                // Otherwise, send the original message to only the first matching filter.
+                let ff = self.filters_mut().remove_first_matching(&msg);
+                if let Some(mut ff) = ff {
+                    if ff.2(msg, self) {
+                        self.filters_mut().insert(ff);
+                    }
+                } else if let Some(reply) = crate::channel::default_reply(&msg) {
+                    let _ = self.channel.send(reply);
+                }
+            }
+            Ok(true)
+        } else {
+            Ok(false)
+        }
+    }
+
+    /// The channel for this connection
+    pub fn channel(&self) -> &Channel {
+        &self.channel
+    }
+}
+
+impl BlockingSender for $c {
+    fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error> {
+        self.channel.send_with_reply_and_block(msg, timeout)
+    }
+}
+
+impl From<Channel> for $c {
+    fn from(channel: Channel) -> $c { $c {
+        channel,
+        filters: Default::default(),
+        all_signal_matches: AtomicBool::new(false),
+    } }
+}
+
+impl channel::Sender for $c {
+    fn send(&self, msg: Message) -> Result<u32, ()> { self.channel.send(msg) }
+}
+
+impl<S: ReadAll, F: FnMut(S, &$c, &Message) -> bool $(+ $ss)* + 'static> MakeSignal<$cb, S, $c> for F {
+    fn make(mut self, mstr: String) -> $cb {
+        Box::new(move |msg: Message, conn: &$c| {
+            if let Ok(s) = S::read(&mut msg.iter_init()) {
+                if self(s, conn, &msg) { return true };
+                let proxy = stdintf::proxy(conn);
+                use crate::blocking::stdintf::org_freedesktop::DBus;
+                let _ = proxy.remove_match(&mstr);
+                false
+            } else { true }
+        })
+    }
+}
+
+impl channel::MatchingReceiver for $c {
+    type F = $cb;
+    fn start_receive(&self, m: MatchRule<'static>, f: Self::F) -> Token {
+        self.filters_mut().add(m, f)
+    }
+    fn stop_receive(&self, id: Token) -> Option<(MatchRule<'static>, Self::F)> {
+        self.filters_mut().remove(id)
+    }
+}
+
+
+
+     }
+}
+
+connimpl!(Connection, FilterCb, Send);
+connimpl!(LocalConnection, LocalFilterCb);
+connimpl!(SyncConnection, SyncFilterCb, Send, Sync);
+
+impl Connection {
+    fn filters_mut(&self) -> std::cell::RefMut<Filters<FilterCb>> { self.filters.borrow_mut() }
+}
+
+impl LocalConnection {
+    fn filters_mut(&self) -> std::cell::RefMut<Filters<LocalFilterCb>> { self.filters.borrow_mut() }
+}
+
+impl SyncConnection {
+    fn filters_mut(&self) -> std::sync::MutexGuard<Filters<SyncFilterCb>> { self.filters.lock().unwrap() }
+}
+
+/// Abstraction over different connections
+pub trait BlockingSender {
+    /// Sends a message over the D-Bus and blocks, waiting for a reply or a timeout. This is used for method calls.
+    ///
+    /// Note: In case of an error reply, this is returned as an Err(), not as a Ok(Message) with the error type.
+    fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error>;
+}
+
+impl BlockingSender for Channel {
+    fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error> {
+        Channel::send_with_reply_and_block(self, msg, timeout)
+    }
+}
+
+/// A struct that wraps a connection, destination and path.
+///
+/// A D-Bus "Proxy" is a client-side object that corresponds to a remote object on the server side.
+/// Calling methods on the proxy object calls methods on the remote object.
+/// Read more in the [D-Bus tutorial](https://dbus.freedesktop.org/doc/dbus-tutorial.html#proxies)
+#[derive(Clone, Debug)]
+pub struct Proxy<'a, C> {
+    /// Destination, i e what D-Bus service you're communicating with
+    pub destination: BusName<'a>,
+    /// Object path on the destination
+    pub path: Path<'a>,
+    /// Timeout for method calls
+    pub timeout: Duration,
+    /// Some way to send and/or receive messages, either blocking or non-blocking.
+    pub connection: C,
+}
+
+impl<'a, C> Proxy<'a, C> {
+    /// Creates a new proxy struct.
+    pub fn new<D: Into<BusName<'a>>, P: Into<Path<'a>>>(dest: D, path: P, timeout: Duration, connection: C) -> Self {
+        Proxy { destination: dest.into(), path: path.into(), timeout, connection }
+    }
+}
+
+impl<'a, T: BlockingSender, C: std::ops::Deref<Target=T>> Proxy<'a, C> {
+// impl<'a, S: std::convert::AsRef<channel::Sender>> Proxy<'a, S> {
+    /// Make a method call using typed input and output arguments, then block waiting for a reply.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use dbus::blocking::{Connection, Proxy};
+    ///
+    /// let conn = Connection::new_session()?;
+    /// let proxy = Proxy::new("org.freedesktop.DBus", "/", std::time::Duration::from_millis(5000), &conn);
+    /// let (has_owner,): (bool,) = proxy.method_call("org.freedesktop.DBus", "NameHasOwner", ("dummy.name.without.owner",))?;
+    /// assert_eq!(has_owner, false);
+    /// # Ok::<(), Box<dyn std::error::Error>>(())
+    /// ```
+    pub fn method_call<'i, 'm, R: ReadAll, A: AppendAll, I: Into<Interface<'i>>, M: Into<Member<'m>>>(&self, i: I, m: M, args: A) -> Result<R, Error> {
+        let mut msg = Message::method_call(&self.destination, &self.path, &i.into(), &m.into());
+        args.append(&mut IterAppend::new(&mut msg));
+        let r = self.connection.send_with_reply_and_block(msg, self.timeout)?;
+        Ok(R::read(&mut r.iter_init())?)
+    }
+
+    /// Starts matching incoming messages on this destination and path.
+    ///
+    /// For matching signals, match_signal might be more convenient.
+    ///
+    /// The match rule will be modified to include this path and destination only.
+    ///
+    /// If call_add_match is true, will notify the D-Bus server that matching should start.
+    pub fn match_start(&self, mut mr: MatchRule<'static>, call_add_match: bool, f: <T as channel::MatchingReceiver>::F)
+    -> Result<Token, Error>
+    where T: channel::MatchingReceiver {
+        mr.path = Some(self.path.clone().into_static());
+        mr.sender = Some(self.destination.clone().into_static());
+        if call_add_match {
+            use crate::blocking::stdintf::org_freedesktop::DBus;
+            let proxy = stdintf::proxy(&*self.connection);
+            proxy.add_match(&mr.match_str())?;
+        }
+
+        Ok(self.connection.start_receive(mr, f))
+    }
+
+    /// Stops matching a signal added with match_start or match_signal.
+    ///
+    /// If call_remove_match is true, will notify the D-Bus server that matching should stop,
+    /// this should be true in case match_signal was used.
+    pub fn match_stop(&self, id: Token, call_remove_match: bool) -> Result<(), Error>
+    where T: channel::MatchingReceiver {
+        if let Some((mr, _)) = self.connection.stop_receive(id) {
+            if call_remove_match {
+                use crate::blocking::stdintf::org_freedesktop::DBus;
+                let proxy = stdintf::proxy(&*self.connection);
+                proxy.remove_match(&mr.match_str())?;
+            }
+        }
+        Ok(())
+    }
+
+    /// Sets up an incoming signal match, that calls the supplied callback every time the signal is received.
+    ///
+    /// The returned value can be used to remove the match. The match is also removed if the callback
+    /// returns "false".
+    pub fn match_signal<S: SignalArgs + ReadAll, F>(&self, f: F) -> Result<Token, Error>
+    where T: channel::MatchingReceiver,
+          F: MakeSignal<<T as channel::MatchingReceiver>::F, S, T>
+    {
+        let mr = S::match_rule(Some(&self.destination), Some(&self.path)).static_clone();
+        let ff = f.make(mr.match_str());
+        self.match_start(mr, true, ff)
+    }
+}
+
+/// Internal helper trait
+pub trait MakeSignal<G, S, T> {
+    /// Internal helper trait
+    fn make(self, mstr: String) -> G;
+}
+
+#[test]
+fn test_add_match() {
+    use self::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged as Ppc;
+    let c = Connection::new_session().unwrap();
+    let x = c.add_match(Ppc::match_rule(None, None), |_: Ppc, _, _| { true }).unwrap();
+    c.remove_match(x).unwrap();
+}
+
+#[test]
+fn test_conn_send_sync() {
+    fn is_send<T: Send>(_: &T) {}
+    fn is_sync<T: Sync>(_: &T) {}
+
+    let c = SyncConnection::new_session().unwrap();
+    is_send(&c);
+    is_sync(&c);
+
+    let c = Connection::new_session().unwrap();
+    is_send(&c);
+}
+
+#[test]
+fn test_peer() {
+    let c = Connection::new_session().unwrap();
+
+    let c_name = c.unique_name().into_static();
+    use std::sync::Arc;
+    let done = Arc::new(false);
+    let d2 = done.clone();
+    let j = std::thread::spawn(move || {
+        let c2 = Connection::new_session().unwrap();
+
+        let proxy = c2.with_proxy(c_name, "/", Duration::from_secs(5));
+        let (s2,): (String,) = proxy.method_call("org.freedesktop.DBus.Peer", "GetMachineId", ()).unwrap();
+        println!("{}", s2);
+        assert_eq!(Arc::strong_count(&d2), 2);
+        s2
+    });
+    assert_eq!(Arc::strong_count(&done), 2);
+
+    for _ in 0..30 {
+        c.process(Duration::from_millis(100)).unwrap();
+        if Arc::strong_count(&done) < 2 { break; }
+    }
+
+    let s2 = j.join().unwrap();
+
+    #[cfg(unix)]
+    {
+        let proxy = c.with_proxy("org.a11y.Bus", "/org/a11y/bus", Duration::from_secs(5));
+        let (s1,): (String,) = proxy.method_call("org.freedesktop.DBus.Peer", "GetMachineId", ()).unwrap();
+
+        assert_eq!(s1, s2);
+    }
+
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/blocking/generated_org_freedesktop_dbus.rs
@@ -0,0 +1,209 @@
+// This code was autogenerated with `dbus-codegen-rust -d org.freedesktop.DBus -p /org/freedesktop/DBus -m none -c blocking -g -i org.freedesktop. --dbuscrate crate --interfaces DBus -o dbus/src/blocking/generated_org_freedesktop_dbus.rs`, see https://github.com/diwic/dbus-rs
+use crate as dbus;
+#[allow(unused_imports)]
+use crate::arg;
+use crate::blocking;
+
+pub trait DBus {
+    fn hello(&self) -> Result<String, dbus::Error>;
+    fn request_name(&self, arg0: &str, arg1: u32) -> Result<u32, dbus::Error>;
+    fn release_name(&self, arg0: &str) -> Result<u32, dbus::Error>;
+    fn start_service_by_name(&self, arg0: &str, arg1: u32) -> Result<u32, dbus::Error>;
+    fn update_activation_environment(&self, arg0: ::std::collections::HashMap<&str, &str>) -> Result<(), dbus::Error>;
+    fn name_has_owner(&self, arg0: &str) -> Result<bool, dbus::Error>;
+    fn list_names(&self) -> Result<Vec<String>, dbus::Error>;
+    fn list_activatable_names(&self) -> Result<Vec<String>, dbus::Error>;
+    fn add_match(&self, arg0: &str) -> Result<(), dbus::Error>;
+    fn remove_match(&self, arg0: &str) -> Result<(), dbus::Error>;
+    fn get_name_owner(&self, arg0: &str) -> Result<String, dbus::Error>;
+    fn list_queued_owners(&self, arg0: &str) -> Result<Vec<String>, dbus::Error>;
+    fn get_connection_unix_user(&self, arg0: &str) -> Result<u32, dbus::Error>;
+    fn get_connection_unix_process_id(&self, arg0: &str) -> Result<u32, dbus::Error>;
+    fn get_adt_audit_session_data(&self, arg0: &str) -> Result<Vec<u8>, dbus::Error>;
+    fn get_connection_selinux_security_context(&self, arg0: &str) -> Result<Vec<u8>, dbus::Error>;
+    fn reload_config(&self) -> Result<(), dbus::Error>;
+    fn get_id(&self) -> Result<String, dbus::Error>;
+    fn get_connection_credentials(&self, arg0: &str) -> Result<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>, dbus::Error>;
+    fn features(&self) -> Result<Vec<String>, dbus::Error>;
+    fn interfaces(&self) -> Result<Vec<String>, dbus::Error>;
+}
+
+impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> DBus for blocking::Proxy<'a, C> {
+
+    fn hello(&self) -> Result<String, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "Hello", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn request_name(&self, arg0: &str, arg1: u32) -> Result<u32, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "RequestName", (arg0, arg1, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn release_name(&self, arg0: &str) -> Result<u32, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "ReleaseName", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn start_service_by_name(&self, arg0: &str, arg1: u32) -> Result<u32, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "StartServiceByName", (arg0, arg1, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn update_activation_environment(&self, arg0: ::std::collections::HashMap<&str, &str>) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "UpdateActivationEnvironment", (arg0, ))
+    }
+
+    fn name_has_owner(&self, arg0: &str) -> Result<bool, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "NameHasOwner", (arg0, ))
+            .and_then(|r: (bool, )| Ok(r.0, ))
+    }
+
+    fn list_names(&self) -> Result<Vec<String>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "ListNames", ())
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn list_activatable_names(&self) -> Result<Vec<String>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "ListActivatableNames", ())
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn add_match(&self, arg0: &str) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "AddMatch", (arg0, ))
+    }
+
+    fn remove_match(&self, arg0: &str) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "RemoveMatch", (arg0, ))
+    }
+
+    fn get_name_owner(&self, arg0: &str) -> Result<String, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetNameOwner", (arg0, ))
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn list_queued_owners(&self, arg0: &str) -> Result<Vec<String>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "ListQueuedOwners", (arg0, ))
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn get_connection_unix_user(&self, arg0: &str) -> Result<u32, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionUnixUser", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn get_connection_unix_process_id(&self, arg0: &str) -> Result<u32, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionUnixProcessID", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn get_adt_audit_session_data(&self, arg0: &str) -> Result<Vec<u8>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetAdtAuditSessionData", (arg0, ))
+            .and_then(|r: (Vec<u8>, )| Ok(r.0, ))
+    }
+
+    fn get_connection_selinux_security_context(&self, arg0: &str) -> Result<Vec<u8>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionSELinuxSecurityContext", (arg0, ))
+            .and_then(|r: (Vec<u8>, )| Ok(r.0, ))
+    }
+
+    fn reload_config(&self) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "ReloadConfig", ())
+    }
+
+    fn get_id(&self) -> Result<String, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetId", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn get_connection_credentials(&self, arg0: &str) -> Result<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionCredentials", (arg0, ))
+            .and_then(|r: (::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>, )| Ok(r.0, ))
+    }
+
+    fn features(&self) -> Result<Vec<String>, dbus::Error> {
+        <Self as blocking::stdintf::org_freedesktop_dbus::Properties>::get(&self, "org.freedesktop.DBus", "Features")
+    }
+
+    fn interfaces(&self) -> Result<Vec<String>, dbus::Error> {
+        <Self as blocking::stdintf::org_freedesktop_dbus::Properties>::get(&self, "org.freedesktop.DBus", "Interfaces")
+    }
+}
+
+#[derive(Debug)]
+pub struct DBusNameOwnerChanged {
+    pub arg0: String,
+    pub arg1: String,
+    pub arg2: String,
+}
+
+impl arg::AppendAll for DBusNameOwnerChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+        arg::RefArg::append(&self.arg1, i);
+        arg::RefArg::append(&self.arg2, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameOwnerChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameOwnerChanged {
+            arg0: i.read()?,
+            arg1: i.read()?,
+            arg2: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameOwnerChanged {
+    const NAME: &'static str = "NameOwnerChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
+
+#[derive(Debug)]
+pub struct DBusNameLost {
+    pub arg0: String,
+}
+
+impl arg::AppendAll for DBusNameLost {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameLost {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameLost {
+            arg0: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameLost {
+    const NAME: &'static str = "NameLost";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
+
+#[derive(Debug)]
+pub struct DBusNameAcquired {
+    pub arg0: String,
+}
+
+impl arg::AppendAll for DBusNameAcquired {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameAcquired {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameAcquired {
+            arg0: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameAcquired {
+    const NAME: &'static str = "NameAcquired";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/blocking/generated_org_freedesktop_standard_interfaces.rs
@@ -0,0 +1,153 @@
+// This code was autogenerated with `dbus-codegen-rust -m none -c blocking -g -i org.freedesktop.DBus --dbuscrate crate --file ./data/standard_interfaces.xml -o ../dbus/src/blocking/generated_org_freedesktop_standard_interfaces.rs`, see https://github.com/diwic/dbus-rs
+use crate as dbus;
+#[allow(unused_imports)]
+use crate::arg;
+use crate::blocking;
+
+pub trait Properties {
+    fn get<R0: for<'b> arg::Get<'b> + 'static>(&self, interface_name: &str, property_name: &str) -> Result<R0, dbus::Error>;
+    fn get_all(&self, interface_name: &str) -> Result<arg::PropMap, dbus::Error>;
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> Result<(), dbus::Error>;
+}
+
+impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> Properties for blocking::Proxy<'a, C> {
+
+    fn get<R0: for<'b> arg::Get<'b> + 'static>(&self, interface_name: &str, property_name: &str) -> Result<R0, dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Properties", "Get", (interface_name, property_name, ))
+            .and_then(|r: (arg::Variant<R0>, )| Ok((r.0).0, ))
+    }
+
+    fn get_all(&self, interface_name: &str) -> Result<arg::PropMap, dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Properties", "GetAll", (interface_name, ))
+            .and_then(|r: (arg::PropMap, )| Ok(r.0, ))
+    }
+
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Properties", "Set", (interface_name, property_name, arg::Variant(value), ))
+    }
+}
+
+#[derive(Debug)]
+pub struct PropertiesPropertiesChanged {
+    pub interface_name: String,
+    pub changed_properties: arg::PropMap,
+    pub invalidated_properties: Vec<String>,
+}
+
+impl arg::AppendAll for PropertiesPropertiesChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.interface_name, i);
+        arg::RefArg::append(&self.changed_properties, i);
+        arg::RefArg::append(&self.invalidated_properties, i);
+    }
+}
+
+impl arg::ReadAll for PropertiesPropertiesChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(PropertiesPropertiesChanged {
+            interface_name: i.read()?,
+            changed_properties: i.read()?,
+            invalidated_properties: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for PropertiesPropertiesChanged {
+    const NAME: &'static str = "PropertiesChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.Properties";
+}
+
+pub trait Introspectable {
+    fn introspect(&self) -> Result<String, dbus::Error>;
+}
+
+impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> Introspectable for blocking::Proxy<'a, C> {
+
+    fn introspect(&self) -> Result<String, dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Introspectable", "Introspect", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+}
+
+pub trait Peer {
+    fn ping(&self) -> Result<(), dbus::Error>;
+    fn get_machine_id(&self) -> Result<String, dbus::Error>;
+}
+
+impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> Peer for blocking::Proxy<'a, C> {
+
+    fn ping(&self) -> Result<(), dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Peer", "Ping", ())
+    }
+
+    fn get_machine_id(&self) -> Result<String, dbus::Error> {
+        self.method_call("org.freedesktop.DBus.Peer", "GetMachineId", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+}
+
+pub trait ObjectManager {
+    fn get_managed_objects(&self) -> Result<::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>, dbus::Error>;
+}
+
+impl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> ObjectManager for blocking::Proxy<'a, C> {
+
+    fn get_managed_objects(&self) -> Result<::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>, dbus::Error> {
+        self.method_call("org.freedesktop.DBus.ObjectManager", "GetManagedObjects", ())
+            .and_then(|r: (::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>, )| Ok(r.0, ))
+    }
+}
+
+#[derive(Debug)]
+pub struct ObjectManagerInterfacesAdded {
+    pub object: dbus::Path<'static>,
+    pub interfaces: ::std::collections::HashMap<String, arg::PropMap>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesAdded {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesAdded {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesAdded {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for ObjectManagerInterfacesAdded {
+    const NAME: &'static str = "InterfacesAdded";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
+
+#[derive(Debug)]
+pub struct ObjectManagerInterfacesRemoved {
+    pub object: dbus::Path<'static>,
+    pub interfaces: Vec<String>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesRemoved {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesRemoved {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesRemoved {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for ObjectManagerInterfacesRemoved {
+    const NAME: &'static str = "InterfacesRemoved";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/channel.rs
@@ -0,0 +1,195 @@
+//! Connection base / building block.
+//!
+//! Contains some helper structs and traits common to all Connection types.-
+
+use crate::{Message, to_c_str, c_str_to_slice, MessageType};
+use crate::message::MatchRule;
+
+#[cfg(not(feature = "native-channel"))]
+mod ffichannel;
+#[cfg(not(feature = "native-channel"))]
+pub use ffichannel::Channel;
+
+#[cfg(feature = "native-channel")]
+mod nativechannel;
+#[cfg(feature = "native-channel")]
+pub use nativechannel::Channel;
+
+
+/// Which bus to connect to
+#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
+pub enum BusType {
+    /// The Session bus - local to every logged in session
+    Session = ffi::DBusBusType::Session as isize,
+    /// The system wide bus
+    System = ffi::DBusBusType::System as isize,
+    /// The bus that started us, if any
+    Starter = ffi::DBusBusType::Starter as isize,
+}
+
+/// Platform-specific file descriptor type
+#[cfg(unix)]
+pub type WatchFd = std::os::unix::io::RawFd;
+
+/// Platform-specific file descriptor type
+#[cfg(windows)]
+pub type WatchFd = std::os::windows::io::RawSocket;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+/// A file descriptor, and an indication whether it should be read from, written to, or both.
+pub struct Watch {
+    /// File descriptor
+    pub fd: WatchFd,
+    /// True if wakeup should happen when the file descriptor is ready for reading
+    pub read: bool,
+    /// True if wakeup should happen when the file descriptor is ready for writing
+    pub write: bool,
+}
+
+/// Abstraction over different connections that send data
+pub trait Sender {
+    /// Schedules a message for sending.
+    ///
+    /// Returns a serial number than can be used to match against a reply.
+    fn send(&self, msg: Message) -> Result<u32, ()>;
+}
+
+/// Use in case you don't want the send the message, but just collect it instead.
+impl Sender for std::cell::RefCell<Vec<Message>> {
+    fn send(&self, msg: Message) -> Result<u32, ()> {
+        self.borrow_mut().push(msg);
+        Ok(0)
+    }
+}
+
+/// Use in case you don't want the send the message, but just collect it instead.
+impl Sender for std::sync::Mutex<Vec<Message>> {
+    fn send(&self, msg: Message) -> Result<u32, ()> {
+        self.lock().unwrap().push(msg);
+        Ok(0)
+    }
+}
+
+/// Token used to identify a callback in the MatchingReceiver trait
+#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub struct Token(pub usize);
+
+/// Abstraction over different connections that receive data
+pub trait MatchingReceiver {
+    /// Type of callback
+    type F;
+    /// Add a callback to be called in case a message matches.
+    ///
+    /// Returns an id that can be used to remove the callback.
+    fn start_receive(&self, m: MatchRule<'static>, f: Self::F) -> Token;
+    /// Remove a previously added callback.
+    fn stop_receive(&self, id: Token) -> Option<(MatchRule<'static>, Self::F)>;
+}
+
+impl Sender for Channel {
+    fn send(&self, msg: Message) -> Result<u32, ()> { Channel::send(self, msg) }
+}
+
+/// Handles what we need to be a good D-Bus citizen.
+///
+/// Call this if you have not handled the message yourself:
+/// * It handles calls to org.freedesktop.DBus.Peer.
+/// * For other method calls, it sends an error reply back that the method was unknown.
+pub fn default_reply(m: &Message) -> Option<Message> {
+    peer(&m).or_else(|| unknown_method(&m))
+}
+
+/// Replies if this is a call to org.freedesktop.DBus.Peer, otherwise returns None.
+fn peer(m: &Message) -> Option<Message> {
+    if let Some(intf) = m.interface() {
+        if &*intf != "org.freedesktop.DBus.Peer" { return None; }
+        if let Some(method) = m.member() {
+            if &*method == "Ping" { return Some(m.method_return()) }
+            if &*method == "GetMachineId" {
+                let mut r = m.method_return();
+                unsafe {
+                    let id = ffi::dbus_get_local_machine_id();
+                    if !id.is_null() {
+                        r = r.append1(c_str_to_slice(&(id as *const _)).unwrap());
+                        ffi::dbus_free(id as *mut _);
+                        return Some(r)
+                    }
+                }
+                return Some(m.error(&"org.freedesktop.DBus.Error.Failed".into(), &to_c_str("Failed to retreive UUID")))
+            }
+        }
+        Some(m.error(&"org.freedesktop.DBus.Error.UnknownMethod".into(), &to_c_str("Method does not exist")))
+    } else { None }
+}
+
+/// For method calls, it replies that the method was unknown, otherwise returns None.
+fn unknown_method(m: &Message) -> Option<Message> {
+    if m.msg_type() != MessageType::MethodCall { return None; }
+    // if m.get_no_reply() { return None; } // The reference implementation does not do this?
+    Some(m.error(&"org.freedesktop.DBus.Error.UnknownMethod".into(), &to_c_str("Path, Interface, or Method does not exist")))
+}
+
+#[test]
+fn test_channel_send_sync() {
+    fn is_send<T: Send>(_: &T) {}
+    fn is_sync<T: Sync>(_: &T) {}
+    let c = Channel::get_private(BusType::Session).unwrap();
+    is_send(&c);
+    is_sync(&c);
+}
+
+#[test]
+fn channel_simple_test() {
+    let mut c = Channel::get_private(BusType::Session).unwrap();
+    assert!(c.is_connected());
+    c.set_watch_enabled(true);
+    let fd = c.watch();
+    println!("{:?}", fd);
+    let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
+    let reply = c.send(m).unwrap();
+    let my_name = c.unique_name().unwrap();
+    loop {
+        while let Some(mut msg) = c.pop_message() {
+            println!("{:?}", msg);
+            if msg.get_reply_serial() == Some(reply) {
+                let r = msg.as_result().unwrap();
+                let z: crate::arg::Array<&str, _>  = r.get1().unwrap();
+                for n in z {
+                    println!("{}", n);
+                    if n == my_name { return; } // Hooray, we found ourselves!
+                }
+                assert!(false);
+            } else if let Some(r) = default_reply(&msg) {
+                c.send(r).unwrap();
+            }
+        }
+        c.read_write(Some(std::time::Duration::from_millis(100))).unwrap();
+    }
+}
+
+#[test]
+fn test_bus_type_is_compatible_with_set() {
+    use std::collections::HashSet;
+
+    let mut set: HashSet<BusType> = HashSet::new();
+    set.insert(BusType::Starter);
+    set.insert(BusType::Starter);
+
+    assert_eq!(set.len(), 1);
+    assert!(!set.contains(&BusType::Session));
+    assert!(!set.contains(&BusType::System));
+    assert!(set.contains(&BusType::Starter));
+}
+
+
+#[test]
+fn watchmap() {
+    let mut c = Channel::get_private(BusType::Session).unwrap();
+    c.set_watch_enabled(true);
+    let w = c.watch();
+    assert_eq!(w.write, false);
+    assert_eq!(w.read, true);
+    c.set_watch_enabled(false);
+    println!("{:?}", w);
+    c.set_watch_enabled(true);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/channel/ffichannel.rs
@@ -0,0 +1,364 @@
+//! Contains some helper structs and traits common to all Connection types.-
+
+use crate::{Error, Message, to_c_str};
+use std::{str, time::Duration, collections::HashMap};
+use std::sync::{Mutex, atomic::AtomicU8, atomic::Ordering};
+use std::ffi::CStr;
+use std::os::raw::{c_void, c_int};
+use super::{BusType, Watch, WatchFd};
+
+#[derive(Debug)]
+struct ConnHandle(*mut ffi::DBusConnection, bool);
+
+unsafe impl Send for ConnHandle {}
+unsafe impl Sync for ConnHandle {}
+
+impl Drop for ConnHandle {
+    fn drop(&mut self) {
+        if self.1 { unsafe {
+            ffi::dbus_connection_close(self.0);
+            ffi::dbus_connection_unref(self.0);
+        }}
+    }
+}
+
+#[derive(Debug, Eq, PartialEq, Hash)]
+struct WatchHandle(*mut ffi::DBusWatch);
+
+unsafe impl Send for WatchHandle {}
+unsafe impl Sync for WatchHandle {}
+
+/// This struct must be boxed as it is called from D-Bus callbacks!
+#[derive(Debug)]
+struct WatchMap {
+    conn: ConnHandle,
+    list: Mutex<HashMap<WatchHandle, (Watch, bool)>>,
+    current_rw: AtomicU8,
+    current_fd: Option<WatchFd>,
+}
+
+fn calc_rw(list: &HashMap<WatchHandle, (Watch, bool)>) -> u8 {
+    let mut r = 0;
+    for (w, b) in list.values() {
+        if *b && w.read { r |= 1; }
+        if *b && w.write { r |= 2; }
+    }
+    r
+}
+
+impl WatchMap {
+    fn new(conn: ConnHandle) -> Box<WatchMap> {
+        extern "C" fn add_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) -> u32 { unsafe {
+            let wm: &WatchMap = &*(data as *mut _);
+            wm.list.lock().unwrap().insert(WatchHandle(watch), Watch::from_raw_enabled(watch));
+            1
+        }}
+        extern "C" fn remove_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) { unsafe {
+            let wm: &WatchMap = &*(data as *mut _);
+            wm.list.lock().unwrap().remove(&WatchHandle(watch));
+        }}
+        extern "C" fn toggled_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) { unsafe {
+            let wm: &WatchMap = &*(data as *mut _);
+            let mut list = wm.list.lock().unwrap();
+            let (_, ref mut b) = list.get_mut(&WatchHandle(watch)).unwrap();
+            *b = ffi::dbus_watch_get_enabled(watch) != 0;
+            wm.current_rw.store(calc_rw(&list), Ordering::Release);
+        }}
+
+        let mut wm = Box::new(WatchMap {
+            conn, list: Default::default(), current_rw: Default::default(), current_fd: None
+        });
+        let wptr: &WatchMap = &wm;
+        if unsafe { ffi::dbus_connection_set_watch_functions(wm.conn.0,
+            Some(add_watch_cb), Some(remove_watch_cb), Some(toggled_watch_cb), wptr as *const _ as *mut _, None) } == 0 {
+                panic!("Cannot enable watch tracking (OOM?)")
+        }
+
+        {
+            let list = wm.list.lock().unwrap();
+            wm.current_rw.store(calc_rw(&list), Ordering::Release);
+
+            // This will never panic in practice, see https://lists.freedesktop.org/archives/dbus/2019-July/017786.html
+            for (w, _) in list.values() {
+                if let Some(ref fd) = &wm.current_fd {
+                    assert_eq!(*fd, w.fd);
+                } else {
+                    wm.current_fd = Some(w.fd);
+                }
+            }
+        }
+
+        wm
+    }
+}
+
+impl Drop for WatchMap {
+    fn drop(&mut self) {
+        let wptr: &WatchMap = &self;
+        if unsafe { ffi::dbus_connection_set_watch_functions(self.conn.0,
+            None, None, None, wptr as *const _ as *mut _, None) } == 0 {
+                panic!("Cannot disable watch tracking (OOM?)")
+        }
+    }
+}
+
+/// Low-level connection - handles read/write to the socket
+///
+/// You probably do not need to worry about this as you would typically
+/// use the various blocking and non-blocking "Connection" structs instead.
+///
+/// This version avoids dbus_connection_dispatch, and thus avoids
+/// callbacks from that function. Instead the same functionality
+/// is implemented in the various blocking and non-blocking "Connection" components.
+///
+/// Blocking operations are clearly marked as such, although if you
+/// try to access the connection from several threads at the same time,
+/// blocking might occur due to an internal mutex inside the dbus library.
+#[derive(Debug)]
+pub struct Channel {
+    handle: ConnHandle,
+    watchmap: Option<Box<WatchMap>>,
+}
+
+impl Drop for Channel {
+    fn drop(&mut self) {
+        self.set_watch_enabled(false); // Make sure "watchmap" is destroyed before "handle" is
+    }
+}
+
+impl Channel {
+    #[inline(always)]
+    pub (crate) fn conn(&self) -> *mut ffi::DBusConnection {
+        self.handle.0
+    }
+
+    fn conn_from_ptr(ptr: *mut ffi::DBusConnection) -> Result<Channel, Error> {
+        let handle = ConnHandle(ptr, true);
+
+        /* No, we don't want our app to suddenly quit if dbus goes down */
+        unsafe { ffi::dbus_connection_set_exit_on_disconnect(ptr, 0) };
+
+        let c = Channel { handle, watchmap: None };
+
+        Ok(c)
+    }
+
+
+    /// Creates a new D-Bus connection.
+    ///
+    /// Blocking: until the connection is up and running.
+    pub fn get_private(bus: BusType) -> Result<Channel, Error> {
+        let mut e = Error::empty();
+        let b = match bus {
+            BusType::Session => ffi::DBusBusType::Session,
+            BusType::System => ffi::DBusBusType::System,
+            BusType::Starter => ffi::DBusBusType::Starter,
+        };
+        let conn = unsafe { ffi::dbus_bus_get_private(b, e.get_mut()) };
+        if conn.is_null() {
+            return Err(e)
+        }
+        Self::conn_from_ptr(conn)
+    }
+
+    /// Creates a new D-Bus connection to a remote address.
+    ///
+    /// Note: for all common cases (System / Session bus) you probably want "get_private" instead.
+    ///
+    /// Blocking: until the connection is established.
+    pub fn open_private(address: &str) -> Result<Channel, Error> {
+        let mut e = Error::empty();
+        let conn = unsafe { ffi::dbus_connection_open_private(to_c_str(address).as_ptr(), e.get_mut()) };
+        if conn.is_null() {
+            return Err(e)
+        }
+        Self::conn_from_ptr(conn)
+    }
+
+    /// Registers a new D-Bus connection with the bus.
+    ///
+    /// Note: `get_private` does this automatically, useful with `open_private`
+    ///
+    /// Blocking: until a "Hello" response is received from the server.
+    pub fn register(&mut self) -> Result<(), Error> {
+        // This function needs to take &mut self, because it changes unique_name and unique_name takes a &self
+        let mut e = Error::empty();
+        if unsafe { ffi::dbus_bus_register(self.conn(), e.get_mut()) == 0 } {
+            Err(e)
+        } else {
+            Ok(())
+        }
+    }
+
+    /// Gets whether the connection is currently open.
+    pub fn is_connected(&self) -> bool {
+        unsafe { ffi::dbus_connection_get_is_connected(self.conn()) != 0 }
+    }
+
+    /// Get the connection's unique name.
+    ///
+    /// It's usually something like ":1.54"
+    pub fn unique_name(&self) -> Option<&str> {
+        let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
+        if c.is_null() { return None; }
+        let s = unsafe { CStr::from_ptr(c) };
+        str::from_utf8(s.to_bytes()).ok()
+    }
+
+
+    /// Puts a message into libdbus out queue, and tries to send it.
+    ///
+    /// Returns a serial number than can be used to match against a reply.
+    ///
+    /// Note: usually the message is sent when this call happens, but in
+    /// case internal D-Bus buffers are full, it will be left in the out queue.
+    /// Call "flush" or "read_write" to retry flushing the out queue.
+    pub fn send(&self, msg: Message) -> Result<u32, ()> {
+        let mut serial = 0u32;
+        let r = unsafe { ffi::dbus_connection_send(self.conn(), msg.ptr(), &mut serial) };
+        if r == 0 { return Err(()); }
+        Ok(serial)
+    }
+
+    /// Sends a message over the D-Bus and waits for a reply. This is used for method calls.
+    ///
+    /// Blocking: until a reply is received or the timeout expires.
+    ///
+    /// Note: In case of an error reply, this is returned as an Err(), not as a Ok(Message) with the error type.
+    ///
+    /// Note: In case pop_message and send_with_reply_and_block is called in parallel from different threads,
+    /// they might race to retreive the reply message from the internal queue.
+    pub fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error> {
+        let mut e = Error::empty();
+        let response = unsafe {
+            ffi::dbus_connection_send_with_reply_and_block(self.conn(), msg.ptr(),
+                timeout.as_millis() as c_int, e.get_mut())
+        };
+        if response.is_null() {
+            return Err(e);
+        }
+        Ok(Message::from_ptr(response, false))
+    }
+
+    /// Flush the queue of outgoing messages.
+    ///
+    /// Blocking: until the outgoing queue is empty.
+    pub fn flush(&self) { unsafe { ffi::dbus_connection_flush(self.conn()) } }
+
+    /// Read and write to the connection.
+    ///
+    /// Incoming messages are put in the internal queue, outgoing messages are written.
+    ///
+    /// Blocking: If there are no messages, for up to timeout, or forever if timeout is None.
+    /// For non-blocking behaviour, set timeout to Some(0).
+    pub fn read_write(&self, timeout: Option<Duration>) -> Result<(), ()> {
+        let t = timeout.map_or(-1, |t| t.as_millis() as c_int);
+        if unsafe { ffi::dbus_connection_read_write(self.conn(), t) == 0 } {
+            Err(())
+        } else {
+            Ok(())
+        }
+    }
+
+    /// Gets whether the output message buffer is non-empty
+    pub fn has_messages_to_send(&self) -> bool {
+        unsafe { ffi::dbus_connection_has_messages_to_send(self.conn()) == 1 }
+    }
+
+    /// Removes a message from the incoming queue, or returns None if the queue is empty.
+    ///
+    /// Use "read_write" first, so that messages are put into the incoming queue.
+    /// For unhandled messages, please call MessageDispatcher::default_dispatch to return
+    /// default replies for method calls.
+    pub fn pop_message(&self) -> Option<Message> {
+        let mptr = unsafe { ffi::dbus_connection_pop_message(self.conn()) };
+        if mptr.is_null() {
+            None
+        } else {
+            let msg = Message::from_ptr(mptr, false);
+            // println!("Incoming: {:?}", msg);
+            Some(msg)
+        }
+    }
+
+    /// Removes a message from the incoming queue, or waits until timeout if the queue is empty.
+    ///
+    pub fn blocking_pop_message(&self, timeout: Duration) -> Result<Option<Message>, Error> {
+        if let Some(msg) = self.pop_message() { return Ok(Some(msg)) }
+        self.read_write(Some(timeout)).map_err(|_|
+            Error::new_failed("Failed to read/write data, disconnected from D-Bus?")
+        )?;
+        Ok(self.pop_message())
+    }
+
+    /// Enables watch tracking, a prequisite for calling watch.
+    ///
+    /// (In theory, this could panic in case libdbus ever changes to listen to
+    /// something else than one file descriptor,
+    /// but this should be extremely unlikely to ever happen.)
+    pub fn set_watch_enabled(&mut self, enable: bool) {
+        if enable == self.watchmap.is_some() { return }
+        if enable {
+            self.watchmap = Some(WatchMap::new(ConnHandle(self.conn(), false)));
+        } else {
+            self.watchmap = None;
+        }
+    }
+
+    /// Gets the file descriptor to listen for read/write.
+    ///
+    /// Panics: if set_watch_enabled is false.
+    ///
+    /// (In theory, this could panic in case libdbus ever changes to listen to
+    /// something else than one file descriptor,
+    /// but this should be extremely unlikely to ever happen.)
+    pub fn watch(&self) -> Watch {
+        let wm = self.watchmap.as_ref().unwrap();
+        let rw = wm.current_rw.load(Ordering::Acquire);
+        Watch {
+            fd: wm.current_fd.unwrap(),
+            read: (rw & 1) != 0,
+            write: (rw & 2) != 0,
+        }
+    }
+
+    /// Get an up-to-date list of file descriptors to watch.
+    ///
+    /// Obsolete - in practice, you can use watch and set_watch_enabled instead.
+    #[deprecated]
+    pub fn watch_fds(&mut self) -> Result<Vec<Watch>, ()> {
+        let en = self.watchmap.is_some();
+        self.set_watch_enabled(true);
+        let mut wlist: Vec<Watch> = self.watchmap.as_ref().unwrap().list.lock().unwrap().values()
+            .map(|&(w, b)| Watch { fd: w.fd, read: b && w.read, write: b && w.write })
+            .collect();
+        self.set_watch_enabled(en);
+
+        if wlist.len() == 2 && wlist[0].fd == wlist[1].fd {
+            // This is always true in practice, see https://lists.freedesktop.org/archives/dbus/2019-July/017786.html
+            wlist = vec!(Watch {
+                fd: wlist[0].fd,
+                read: wlist[0].read || wlist[1].read,
+                write: wlist[0].write || wlist[1].write
+            });
+        }
+
+        Ok(wlist)
+    }
+}
+
+
+impl Watch {
+    unsafe fn from_raw_enabled(watch: *mut ffi::DBusWatch) -> (Self, bool) {
+        #[cfg(unix)]
+        let mut w = Watch {fd: ffi::dbus_watch_get_unix_fd(watch), read: false, write: false};
+        #[cfg(windows)]
+        let mut w = Watch {fd: ffi::dbus_watch_get_socket(watch) as WatchFd, read: false, write: false};
+        let enabled = ffi::dbus_watch_get_enabled(watch) != 0;
+        let flags = ffi::dbus_watch_get_flags(watch);
+        use std::os::raw::c_uint;
+        w.read = (flags & ffi::DBUS_WATCH_READABLE as c_uint) != 0;
+        w.write = (flags & ffi::DBUS_WATCH_WRITABLE as c_uint) != 0;
+        (w, enabled)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/channel/nativechannel.rs
@@ -0,0 +1,253 @@
+use crate::{Error, Message};
+use std::time::Duration;
+use super::{BusType, Watch};
+use futures_util::lock::Mutex as FMutex;
+use std::sync::Mutex;
+use futures_executor::block_on;
+use dbus_native_channel::address;
+use std::error::Error as stdError;
+use futures_util::io as fio;
+use std::pin::Pin;
+use std::os::unix::net::UnixStream;
+use std::collections::VecDeque;
+use std::os::unix::io::{RawFd, AsRawFd};
+
+/// Low-level connection - handles read/write to the socket
+///
+/// You probably do not need to worry about this as you would typically
+/// use the various blocking and non-blocking "Connection" structs instead.
+///
+/// This version avoids any dependency on the C dbus library, making it possible
+/// to use with async rust code etc.
+//#[derive(Debug)]
+pub struct Channel {
+    unique_name: Option<crate::strings::BusName<'static>>,
+    out_queue: Mutex<(u32, VecDeque<Message>)>,
+    in_queue: Mutex<VecDeque<Message>>,
+    reader: FMutex<Pin<Box<dyn fio::AsyncBufRead + Send>>>,
+    writer: FMutex<Pin<Box<dyn fio::AsyncWrite + Send>>>,
+    raw_fd: RawFd,
+    unix_fd: bool,
+}
+
+async fn do_auth<W: fio::AsyncWrite + std::marker::Unpin, R: fio::AsyncBufRead + std::marker::Unpin>(r: &mut R, w: &mut W) -> Result<bool, Box<dyn stdError>> {
+    use dbus_native_channel::authentication::Authentication;
+    use fio::{AsyncWriteExt, AsyncBufReadExt};
+    let (mut auth, s) = Authentication::new(true);
+    w.write_all(s.as_bytes()).await?;
+    loop {
+        let mut v = vec!();
+        r.read_until(b'\n', &mut v).await?;
+        let s = auth.handle(&v)?;
+        w.write_all(s.as_bytes()).await?;
+        if let Authentication::Begin(unixfd) = &auth {
+            return Ok(*unixfd)
+        }
+    }
+}
+
+impl Channel {
+
+    /// Creates a new D-Bus connection.
+    ///
+    /// Blocking: until the connection is up and running.
+    pub fn get_private(bus: BusType) -> Result<Channel, Error> {
+        block_on(async {
+            Self::get_private_async(bus, |s| {
+                // s.set_nonblocking(true).unwrap();
+                let s2 = s.try_clone().unwrap();
+                let r = fio::AllowStdIo::new(std::io::BufReader::new(s));
+                let w = fio::AllowStdIo::new(s2);
+                (r, w)
+            }).await.map_err(|x| Error::new_failed(&x.to_string()))
+        })
+    }
+
+    /// Creates a new D-Bus connection without blocking.
+    pub async fn get_private_async<R, W, F>(bus: BusType, f: F) -> Result<Channel, Box<dyn stdError>>
+    where
+        R: fio::AsyncBufRead + 'static + Send,
+        W: fio::AsyncWrite + 'static + Send,
+        F: FnOnce(UnixStream) -> (R, W) {
+        let addr = match bus {
+            BusType::Starter => address::read_starter_address(),
+            BusType::Session => address::read_session_address(),
+            BusType::System => address::read_system_address(),
+        }?;
+        // Tokio does not do this any less blocking than we do here.
+        let stream = address::connect_blocking(&addr)?;
+        let raw_fd = stream.as_raw_fd();
+        let (r, w) = f(stream);
+        let (mut r, mut w) = (Box::pin(r), Box::pin(w));
+        let unix_fd = do_auth(&mut r, &mut w).await?;
+        // dbg!(&unix_fd);
+        let mut c = Channel {
+            unique_name: None,
+            raw_fd,
+            unix_fd,
+            in_queue: Default::default(),
+            out_queue: Default::default(),
+            reader: FMutex::new(r),
+            writer: FMutex::new(w),
+        };
+        let msg = Message::new_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello")?;
+        let r = c.send_with_reply_async(msg).await?;
+        let s: String = r.read1()?;
+        c.unique_name = Some(crate::strings::BusName::new(s)?);
+        Ok(c)
+    }
+
+    /// Puts a message into the out queue, without trying to send it.
+    ///
+    /// Returns a serial number than can be used to match against a reply.
+    ///
+    /// Note:
+    /// Call "flush" to flush the out queue.
+    pub fn send(&self, mut msg: Message) -> Result<u32, ()> {
+        let mut q = self.out_queue.lock().unwrap();
+        q.0 += 1;
+        let serial = q.0;
+        msg.set_serial(serial);
+        q.1.push_back(msg);
+        Ok(serial)
+    }
+
+    async fn write_message(&self, msg: Message) -> Result<(), fio::Error> {
+        use fio::AsyncWriteExt;
+        let mut v = vec!();
+        let _: Result<(), ()> = msg.marshal(|b| {
+            // At some point we might be able to skip this copy. For now let's just try to get
+            // things up and running.
+            v.extend_from_slice(b);
+            Ok(())
+        });
+        let mut writer = self.writer.lock().await;
+        writer.write_all(&v).await
+    }
+
+    async fn read_message(&self) -> Result<Message, Error> {
+        use fio::AsyncReadExt;
+        let mut v = vec![0; 16];
+        let mut reader = self.reader.lock().await;
+        reader.read_exact(&mut v).await.map_err(|e| Error::new_failed(&e.to_string()))?;
+        let count = Message::demarshal_bytes_needed(&v).map_err(|_| Error::new_failed("Protocol error"))?;
+        // dbg!(&v, &count);
+        v.resize(count, 0);
+        reader.read_exact(&mut v[16..]).await.map_err(|e| Error::new_failed(&e.to_string()))?;
+        // dbg!(&v, &count);
+        Message::demarshal(&v)
+    }
+
+    /// Note: Calling this from more than one thread in parallel might result in reordering
+    /// as well as mutex blocking.
+    pub async fn flush_async(&self) -> Result<(), Error> {
+        loop {
+            let msg = {
+                let mut q = self.out_queue.lock().unwrap();
+                if let Some(msg) = q.1.pop_front() { msg } else { return Ok(()) }
+            };
+            self.write_message(msg).await.map_err(|e| Error::new_failed(&e.to_string()))?;
+        }
+    }
+
+    /// Flush the queue of outgoing messages.
+    ///
+    /// Blocking: until the outgoing queue is empty.
+    pub fn flush(&self) {
+        block_on(async {
+            self.flush_async().await.unwrap();
+        });
+    }
+
+    /// Removes a message from the incoming queue, or waits until timeout if the queue is empty.
+    ///
+    pub fn blocking_pop_message(&self, _timeout: Duration) -> Result<Option<Message>, Error> {
+        if let Some(msg) = self.pop_message() { return Ok(Some(msg)) }
+        // TODO: Timeout
+        block_on(async {
+            let msg = self.read_message().await?;
+            Ok(Some(msg))
+        })
+    }
+
+    /// This function does nothing. Provided for compatibility
+    pub fn set_watch_enabled(&mut self, _enable: bool) {
+    }
+
+    /// Gets the file descriptor to listen for read/write.
+    pub fn watch(&self) -> Watch {
+        Watch {
+            fd: self.as_raw_fd(),
+            read: true,
+            write: false,
+        }
+    }
+
+    /// Gets whether the connection is currently open.
+    pub fn is_connected(&self) -> bool {
+        // TODO
+        true
+    }
+
+    /// Removes a message from the incoming queue, or returns None if the queue is empty.
+    pub fn pop_message(&self) -> Option<Message> {
+        let mut q = self.in_queue.lock().unwrap();
+        q.pop_front()
+    }
+
+    /// Read and write to the connection.
+    ///
+    /// Incoming messages are put in the internal queue, outgoing messages are written.
+    ///
+    /// Blocking: If there are no messages, for up to timeout, or forever if timeout is None.
+    /// For non-blocking behaviour, set timeout to Some(0).
+    pub fn read_write(&self, _timeout: Option<Duration>) -> Result<(), ()> {
+        block_on(async {
+            // TODO: Timeout
+            self.flush_async().await.map_err(|_| ())?;
+            let msg = self.read_message().await.map_err(|_| ())?;
+            let mut q = self.in_queue.lock().unwrap();
+            q.push_back(msg);
+            Ok(())
+        })
+    }
+
+    /// Sends a message over the D-Bus and waits for a reply. This is used for method calls.
+    ///
+    /// Blocking: until a reply is received or the timeout expires.
+    ///
+    /// Note: In case of an error reply, this is returned as an Err(), not as a Ok(Message) with the error type.
+    ///
+    /// Note: In case pop_message and send_with_reply_and_block is called in parallel from different threads,
+    /// they might race to retreive the reply message from the internal queue.
+    pub fn send_with_reply_and_block(&self, msg: Message, _timeout: Duration) -> Result<Message, Error> {
+        block_on(async {
+            // TODO: Timeout
+            self.send_with_reply_async(msg).await
+        })
+    }
+
+    pub async fn send_with_reply_async(&self, msg: Message) -> Result<Message, Error> {
+        let serial = self.send(msg).map_err(|_| Error::new_failed("Failed to send message"))?;
+        self.flush_async().await?;
+        loop {
+            let msg = self.read_message().await?;
+            if msg.get_reply_serial() == Some(serial) {
+                return Ok(msg);
+            }
+            let mut q = self.in_queue.lock().unwrap();
+            q.push_back(msg)
+        }
+    }
+
+    /// Get the connection's unique name.
+    ///
+    /// It's usually something like ":1.54"
+    pub fn unique_name(&self) -> Option<&str> {
+        self.unique_name.as_ref().map(|x| &**x)
+    }
+}
+
+impl AsRawFd for Channel {
+    fn as_raw_fd(&self) -> RawFd { self.raw_fd }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/error.rs
@@ -0,0 +1,182 @@
+use crate::arg::TypeMismatchError;
+use std::ffi::CString;
+use std::{ptr, fmt};
+use crate::{arg, to_c_str, c_str_to_slice, init_dbus, Message};
+use crate::strings::ErrorName;
+use std::error::Error as stdError;
+
+/// D-Bus Error wrapper.
+///
+/// This is a wrapper around the libc dbus error object.
+pub struct Error {
+    e: ffi::DBusError,
+}
+
+unsafe impl Send for Error {}
+
+// Note! For this Sync impl to be safe, it requires that no functions that take &self,
+// actually calls into FFI. All functions that call into FFI with a ffi::DBusError
+// must take &mut self.
+
+unsafe impl Sync for Error {}
+
+impl Error {
+
+    /// Create a new custom D-Bus Error.
+    pub fn new_custom<'a, N: Into<ErrorName<'a>>>(name: N, message: &str) -> Error {
+        let n = to_c_str(&name.into());
+        let m = to_c_str(&message.replace("%","%%"));
+        let mut e = Error::empty();
+
+        unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
+        e
+    }
+
+    /// Create a new generic D-Bus Error with "org.freedesktop.DBus.Error.Failed" as the Error name.
+    pub fn new_failed(message: &str) -> Error {
+        Error::new_custom("org.freedesktop.DBus.Error.Failed", message)
+    }
+
+    pub (crate) fn empty() -> Error {
+        init_dbus();
+        let mut e = ffi::DBusError {
+            name: ptr::null(),
+            message: ptr::null(),
+            dummy: 0,
+            padding1: ptr::null()
+        };
+        unsafe { ffi::dbus_error_init(&mut e); }
+        Error{ e: e }
+    }
+
+    /// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
+    pub fn name(&self) -> Option<&str> {
+        c_str_to_slice(&self.e.name)
+    }
+
+    /// Custom message, e g 'Could not find a matching object path'
+    pub fn message(&self) -> Option<&str> {
+        c_str_to_slice(&self.e.message)
+    }
+
+    pub (crate) fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
+}
+
+impl Drop for Error {
+    fn drop(&mut self) {
+        unsafe { ffi::dbus_error_free(&mut self.e); }
+    }
+}
+
+impl fmt::Debug for Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
+            self.name().unwrap_or(""))
+    }
+}
+
+impl stdError for Error {
+    fn description(&self) -> &str { "D-Bus error" }
+}
+
+impl fmt::Display for Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        if let Some(x) = self.message() {
+             write!(f, "{}", x)
+        } else { Ok(()) }
+    }
+}
+
+impl From<arg::TypeMismatchError> for Error {
+    fn from(t: arg::TypeMismatchError) -> Error {
+        Error::new_custom("org.freedesktop.DBus.Error.Failed", &format!("{}", t))
+    }
+}
+
+
+impl From<MethodErr> for Error {
+    fn from(t: MethodErr) -> Error {
+        Error::new_custom(t.errorname(), t.description())
+    }
+}
+
+
+#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
+/// A D-Bus Method Error, containing an error name and a description.
+///
+/// Unlike the "Error" struct, this is a Rust native struct.
+pub struct MethodErr(ErrorName<'static>, String);
+
+impl MethodErr {
+    /// Create an Invalid Args MethodErr.
+    pub fn invalid_arg<T: fmt::Debug + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.InvalidArgs", format!("Invalid argument {:?}", a)).into()
+    }
+    /// Create a MethodErr that there are not enough arguments given.
+    pub fn no_arg() -> MethodErr {
+        ("org.freedesktop.DBus.Error.InvalidArgs", "Not enough arguments").into()
+    }
+    /// Create a MethodErr that the method failed in the way specified.
+    pub fn failed<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.Failed", a.to_string()).into()
+    }
+
+    /// Create a MethodErr that the Object path was unknown.
+    pub fn no_path<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownObject", format!("Unknown object path {}", a)).into()
+    }
+
+    /// Create a MethodErr that the Interface was unknown.
+    pub fn no_interface<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownInterface", format!("Unknown interface {}", a)).into()
+    }
+    /// Create a MethodErr that the Method was unknown.
+    pub fn no_method<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownMethod", format!("Unknown method {}", a)).into()
+    }
+    /// Create a MethodErr that the Property was unknown.
+    pub fn no_property<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.UnknownProperty", format!("Unknown property {}", a)).into()
+    }
+    /// Create a MethodErr that the Property was read-only.
+    pub fn ro_property<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
+        ("org.freedesktop.DBus.Error.PropertyReadOnly", format!("Property {} is read only", a)).into()
+    }
+
+    /// Error name accessor
+    pub fn errorname(&self) -> &ErrorName<'static> { &self.0 }
+    /// Description accessor
+    pub fn description(&self) -> &str { &self.1 }
+
+    /// Creates an error reply from a method call message.
+    ///
+    /// Note: You normally don't need to use this function,
+    /// as it is called internally from Tree::handle.
+    pub fn to_message(&self, msg: &Message) -> Message {
+        msg.error(&self.0, &CString::new(&*self.1).unwrap())
+    }
+}
+
+impl fmt::Display for MethodErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "{}", self.description())
+    }
+}
+
+impl stdError for MethodErr {}
+
+impl From<TypeMismatchError> for MethodErr {
+    fn from(t: TypeMismatchError) -> MethodErr { ("org.freedesktop.DBus.Error.Failed", format!("{}", t)).into() }
+}
+
+impl<T: Into<ErrorName<'static>>, M: Into<String>> From<(T, M)> for MethodErr {
+    fn from((t, m): (T, M)) -> MethodErr { MethodErr(t.into(), m.into()) }
+}
+
+impl From<Error> for MethodErr {
+    fn from(t: Error) -> MethodErr {
+        let n = t.name().unwrap_or("org.freedesktop.DBus.Error.Failed");
+        let m = t.message().unwrap_or("Unknown error");
+        MethodErr(String::from(n).into(), m.into())
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/ffidisp.rs
@@ -0,0 +1,307 @@
+//! A connection that uses FFI callbacks to dispatch messages.
+//!
+//! This is the legacy design used up to 0.6.x. It is not recommended for new development.
+
+
+use super::{Error, ffi, Message, MessageType};
+use crate::strings::{BusName, Path, Member, Interface};
+use crate::arg::{AppendAll, ReadAll, IterAppend};
+use crate::message::SignalArgs;
+
+pub mod stdintf;
+
+mod connection;
+
+pub use connection::{Connection, ConnMsgs};
+
+/// A convenience struct that wraps connection, destination and path.
+///
+/// Useful if you want to make many method calls to the same destination path.
+#[derive(Clone, Debug)]
+pub struct ConnPath<'a, C> {
+    /// Some way to access the connection, e g a &Connection or Rc<Connection>
+    pub conn: C,
+    /// Destination, i e what D-Bus service you're communicating with
+    pub dest: BusName<'a>,
+    /// Object path on the destination
+    pub path: Path<'a>,
+    /// Timeout in milliseconds for blocking method calls
+    pub timeout: i32,
+}
+
+impl<'a, C: ::std::ops::Deref<Target=Connection>> ConnPath<'a, C> {
+    /// Make a D-Bus method call, where you can append arguments inside the closure.
+    pub fn method_call_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<Message, Error> {
+        let mut msg = Message::method_call(&self.dest, &self.path, i, m);
+        f(&mut msg);
+        self.conn.send_with_reply_and_block(msg, self.timeout)
+    }
+
+    /// Emit a D-Bus signal, where you can append arguments inside the closure.
+    pub fn signal_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<u32, Error> {
+        let mut msg = Message::signal(&self.path, i, m);
+        f(&mut msg);
+        self.conn.send(msg).map_err(|_| Error::new_failed("Sending signal failed"))
+    }
+
+    /// Emit a D-Bus signal, where the arguments are in a struct.
+    pub fn emit<S: SignalArgs + AppendAll>(&self, signal: &S) -> Result<u32, Error> {
+        let msg = signal.to_emit_message(&self.path);
+        self.conn.send(msg).map_err(|_| Error::new_failed("Sending signal failed"))
+    }
+
+    /// Make a method call using typed input and output arguments.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use dbus::ffidisp::{Connection, BusType};
+    ///
+    /// let conn = Connection::get_private(BusType::Session)?;
+    /// let dest = conn.with_path("org.freedesktop.DBus", "/", 5000);
+    /// let (has_owner,): (bool,) = dest.method_call("org.freedesktop.DBus", "NameHasOwner", ("dummy.name.without.owner",))?;
+    /// assert_eq!(has_owner, false);
+    /// # Ok::<(), Box<dyn std::error::Error>>(())
+    /// ```
+    pub fn method_call<'i, 'm, R: ReadAll, A: AppendAll, I: Into<Interface<'i>>, M: Into<Member<'m>>>(&self, i: I, m: M, args: A) -> Result<R, Error> {
+        let mut r = self.method_call_with_args(&i.into(), &m.into(), |mut msg| {
+            args.append(&mut IterAppend::new(&mut msg));
+        })?;
+        r.as_result()?;
+        Ok(R::read(&mut r.iter_init())?)
+    }
+}
+
+/// The type of function to use for replacing the message callback.
+///
+/// See the documentation for Connection::replace_message_callback for more information.
+pub type MessageCallback = Box<dyn FnMut(&Connection, Message) -> bool + 'static>;
+
+pub use crate::ffi::DBusRequestNameReply as RequestNameReply;
+pub use crate::ffi::DBusReleaseNameReply as ReleaseNameReply;
+pub use crate::ffi::DBusBusType as BusType;
+
+mod watch;
+
+pub use self::watch::{Watch, WatchEvent};
+use watch::WatchList;
+
+#[repr(C)]
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
+/// Flags to use for Connection::register_name.
+///
+/// More than one flag can be specified, if so just add their values.
+pub enum NameFlag {
+    /// Allow another service to become the primary owner if requested
+    AllowReplacement = ffi::DBUS_NAME_FLAG_ALLOW_REPLACEMENT as isize,
+    /// Request to replace the current primary owner
+    ReplaceExisting = ffi::DBUS_NAME_FLAG_REPLACE_EXISTING as isize,
+    /// If we can not become the primary owner do not place us in the queue
+    DoNotQueue = ffi::DBUS_NAME_FLAG_DO_NOT_QUEUE as isize,
+}
+
+impl NameFlag {
+    /// u32 value of flag.
+    pub fn value(self) -> u32 { self as u32 }
+}
+
+/// When listening for incoming events on the D-Bus, this enum will tell you what type
+/// of incoming event has happened.
+#[derive(Debug)]
+pub enum ConnectionItem {
+    /// No event between now and timeout
+    Nothing,
+    /// Incoming method call
+    MethodCall(Message),
+    /// Incoming signal
+    Signal(Message),
+    /// Incoming method return, including method return errors (mostly used for Async I/O)
+    MethodReturn(Message),
+}
+
+impl From<Message> for ConnectionItem {
+    fn from(m: Message) -> Self {
+        let mtype = m.msg_type();
+        match mtype {
+            MessageType::Signal => ConnectionItem::Signal(m),
+            MessageType::MethodReturn => ConnectionItem::MethodReturn(m),
+            MessageType::Error => ConnectionItem::MethodReturn(m),
+            MessageType::MethodCall => ConnectionItem::MethodCall(m),
+        }
+    }
+}
+
+
+
+
+#[derive(Clone, Debug)]
+/// Type of messages to be handled by a MsgHandler.
+///
+/// Note: More variants can be added in the future; but unless you're writing your own D-Bus engine
+/// you should not have to match on these anyway.
+pub enum MsgHandlerType {
+    /// Handle all messages
+    All,
+    /// Handle only messages of a specific type
+    MsgType(MessageType),
+    /// Handle only method replies with this serial number
+    Reply(u32),
+}
+
+impl MsgHandlerType {
+    fn matches_msg(&self, m: &Message) -> bool {
+        match *self {
+            MsgHandlerType::All => true,
+            MsgHandlerType::MsgType(t) => m.msg_type() == t,
+            MsgHandlerType::Reply(serial) => {
+                let t = m.msg_type();
+                ((t == MessageType::MethodReturn) || (t == MessageType::Error)) && (m.get_reply_serial() == Some(serial))
+            }
+        }
+    }
+}
+
+/// A trait for handling incoming messages.
+pub trait MsgHandler {
+    /// Type of messages for which the handler will be called
+    ///
+    /// Note: The return value of this function might be cached, so it must return the same value all the time.
+    fn handler_type(&self) -> MsgHandlerType;
+
+    /// Function to be called if the message matches the MsgHandlerType
+    fn handle_msg(&mut self, _msg: &Message) -> Option<MsgHandlerResult> { None }
+}
+
+/// The result from MsgHandler::handle.
+#[derive(Debug, Default)]
+pub struct MsgHandlerResult {
+    /// Indicates that the message has been dealt with and should not be processed further.
+    pub handled: bool,
+    /// Indicates that this MsgHandler no longer wants to receive messages and should be removed.
+    pub done: bool,
+    /// Messages to send (e g, a reply to a method call)
+    pub reply: Vec<Message>,
+}
+
+
+type MsgHandlerList = Vec<Box<dyn MsgHandler>>;
+
+/// The struct returned from `Connection::send_and_reply`.
+///
+/// It implements the `MsgHandler` trait so you can use `Connection::add_handler`.
+pub struct MessageReply<F>(Option<F>, u32);
+
+impl<'a, F: FnOnce(Result<&Message, Error>) + 'a> MsgHandler for MessageReply<F> {
+    fn handler_type(&self) -> MsgHandlerType { MsgHandlerType::Reply(self.1) }
+    fn handle_msg(&mut self, msg: &Message) -> Option<MsgHandlerResult> {
+        let e = match msg.msg_type() {
+            MessageType::MethodReturn => Ok(msg),
+            MessageType::Error => Err(msg.set_error_from_msg().unwrap_err()),
+            _ => unreachable!(),
+        };
+        debug_assert_eq!(msg.get_reply_serial(), Some(self.1));
+        self.0.take().unwrap()(e);
+        return Some(MsgHandlerResult { handled: true, done: true, reply: Vec::new() })
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::{Connection, BusType, ConnectionItem, NameFlag,
+        RequestNameReply, ReleaseNameReply};
+    use crate::Message;
+
+    #[test]
+    fn connection() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = c.unique_name();
+        assert!(n.starts_with(":1."));
+        println!("Connected to DBus, unique name: {}", n);
+    }
+
+    #[test]
+    fn invalid_message() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
+        let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
+        assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
+    }
+
+    #[test]
+    fn object_path() {
+        use  std::sync::mpsc;
+        let (tx, rx) = mpsc::channel();
+        let thread = ::std::thread::spawn(move || {
+            let c = Connection::get_private(BusType::Session).unwrap();
+            c.register_object_path("/hello").unwrap();
+            // println!("Waiting...");
+            tx.send(c.unique_name()).unwrap();
+            for n in c.iter(1000) {
+                // println!("Found message... ({})", n);
+                match n {
+                    ConnectionItem::MethodCall(ref m) => {
+                        let reply = Message::new_method_return(m).unwrap();
+                        c.send(reply).unwrap();
+                        break;
+                    }
+                    _ => {}
+                }
+            }
+            c.unregister_object_path("/hello");
+        });
+
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = rx.recv().unwrap();
+        let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
+        println!("Sending...");
+        let r = c.send_with_reply_and_block(m, 8000).unwrap();
+        let reply = r.get_items();
+        println!("{:?}", reply);
+        thread.join().unwrap();
+
+    }
+
+    #[test]
+    fn register_name() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let n = format!("com.example.hello.test.register_name");
+        assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
+        assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
+    }
+
+    #[test]
+    fn signal() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let iface = "com.example.signaltest";
+        let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
+        c.add_match(&mstr).unwrap();
+        let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
+        let uname = c.unique_name();
+        c.send(m).unwrap();
+        for n in c.iter(1000) {
+            match n {
+                ConnectionItem::Signal(s) => {
+                    let (p, i, m) = (s.path(), s.interface(), s.member());
+                    match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
+                        ("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
+                            assert_eq!(&*s.sender().unwrap(), &*uname);
+                            break;
+                        },
+                        (_, _, _) => println!("Other signal: {:?}", s),
+                    }
+                }
+                _ => {},
+            }
+        }
+        c.remove_match(&mstr).unwrap();
+    }
+
+
+    #[test]
+    fn watch() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        let d = c.watch_fds();
+        assert!(d.len() > 0);
+        println!("Fds to watch: {:?}", d);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/ffidisp/connection.rs
@@ -0,0 +1,632 @@
+//! Contains structs and traits relevant to the connection itself, and dispatching incoming messages.
+
+use crate::{Error, Message, MessageType, c_str_to_slice, channel::WatchFd, ffi, to_c_str};
+use crate::ffidisp::ConnPath;
+use std::{fmt, mem, ptr, thread, panic, ops};
+use std::{collections::VecDeque, time::Duration};
+use std::cell::{Cell, RefCell};
+use std::os::raw::{c_void, c_char, c_int, c_uint};
+use crate::strings::{BusName, Path};
+use super::{Watch, WatchList, MessageCallback, ConnectionItem, MsgHandler, MsgHandlerList, MessageReply, BusType};
+
+
+/* Since we register callbacks with userdata pointers,
+   we need to make sure the connection pointer does not move around.
+   Hence this extra indirection. */
+struct IConnection {
+    conn: Cell<*mut ffi::DBusConnection>,
+    pending_items: RefCell<VecDeque<Message>>,
+    watches: Option<Box<WatchList>>,
+    handlers: RefCell<super::MsgHandlerList>,
+
+    filter_cb: RefCell<Option<MessageCallback>>,
+    filter_cb_panic: RefCell<thread::Result<()>>,
+}
+
+/// A D-Bus connection. Start here if you want to get on the D-Bus!
+pub struct Connection {
+    i: Box<IConnection>,
+}
+
+pub (crate) fn conn_handle(c: &Connection) -> *mut ffi::DBusConnection {
+    c.i.conn.get()
+}
+
+extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
+    user_data: *mut c_void) -> ffi::DBusHandlerResult {
+
+    let i: &IConnection = unsafe { mem::transmute(user_data) };
+    let connref: panic::AssertUnwindSafe<&Connection> = unsafe { mem::transmute(&i) };
+    if i.conn.get() != conn || i.filter_cb_panic.try_borrow().is_err() {
+        // This should never happen, but let's be extra sure
+        // process::abort(); ??
+        return ffi::DBusHandlerResult::Handled;
+    }
+    if i.filter_cb_panic.borrow().is_err() {
+        // We're in panic mode. Let's quit this ASAP
+        return ffi::DBusHandlerResult::Handled;
+    }
+
+    let fcb = panic::AssertUnwindSafe(&i.filter_cb);
+    let r = panic::catch_unwind(|| {
+        let m = Message::from_ptr(msg, true);
+        let mut cb = fcb.borrow_mut().take().unwrap(); // Take the callback out while we call it.
+        let r = cb(connref.0, m);
+        let mut cb2 = fcb.borrow_mut(); // If the filter callback has not been replaced, put it back in.
+        if cb2.is_none() { *cb2 = Some(cb) };
+        r
+    });
+
+    match r {
+        Ok(false) => ffi::DBusHandlerResult::NotYetHandled,
+        Ok(true) => ffi::DBusHandlerResult::Handled,
+        Err(e) => {
+            *i.filter_cb_panic.borrow_mut() = Err(e);
+            ffi::DBusHandlerResult::Handled
+        }
+    }
+}
+
+fn default_filter_callback(c: &Connection, m: Message) -> bool {
+    let b = m.msg_type() == MessageType::Signal;
+    c.i.pending_items.borrow_mut().push_back(m);
+    b
+}
+
+extern "C" fn object_path_message_cb(_conn: *mut ffi::DBusConnection, _msg: *mut ffi::DBusMessage,
+    _user_data: *mut c_void) -> ffi::DBusHandlerResult {
+    /* Already pushed in filter_message_cb, so we just set the handled flag here to disable the
+       "default" handler. */
+    ffi::DBusHandlerResult::Handled
+}
+
+impl Connection {
+    #[inline(always)]
+    fn conn(&self) -> *mut ffi::DBusConnection {
+        self.i.conn.get()
+    }
+
+    fn conn_from_ptr(conn: *mut ffi::DBusConnection) -> Result<Connection, Error> {
+        let mut c = Connection { i: Box::new(IConnection {
+            conn: Cell::new(conn),
+            pending_items: RefCell::new(VecDeque::new()),
+            watches: None,
+            handlers: RefCell::new(vec!()),
+            filter_cb: RefCell::new(Some(Box::new(default_filter_callback))),
+            filter_cb_panic: RefCell::new(Ok(())),
+        })};
+
+        /* No, we don't want our app to suddenly quit if dbus goes down */
+        unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
+        assert!(unsafe {
+            ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb), mem::transmute(&*c.i), None)
+        } != 0);
+
+        c.i.watches = Some(WatchList::new(&c, Box::new(|_| {})));
+        Ok(c)
+    }
+
+    /// Creates a new connection to the session bus.
+    ///
+    /// Just a shortcut for `get_private(BusType::Session)`.
+    pub fn new_session() -> Result<Connection, Error> { Self::get_private(BusType::Session) }
+
+    /// Creates a new connection to the system bus.
+    ///
+    /// Just a shortcut for `get_private(BusType::System)`.
+    pub fn new_system() -> Result<Connection, Error> { Self::get_private(BusType::System) }
+
+    /// Creates a new D-Bus connection.
+    pub fn get_private(bus: BusType) -> Result<Connection, Error> {
+        let mut e = Error::empty();
+        let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
+        if conn.is_null() {
+            return Err(e)
+        }
+        Self::conn_from_ptr(conn)
+    }
+
+    /// Creates a new D-Bus connection to a remote address.
+    ///
+    /// Note: for all common cases (System / Session bus) you probably want "get_private" instead.
+    pub fn open_private(address: &str) -> Result<Connection, Error> {
+        let mut e = Error::empty();
+        let conn = unsafe { ffi::dbus_connection_open_private(to_c_str(address).as_ptr(), e.get_mut()) };
+        if conn.is_null() {
+            return Err(e)
+        }
+        Self::conn_from_ptr(conn)
+    }
+
+    /// Registers a new D-Bus connection with the bus.
+    ///
+    /// Note: `get_private` does this automatically, useful with `open_private`
+    pub fn register(&self) -> Result<(), Error> {
+        let mut e = Error::empty();
+        if unsafe { ffi::dbus_bus_register(self.conn(), e.get_mut()) == 0 } {
+            Err(e)
+        } else {
+            Ok(())
+        }
+    }
+
+    /// Gets whether the connection is currently open.
+    pub fn is_connected(&self) -> bool {
+        unsafe { ffi::dbus_connection_get_is_connected(self.conn()) != 0 }
+    }
+
+    /// Sends a message over the D-Bus and waits for a reply.
+    /// This is usually used for method calls.
+    pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
+        let mut e = Error::empty();
+        let response = unsafe {
+            ffi::dbus_connection_send_with_reply_and_block(self.conn(), msg.ptr(),
+                timeout_ms as c_int, e.get_mut())
+        };
+        if response.is_null() {
+            return Err(e);
+        }
+        Ok(Message::from_ptr(response, false))
+    }
+
+    /// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
+    pub fn send(&self, msg: Message) -> Result<u32,()> {
+        let mut serial = 0u32;
+        let r = unsafe { ffi::dbus_connection_send(self.conn(), msg.ptr(), &mut serial) };
+        if r == 0 { return Err(()); }
+        unsafe { ffi::dbus_connection_flush(self.conn()) };
+        Ok(serial)
+    }
+
+    /// Sends a message over the D-Bus, returning a MessageReply.
+    ///
+    /// Call add_handler on the result to start waiting for reply. This should be done before next call to `incoming` or `iter`.
+    pub fn send_with_reply<'a, F: FnOnce(Result<&Message, Error>) + 'a>(&self, msg: Message, f: F) -> Result<MessageReply<F>, ()> {
+        let serial = self.send(msg)?;
+        Ok(MessageReply(Some(f), serial))
+    }
+
+    /// Adds a message handler to the connection.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use std::{cell, rc};
+    /// use dbus::{ffidisp::Connection, Message};
+    ///
+    /// let c = Connection::new_session().unwrap();
+    /// let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
+    ///
+    /// let done: rc::Rc<cell::Cell<bool>> = Default::default();
+    /// let done2 = done.clone();
+    /// c.add_handler(c.send_with_reply(m, move |reply| {
+    ///     let v: Vec<&str> = reply.unwrap().read1().unwrap();
+    ///     println!("The names on the D-Bus are: {:?}", v);
+    ///     done2.set(true);
+    /// }).unwrap());
+    /// while !done.get() { c.incoming(100).next(); }
+    /// ```
+    pub fn add_handler<H: MsgHandler + 'static>(&self, h: H) {
+        let h = Box::new(h);
+        self.i.handlers.borrow_mut().push(h);
+    }
+
+    /// Removes a MsgHandler from the connection.
+    ///
+    /// If there are many MsgHandlers, it is not specified which one will be returned.
+    ///
+    /// There might be more methods added later on, which give better ways to deal
+    /// with the list of MsgHandler currently on the connection. If this would help you,
+    /// please [file an issue](https://github.com/diwic/dbus-rs/issues).
+    pub fn extract_handler(&self) -> Option<Box<dyn MsgHandler>> {
+        self.i.handlers.borrow_mut().pop()
+    }
+
+    /// Get the connection's unique name.
+    pub fn unique_name(&self) -> String {
+        let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
+        c_str_to_slice(&c).unwrap_or("").to_string()
+    }
+
+    /// Check if there are new incoming events
+    ///
+    /// If there are no incoming events, ConnectionItems::Nothing will be returned.
+    /// See ConnectionItems::new if you want to customize this behaviour.
+    pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
+        ConnectionItems::new(self, Some(timeout_ms), false)
+    }
+
+    /// Check if there are new incoming events
+    ///
+    /// Supersedes "iter".
+    pub fn incoming(&self, timeout_ms: u32) -> ConnMsgs<&Self> {
+        ConnMsgs { conn: &self, timeout_ms: Some(timeout_ms) }
+    }
+
+    /// Register an object path.
+    pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
+        let mut e = Error::empty();
+        let p = to_c_str(path);
+        let vtable = ffi::DBusObjectPathVTable {
+            unregister_function: None,
+            message_function: Some(object_path_message_cb),
+            dbus_internal_pad1: None,
+            dbus_internal_pad2: None,
+            dbus_internal_pad3: None,
+            dbus_internal_pad4: None,
+        };
+        let r = unsafe {
+            let user_data: *mut c_void = mem::transmute(&*self.i);
+            ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
+        };
+        if r == 0 { Err(e) } else { Ok(()) }
+    }
+
+    /// Unregister an object path.
+    pub fn unregister_object_path(&self, path: &str) {
+        let p = to_c_str(path);
+        let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
+        if r == 0 { panic!("Out of memory"); }
+    }
+
+    /// List registered object paths.
+    pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
+        let p = to_c_str(path);
+        let mut clist: *mut *mut c_char = ptr::null_mut();
+        let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
+        if r == 0 { panic!("Out of memory"); }
+        let mut v = Vec::new();
+        let mut i = 0;
+        loop {
+            let s = unsafe {
+                let citer = clist.offset(i);
+                if *citer == ptr::null_mut() { break };
+                mem::transmute(citer)
+            };
+            v.push(format!("{}", c_str_to_slice(s).unwrap()));
+            i += 1;
+        }
+        unsafe { ffi::dbus_free_string_array(clist) };
+        v
+    }
+
+    /// Register a name.
+    pub fn register_name(&self, name: &str, flags: u32) -> Result<super::RequestNameReply, Error> {
+        let mut e = Error::empty();
+        let n = to_c_str(name);
+        let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
+        if r == -1 { Err(e) } else { Ok(unsafe { mem::transmute(r) }) }
+    }
+
+    /// Release a name.
+    pub fn release_name(&self, name: &str) -> Result<super::ReleaseNameReply, Error> {
+        let mut e = Error::empty();
+        let n = to_c_str(name);
+        let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
+        if r == -1 { Err(e) } else { Ok(unsafe { mem::transmute(r) }) }
+    }
+
+    /// Add a match rule to match messages on the message bus.
+    ///
+    /// See the `unity_focused_window` example for how to use this to catch signals.
+    /// (The syntax of the "rule" string is specified in the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules).)
+    pub fn add_match(&self, rule: &str) -> Result<(), Error> {
+        let mut e = Error::empty();
+        let n = to_c_str(rule);
+        unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
+        if e.name().is_some() { Err(e) } else { Ok(()) }
+    }
+
+    /// Remove a match rule to match messages on the message bus.
+    pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
+        let mut e = Error::empty();
+        let n = to_c_str(rule);
+        unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
+        if e.name().is_some() { Err(e) } else { Ok(()) }
+    }
+
+    /// Async I/O: Get an up-to-date list of file descriptors to watch.
+    ///
+    /// See the `Watch` struct for an example.
+    pub fn watch_fds(&self) -> Vec<Watch> {
+        self.i.watches.as_ref().unwrap().get_enabled_fds()
+    }
+
+    /// Async I/O: Call this function whenever you detected an event on the Fd,
+    /// Flags are a set of WatchEvent bits.
+    /// The returned iterator will return pending items only, never block for new events.
+    ///
+    /// See the `Watch` struct for an example.
+    pub fn watch_handle(&self, fd: WatchFd, flags: c_uint) -> ConnectionItems {
+        self.i.watches.as_ref().unwrap().watch_handle(fd, flags);
+        ConnectionItems::new(self, None, true)
+    }
+
+    /// Create a convenience struct for easier calling of many methods on the same destination and path.
+    pub fn with_path<'a, D: Into<BusName<'a>>, P: Into<Path<'a>>>(&'a self, dest: D, path: P, timeout_ms: i32) ->
+        ConnPath<'a, &'a Connection> {
+        ConnPath { conn: self, dest: dest.into(), path: path.into(), timeout: timeout_ms }
+    }
+
+    /// Replace the default message callback. Returns the previously set callback.
+    ///
+    /// By default, when you call ConnectionItems::next, all relevant incoming messages
+    /// are returned through the ConnectionItems iterator, and
+    /// irrelevant messages are passed on to libdbus's default handler.
+    /// If you need to customize this behaviour (i e, to handle all incoming messages yourself),
+    /// you can set this message callback yourself. A few caveats apply:
+    ///
+    /// Return true from the callback to disable libdbus's internal handling of the message, or
+    /// false to allow it. In other words, true and false correspond to
+    /// `DBUS_HANDLER_RESULT_HANDLED` and `DBUS_HANDLER_RESULT_NOT_YET_HANDLED` respectively.
+    ///
+    /// Be sure to call the previously set callback from inside your callback,
+    /// if you want, e.g. ConnectionItems::next to yield the message.
+    ///
+    /// You can unset the message callback (might be useful to satisfy the borrow checker), but
+    /// you will get a panic if you call ConnectionItems::next while the message callback is unset.
+    /// The message callback will be temporary unset while inside a message callback, so calling
+    /// ConnectionItems::next recursively will also result in a panic.
+    ///
+    /// If your message callback panics, ConnectionItems::next will panic, too.
+    ///
+    /// # Examples
+    ///
+    /// Replace the default callback with our own:
+    ///
+    /// ```ignore
+    /// use dbus::ffidisp::Connection;
+    /// let c = Connection::new_session().unwrap();
+    /// // Set our callback
+    /// c.replace_message_callback(Some(Box::new(move |conn, msg| {
+    ///     println!("Got message: {:?}", msg.get_items());
+    ///     // Let libdbus handle some things by default,
+    ///     // like "nonexistent object" error replies to method calls
+    ///     false
+    /// })));
+    ///
+    /// for _ in c.iter(1000) {
+    ///    // Only `ConnectionItem::Nothing` would be ever yielded here.
+    /// }
+    /// ```
+    ///
+    /// Chain our callback to filter out some messages before `iter().next()`:
+    ///
+    /// ```
+    /// use dbus::{ffidisp::Connection, MessageType};
+    /// let c = Connection::new_session().unwrap();
+    /// // Take the previously set callback
+    /// let mut old_cb = c.replace_message_callback(None).unwrap();
+    /// // Set our callback
+    /// c.replace_message_callback(Some(Box::new(move |conn, msg| {
+    ///     // Handle all signals on the spot
+    ///     if msg.msg_type() == MessageType::Signal {
+    ///         println!("Got signal: {:?}", msg.get_items());
+    ///         // Stop all further processing of the message
+    ///         return true;
+    ///     }
+    ///     // Delegate the rest of the messages to the previous callback
+    ///     // in chain, e.g. to have them yielded by `iter().next()`
+    ///     old_cb(conn, msg)
+    /// })));
+    ///
+    /// # if false {
+    /// for _ in c.iter(1000) {
+    ///    // `ConnectionItem::Signal` would never be yielded here.
+    /// }
+    /// # }
+    /// ```
+    pub fn replace_message_callback(&self, f: Option<MessageCallback>) -> Option<MessageCallback> {
+        mem::replace(&mut *self.i.filter_cb.borrow_mut(), f)
+    }
+
+    /// Sets a callback to be called if a file descriptor status changes.
+    ///
+    /// For async I/O. In rare cases, the number of fds to poll for read/write can change.
+    /// If this ever happens, you'll get a callback. The watch changed is provided as a parameter.
+    ///
+    /// In rare cases this might not even happen in the thread calling anything on the connection,
+    /// so the callback needs to be `Send`.
+    /// A mutex is held during the callback. If you try to call set_watch_callback from a callback,
+    /// you will deadlock.
+    ///
+    /// (Previously, this was instead put in a ConnectionItem queue, but this was not working correctly.
+    /// see https://github.com/diwic/dbus-rs/issues/99 for additional info.)
+    pub fn set_watch_callback(&self, f: Box<dyn Fn(Watch) + Send>) { self.i.watches.as_ref().unwrap().set_on_update(f); }
+
+    fn check_panic(&self) {
+        let p = mem::replace(&mut *self.i.filter_cb_panic.borrow_mut(), Ok(()));
+        if let Err(perr) = p { panic::resume_unwind(perr); }
+    }
+
+    fn next_msg(&self) -> Option<Message> {
+        while let Some(msg) = self.i.pending_items.borrow_mut().pop_front() {
+            let mut v: MsgHandlerList = mem::replace(&mut *self.i.handlers.borrow_mut(), vec!());
+            let b = msghandler_process(&mut v, &msg, self);
+            let mut v2 = self.i.handlers.borrow_mut();
+            v.append(&mut *v2);
+            *v2 = v;
+            if !b { return Some(msg) };
+        };
+        None
+    }
+
+}
+
+impl Drop for Connection {
+    fn drop(&mut self) {
+        unsafe {
+            ffi::dbus_connection_close(self.conn());
+            ffi::dbus_connection_unref(self.conn());
+        }
+    }
+}
+
+impl fmt::Debug for Connection {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        write!(f, "D-Bus Connection({})", self.unique_name())
+    }
+}
+
+impl crate::channel::Sender for Connection {
+    fn send(&self, msg: Message) -> Result<u32, ()> { Connection::send(self, msg) }
+}
+
+impl crate::blocking::BlockingSender for Connection {
+    fn send_with_reply_and_block(&self, msg: Message, timeout: Duration) -> Result<Message, Error> {
+        Connection::send_with_reply_and_block(self, msg, timeout.as_millis() as i32)
+    }
+}
+
+
+fn msghandler_process(v: &mut MsgHandlerList, m: &Message, c: &Connection) -> bool {
+    let mut ii: isize = -1;
+    loop {
+        ii += 1;
+        let i = ii as usize;
+        if i >= v.len() { return false };
+
+        if !v[i].handler_type().matches_msg(m) { continue; }
+        if let Some(r) = v[i].handle_msg(m) {
+            for msg in r.reply.into_iter() { c.send(msg).unwrap(); }
+            if r.done { v.remove(i); ii -= 1; }
+            if r.handled { return true; }
+        }
+    }
+}
+
+/// ConnectionItem iterator
+pub struct ConnectionItems<'a> {
+    c: &'a Connection,
+    timeout_ms: Option<i32>,
+    end_on_timeout: bool,
+    handlers: MsgHandlerList,
+}
+
+impl<'a> ConnectionItems<'a> {
+    /// Builder method that adds a new msg handler.
+    ///
+    /// Note: Likely to changed/refactored/removed in next release
+    pub fn with<H: 'static + MsgHandler>(mut self, h: H) -> Self {
+        self.handlers.push(Box::new(h)); self
+    }
+
+    // Returns true if processed, false if not
+    fn process_handlers(&mut self, ci: &ConnectionItem) -> bool {
+        let m = match *ci {
+            ConnectionItem::MethodReturn(ref msg) => msg,
+            ConnectionItem::Signal(ref msg) => msg,
+            ConnectionItem::MethodCall(ref msg) => msg,
+            ConnectionItem::Nothing => return false,
+        };
+
+        msghandler_process(&mut self.handlers, m, &self.c)
+    }
+
+    /// Access and modify message handlers
+    ///
+    /// Note: Likely to changed/refactored/removed in next release
+    pub fn msg_handlers(&mut self) -> &mut Vec<Box<dyn MsgHandler>> { &mut self.handlers }
+
+    /// Creates a new ConnectionItems iterator
+    ///
+    /// For io_timeout, setting None means the fds will not be read/written. I e, only pending
+    /// items in libdbus's internal queue will be processed.
+    ///
+    /// For end_on_timeout, setting false will means that the iterator will never finish (unless
+    /// the D-Bus server goes down). Instead, ConnectionItem::Nothing will be returned in case no
+    /// items are in queue.
+    pub fn new(conn: &'a Connection, io_timeout: Option<i32>, end_on_timeout: bool) -> Self {
+        ConnectionItems {
+            c: conn,
+            timeout_ms: io_timeout,
+            end_on_timeout: end_on_timeout,
+            handlers: Vec::new(),
+        }
+    }
+}
+
+impl<'a> Iterator for ConnectionItems<'a> {
+    type Item = ConnectionItem;
+    fn next(&mut self) -> Option<ConnectionItem> {
+        loop {
+            if self.c.i.filter_cb.borrow().is_none() { panic!("ConnectionItems::next called recursively or with a MessageCallback set to None"); }
+            let i: Option<ConnectionItem> = self.c.next_msg().map(|x| x.into());
+            if let Some(ci) = i {
+                if !self.process_handlers(&ci) { return Some(ci); }
+            }
+
+            if let Some(t) = self.timeout_ms {
+                let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), t as c_int) };
+                self.c.check_panic();
+                if !self.c.i.pending_items.borrow().is_empty() { continue };
+                if r == 0 { return None; }
+            }
+
+            let r = unsafe { ffi::dbus_connection_dispatch(self.c.conn()) };
+            self.c.check_panic();
+
+            if !self.c.i.pending_items.borrow().is_empty() { continue };
+            if r == ffi::DBusDispatchStatus::DataRemains { continue };
+            if r == ffi::DBusDispatchStatus::Complete { return if self.end_on_timeout { None } else { Some(ConnectionItem::Nothing) } };
+            panic!("dbus_connection_dispatch failed");
+        }
+    }
+}
+
+/// Iterator over incoming messages on a connection.
+#[derive(Debug, Clone)]
+pub struct ConnMsgs<C> {
+    /// The connection or some reference to it.
+    pub conn: C,
+    /// How many ms dbus should block, waiting for incoming messages until timing out.
+    ///
+    /// If set to None, the dbus library will not read/write from file descriptors at all.
+    /// Instead the iterator will end when there's nothing currently in the queue.
+    pub timeout_ms: Option<u32>,
+}
+
+impl<C: ops::Deref<Target = Connection>> Iterator for ConnMsgs<C> {
+    type Item = Message;
+    fn next(&mut self) -> Option<Self::Item> {
+
+        loop {
+            let iconn = &self.conn.i;
+            if iconn.filter_cb.borrow().is_none() { panic!("ConnMsgs::next called recursively or with a MessageCallback set to None"); }
+            let i = self.conn.next_msg();
+            if let Some(ci) = i { return Some(ci); }
+
+            if let Some(t) = self.timeout_ms {
+                let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.conn.conn(), t as c_int) };
+                self.conn.check_panic();
+                if !iconn.pending_items.borrow().is_empty() { continue };
+                if r == 0 { return None; }
+            }
+
+            let r = unsafe { ffi::dbus_connection_dispatch(self.conn.conn()) };
+            self.conn.check_panic();
+
+            if !iconn.pending_items.borrow().is_empty() { continue };
+            if r == ffi::DBusDispatchStatus::DataRemains { continue };
+            if r == ffi::DBusDispatchStatus::Complete { return None }
+            panic!("dbus_connection_dispatch failed");
+        }
+    }
+}
+
+#[test]
+fn message_reply() {
+    use std::{cell, rc};
+    let c = Connection::get_private(BusType::Session).unwrap();
+    assert!(c.is_connected());
+    let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
+    let quit = rc::Rc::new(cell::Cell::new(false));
+    let quit2 = quit.clone();
+    let reply = c.send_with_reply(m, move |result| {
+        let r = result.unwrap();
+        let _: crate::arg::Array<&str, _>  = r.get1().unwrap();
+        quit2.set(true);
+    }).unwrap();
+    for _ in c.iter(1000).with(reply) { if quit.get() { return; } }
+    assert!(false);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/ffidisp/stdintf.rs
@@ -0,0 +1,233 @@
+//! This module contains some standard interfaces and an easy way to call them.
+//!
+//! See the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces) for more information about these standard interfaces.
+//! 
+//! The code here was originally created by dbus-codegen.
+//!
+//! # Example
+//! ```
+//! use dbus::ffidisp::{Connection, BusType};
+//! use dbus::ffidisp::stdintf::org_freedesktop_dbus::Introspectable;
+//! let c = Connection::get_private(BusType::Session).unwrap();
+//! let p = c.with_path("org.freedesktop.DBus", "/", 10000);
+//! println!("Introspection XML: {}", p.introspect().unwrap());
+//! ```
+//!
+
+#![allow(missing_docs)]
+
+pub use self::org_freedesktop_dbus::Peer as OrgFreedesktopDBusPeer;
+
+pub use self::org_freedesktop_dbus::Introspectable as OrgFreedesktopDBusIntrospectable;
+
+pub use self::org_freedesktop_dbus::Properties as OrgFreedesktopDBusProperties;
+
+pub use self::org_freedesktop_dbus::ObjectManager as OrgFreedesktopDBusObjectManager;
+
+pub mod org_freedesktop_dbus {
+
+use crate::{arg, message, ffidisp};
+
+/// Method of the [org.freedesktop.DBus.Introspectable](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-introspectable) interface.
+pub trait Introspectable {
+    type Err;
+    fn introspect(&self) -> Result<String, Self::Err>;
+}
+
+impl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> Introspectable for ffidisp::ConnPath<'a, C> {
+    type Err = crate::Error;
+
+    fn introspect(&self) -> Result<String, Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Introspectable".into(), &"Introspect".into(), |_| {
+        })?;
+        m.as_result()?;
+        let mut i = m.iter_init();
+        let xml: String = i.read()?;
+        Ok(xml)
+    }
+}
+
+/// Methods of the [org.freedesktop.DBus.Properties](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties) interface.
+pub trait Properties {
+    type Err;
+    fn get<R0: for<'b> arg::Get<'b>>(&self, interface_name: &str, property_name: &str) -> Result<R0, Self::Err>;
+    fn get_all(&self, interface_name: &str) -> Result<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>, Self::Err>;
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> Result<(), Self::Err>;
+}
+
+impl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> Properties for ffidisp::ConnPath<'a, C> {
+    type Err = crate::Error;
+
+    fn get<R0: for<'b> arg::Get<'b>>(&self, interface_name: &str, property_name: &str) -> Result<R0, Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Properties".into(), &"Get".into(), |msg| {
+            let mut i = arg::IterAppend::new(msg);
+            i.append(interface_name);
+            i.append(property_name);
+        })?;
+        m.as_result()?;
+        let mut i = m.iter_init();
+        let value: arg::Variant<R0> = i.read()?;
+        Ok(value.0)
+    }
+
+    fn get_all(&self, interface_name: &str) -> Result<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>, Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Properties".into(), &"GetAll".into(), |msg| {
+            let mut i = arg::IterAppend::new(msg);
+            i.append(interface_name);
+        })?;
+        m.as_result()?;
+        let mut i = m.iter_init();
+        let properties: ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>> = i.read()?;
+        Ok(properties)
+    }
+
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> Result<(), Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Properties".into(), &"Set".into(), |msg| {
+            let mut i = arg::IterAppend::new(msg);
+            i.append(interface_name);
+            i.append(property_name);
+            i.append(arg::Variant(value));
+        })?;
+        m.as_result()?;
+        Ok(())
+    }
+}
+
+#[derive(Debug, Default)]
+/// Struct to send/receive the PropertiesChanged signal of the
+/// [org.freedesktop.DBus.Properties](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties) interface.
+pub struct PropertiesPropertiesChanged {
+    pub interface_name: String,
+    pub changed_properties: ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>,
+    pub invalidated_properties: Vec<String>,
+}
+
+impl arg::AppendAll for PropertiesPropertiesChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.interface_name, i);
+        arg::RefArg::append(&self.changed_properties, i);
+        arg::RefArg::append(&self.invalidated_properties ,i);
+    }
+}
+
+impl arg::ReadAll for PropertiesPropertiesChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(PropertiesPropertiesChanged {
+            interface_name: i.read()?,
+            changed_properties: i.read()?,
+            invalidated_properties: i.read()?,
+        })
+    }
+}
+
+impl message::SignalArgs for PropertiesPropertiesChanged {
+    const NAME: &'static str = "PropertiesChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.Properties";
+}
+
+/// Method of the [org.freedesktop.DBus.ObjectManager](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager) interface.
+pub trait ObjectManager {
+    type Err;
+    fn get_managed_objects(&self) -> Result<::std::collections::HashMap<crate::Path<'static>, ::std::collections::HashMap<String, ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>>>, Self::Err>;
+}
+
+impl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> ObjectManager for ffidisp::ConnPath<'a, C> {
+    type Err = crate::Error;
+
+    fn get_managed_objects(&self) -> Result<::std::collections::HashMap<crate::Path<'static>, ::std::collections::HashMap<String, ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>>>, Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.ObjectManager".into(), &"GetManagedObjects".into(), |_| {
+        })?;
+        m.as_result()?;
+        let mut i = m.iter_init();
+        let objects: ::std::collections::HashMap<crate::Path<'static>, ::std::collections::HashMap<String, ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>>> = i.read()?;
+        Ok(objects)
+    }
+}
+
+#[derive(Debug, Default)]
+/// Struct to send/receive the InterfacesAdded signal of the
+/// [org.freedesktop.DBus.ObjectManager](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager) interface.
+pub struct ObjectManagerInterfacesAdded {
+    pub object: crate::Path<'static>,
+    pub interfaces: ::std::collections::HashMap<String, ::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg>>>>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesAdded {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesAdded {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesAdded {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl message::SignalArgs for ObjectManagerInterfacesAdded {
+    const NAME: &'static str = "InterfacesAdded";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
+
+#[derive(Debug, Default)]
+/// Struct to send/receive the InterfacesRemoved signal of the
+/// [org.freedesktop.DBus.ObjectManager](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager) interface.
+pub struct ObjectManagerInterfacesRemoved {
+    pub object: crate::Path<'static>,
+    pub interfaces: Vec<String>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesRemoved {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesRemoved {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesRemoved {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl message::SignalArgs for ObjectManagerInterfacesRemoved {
+    const NAME: &'static str = "InterfacesRemoved";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
+
+/// Methods of the [org.freedesktop.DBus.Peer](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-peer) interface.
+pub trait Peer {
+    type Err;
+    fn ping(&self) -> Result<(), Self::Err>;
+    fn get_machine_id(&self) -> Result<String, Self::Err>;
+}
+
+impl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> Peer for ffidisp::ConnPath<'a, C> {
+    type Err = crate::Error;
+
+    fn ping(&self) -> Result<(), Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Peer".into(), &"Ping".into(), |_| {
+        })?;
+        m.as_result()?;
+        Ok(())
+    }
+
+    fn get_machine_id(&self) -> Result<String, Self::Err> {
+        let mut m = self.method_call_with_args(&"org.freedesktop.DBus.Peer".into(), &"GetMachineId".into(), |_| {
+        })?;
+        m.as_result()?;
+        let mut i = m.iter_init();
+        let machine_uuid: String = i.read()?;
+        Ok(machine_uuid)
+    }
+}
+
+
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/ffidisp/watch.rs
@@ -0,0 +1,283 @@
+use crate::{channel::WatchFd, ffi};
+use libc;
+use crate::ffidisp::Connection;
+
+use std::mem;
+use std::sync::{Mutex, RwLock};
+#[cfg(unix)]
+use std::os::unix::io::{RawFd, AsRawFd};
+#[cfg(windows)]
+use std::os::windows::io::{RawSocket, AsRawSocket};
+#[cfg(unix)]
+use libc::{POLLIN, POLLOUT, POLLERR, POLLHUP};
+#[cfg(windows)]
+use winapi::um::winsock2::{POLLIN, POLLOUT, POLLERR, POLLHUP};
+use std::os::raw::{c_void, c_uint};
+
+/// A file descriptor to watch for incoming events (for async I/O).
+///
+/// # Example
+/// ```
+/// extern crate libc;
+/// extern crate dbus;
+/// fn main() {
+///     use dbus::ffidisp::{Connection, BusType, WatchEvent};
+///     let c = Connection::get_private(BusType::Session).unwrap();
+///
+///     // Get a list of fds to poll for
+///     let mut fds: Vec<_> = c.watch_fds().iter().map(|w| w.to_pollfd()).collect();
+///
+///     // Poll them with a 1 s timeout
+///     let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, 1000) };
+///     assert!(r >= 0);
+///
+///     // And handle incoming events
+///     for pfd in fds.iter().filter(|pfd| pfd.revents != 0) {
+///         for item in c.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
+///             // Handle item
+///             println!("Received ConnectionItem: {:?}", item);
+///         }
+///     }
+/// }
+/// ```
+
+#[repr(C)]
+#[derive(Debug, PartialEq, Copy, Clone)]
+/// The enum is here for backwards compatibility mostly.
+///
+/// It should really be bitflags instead.
+pub enum WatchEvent {
+    /// The fd is readable
+    Readable = ffi::DBUS_WATCH_READABLE as isize,
+    /// The fd is writable
+    Writable = ffi::DBUS_WATCH_WRITABLE as isize,
+    /// An error occured on the fd
+    Error = ffi::DBUS_WATCH_ERROR as isize,
+    /// The fd received a hangup.
+    Hangup = ffi::DBUS_WATCH_HANGUP as isize,
+}
+
+impl WatchEvent {
+    /// After running poll, this transforms the revents into a parameter you can send into `Connection::watch_handle`
+    pub fn from_revents(revents: libc::c_short) -> c_uint {
+        0 +
+        if (revents & POLLIN) != 0 { WatchEvent::Readable as c_uint } else { 0 } +
+        if (revents & POLLOUT) != 0 { WatchEvent::Writable as c_uint } else { 0 } +
+        if (revents & POLLERR) != 0 { WatchEvent::Error as c_uint } else { 0 } +
+        if (revents & POLLHUP) != 0 { WatchEvent::Hangup as c_uint } else { 0 }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+/// A file descriptor, and an indication whether it should be read from, written to, or both.
+pub struct Watch {
+    fd: WatchFd,
+    read: bool,
+    write: bool,
+}
+
+impl Watch {
+    /// Get the RawFd this Watch is for
+    pub fn fd(&self) -> WatchFd { self.fd }
+    /// Add POLLIN to events to listen for
+    pub fn readable(&self) -> bool { self.read }
+    /// Add POLLOUT to events to listen for
+    pub fn writable(&self) -> bool { self.write }
+    /// Returns the current watch as a libc::pollfd, to use with libc::poll
+    #[cfg(unix)]
+    pub fn to_pollfd(&self) -> libc::pollfd {
+        libc::pollfd { fd: self.fd, revents: 0, events: POLLERR + POLLHUP +
+            if self.readable() { POLLIN } else { 0 } +
+            if self.writable() { POLLOUT } else { 0 },
+        }
+    }
+    /// Returns the current watch as a winapi::um::winsock2::WSAPOLLFD, to use with winapi::um::winsock2::WSAPoll
+    #[cfg(windows)]
+    pub fn to_pollfd(&self) -> winapi::um::winsock2::WSAPOLLFD {
+        winapi::um::winsock2::WSAPOLLFD {
+            fd: self.fd as winapi::um::winsock2::SOCKET,
+            revents: 0, events: 0 +
+            if self.readable() { POLLIN } else { 0 } +
+            if self.writable() { POLLOUT } else { 0 },
+        }
+    }
+}
+
+#[cfg(unix)]
+impl AsRawFd for Watch {
+    fn as_raw_fd(&self) -> RawFd { self.fd }
+}
+
+#[cfg(windows)]
+impl AsRawSocket for Watch {
+    fn as_raw_socket(&self) -> RawSocket { self.fd }
+}
+
+/// Note - internal struct, not to be used outside API. Moving it outside its box will break things.
+pub struct WatchList {
+    watches: RwLock<Vec<*mut ffi::DBusWatch>>,
+    enabled_fds: Mutex<Vec<Watch>>,
+    on_update: Mutex<Box<dyn Fn(Watch) + Send>>,
+}
+
+impl WatchList {
+    pub fn new(c: &Connection, on_update: Box<dyn Fn(Watch) + Send>) -> Box<WatchList> {
+        let w = Box::new(WatchList { on_update: Mutex::new(on_update), watches: RwLock::new(vec!()), enabled_fds: Mutex::new(vec!()) });
+        if unsafe { ffi::dbus_connection_set_watch_functions(crate::ffidisp::connection::conn_handle(c),
+            Some(add_watch_cb), Some(remove_watch_cb), Some(toggled_watch_cb), &*w as *const _ as *mut _, None) } == 0 {
+            panic!("dbus_connection_set_watch_functions failed");
+        }
+        w
+    }
+
+    pub fn set_on_update(&self, on_update: Box<dyn Fn(Watch) + Send>) { *self.on_update.lock().unwrap() = on_update; }
+
+    pub fn watch_handle(&self, fd: WatchFd, flags: c_uint) {
+        // println!("watch_handle {} flags {}", fd, flags);
+        for &q in self.watches.read().unwrap().iter() {
+            let w = self.get_watch(q);
+            if w.fd != fd { continue };
+            if unsafe { ffi::dbus_watch_handle(q, flags) } == 0 {
+                panic!("dbus_watch_handle failed");
+            }
+            self.update(q);
+        };
+    }
+
+    pub fn get_enabled_fds(&self) -> Vec<Watch> {
+        self.enabled_fds.lock().unwrap().clone()
+    }
+
+    fn get_watch(&self, watch: *mut ffi::DBusWatch) -> Watch {
+        #[cfg(unix)]
+        let mut w = Watch { fd: unsafe { ffi::dbus_watch_get_unix_fd(watch) }, read: false, write: false};
+        #[cfg(windows)]
+        let mut w = Watch { fd: unsafe { ffi::dbus_watch_get_socket(watch) as RawSocket }, read: false, write: false};
+        let enabled = self.watches.read().unwrap().contains(&watch) && unsafe { ffi::dbus_watch_get_enabled(watch) != 0 };
+        let flags = unsafe { ffi::dbus_watch_get_flags(watch) };
+        if enabled {
+            w.read = (flags & WatchEvent::Readable as c_uint) != 0;
+            w.write = (flags & WatchEvent::Writable as c_uint) != 0;
+        }
+        // println!("Get watch fd {:?} ptr {:?} enabled {:?} flags {:?}", w, watch, enabled, flags);
+        w
+    }
+
+    fn update(&self, watch: *mut ffi::DBusWatch) {
+        let mut w = self.get_watch(watch);
+
+        for &q in self.watches.read().unwrap().iter() {
+            if q == watch { continue };
+            let ww = self.get_watch(q);
+            if ww.fd != w.fd { continue };
+            w.read |= ww.read;
+            w.write |= ww.write;
+        }
+        // println!("Updated sum: {:?}", w);
+
+        {
+            let mut fdarr = self.enabled_fds.lock().unwrap();
+
+            if w.write || w.read {
+                if fdarr.contains(&w) { return; } // Nothing changed
+            }
+            else if !fdarr.iter().any(|q| w.fd == q.fd) { return; } // Nothing changed
+
+            fdarr.retain(|f| f.fd != w.fd);
+            if w.write || w.read { fdarr.push(w) };
+        }
+        let func = self.on_update.lock().unwrap();
+        (*func)(w);
+    }
+}
+
+extern "C" fn add_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) -> u32 {
+    let wlist: &WatchList = unsafe { mem::transmute(data) };
+    // println!("Add watch {:?}", watch);
+    wlist.watches.write().unwrap().push(watch);
+    wlist.update(watch);
+    1
+}
+
+extern "C" fn remove_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) {
+    let wlist: &WatchList = unsafe { mem::transmute(data) };
+    // println!("Removed watch {:?}", watch);
+    wlist.watches.write().unwrap().retain(|w| *w != watch);
+    wlist.update(watch);
+}
+
+extern "C" fn toggled_watch_cb(watch: *mut ffi::DBusWatch, data: *mut c_void) {
+    let wlist: &WatchList = unsafe { mem::transmute(data) };
+    // println!("Toggled watch {:?}", watch);
+    wlist.update(watch);
+}
+
+#[cfg(test)]
+mod test {
+    #[cfg(unix)]
+    use libc;
+    use super::super::{Connection, Message, BusType, WatchEvent, ConnectionItem, MessageType};
+    use super::{POLLIN, POLLOUT};
+
+    #[test]
+    fn test_async() {
+        let c = Connection::get_private(BusType::Session).unwrap();
+        c.register_object_path("/test").unwrap();
+        let m = Message::new_method_call(&c.unique_name(), "/test", "com.example.asynctest", "AsyncTest").unwrap();
+        let serial = c.send(m).unwrap();
+        println!("Async: sent serial {}", serial);
+
+        let mut fds: Vec<_> = c.watch_fds().iter().map(|w| w.to_pollfd()).collect();
+        let mut new_fds = None;
+        let mut i = 0;
+        let mut success = false;
+        while !success {
+            i += 1;
+            if let Some(q) = new_fds { fds = q; new_fds = None };
+
+            for f in fds.iter_mut() { f.revents = 0 };
+
+            #[cfg(unix)]
+            assert!(unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, 1000) } > 0);
+
+            #[cfg(windows)]
+            assert!(unsafe { winapi::um::winsock2::WSAPoll(fds.as_mut_ptr(), fds.len() as u32, 1000) } > 0);
+
+            for f in fds.iter().filter(|pfd| pfd.revents != 0) {
+                let m = WatchEvent::from_revents(f.revents);
+                println!("Async: fd {}, revents {} -> {}", f.fd, f.revents, m);
+                assert!(f.revents & POLLIN != 0 || f.revents & POLLOUT != 0);
+
+                #[cfg(unix)]
+                let fd = f.fd;
+                #[cfg(windows)]
+                let fd = f.fd as std::os::windows::io::RawSocket;
+
+                for e in c.watch_handle(fd, m) {
+                    println!("Async: got {:?}", e);
+                    match e {
+                        ConnectionItem::MethodCall(m) => {
+                            assert_eq!(m.msg_type(), MessageType::MethodCall);
+                            assert_eq!(&*m.path().unwrap(), "/test");
+                            assert_eq!(&*m.interface().unwrap(), "com.example.asynctest");
+                            assert_eq!(&*m.member().unwrap(), "AsyncTest");
+                            let mut mr = Message::new_method_return(&m).unwrap();
+                            mr.append_items(&["Goodies".into()]);
+                            c.send(mr).unwrap();
+                        }
+                        ConnectionItem::MethodReturn(m) => {
+                            assert_eq!(m.msg_type(), MessageType::MethodReturn);
+                            assert_eq!(m.get_reply_serial().unwrap(), serial);
+                            let i = m.get_items();
+                            let s: &str = i[0].inner().unwrap();
+                            assert_eq!(s, "Goodies");
+                            success = true;
+                        }
+                        _ => (),
+                    }
+                }
+                if i > 100 { panic!() };
+            }
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/filters.rs
@@ -0,0 +1,57 @@
+use std::collections::BTreeMap;
+use std::vec::Vec;
+use crate::message::MatchRule;
+use crate::Message;
+use crate::channel::Token;
+
+pub struct Filters<F> {
+    list: BTreeMap<Token, (MatchRule<'static>, F)>,
+    nextid: Token,
+}
+
+
+impl<F> Default for Filters<F> {
+    fn default() -> Self { Filters {
+        list: BTreeMap::new(),
+        nextid: Token(1),
+    }}
+}
+
+impl<F> Filters<F> {
+    pub fn add(&mut self, m: MatchRule<'static>, f: F) -> Token {
+        let id = self.nextid;
+        self.nextid.0 += 1;
+        self.list.insert(id, (m, f));
+        id
+    }
+
+    pub fn insert(&mut self, (t, m, f): (Token, MatchRule<'static>, F)) {
+        self.list.insert(t, (m, f));
+    }
+
+    pub fn remove(&mut self, id: Token) -> Option<(MatchRule<'static>, F)> {
+        self.list.remove(&id)
+    }
+
+    /// Removes and returns the first filter which matches the given message.
+    pub fn remove_first_matching(&mut self, msg: &Message) -> Option<(Token, MatchRule<'static>, F)> {
+        if let Some(k) = self.list.iter_mut().find_map(|(k, v)| if v.0.matches(&msg) { Some(*k) } else { None }) {
+            let v = self.list.remove(&k).unwrap();
+            Some((k, v.0, v.1))
+        } else {
+            None
+        }
+    }
+
+    /// Removes and returns all filters which match the given message.
+    pub fn remove_all_matching(&mut self, msg: &Message) -> Vec<(Token, MatchRule<'static>, F)> {
+        let matching: Vec<_> = self.list.iter().filter_map(|(k, v)| if v.0.matches(&msg) { Some(*k) } else { None }).collect();
+        matching
+            .into_iter()
+            .map(|k| {
+                let v = self.list.remove(&k).unwrap();
+                (k, v.0, v.1)
+            })
+            .collect()
+    }
+}
--- a/third_party/rust/dbus/src/lib.rs
+++ b/third_party/rust/dbus/src/lib.rs
@@ -1,284 +1,68 @@
 //! D-Bus bindings for Rust
 //!
 //! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
 //! for communication between processes. It is present by default on almost every
 //! Linux distribution out there, and runs in two instances - one per session, and one
 //! system-wide.
 //!
 //! In addition to the API documentation, which you're currently reading, you might want to
-//! look in the examples directory, which contains many examples and an argument guide.
-//! README.md also contain a few quick "getting started" examples.
+//! look in the examples directory, which contains many examples and some additional documents.
+//! README.md also contains a few quick "getting started" examples (as well as information about
+//! the `futures` and `no-string-validation` features).
 //!
-//! In addition to this crate, there are two companion crates, dbus-codegen for generating Rust
-//! code from D-Bus introspection data, and dbus-tokio for integrating D-Bus with [Tokio](http://tokio.rs).
-//! However, at the time of this writing, these are far less mature than this crate. 
+//! In addition to this crate, there are some companion crates:
+//!  * dbus-tokio for integrating D-Bus with [Tokio](http://tokio.rs)
+//!  * dbus-codegen for generating code from D-Bus introspection data
+//!  * libdbus-sys contains the raw bindings to the C libdbus library.
 
 #![warn(missing_docs)]
 
 extern crate libc;
 
-pub use ffi::DBusBusType as BusType;
-pub use connection::DBusNameFlag as NameFlag;
-pub use ffi::DBusRequestNameReply as RequestNameReply;
-pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
-pub use ffi::DBusMessageType as MessageType;
-
-pub use message::{Message, MessageItem, MessageItemArray, FromMessageItem, OwnedFd, ArrayError, ConnPath};
-pub use connection::{Connection, ConnectionItems, ConnectionItem, ConnMsgs, MsgHandler, MsgHandlerResult, MsgHandlerType, MessageCallback};
-pub use prop::PropHandler;
-pub use prop::Props;
-pub use watch::{Watch, WatchEvent};
-pub use signalargs::SignalArgs;
-
-/// A TypeSig describes the type of a MessageItem.
-#[deprecated(note="Use Signature instead")]
-pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
-
-use std::ffi::{CString, CStr};
-use std::ptr;
-use std::os::raw::c_char;
-
 #[allow(missing_docs)]
 extern crate libdbus_sys as ffi;
-mod message;
-mod prop;
-mod watch;
-mod connection;
-mod signalargs;
+
+pub use crate::message::{Message, MessageType};
+
+pub mod message;
+
+pub mod ffidisp;
+
+mod error;
+pub use error::{Error, MethodErr};
 
-mod matchrule;
-pub use matchrule::MatchRule;
+pub mod channel;
+
+mod filters;
+
+pub mod blocking;
 
-mod strings;
-pub use strings::{Signature, Path, Interface, Member, ErrorName, BusName};
+#[cfg(feature = "futures")]
+pub mod nonblock;
+
+pub mod strings;
+pub use crate::strings::{Signature, Path};
 
 pub mod arg;
 
-pub mod stdintf;
+// pub mod tree;
 
-pub mod tree;
+static INITDBUS: std::sync::Once = std::sync::Once::new();
 
-static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
+use std::ffi::{CString, CStr};
+use std::os::raw::c_char;
 
 fn init_dbus() {
     INITDBUS.call_once(|| {
         if unsafe { ffi::dbus_threads_init_default() } == 0 {
             panic!("Out of memory when trying to initialize D-Bus library!");
         }
     });
 }
 
-/// D-Bus Error wrapper.
-pub struct Error {
-    e: ffi::DBusError,
-}
-
-unsafe impl Send for Error {}
-
-// Note! For this Sync impl to be safe, it requires that no functions that take &self,
-// actually calls into FFI. All functions that call into FFI with a ffi::DBusError
-// must take &mut self.
-
-unsafe impl Sync for Error {}
-
 fn c_str_to_slice(c: & *const c_char) -> Option<&str> {
-    if *c == ptr::null() { None }
+    if c.is_null() { None }
     else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
 }
 
 fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
-
-impl Error {
-
-    /// Create a new custom D-Bus Error.
-    pub fn new_custom(name: &str, message: &str) -> Error {
-        let n = to_c_str(name);
-        let m = to_c_str(&message.replace("%","%%"));
-        let mut e = Error::empty();
-
-        unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
-        e
-    }
-
-    fn empty() -> Error {
-        init_dbus();
-        let mut e = ffi::DBusError {
-            name: ptr::null(),
-            message: ptr::null(),
-            dummy: 0,
-            padding1: ptr::null()
-        };
-        unsafe { ffi::dbus_error_init(&mut e); }
-        Error{ e: e }
-    }
-
-    /// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
-    pub fn name(&self) -> Option<&str> {
-        c_str_to_slice(&self.e.name)
-    }
-
-    /// Custom message, e g 'Could not find a matching object path'
-    pub fn message(&self) -> Option<&str> {
-        c_str_to_slice(&self.e.message)
-    }
-
-    fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
-}
-
-impl Drop for Error {
-    fn drop(&mut self) {
-        unsafe { ffi::dbus_error_free(&mut self.e); }
-    }
-}
-
-impl std::fmt::Debug for Error {
-    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
-        write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
-            self.name().unwrap_or(""))
-    }
-}
-
-impl std::error::Error for Error {
-    fn description(&self) -> &str { "D-Bus error" }
-}
-
-impl std::fmt::Display for Error {
-    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
-        if let Some(x) = self.message() {
-             write!(f, "{:?}", x.to_string())
-        } else { Ok(()) }
-    }
-}
-
-impl From<arg::TypeMismatchError> for Error {
-    fn from(t: arg::TypeMismatchError) -> Error {
-        Error::new_custom("org.freedesktop.DBus.Error.Failed", &format!("{}", t))
-    }
-}
-
-impl From<tree::MethodErr> for Error {
-    fn from(t: tree::MethodErr) -> Error {
-        Error::new_custom(t.errorname(), t.description())
-    }
-}
-
-#[cfg(test)]
-mod test {
-    use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
-        RequestNameReply, ReleaseNameReply};
-
-    #[test]
-    fn connection() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let n = c.unique_name();
-        assert!(n.starts_with(":1."));
-        println!("Connected to DBus, unique name: {}", n);
-    }
-
-    #[test]
-    fn invalid_message() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
-        let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
-        assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
-    }
-
-    #[test]
-    fn message_listnames() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let m = Message::method_call(&"org.freedesktop.DBus".into(), &"/".into(),
-            &"org.freedesktop.DBus".into(), &"ListNames".into());
-        let r = c.send_with_reply_and_block(m, 2000).unwrap();
-        let reply = r.get_items();
-        println!("{:?}", reply);
-    }
-
-    #[test]
-    fn message_namehasowner() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
-        m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
-        let r = c.send_with_reply_and_block(m, 2000).unwrap();
-        let reply = r.get_items();
-        println!("{:?}", reply);
-        assert_eq!(reply, vec!(MessageItem::Bool(true)));
-    }
-
-    #[test]
-    fn object_path() {
-        use  std::sync::mpsc;
-        let (tx, rx) = mpsc::channel();
-        let thread = ::std::thread::spawn(move || {
-            let c = Connection::get_private(BusType::Session).unwrap();
-            c.register_object_path("/hello").unwrap();
-            // println!("Waiting...");
-            tx.send(c.unique_name()).unwrap();
-            for n in c.iter(1000) {
-                // println!("Found message... ({})", n);
-                match n {
-                    ConnectionItem::MethodCall(ref m) => {
-                        let reply = Message::new_method_return(m).unwrap();
-                        c.send(reply).unwrap();
-                        break;
-                    }
-                    _ => {}
-                }
-            }
-            c.unregister_object_path("/hello");
-        });
-
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let n = rx.recv().unwrap();
-        let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
-        println!("Sending...");
-        let r = c.send_with_reply_and_block(m, 8000).unwrap();
-        let reply = r.get_items();
-        println!("{:?}", reply);
-        thread.join().unwrap();
-
-    }
-
-    #[test]
-    fn register_name() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let n = format!("com.example.hello.test.register_name");
-        assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
-        assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
-    }
-
-    #[test]
-    fn signal() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let iface = "com.example.signaltest";
-        let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
-        c.add_match(&mstr).unwrap();
-        let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
-        let uname = c.unique_name();
-        c.send(m).unwrap();
-        for n in c.iter(1000) {
-            match n {
-                ConnectionItem::Signal(s) => {
-                    let (_, p, i, m) = s.headers();
-                    match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
-                        ("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
-                            assert_eq!(&*s.sender().unwrap(), &*uname);
-                            break;
-                        },
-                        (_, _, _) => println!("Other signal: {:?}", s.headers()),
-                    }
-                }
-                _ => {},
-            }
-        }
-        c.remove_match(&mstr).unwrap();
-    }
-
-
-    #[test]
-    fn watch() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let d = c.watch_fds();
-        assert!(d.len() > 0);
-        println!("Fds to watch: {:?}", d);
-    }
-}
--- a/third_party/rust/dbus/src/message.rs
+++ b/third_party/rust/dbus/src/message.rs
@@ -1,715 +1,213 @@
-use std::borrow::Cow;
-use std::{fmt, mem, ptr, ops};
-use super::{ffi, Error, MessageType, Signature, libc, to_c_str, c_str_to_slice, init_dbus};
-use super::{BusName, Path, Interface, Member, ErrorName, Connection, SignalArgs};
-use std::os::unix::io::{RawFd, AsRawFd};
-use std::ffi::CStr;
-use std::os::raw::{c_void, c_char, c_int};
-
-use super::arg::{Append, IterAppend, Get, Iter, Arg, RefArg, TypeMismatchError};
-
-#[derive(Debug,Copy,Clone)]
-/// Errors that can happen when creating a MessageItem::Array.
-pub enum ArrayError {
-    /// The array is empty.
-    EmptyArray,
-    /// The array is composed of different element types.
-    DifferentElementTypes,
-    /// The supplied signature is not a valid array signature
-    InvalidSignature,
-}
-
-fn new_dbus_message_iter() -> ffi::DBusMessageIter { unsafe { mem::zeroed() }}
-
-
-/// An RAII wrapper around Fd to ensure that file descriptor is closed
-/// when the scope ends.
-#[derive(Debug, PartialEq, PartialOrd)]
-pub struct OwnedFd {
-    fd: RawFd
-}
-
-impl OwnedFd {
-    /// Create a new OwnedFd from a RawFd.
-    pub fn new(fd: RawFd) -> OwnedFd {
-        OwnedFd { fd: fd }
-    }
-
-    /// Convert an OwnedFD back into a RawFd.
-    pub fn into_fd(self) -> RawFd {
-        let s = self.fd;
-        ::std::mem::forget(self);
-        s
-    }
-}
-
-impl Drop for OwnedFd {
-    fn drop(&mut self) {
-        unsafe { libc::close(self.fd); }
-    }
-}
+//! Contains structs and traits closely related to D-Bus messages.
 
-impl Clone for OwnedFd {
-    fn clone(&self) -> OwnedFd {
-        OwnedFd::new(unsafe { libc::dup(self.fd) } ) // FIXME: handle errors
-    }
-}
-
-impl AsRawFd for OwnedFd {
-    fn as_raw_fd(&self) -> RawFd {
-        self.fd
-    }
-}
-
-#[derive(Debug, Clone, PartialEq, PartialOrd)]
-/// An array of MessageItem where every MessageItem is of the same type.
-pub struct MessageItemArray {
-    v: Vec<MessageItem>,
-    // signature includes the "a"!
-    sig: Signature<'static>,
-}
+use std::{fmt, ptr};
+use super::{ffi, Error, libc, init_dbus};
+use crate::strings::{BusName, Path, Interface, Member, ErrorName};
+use std::ffi::CStr;
 
-impl MessageItemArray {
-    /// Creates a new array where every element has the supplied signature.
-    ///
-    /// Signature is the full array signature, not the signature of the element.
-    pub fn new(v: Vec<MessageItem>, sig: Signature<'static>) -> Result<MessageItemArray, ArrayError> {
-        let a = MessageItemArray {v: v, sig: sig };
-        if a.sig.as_bytes()[0] != ffi::DBUS_TYPE_ARRAY as u8 { return Err(ArrayError::InvalidSignature) }
-        {
-            let esig = a.element_signature();
-            for i in &a.v {
-                let b = if let MessageItem::DictEntry(ref k, ref v) = *i {
-                     let s = format!("{{{}{}}}", k.signature(), v.signature());
-                     s.as_bytes() == esig.to_bytes()
-                } else {
-                     i.signature().as_cstr() == esig
-                };
-                if !b { return Err(ArrayError::DifferentElementTypes) }
-            }
-        }
-        Ok(a)
-    }
-
-    fn element_signature(&self) -> &CStr {
-        let z = &self.sig.as_cstr().to_bytes_with_nul()[1..];
-        unsafe { CStr::from_bytes_with_nul_unchecked(z) }
-    }
-
-    fn make_sig(m: &MessageItem) -> Signature<'static> {
-        if let MessageItem::DictEntry(ref k, ref v) = *m {
-            Signature::new(format!("a{{{}{}}}", k.signature(), v.signature())).unwrap()
-        } else {
-            Signature::new(format!("a{}", m.signature())).unwrap()
-        }
-    }
+use super::arg::{Append, AppendAll, IterAppend, ReadAll, Get, Iter, Arg, RefArg, TypeMismatchError};
 
-    /// Signature of array (full array signature)
-    pub fn signature(&self) -> &Signature<'static> { &self.sig }
-
-    /// Consumes the MessageItemArray in order to allow you to modify the individual items of the array.
-    pub fn into_vec(self) -> Vec<MessageItem> { self.v }
-}
-
-impl ops::Deref for MessageItemArray {
-    type Target = [MessageItem];
-    fn deref(&self) -> &Self::Target { &self.v }
-}
-
-
-/// MessageItem - used as parameters and return values from
-/// method calls, or as data added to a signal (old, enum version).
-///
-/// Note that the newer generic design (see `arg` module) is both faster
-/// and less error prone than MessageItem, and should be your first hand choice
-/// whenever applicable.
-#[derive(Debug, PartialEq, PartialOrd, Clone)]
-pub enum MessageItem {
-    /// A D-Bus array requires all elements to be of the same type.
-    /// All elements must match the Signature.
-    Array(MessageItemArray),
-    /// A D-Bus struct allows for values of different types.
-    Struct(Vec<MessageItem>),
-    /// A D-Bus variant is a wrapper around another `MessageItem`, which
-    /// can be of any type.
-    Variant(Box<MessageItem>),
-    /// A D-Bus dictionary entry. These are only allowed inside an array.
-    DictEntry(Box<MessageItem>, Box<MessageItem>),
-    /// A D-Bus objectpath requires its content to be a valid objectpath,
-    /// so this cannot be any string.
-    ObjectPath(Path<'static>),
-    /// A D-Bus String is zero terminated, so no \0 s in the String, please.
-    /// (D-Bus strings are also - like Rust strings - required to be valid UTF-8.)
-    Str(String),
-    /// A D-Bus boolean type.
-    Bool(bool),
-    /// A D-Bus unsigned 8 bit type.
-    Byte(u8),
-    /// A D-Bus signed 16 bit type.
-    Int16(i16),
-    /// A D-Bus signed 32 bit type.
-    Int32(i32),
-    /// A D-Bus signed 64 bit type.
-    Int64(i64),
-    /// A D-Bus unsigned 16 bit type.
-    UInt16(u16),
-    /// A D-Bus unsigned 32 bit type.
-    UInt32(u32),
-    /// A D-Bus unsigned 64 bit type.
-    UInt64(u64),
-    /// A D-Bus IEEE-754 double-precision floating point type.
-    Double(f64),
-    /// D-Bus allows for sending file descriptors, which can be used to
-    /// set up SHM, unix pipes, or other communication channels.
-    UnixFd(OwnedFd),
-}
-
-fn iter_get_basic<T>(i: &mut ffi::DBusMessageIter) -> T {
-    unsafe {
-        let mut c: T = mem::zeroed();
-        let p = &mut c as *mut _ as *mut c_void;
-        ffi::dbus_message_iter_get_basic(i, p);
-        c
-    }
-}
-
-fn iter_append_array(i: &mut ffi::DBusMessageIter, a: &[MessageItem], t: &CStr) {
-    let mut subiter = new_dbus_message_iter();
-
-    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_ARRAY, t.as_ptr(), &mut subiter) } != 0);
-    for item in a.iter() {
-//        assert!(item.type_sig() == t);
-        item.iter_append(&mut subiter);
-    }
-    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
-}
-
-fn iter_append_struct(i: &mut ffi::DBusMessageIter, a: &[MessageItem]) {
-    let mut subiter = new_dbus_message_iter();
-    let res = unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_STRUCT, ptr::null(), &mut subiter) };
-    assert!(res != 0);
-    for item in a.iter() {
-        item.iter_append(&mut subiter);
-    }
-    let res2 = unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) };
-    assert!(res2 != 0);
-}
-
-fn iter_append_variant(i: &mut ffi::DBusMessageIter, a: &MessageItem) {
-    let mut subiter = new_dbus_message_iter();
-    let asig = a.signature();
-    let atype = asig.as_cstr();
-    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_VARIANT, atype.as_ptr(), &mut subiter) } != 0);
-    a.iter_append(&mut subiter);
-    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
-}
-
-fn iter_append_dict(i: &mut ffi::DBusMessageIter, k: &MessageItem, v: &MessageItem) {
-    let mut subiter = new_dbus_message_iter();
-    assert!(unsafe { ffi::dbus_message_iter_open_container(i, ffi::DBUS_TYPE_DICT_ENTRY, ptr::null(), &mut subiter) } != 0);
-    k.iter_append(&mut subiter);
-    v.iter_append(&mut subiter);
-    assert!(unsafe { ffi::dbus_message_iter_close_container(i, &mut subiter) } != 0);
+#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
+/// One of the four different message types.
+pub enum MessageType {
+    /// This is a method call D-Bus message
+    MethodCall = 1,
+    /// This is a method return Ok D-Bus message, used when the method call message was successfully processed
+    MethodReturn = 2,
+    /// This is a method return with error D-Bus message, used when the method call message could not be handled
+    Error = 3,
+    /// This is a signal, usually sent to whoever wants to listen
+    Signal = 4,
 }
 
-impl MessageItem {
-    /// Get the D-Bus Signature for this MessageItem.
-    ///
-    /// Note: Since dictionary entries have no valid signature, calling this function for a dict entry will cause a panic.
-    pub fn signature(&self) -> Signature<'static> {
-        use arg::Variant;
-        match *self {
-            MessageItem::Str(_) => <String as Arg>::signature(),
-            MessageItem::Bool(_) => <bool as Arg>::signature(),
-            MessageItem::Byte(_) => <u8 as Arg>::signature(),
-            MessageItem::Int16(_) => <i16 as Arg>::signature(),
-            MessageItem::Int32(_) => <i32 as Arg>::signature(),
-            MessageItem::Int64(_) => <i64 as Arg>::signature(),
-            MessageItem::UInt16(_) => <u16 as Arg>::signature(),
-            MessageItem::UInt32(_) => <u32 as Arg>::signature(),
-            MessageItem::UInt64(_) => <u64 as Arg>::signature(),
-            MessageItem::Double(_) => <f64 as Arg>::signature(),
-            MessageItem::Array(ref a) => a.sig.clone(),
-            MessageItem::Struct(ref s) => Signature::new(format!("({})", s.iter().fold(String::new(), |s, i| s + &*i.signature()))).unwrap(),
-            MessageItem::Variant(_) => <Variant<u8> as Arg>::signature(),
-            MessageItem::DictEntry(_, _) => { panic!("Dict entries are only valid inside arrays, and therefore has no signature on their own") },
-            MessageItem::ObjectPath(_) => <Path as Arg>::signature(),
-            MessageItem::UnixFd(_) => <OwnedFd as Arg>::signature(),
-        }
-    }
-
-    /// Get the D-Bus ASCII type-code for this MessageItem.
-    #[deprecated(note="superseded by signature")]
-    #[allow(deprecated)]
-    pub fn type_sig(&self) -> super::TypeSig<'static> {
-        Cow::Owned(format!("{}", self.signature()))
-    }
-
-    /// Get the integer value for this MessageItem's type-code.
-    pub fn array_type(&self) -> i32 {
-        let s = match self {
-            &MessageItem::Str(_) => ffi::DBUS_TYPE_STRING,
-            &MessageItem::Bool(_) => ffi::DBUS_TYPE_BOOLEAN,
-            &MessageItem::Byte(_) => ffi::DBUS_TYPE_BYTE,
-            &MessageItem::Int16(_) => ffi::DBUS_TYPE_INT16,
-            &MessageItem::Int32(_) => ffi::DBUS_TYPE_INT32,
-            &MessageItem::Int64(_) => ffi::DBUS_TYPE_INT64,
-            &MessageItem::UInt16(_) => ffi::DBUS_TYPE_UINT16,
-            &MessageItem::UInt32(_) => ffi::DBUS_TYPE_UINT32,
-            &MessageItem::UInt64(_) => ffi::DBUS_TYPE_UINT64,
-            &MessageItem::Double(_) => ffi::DBUS_TYPE_DOUBLE,
-            &MessageItem::Array(_) => ffi::DBUS_TYPE_ARRAY,
-            &MessageItem::Struct(_) => ffi::DBUS_TYPE_STRUCT,
-            &MessageItem::Variant(_) => ffi::DBUS_TYPE_VARIANT,
-            &MessageItem::DictEntry(_,_) => ffi::DBUS_TYPE_DICT_ENTRY,
-            &MessageItem::ObjectPath(_) => ffi::DBUS_TYPE_OBJECT_PATH,
-            &MessageItem::UnixFd(_) => ffi::DBUS_TYPE_UNIX_FD,
-        };
-        s as i32
-    }
-
-    /// Creates a (String, Variant) dictionary from an iterator with Result passthrough (an Err will abort and return that Err)
-    pub fn from_dict<E, I: Iterator<Item=Result<(String, MessageItem),E>>>(i: I) -> Result<MessageItem, E> {
-        let mut v = Vec::new();
-        for r in i {
-            let (s, vv) = try!(r);
-            v.push((s.into(), Box::new(vv).into()).into());
-        }
-        Ok(MessageItem::Array(MessageItemArray::new(v, Signature::new("a{sv}").unwrap()).unwrap()))
-    }
-
-    /// Creates an MessageItem::Array from a list of MessageItems.
-    ///
-    /// Note: This requires `v` to be non-empty. See also
-    /// `MessageItem::from(&[T])`, which can handle empty arrays as well.
-    pub fn new_array(v: Vec<MessageItem>) -> Result<MessageItem,ArrayError> {
-        if v.len() == 0 {
-            return Err(ArrayError::EmptyArray);
-        }
-        let s = MessageItemArray::make_sig(&v[0]);
-        Ok(MessageItem::Array(MessageItemArray::new(v, s)?))
-    }
-
-
-    fn new_array2<D, I>(i: I) -> MessageItem
-    where D: Into<MessageItem>, D: Default, I: Iterator<Item=D> {
-        let v: Vec<MessageItem> = i.map(|ii| ii.into()).collect();
-        let s = {
-            let d;
-            let t = if v.len() == 0 { d = D::default().into(); &d } else { &v[0] };
-            MessageItemArray::make_sig(t)
-        };
-        MessageItem::Array(MessageItemArray::new(v, s).unwrap())
-    }
-
-    fn new_array3<'b, D: 'b, I>(i: I) -> MessageItem
-    where D: Into<MessageItem> + Default + Clone, I: Iterator<Item=&'b D> {
-        MessageItem::new_array2(i.map(|ii| ii.clone()))
-    }
-
-    fn from_iter_single(i: &mut ffi::DBusMessageIter) -> Option<MessageItem> {
-        let t = unsafe { ffi::dbus_message_iter_get_arg_type(i) };
-        match t {
-            ffi::DBUS_TYPE_INVALID => { None },
-            ffi::DBUS_TYPE_DICT_ENTRY => {
-                let mut subiter = new_dbus_message_iter();
-                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
-                let a = MessageItem::from_iter(&mut subiter);
-                if a.len() != 2 { panic!("D-Bus dict entry error"); }
-                let mut a = a.into_iter();
-                let key = Box::new(a.next().unwrap());
-                let value = Box::new(a.next().unwrap());
-                Some(MessageItem::DictEntry(key, value))
-            }
-            ffi::DBUS_TYPE_VARIANT => {
-                let mut subiter = new_dbus_message_iter();
-                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
-                let a = MessageItem::from_iter(&mut subiter);
-                if a.len() != 1 { panic!("D-Bus variant error"); }
-                Some(MessageItem::Variant(Box::new(a.into_iter().next().unwrap())))
-            }
-            ffi::DBUS_TYPE_ARRAY => {
-                let mut subiter = new_dbus_message_iter();
-                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
-                let c = unsafe { ffi::dbus_message_iter_get_signature(&mut subiter) };
-                let s = format!("a{}", c_str_to_slice(&(c as *const c_char)).unwrap());
-                unsafe { ffi::dbus_free(c as *mut c_void) };
-                let t = Signature::new(s).unwrap();
+impl<'a> TryFrom<&'a str> for MessageType {
+    type Error = ();
 
-                let a = MessageItem::from_iter(&mut subiter);
-                Some(MessageItem::Array(MessageItemArray { v: a, sig: t }))
-            },
-            ffi::DBUS_TYPE_STRUCT => {
-                let mut subiter = new_dbus_message_iter();
-                unsafe { ffi::dbus_message_iter_recurse(i, &mut subiter) };
-                Some(MessageItem::Struct(MessageItem::from_iter(&mut subiter)))
-            },
-            ffi::DBUS_TYPE_STRING => {
-                let mut c: *const c_char = ptr::null();
-                unsafe {
-                    let p: *mut c_void = mem::transmute(&mut c);
-                    ffi::dbus_message_iter_get_basic(i, p);
-                };
-                Some(MessageItem::Str(c_str_to_slice(&c).expect("D-Bus string error").to_string()))
-            },
-            ffi::DBUS_TYPE_OBJECT_PATH => {
-                let mut c: *const c_char = ptr::null();
-                unsafe {
-                    let p: *mut c_void = mem::transmute(&mut c);
-                    ffi::dbus_message_iter_get_basic(i, p);
-                };
-                let o = Path::new(c_str_to_slice(&c).expect("D-Bus object path error")).ok().expect("D-Bus object path error");
-                Some(MessageItem::ObjectPath(o))
-            },
-            ffi::DBUS_TYPE_UNIX_FD => Some(MessageItem::UnixFd(OwnedFd::new(iter_get_basic(i)))),
-            ffi::DBUS_TYPE_BOOLEAN => Some(MessageItem::Bool(iter_get_basic::<u32>(i) != 0)),
-            ffi::DBUS_TYPE_BYTE => Some(MessageItem::Byte(iter_get_basic(i))),
-            ffi::DBUS_TYPE_INT16 => Some(MessageItem::Int16(iter_get_basic(i))),
-            ffi::DBUS_TYPE_INT32 => Some(MessageItem::Int32(iter_get_basic(i))),
-            ffi::DBUS_TYPE_INT64 => Some(MessageItem::Int64(iter_get_basic(i))),
-            ffi::DBUS_TYPE_UINT16 => Some(MessageItem::UInt16(iter_get_basic(i))),
-            ffi::DBUS_TYPE_UINT32 => Some(MessageItem::UInt32(iter_get_basic(i))),
-            ffi::DBUS_TYPE_UINT64 => Some(MessageItem::UInt64(iter_get_basic(i))),
-            ffi::DBUS_TYPE_DOUBLE => Some(MessageItem::Double(iter_get_basic(i))),
-            _ => { None /* Only the new msgarg module supports signatures */ }
-        }
-    }
-
-    fn from_iter(i: &mut ffi::DBusMessageIter) -> Vec<MessageItem> {
-        let mut v = Vec::new();
-        while let Some(m) = Self::from_iter_single(i) {
-            v.push(m);
-            unsafe { ffi::dbus_message_iter_next(i) };
-        }
-        v
-    }
-
-    fn iter_append_basic<T>(&self, i: &mut ffi::DBusMessageIter, v: T) {
-        let t = self.array_type() as c_int;
-        let p = &v as *const _ as *const c_void;
-        unsafe {
-            ffi::dbus_message_iter_append_basic(i, t, p);
-        }
-    }
-
-    fn iter_append(&self, i: &mut ffi::DBusMessageIter) {
-        match self {
-            &MessageItem::Str(ref s) => unsafe {
-                let c = to_c_str(s);
-                let p = mem::transmute(&c);
-                ffi::dbus_message_iter_append_basic(i, ffi::DBUS_TYPE_STRING, p);
-            },
-            &MessageItem::Bool(b) => self.iter_append_basic(i, if b { 1u32 } else { 0u32 }),
-            &MessageItem::Byte(b) => self.iter_append_basic(i, b),
-            &MessageItem::Int16(b) => self.iter_append_basic(i, b),
-            &MessageItem::Int32(b) => self.iter_append_basic(i, b),
-            &MessageItem::Int64(b) => self.iter_append_basic(i, b),
-            &MessageItem::UInt16(b) => self.iter_append_basic(i, b),
-            &MessageItem::UInt32(b) => self.iter_append_basic(i, b),
-            &MessageItem::UInt64(b) => self.iter_append_basic(i, b),
-            &MessageItem::UnixFd(ref b) => self.iter_append_basic(i, b.as_raw_fd()),
-            &MessageItem::Double(b) => self.iter_append_basic(i, b),
-            &MessageItem::Array(ref a) => iter_append_array(i, &a.v, a.element_signature()),
-            &MessageItem::Struct(ref v) => iter_append_struct(i, &**v),
-            &MessageItem::Variant(ref b) => iter_append_variant(i, &**b),
-            &MessageItem::DictEntry(ref k, ref v) => iter_append_dict(i, &**k, &**v),
-            &MessageItem::ObjectPath(ref s) => unsafe {
-                let c: *const libc::c_char = s.as_ref().as_ptr();
-                let p = mem::transmute(&c);
-                ffi::dbus_message_iter_append_basic(i, ffi::DBUS_TYPE_OBJECT_PATH, p);
-            }
-        }
-    }
-
-    fn copy_to_iter(i: &mut ffi::DBusMessageIter, v: &[MessageItem]) {
-        for item in v.iter() {
-            item.iter_append(i);
-        }
-    }
-
-    /// Conveniently get the inner value of a `MessageItem`
-    ///
-    /// # Example
-    /// ```
-    /// use dbus::MessageItem;
-    /// let m: MessageItem = 5i64.into();
-    /// let s: i64 = m.inner().unwrap();
-    /// assert_eq!(s, 5i64);
-    /// ```
-    pub fn inner<'a, T: FromMessageItem<'a>>(&'a self) -> Result<T, ()> {
-        T::from(self)
-    }
-}
-
-
-// For use by the msgarg module
-pub fn append_messageitem(i: &mut ffi::DBusMessageIter, m: &MessageItem) {
-    m.iter_append(i)
-}
-
-// For use by the msgarg module
-pub fn get_messageitem(i: &mut ffi::DBusMessageIter) -> Option<MessageItem> {
-    MessageItem::from_iter_single(i)
-}
-
-
-macro_rules! msgitem_convert {
-    ($t: ty, $s: ident) => {
-        impl From<$t> for MessageItem { fn from(i: $t) -> MessageItem { MessageItem::$s(i) } }
-
-        impl<'a> FromMessageItem<'a> for $t {
-            fn from(i: &'a MessageItem) -> Result<$t,()> {
-                if let &MessageItem::$s(ref b) = i { Ok(*b) } else { Err(()) }
-            }
+    fn try_from(value: &'a str) -> Result<Self, <crate::message::MessageType as TryFrom<&'a str>>::Error> {
+        match value {
+            "error" => Ok(MessageType::Error),
+            "method_call" => Ok(MessageType::MethodCall),
+            "method_return" => Ok(MessageType::MethodReturn),
+            "signal" => Ok(MessageType::Signal),
+            _ => Err(())
         }
     }
 }
 
-msgitem_convert!(u8, Byte);
-msgitem_convert!(u64, UInt64);
-msgitem_convert!(u32, UInt32);
-msgitem_convert!(u16, UInt16);
-msgitem_convert!(i16, Int16);
-msgitem_convert!(i32, Int32);
-msgitem_convert!(i64, Int64);
-msgitem_convert!(f64, Double);
-msgitem_convert!(bool, Bool);
-
-
-/// Create a `MessageItem::Array`.
-impl<'a, T> From<&'a [T]> for MessageItem
-where T: Into<MessageItem> + Clone + Default {
-    fn from(i: &'a [T]) -> MessageItem {
-        MessageItem::new_array3(i.iter())
-    }
-}
-
-impl<'a> From<&'a str> for MessageItem { fn from(i: &str) -> MessageItem { MessageItem::Str(i.to_string()) } }
-
-impl From<String> for MessageItem { fn from(i: String) -> MessageItem { MessageItem::Str(i) } }
-
-impl From<Path<'static>> for MessageItem { fn from(i: Path<'static>) -> MessageItem { MessageItem::ObjectPath(i) } }
-
-impl From<OwnedFd> for MessageItem { fn from(i: OwnedFd) -> MessageItem { MessageItem::UnixFd(i) } }
-
-/// Create a `MessageItem::Variant`
-impl From<Box<MessageItem>> for MessageItem {
-    fn from(i: Box<MessageItem>) -> MessageItem { MessageItem::Variant(i) }
-}
-
-/// Create a `MessageItem::DictEntry`
-impl From<(MessageItem, MessageItem)> for MessageItem {
-    fn from(i: (MessageItem, MessageItem)) -> MessageItem {
-        MessageItem::DictEntry(Box::new(i.0), Box::new(i.1))
-    }
-}
-
-/// Helper trait for `MessageItem::inner()`
-pub trait FromMessageItem<'a> :Sized {
-    /// Allows converting from a MessageItem into the type it contains.
-    fn from(i: &'a MessageItem) -> Result<Self, ()>;
-}
+mod signalargs;
+pub use self::signalargs::SignalArgs;
 
-impl<'a> FromMessageItem<'a> for &'a str {
-    fn from(i: &'a MessageItem) -> Result<&'a str,()> {
-        match i {
-            &MessageItem::Str(ref b) => Ok(&b),
-            &MessageItem::ObjectPath(ref b) => Ok(&b),
-            _ => Err(()),
-        }
-    }
-}
-
-impl<'a> FromMessageItem<'a> for &'a String {
-    fn from(i: &'a MessageItem) -> Result<&'a String,()> { if let &MessageItem::Str(ref b) = i { Ok(&b) } else { Err(()) } }
-}
-
-impl<'a> FromMessageItem<'a> for &'a Path<'static> {
-    fn from(i: &'a MessageItem) -> Result<&'a Path<'static>,()> { if let &MessageItem::ObjectPath(ref b) = i { Ok(&b) } else { Err(()) } }
-}
-
-impl<'a> FromMessageItem<'a> for &'a MessageItem {
-    fn from(i: &'a MessageItem) -> Result<&'a MessageItem,()> { if let &MessageItem::Variant(ref b) = i { Ok(&**b) } else { Err(()) } }
-}
+mod matchrule;
+pub use self::matchrule::MatchRule;
+use std::convert::TryFrom;
 
-impl<'a> FromMessageItem<'a> for &'a Vec<MessageItem> {
-    fn from(i: &'a MessageItem) -> Result<&'a Vec<MessageItem>,()> {
-        match i {
-            &MessageItem::Array(ref b) => Ok(&b.v),
-            &MessageItem::Struct(ref b) => Ok(&b),
-            _ => Err(()),
-        }
-    }
-}
-
-impl<'a> FromMessageItem<'a> for &'a [MessageItem] {
-    fn from(i: &'a MessageItem) -> Result<&'a [MessageItem],()> { i.inner::<&Vec<MessageItem>>().map(|s| &**s) }
-}
+mod parser;
+pub use self::parser::Error as MatchRuleParserError;
 
-impl<'a> FromMessageItem<'a> for &'a OwnedFd {
-    fn from(i: &'a MessageItem) -> Result<&'a OwnedFd,()> { if let &MessageItem::UnixFd(ref b) = i { Ok(b) } else { Err(()) } }
-}
-
-impl<'a> FromMessageItem<'a> for (&'a MessageItem, &'a MessageItem) {
-    fn from(i: &'a MessageItem) -> Result<(&'a MessageItem, &'a MessageItem),()> {
-        if let &MessageItem::DictEntry(ref k, ref v) = i { Ok((&**k, &**v)) } else { Err(()) }
-    }
-}
-
-
-/// A D-Bus message. A message contains some headers (e g sender and destination address)
-/// and a list of MessageItems.
+/// A D-Bus message. A message contains headers - usually destination address, path, interface and member,
+/// and a list of arguments.
 pub struct Message {
     msg: *mut ffi::DBusMessage,
 }
 
 unsafe impl Send for Message {}
 
 impl Message {
     /// Creates a new method call message.
     pub fn new_method_call<'d, 'p, 'i, 'm, D, P, I, M>(destination: D, path: P, iface: I, method: M) -> Result<Message, String>
     where D: Into<BusName<'d>>, P: Into<Path<'p>>, I: Into<Interface<'i>>, M: Into<Member<'m>> {
         init_dbus();
         let (d, p, i, m) = (destination.into(), path.into(), iface.into(), method.into());
         let ptr = unsafe {
-            ffi::dbus_message_new_method_call(d.as_ref().as_ptr(), p.as_ref().as_ptr(), i.as_ref().as_ptr(), m.as_ref().as_ptr())
+            ffi::dbus_message_new_method_call(d.as_ptr(), p.as_ptr(), i.as_ptr(), m.as_ptr())
         };
-        if ptr == ptr::null_mut() { Err("D-Bus error: dbus_message_new_method_call failed".into()) }
+        if ptr.is_null() { Err("D-Bus error: dbus_message_new_method_call failed".into()) }
         else { Ok(Message { msg: ptr}) }
     }
 
     /// Creates a new method call message.
     pub fn method_call(destination: &BusName, path: &Path, iface: &Interface, name: &Member) -> Message {
         init_dbus();
         let ptr = unsafe {
-            ffi::dbus_message_new_method_call(destination.as_ref().as_ptr(), path.as_ref().as_ptr(),
-                iface.as_ref().as_ptr(), name.as_ref().as_ptr())
+            ffi::dbus_message_new_method_call(destination.as_ptr(), path.as_ptr(),
+                iface.as_ptr(), name.as_ptr())
+        };
+        if ptr.is_null() { panic!("D-Bus error: dbus_message_new_method_call failed") }
+        Message { msg: ptr}
+    }
+
+    /// Creates a new message that is a replica of this message, but without a serial.
+    ///
+    /// May fail if out of memory or file descriptors.
+    pub fn duplicate(&self) -> Result<Self, String> {
+        let ptr = unsafe {
+            ffi::dbus_message_copy(self.msg)
         };
-        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_signal failed") }
-        Message { msg: ptr}
+        if ptr.is_null() {
+            Err("D-Bus error: dbus_message_copy failed".into())
+        } else {
+            Ok(Message { msg: ptr })
+        }
+    }
+
+    /// Creates a new method call message.
+    pub fn call_with_args<'d, 'p, 'i, 'm, A, D, P, I, M>(destination: D, path: P, iface: I, method: M, args: A) -> Message
+    where D: Into<BusName<'d>>, P: Into<Path<'p>>, I: Into<Interface<'i>>, M: Into<Member<'m>>, A: AppendAll {
+        let mut msg = Message::method_call(&destination.into(), &path.into(), &iface.into(), &method.into());
+        msg.append_all(args);
+        msg
     }
 
     /// Creates a new signal message.
     pub fn new_signal<P, I, M>(path: P, iface: I, name: M) -> Result<Message, String>
-    where P: Into<Vec<u8>>, I: Into<Vec<u8>>, M: Into<Vec<u8>> {
+    where P: Into<String>, I: Into<String>, M: Into<String> {
         init_dbus();
 
-        let p = try!(Path::new(path));
-        let i = try!(Interface::new(iface));
-        let m = try!(Member::new(name));
+        let p = Path::new(path)?;
+        let i = Interface::new(iface)?;
+        let m = Member::new(name)?;
 
         let ptr = unsafe {
-            ffi::dbus_message_new_signal(p.as_ref().as_ptr(), i.as_ref().as_ptr(), m.as_ref().as_ptr())
+            ffi::dbus_message_new_signal(p.as_ptr(), i.as_ptr(), m.as_ptr())
         };
-        if ptr == ptr::null_mut() { Err("D-Bus error: dbus_message_new_signal failed".into()) }
+        if ptr.is_null() { Err("D-Bus error: dbus_message_new_signal failed".into()) }
         else { Ok(Message { msg: ptr}) }
     }
 
     /// Creates a new signal message.
     pub fn signal(path: &Path, iface: &Interface, name: &Member) -> Message {
         init_dbus();
         let ptr = unsafe {
-            ffi::dbus_message_new_signal(path.as_ref().as_ptr(), iface.as_ref().as_ptr(), name.as_ref().as_ptr())
+            ffi::dbus_message_new_signal(path.as_ptr(), iface.as_ptr(), name.as_ptr())
         };
-        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_signal failed") }
+        if ptr.is_null() { panic!("D-Bus error: dbus_message_new_signal failed") }
         Message { msg: ptr}
     }
 
     /// Creates a method reply for this method call.
     pub fn new_method_return(m: &Message) -> Option<Message> {
         let ptr = unsafe { ffi::dbus_message_new_method_return(m.msg) };
-        if ptr == ptr::null_mut() { None } else { Some(Message { msg: ptr} ) }
+        if ptr.is_null() { None } else { Some(Message { msg: ptr} ) }
     }
 
     /// Creates a method return (reply) for this method call.
     pub fn method_return(&self) -> Message {
         let ptr = unsafe { ffi::dbus_message_new_method_return(self.msg) };
-        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_method_return failed") }
+        if ptr.is_null() { panic!("D-Bus error: dbus_message_new_method_return failed") }
         Message {msg: ptr}
     }
 
-    /// The old way to create a new error reply
-    pub fn new_error(m: &Message, error_name: &str, error_message: &str) -> Option<Message> {
-        let (en, em) = (to_c_str(error_name), to_c_str(error_message));
-        let ptr = unsafe { ffi::dbus_message_new_error(m.msg, en.as_ptr(), em.as_ptr()) };
-        if ptr == ptr::null_mut() { None } else { Some(Message { msg: ptr} ) }
+    /// Creates a reply for a method call message.
+    ///
+    /// Panics if called for a message which is not a method call.
+    pub fn return_with_args<A: AppendAll>(&self, args: A) -> Message {
+        let mut m = self.method_return();
+        m.append_all(args);
+        m
     }
 
     /// Creates a new error reply
     pub fn error(&self, error_name: &ErrorName, error_message: &CStr) -> Message {
-        let ptr = unsafe { ffi::dbus_message_new_error(self.msg, error_name.as_ref().as_ptr(), error_message.as_ptr()) };
-        if ptr == ptr::null_mut() { panic!("D-Bus error: dbus_message_new_error failed") }
+        let ptr = unsafe { ffi::dbus_message_new_error(self.msg, error_name.as_ptr(), error_message.as_ptr()) };
+        if ptr.is_null() { panic!("D-Bus error: dbus_message_new_error failed") }
         Message { msg: ptr}
     }
 
     /// Get the MessageItems that make up the message.
     ///
     /// Note: use `iter_init` or `get1`/`get2`/etc instead for faster access to the arguments.
     /// This method is provided for backwards compatibility.
-    pub fn get_items(&self) -> Vec<MessageItem> {
-        let mut i = new_dbus_message_iter();
-        match unsafe { ffi::dbus_message_iter_init(self.msg, &mut i) } {
-            0 => Vec::new(),
-            _ => MessageItem::from_iter(&mut i)
-        }
+    pub fn get_items(&self) -> Vec<crate::arg::messageitem::MessageItem> {
+        let mut i = self.iter_init();
+        let mut v = vec!();
+        while let Some(z) = crate::arg::messageitem::MessageItem::get(&mut i) { v.push(z); i.next(); }
+        v
     }
 
     /// Get the D-Bus serial of a message, if one was specified.
-    pub fn get_serial(&self) -> u32 {
-        unsafe { ffi::dbus_message_get_serial(self.msg) }
+    pub fn get_serial(&self) -> Option<u32> {
+        let x = unsafe { ffi::dbus_message_get_serial(self.msg) };
+        if x == 0 { None } else { Some(x) }
     }
 
     /// Get the serial of the message this message is a reply to, if present.
     pub fn get_reply_serial(&self) -> Option<u32> {
         let s = unsafe { ffi::dbus_message_get_reply_serial(self.msg) };
         if s == 0 { None } else { Some(s) }
     }
 
     /// Returns true if the message does not expect a reply.
     pub fn get_no_reply(&self) -> bool { unsafe { ffi::dbus_message_get_no_reply(self.msg) != 0 } }
 
     /// Set whether or not the message expects a reply.
     ///
     /// Set to true if you send a method call and do not want a reply.
-    pub fn set_no_reply(&self, v: bool) {
+    pub fn set_no_reply(&mut self, v: bool) {
         unsafe { ffi::dbus_message_set_no_reply(self.msg, if v { 1 } else { 0 }) }
     }
 
     /// Returns true if the message can cause a service to be auto-started.
     pub fn get_auto_start(&self) -> bool { unsafe { ffi::dbus_message_get_auto_start(self.msg) != 0 } }
 
     /// Sets whether or not the message can cause a service to be auto-started.
     ///
     /// Defaults to true.
-    pub fn set_auto_start(&self, v: bool) {
+    pub fn set_auto_start(&mut self, v: bool) {
         unsafe { ffi::dbus_message_set_auto_start(self.msg, if v { 1 } else { 0 }) }
     }
 
     /// Add one or more MessageItems to this Message.
     ///
     /// Note: using `append1`, `append2` or `append3` might be faster, especially for large arrays.
     /// This method is provided for backwards compatibility.
-    pub fn append_items(&mut self, v: &[MessageItem]) {
-        let mut i = new_dbus_message_iter();
-        unsafe { ffi::dbus_message_iter_init_append(self.msg, &mut i) };
-        MessageItem::copy_to_iter(&mut i, v);
-    }
-
-    /// Appends one MessageItem to a message.
-    /// Use in builder style: e g `m.method_return().append(7i32)`
-    ///
-    /// Note: using `append1`, `append2` or `append3` might be faster, especially for large arrays.
-    /// This method is provided for backwards compatibility.
-    pub fn append<I: Into<MessageItem>>(self, v: I) -> Self {
-        let mut i = new_dbus_message_iter();
-        unsafe { ffi::dbus_message_iter_init_append(self.msg, &mut i) };
-        MessageItem::copy_to_iter(&mut i, &[v.into()]);
-        self
+    pub fn append_items(&mut self, v: &[crate::arg::messageitem::MessageItem]) {
+        let mut ia = IterAppend::new(self);
+        for a in v { a.append_by_ref(&mut ia); }
     }
 
     /// Appends one argument to this message.
     /// Use in builder style: e g `m.method_return().append1(7i32)`
     pub fn append1<A: Append>(mut self, a: A) -> Self {
         {
             let mut m = IterAppend::new(&mut self);
             m.append(a);
@@ -742,17 +240,23 @@ impl Message {
     pub fn append_ref<A: RefArg>(mut self, r: &[A]) -> Self {
         {
             let mut m = IterAppend::new(&mut self);
             for rr in r {
                 rr.append(&mut m);
             }
         }
         self
-    } 
+    }
+
+    /// Appends arguments to a message.
+    pub fn append_all<A: AppendAll>(&mut self, a: A) {
+        let mut m = IterAppend::new(self);
+        a.append(&mut m);
+    }
 
     /// Gets the first argument from the message, if that argument is of type G1.
     /// Returns None if there are not enough arguments, or if types don't match.
     pub fn get1<'a, G1: Get<'a>>(&'a self) -> Option<G1> {
         let mut i = Iter::new(&self);
         i.get()
     }
 
@@ -813,340 +317,237 @@ impl Message {
         i.read()
     }
 
     /// Gets the first two arguments from the message, if those arguments are of type G1 and G2.
     ///
     /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
     pub fn read2<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>>(&'a self) -> Result<(G1, G2), TypeMismatchError> {
         let mut i = Iter::new(&self);
-        Ok((try!(i.read()), try!(i.read())))
+        Ok((i.read()?, i.read()?))
     }
 
     /// Gets the first three arguments from the message, if those arguments are of type G1, G2 and G3.
     ///
     /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
-    pub fn read3<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>>(&'a self) -> 
+    pub fn read3<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>>(&'a self) ->
         Result<(G1, G2, G3), TypeMismatchError> {
         let mut i = Iter::new(&self);
-        Ok((try!(i.read()), try!(i.read()), try!(i.read())))
+        Ok((i.read()?, i.read()?, i.read()?))
     }
 
     /// Gets the first four arguments from the message, if those arguments are of type G1, G2, G3 and G4.
     ///
     /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
     pub fn read4<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>, G4: Arg + Get<'a>>(&'a self) ->
         Result<(G1, G2, G3, G4), TypeMismatchError> {
         let mut i = Iter::new(&self);
-        Ok((try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read())))
+        Ok((i.read()?, i.read()?, i.read()?, i.read()?))
     }
 
     /// Gets the first five arguments from the message, if those arguments are of type G1, G2, G3, G4 and G5.
     ///
     /// Returns a TypeMismatchError if there are not enough arguments, or if types don't match.
     /// Note: If you need more than five arguments, use `iter_init` instead.
     pub fn read5<'a, G1: Arg + Get<'a>, G2: Arg + Get<'a>, G3: Arg + Get<'a>, G4: Arg + Get<'a>, G5: Arg + Get<'a>>(&'a self) ->
         Result<(G1, G2, G3, G4, G5), TypeMismatchError> {
         let mut i = Iter::new(&self);
-        Ok((try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read()), try!(i.read())))
+        Ok((i.read()?, i.read()?, i.read()?, i.read()?, i.read()?))
+    }
+
+    /// Gets arguments from a message.
+    ///
+    /// If this was an error reply or if types mismatch, an error is returned.
+    pub fn read_all<R: ReadAll>(&self) -> Result<R, Error> {
+        self.set_error_from_msg()?;
+        Ok(R::read(&mut self.iter_init())?)
     }
 
     /// Returns a struct for retreiving the arguments from a message. Supersedes get_items().
-    pub fn iter_init<'a>(&'a self) -> Iter<'a> { Iter::new(&self) }
+    pub fn iter_init(&self) -> Iter { Iter::new(&self) }
 
     /// Gets the MessageType of the Message.
     pub fn msg_type(&self) -> MessageType {
-        unsafe { mem::transmute(ffi::dbus_message_get_type(self.msg)) }
+        match unsafe { ffi::dbus_message_get_type(self.msg) } {
+            1 => MessageType::MethodCall,
+            2 => MessageType::MethodReturn,
+            3 => MessageType::Error,
+            4 => MessageType::Signal,
+            x => panic!("Invalid message type {}", x),
+        }
     }
 
-    fn msg_internal_str<'a>(&'a self, c: *const libc::c_char) -> Option<&'a [u8]> {
-        if c == ptr::null() { None }
-        else { Some( unsafe { CStr::from_ptr(c) }.to_bytes_with_nul()) }
+    fn msg_internal_str<'a>(&'a self, c: *const libc::c_char) -> Option<&'a str> {
+        if c.is_null() { return None };
+        let cc = unsafe { CStr::from_ptr(c) };
+        std::str::from_utf8(cc.to_bytes_with_nul()).ok()
     }
 
     /// Gets the name of the connection that originated this message.
-    pub fn sender<'a>(&'a self) -> Option<BusName<'a>> {
+    pub fn sender(&self) -> Option<BusName> {
         self.msg_internal_str(unsafe { ffi::dbus_message_get_sender(self.msg) })
             .map(|s| unsafe { BusName::from_slice_unchecked(s) })
     }
 
-    /// Returns a tuple of (Message type, Path, Interface, Member) of the current message.
-    pub fn headers(&self) -> (MessageType, Option<String>, Option<String>, Option<String>) {
-        let p = unsafe { ffi::dbus_message_get_path(self.msg) };
-        let i = unsafe { ffi::dbus_message_get_interface(self.msg) };
-        let m = unsafe { ffi::dbus_message_get_member(self.msg) };
-        (self.msg_type(),
-         c_str_to_slice(&p).map(|s| s.to_string()),
-         c_str_to_slice(&i).map(|s| s.to_string()),
-         c_str_to_slice(&m).map(|s| s.to_string()))
-    }
-
     /// Gets the object path this Message is being sent to.
-    pub fn path<'a>(&'a self) -> Option<Path<'a>> {
+    pub fn path(&self) -> Option<Path> {
         self.msg_internal_str(unsafe { ffi::dbus_message_get_path(self.msg) })
             .map(|s| unsafe { Path::from_slice_unchecked(s) })
     }
 
     /// Gets the destination this Message is being sent to.
-    pub fn destination<'a>(&'a self) -> Option<BusName<'a>> {
+    pub fn destination(&self) -> Option<BusName> {
         self.msg_internal_str(unsafe { ffi::dbus_message_get_destination(self.msg) })
             .map(|s| unsafe { BusName::from_slice_unchecked(s) })
     }
 
     /// Sets the destination of this Message
     ///
     /// If dest is none, that means broadcast to all relevant destinations.
     pub fn set_destination(&mut self, dest: Option<BusName>) {
         let c_dest = dest.as_ref().map(|d| d.as_cstr().as_ptr()).unwrap_or(ptr::null());
         assert!(unsafe { ffi::dbus_message_set_destination(self.msg, c_dest) } != 0);
     }
 
     /// Gets the interface this Message is being sent to.
-    pub fn interface<'a>(&'a self) -> Option<Interface<'a>> {
+    pub fn interface(&self) -> Option<Interface> {
         self.msg_internal_str(unsafe { ffi::dbus_message_get_interface(self.msg) })
             .map(|s| unsafe { Interface::from_slice_unchecked(s) })
     }
 
     /// Gets the interface member being called.
-    pub fn member<'a>(&'a self) -> Option<Member<'a>> {
+    pub fn member(&self) -> Option<Member> {
         self.msg_internal_str(unsafe { ffi::dbus_message_get_member(self.msg) })
             .map(|s| unsafe { Member::from_slice_unchecked(s) })
     }
 
     /// When the remote end returns an error, the message itself is
     /// correct but its contents is an error. This method will
     /// transform such an error to a D-Bus Error or otherwise return
     /// the original message.
     pub fn as_result(&mut self) -> Result<&mut Message, Error> {
         self.set_error_from_msg().map(|_| self)
     }
 
-    pub (super) fn set_error_from_msg(&self) -> Result<(), Error> {
+    pub (crate) fn set_error_from_msg(&self) -> Result<(), Error> {
         let mut e = Error::empty();
         if unsafe { ffi::dbus_set_error_from_message(e.get_mut(), self.msg) } != 0 { Err(e) }
         else { Ok(()) }
     }
 
     pub (crate) fn ptr(&self) -> *mut ffi::DBusMessage { self.msg }
 
     pub (crate) fn from_ptr(ptr: *mut ffi::DBusMessage, add_ref: bool) -> Message {
         if add_ref {
             unsafe { ffi::dbus_message_ref(ptr) };
         }
         Message { msg: ptr }
     }
 
+    /// Sets serial number manually - mostly for internal use
+    ///
+    /// When sending a message, a serial will be automatically assigned, so you don't need to call
+    /// this method. However, it can be very useful in test code that is supposed to handle a method call.
+    /// This way, you can create a method call and handle it without sending it to a real D-Bus instance.
+    pub fn set_serial(&mut self, val: u32) {
+        unsafe { ffi::dbus_message_set_serial(self.msg, val) };
+    }
+
+    /// Marshals a message - mostly for internal use
+    ///
+    /// The function f will be called one or more times with bytes to be written somewhere.
+    /// You should call set_serial to manually set a serial number before calling this function
+    pub fn marshal<E, F: FnMut(&[u8]) -> Result<(), E>>(&self, mut f: F) -> Result<(), E> {
+        let mut len = 0;
+        let mut data = ptr::null_mut();
+        if unsafe { ffi::dbus_message_marshal(self.msg, &mut data, &mut len) } == 0 {
+            panic!("out of memory");
+        }
+        let s = unsafe { std::slice::from_raw_parts(data as *mut u8 as *const u8, len as usize) };
+        let r = f(s);
+        unsafe { ffi::dbus_free(data as *mut _) };
+        r
+    }
+
+    /// Demarshals a message - mostly for internal use
+    pub fn demarshal(data: &[u8]) -> Result<Self, Error> {
+        let mut e = Error::empty();
+        let p = unsafe { ffi::dbus_message_demarshal(data.as_ptr() as *const _, data.len() as _, e.get_mut()) };
+        if p == ptr::null_mut() {
+            Err(e)
+        } else {
+            Ok(Self::from_ptr(p, false))
+        }
+    }
+
+    /// Returns the size of the message - mostly for internal use
+    ///
+    /// Returns Err(()) on protocol errors. Make sure you have at least 16 bytes in the buffer
+    /// before calling this method.
+    pub fn demarshal_bytes_needed(data: &[u8]) -> Result<usize, ()> {
+        const MIN_HEADER: usize = 16;
+        if data.len() < MIN_HEADER { return Ok(MIN_HEADER); }
+        let x = unsafe { ffi::dbus_message_demarshal_bytes_needed(data.as_ptr() as *const _, data.len() as _) };
+        if x < MIN_HEADER as _ { Err(()) } else { Ok(x as usize) }
+    }
+
 }
 
 impl Drop for Message {
     fn drop(&mut self) {
         unsafe {
             ffi::dbus_message_unref(self.msg);
         }
     }
 }
 
 impl fmt::Debug for Message {
     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        write!(f, "{:?}", self.headers())
+        let mut x = f.debug_struct("Message");
+        x.field("Type", &self.msg_type());
+        // The &&** derefs to a &&str, which implements &dyn Debug
+        if let Some(ref path) = self.path() { x.field("Path", &&**path); }
+        if let Some(ref iface) = self.interface() { x.field("Interface", &&**iface); }
+        if let Some(ref member) = self.member() { x.field("Member", &&**member); }
+        if let Some(ref sender) = self.sender() { x.field("Sender", &&**sender); }
+        if let Some(ref dest) = self.destination() { x.field("Destination", &&**dest); }
+        if let Some(ref serial) = self.get_serial() { x.field("Serial", serial); }
+        if let Some(ref rs) = self.get_reply_serial() { x.field("ReplySerial", rs); }
+        let mut args = vec!();
+        let mut iter = self.iter_init();
+        while let Some(a) = iter.get_refarg() {
+            args.push(a);
+            iter.next();
+        }
+        let args2: &[_] = &args;
+        x.field("Args", &args2);
+        x.finish()
     }
 }
 
-/// A convenience struct that wraps connection, destination and path.
-///
-/// Useful if you want to make many method calls to the same destination path.
-#[derive(Clone, Debug)]
-pub struct ConnPath<'a, C> {
-    /// Some way to access the connection, e g a &Connection or Rc<Connection>
-    pub conn: C,
-    /// Destination, i e what D-Bus service you're communicating with
-    pub dest: BusName<'a>,
-    /// Object path on the destination
-    pub path: Path<'a>,
-    /// Timeout in milliseconds for blocking method calls
-    pub timeout: i32,
-}
-
-impl<'a, C: ::std::ops::Deref<Target=Connection>> ConnPath<'a, C> {
-    /// Make a D-Bus method call, where you can append arguments inside the closure.
-    pub fn method_call_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<Message, Error> {
-        let mut msg = Message::method_call(&self.dest, &self.path, i, m);
-        f(&mut msg);
-        self.conn.send_with_reply_and_block(msg, self.timeout)
-    }
-
-    /// Emit a D-Bus signal, where you can append arguments inside the closure.
-    pub fn signal_with_args<F: FnOnce(&mut Message)>(&self, i: &Interface, m: &Member, f: F) -> Result<u32, Error> {
-        let mut msg = Message::signal(&self.path, i, m);
-        f(&mut msg);
-        self.conn.send(msg).map_err(|_| Error::new_custom("org.freedesktop.DBus.Error.Failed", "Sending signal failed"))
-    }
-
-    /// Emit a D-Bus signal, where the arguments are in a struct.
-    pub fn emit<S: SignalArgs>(&self, signal: &S) -> Result<u32, Error> {
-        let msg = signal.to_emit_message(&self.path);
-        self.conn.send(msg).map_err(|_| Error::new_custom("org.freedesktop.DBus.Error.Failed", "Sending signal failed"))
-    }
-}
-
-// For purpose of testing the library only.
-#[cfg(test)]
-pub (crate) fn message_set_serial(m: &mut Message, s: u32) {
-    unsafe { ffi::dbus_message_set_serial(m.msg, s) };
-}
-
 #[cfg(test)]
 mod test {
-    extern crate tempdir;
-
-    use super::super::{Connection, Message, MessageType, BusType, MessageItem, OwnedFd, libc, Path, BusName};
-
-    #[test]
-    fn unix_fd() {
-        use std::io::prelude::*;
-        use std::io::SeekFrom;
-        use std::fs::OpenOptions;
-        use std::os::unix::io::AsRawFd;
-
-        let c = Connection::get_private(BusType::Session).unwrap();
-        c.register_object_path("/hello").unwrap();
-        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
-        let tempdir = tempdir::TempDir::new("dbus-rs-test").unwrap();
-        let mut filename = tempdir.path().to_path_buf();
-        filename.push("test");
-        println!("Creating file {:?}", filename);
-        let mut file = OpenOptions::new().create(true).read(true).write(true).open(&filename).unwrap();
-        file.write_all(b"z").unwrap();
-        file.seek(SeekFrom::Start(0)).unwrap();
-        let ofd = OwnedFd::new(file.as_raw_fd());
-        m.append_items(&[MessageItem::UnixFd(ofd.clone())]);
-        println!("Sending {:?}", m.get_items());
-        c.send(m).unwrap();
-
-        loop { for n in c.incoming(1000) {
-            if n.msg_type() == MessageType::MethodCall {
-                let z: OwnedFd = n.read1().unwrap();
-                println!("Got {:?}", z);
-                let mut q: libc::c_char = 100;
-                assert_eq!(1, unsafe { libc::read(z.as_raw_fd(), &mut q as *mut _ as *mut libc::c_void, 1) });
-                assert_eq!(q, 'z' as libc::c_char);
-                return;
-            } else {
-                println!("Got {:?}", n);
-            }
-        }}
-    }
-
-    #[test]
-    fn message_types() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        c.register_object_path("/hello").unwrap();
-        let mut m = Message::new_method_call(&c.unique_name(), "/hello", "com.example.hello", "Hello").unwrap();
-        m.append_items(&[
-            2000u16.into(),
-            MessageItem::new_array(vec!(129u8.into())).unwrap(),
-            ["Hello", "world"][..].into(),
-            987654321u64.into(),
-            (-1i32).into(),
-            format!("Hello world").into(),
-            (-3.14f64).into(),
-            MessageItem::Struct(vec!(256i16.into())),
-            Path::new("/some/path").unwrap().into(),
-            MessageItem::new_array(vec!((123543u32.into(), true.into()).into())).unwrap()
-        ]);
-        let sending = format!("{:?}", m.get_items());
-        println!("Sending {}", sending);
-        c.send(m).unwrap();
-
-        loop { for n in c.incoming(1000) {
-            if n.msg_type() == MessageType::MethodCall {
-                let receiving = format!("{:?}", n.get_items());
-                println!("Receiving {}", receiving);
-                assert_eq!(sending, receiving);
-                return;
-            } else {
-                println!("Got {:?}", n);
-            }
-        }}
-    }
-
-    #[test]
-    fn dict_of_dicts() {
-        use std::collections::BTreeMap;
-
-        let officeactions: BTreeMap<&'static str, MessageItem> = BTreeMap::new();
-        let mut officethings = BTreeMap::new();
-        officethings.insert("pencil", 2u16.into());
-        officethings.insert("paper", 5u16.into());
-        let mut homethings = BTreeMap::new();
-        homethings.insert("apple", 11u16.into());
-        let mut homeifaces = BTreeMap::new();
-        homeifaces.insert("getThings", homethings);
-        let mut officeifaces = BTreeMap::new();
-        officeifaces.insert("getThings", officethings);
-        officeifaces.insert("getActions", officeactions);
-        let mut paths = BTreeMap::new();
-        paths.insert("/hello/office", officeifaces);
-        paths.insert("/hello/home", homeifaces);
-
-        println!("Original treemap: {:?}", paths);
-        let m = MessageItem::new_array(paths.iter().map(
-            |(path, ifaces)| (MessageItem::ObjectPath(Path::new(*path).unwrap()),
-                MessageItem::new_array(ifaces.iter().map(
-                    |(iface, props)| (iface.to_string().into(),
-                        MessageItem::from_dict::<(),_>(props.iter().map(
-                            |(name, value)| Ok((name.to_string(), value.clone()))
-                        )).unwrap()
-                    ).into()
-                ).collect()).unwrap()
-            ).into()
-        ).collect()).unwrap();
-        println!("As MessageItem: {:?}", m);
-        assert_eq!(&*m.signature(), "a{oa{sa{sv}}}");
-
-        let c = Connection::get_private(BusType::Session).unwrap();
-        c.register_object_path("/hello").unwrap();
-        let mut msg = Message::new_method_call(&c.unique_name(), "/hello", "org.freedesktop.DBusObjectManager", "GetManagedObjects").unwrap();
-        msg.append_items(&[m]);
-        let sending = format!("{:?}", msg.get_items());
-        println!("Sending {}", sending);
-        c.send(msg).unwrap();
-
-        loop { for n in c.incoming(1000) {
-            if n.msg_type() == MessageType::MethodCall {
-                let receiving = format!("{:?}", n.get_items());
-                println!("Receiving {}", receiving);
-                assert_eq!(sending, receiving);
-                return;
-            } else {
-                println!("Got {:?}", n);
-            }
-        } }
-    }
-
-    #[test]
-    fn issue24() {
-        let c = Connection::get_private(BusType::Session).unwrap();
-        let mut m = Message::new_method_call("org.test.rust", "/", "org.test.rust", "Test").unwrap();
-
-        let a = MessageItem::from("test".to_string());
-        let b = MessageItem::from("test".to_string());
-        let foo = MessageItem::Struct(vec!(a, b));
-        let bar = foo.clone();
-
-        let args = [MessageItem::new_array(vec!(foo, bar)).unwrap()];
-        println!("{:?}", args);
-
-        m.append_items(&args);
-        c.send(m).unwrap();
-    }
+    use crate::{Message};
+    use crate::strings::BusName;
 
     #[test]
     fn set_valid_destination() {
         let mut m = Message::new_method_call("org.test.rust", "/", "org.test.rust", "Test").unwrap();
         let d = Some(BusName::new(":1.14").unwrap());
         m.set_destination(d);
 
         assert!(!m.get_no_reply());
         m.set_no_reply(true);
         assert!(m.get_no_reply());
     }
+
+    #[test]
+    fn marshal() {
+        let mut m = Message::new_method_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello").unwrap();
+        m.set_serial(1);
+        let r = m.marshal(|d| {
+            let m2 = Message::demarshal(d).unwrap();
+            assert_eq!(&*m2.path().unwrap(), "/org/freedesktop/DBus");
+            Err(45)
+        });
+        assert_eq!(45, r.unwrap_err());
+    }
 }
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/message/matchrule.rs
@@ -0,0 +1,177 @@
+use crate::{Message, MessageType};
+use crate::strings::{BusName, Path, Interface, Member};
+use crate::message::parser;
+
+#[derive(Clone, Debug, Default)]
+/// A "match rule", that can match Messages on its headers.
+///
+/// A field set to "None" means no filter for that header,
+/// a field set to "Some(_)" must match exactly.
+pub struct MatchRule<'a> {
+    /// Match on message type (you typically want to do this)
+    pub msg_type: Option<MessageType>,
+    /// Match on message sender
+    pub sender: Option<BusName<'a>>,
+    /// If false (the default), match if sender could possibly match, due to mismatch between unique names and taken bus names
+    pub strict_sender: bool,
+    /// Match on message object path
+    pub path: Option<Path<'a>>,
+    /// If true, will match all subpaths to the path as well as the path itself. Defaults to false.
+    pub path_is_namespace: bool,
+    /// Match on message interface
+    pub interface: Option<Interface<'a>>,
+    /// Match on message member (signal or method name)
+    pub member: Option<Member<'a>>,
+    /// If true, also receive messages not intended for us. Defaults to false.
+    pub eavesdrop: bool,
+    _more_fields_may_come: (),
+}
+
+fn msg_type_str(m: MessageType) -> &'static str {
+    use crate::MessageType::*;
+    match m {
+        Signal => "signal",
+        MethodCall => "method_call",
+        MethodReturn => "method_return",
+        Error => "error",
+    }
+}
+
+
+impl<'a> MatchRule<'a> {
+    /// Make a string which you can use in the call to "add_match".
+    pub fn match_str(&self) -> String {
+        let mut v = vec!();
+        if let Some(x) = self.msg_type { v.push(("type", msg_type_str(x))) };
+        if let Some(ref x) = self.sender { v.push(("sender", &x)) };
+        let pn = if self.path_is_namespace { "path_namespace" } else { "path" };
+        if let Some(ref x) = self.path { v.push((pn, &x)) };
+        if let Some(ref x) = self.interface { v.push(("interface", &x)) };
+        if let Some(ref x) = self.member { v.push(("member", &x)) };
+        if self.eavesdrop { v.push(("eavesdrop", "true")) };
+
+        // For now we don't need to worry about internal quotes in strings as those are not valid names.
+        // If we start matching against arguments, we need to worry.
+        let v: Vec<_> = v.into_iter().map(|(k, v)| format!("{}='{}'", k, v)).collect();
+        v.join(",")
+    }
+
+    fn path_match(&self, msg: &Message) -> bool {
+        if let Some(ref x) = self.path {
+            if let Some(ref p) = msg.path() {
+                if x != p {
+                    if self.path_is_namespace {
+                        p.starts_with(&**x) && &p[x.len()..x.len() + 1] == "/"
+                    } else { false }
+                } else { true }
+            } else { false }
+        } else { true }
+    }
+
+    /// Returns whether or not the message matches the rule.
+    pub fn matches(&self, msg: &Message) -> bool {
+        if let Some(x) = self.msg_type { if x != msg.msg_type() { return false; } };
+
+        if let Some(ref x) = self.sender {
+            if let Some(s) = msg.sender() {
+                let check = self.strict_sender || (s.starts_with(":") == x.starts_with(":"));
+                if check && s != *x { return false; }
+            } else if self.strict_sender { return false; }
+        };
+        if !self.path_match(msg) { return false; }
+        if self.interface.is_some() && msg.interface() != self.interface { return false; };
+        if self.member.is_some() && msg.member() != self.member { return false; };
+        true
+    }
+
+    /// Create a new struct which matches every message.
+    pub fn new() -> Self { Default::default() }
+
+    /// Create a new struct which matches every incoming method call message.
+    pub fn new_method_call() -> Self {
+        let mut m = Self::new();
+        m.msg_type = Some(MessageType::MethodCall);
+        m
+    }
+
+    /// Create a new struct which matches signals on the interface and member name.
+    pub fn new_signal<I: Into<Interface<'a>>, N: Into<Member<'a>>>(intf: I, name: N) -> Self {
+        let mut m = Self::new();
+        m.msg_type = Some(MessageType::Signal);
+        m.interface = Some(intf.into());
+        m.member = Some(name.into());
+        m
+    }
+
+    /// Returns a clone with no borrowed references
+    pub fn static_clone(&self) -> MatchRule<'static> {
+        MatchRule {
+            msg_type: self.msg_type,
+            sender: self.sender.as_ref().map(|x| x.clone().into_static()),
+            strict_sender: self.strict_sender,
+            path: self.path.as_ref().map(|x| x.clone().into_static()),
+            interface: self.interface.as_ref().map(|x| x.clone().into_static()),
+            member: self.member.as_ref().map(|x| x.clone().into_static()),
+            path_is_namespace: self.path_is_namespace,
+            eavesdrop: self.eavesdrop,
+            _more_fields_may_come: (),
+        }
+    }
+
+    /// Enables eavesdropping for the generated message.
+    /// You probably want to use [BecomeMonitor](https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-become-monitor) instead
+    pub fn with_eavesdrop(mut self) -> Self {
+        self.eavesdrop = true;
+        self
+    }
+
+    /// Sets the MatchRule to match on the message sender
+    pub fn with_sender(mut self, sender: impl Into<BusName<'a>>) -> Self {
+        self.sender = Some(sender.into());
+        self
+    }
+
+    /// Sets the MatchRule to match on the message sender and be strict
+    pub fn with_strict_sender(mut self, sender: impl Into<BusName<'a>>) -> Self {
+        self.sender = Some(sender.into());
+        self.strict_sender = true;
+        self
+    }
+
+    /// Sets the MatchRule to match on the message path and treat it as a namespace
+    pub fn with_namespaced_path(mut self, path: impl Into<Path<'a>>) -> Self {
+        self.path = Some(path.into());
+        self.path_is_namespace = true;
+        self
+    }
+
+    /// Sets the MatchRule to match on the message path
+    pub fn with_path(mut self, path: impl Into<Path<'a>>) -> Self {
+        self.path = Some(path.into());
+        self
+    }
+
+    /// Sets the MatchRule to match on the message interface
+    pub fn with_interface(mut self, intf: impl Into<Interface<'a>>) -> Self {
+        self.interface = Some(intf.into());
+        self
+    }
+
+    /// Sets the MatchRule to match on the message member
+    pub fn with_member(mut self, member: impl Into<Member<'a>>) -> Self {
+        self.member = Some(member.into());
+        self
+    }
+
+    /// Sets the MatchRule to match on the message type. This will usually be `"signal"`
+    pub fn with_type(mut self, ty: MessageType) -> Self {
+        self.msg_type = Some(ty);
+        self
+    }
+
+    /// Tries parsing a MatchRule from a String. Please note however that not all features supported
+    /// by DBus are supported by dbus-rs (yet). args and destinations are not supported yet.
+    pub fn parse(text: &'a str) -> Result<Self, parser::Error> {
+        parser::Parser::new(text)?.parse()
+    }
+}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/message/parser.rs
@@ -0,0 +1,261 @@
+use std::error::Error as stdError;
+use std::fmt::{Debug, Formatter, Display};
+use crate::message::MatchRule;
+use crate::{MessageType, Path};
+use std::convert::TryFrom;
+use crate::strings::{Interface, BusName, Member};
+
+// Our grammar:
+// rules: rule (, rule)*
+// rule: sender | type | interface | member | path | path_namespace | destination | arg | arg_path
+// bool : 'true' | 'false'
+// type: "type" "=" message_type
+// message_type: "'signal'" | "'method_call'" | "'method_return'" | "'error'"
+// sender: "sender" "=" string
+// interface: "interface" "=" string
+// member: "member" "=" string
+// path: "path" "=" string
+// path_namespace: "path_namespace" "=" string
+// destination: "destination" "=" string
+// arg: "arg" 0-63 "=" string
+// arg_path: "arg" 0-63 "path" "=" string
+// eavesdrop: "eavesdrop" "=" bool
+
+
+#[derive(Clone, Debug)]
+/// Error type that covers errors that might happen during parsing.
+pub enum Error {
+    /// The type specified in the match rule is unknown
+    UnknownType,
+    /// The key is wrong / unsupported
+    UnknownKey,
+    /// Boolean could not be parsed
+    BadBoolean,
+    /// Error that occured while converting a string to a DBus format
+    BadConversion(String),
+}
+
+impl Display for Error {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "Error while parsing MatchRule: ")?;
+        match self {
+            Error::UnknownType => {
+                write!(f, "Unsupported message type")
+            }
+            Error::UnknownKey => {
+                write!(f, "Unknown key used")
+            }
+            Error::BadBoolean => {
+                write!(f, "Got bad boolean value")
+            }
+            Error::BadConversion(err) => {
+                write!(f, "Error while converting: {}", err)
+            }
+        }
+    }
+}
+
+impl stdError for Error {}
+
+/// Key-Value-pair
+pub type TokenRule<'a> = (&'a str, &'a str);
+/// Fixed size buffer for match rule tokens
+pub type TokenBuffer<'a> = Vec<TokenRule<'a>>;
+
+#[derive(Clone, Debug)]
+/// Tokenizes a match rule into key-value-pairs
+struct Tokenizer<'a> {
+    text: &'a str,
+}
+
+impl<'a> Tokenizer<'a> {
+    /// Builds a new tokenizer for the input &str
+    pub fn new(text: &'a str) -> Self {
+        Self {
+            text,
+        }
+    }
+
+    /// Parse the key part of the key-value-pair. This is rather easy as all keys are rather
+    /// easily defined and may only contain `[a-z0-9]` so we can simply split at `'='`.
+    fn key(&self) -> (&'a str, &'a str) {
+        let index = self.text.find('=').unwrap_or_else(|| self.text.len());
+
+        ((&self.text[..index]).trim(), &self.text[index + 1..])
+    }
+
+    /// Parses values as generic strings.
+    /// This does not do any validation (yet) with regards to supported characters.
+    fn value(&self) -> (&'a str, &'a str) {
+        let mut i = 0;
+        let mut quoted = false;
+        let mut escape = false;
+
+        for c in self.text.chars() {
+            match c {
+                '\'' if !escape => {
+                    quoted = !quoted;
+                }
+                ',' if !quoted => {
+                    break;
+                }
+                '\\' if !quoted => {
+                    escape = true;
+                    i += 1;
+                    continue;
+                }
+                _ => {}
+            }
+            escape = false;
+
+            i += 1;
+        }
+
+        // Skip comma if there is still space in the buffer
+        let j = if self.text.len() == i { i } else { i + 1 };
+        ((&self.text[..i]).trim(), &self.text[j..])
+    }
+
+    /// Tokenizes a string into key-value-pairs
+    pub fn tokenize(&mut self) -> Result<TokenBuffer<'a>, Error> {
+        let mut rules = TokenBuffer::new();
+
+        while !self.text.is_empty() {
+            let (key, rest) = self.key();
+            self.text = rest;
+            let (value, rest) = self.value();
+            self.text = rest;
+            rules.push((key, value))
+        }
+        Ok(rules)
+    }
+}
+
+#[derive(Clone, Debug)]
+/// Helper struct for parsing MatchRule's
+pub struct Parser<'a> {
+    tokens: TokenBuffer<'a>,
+}
+
+impl<'a> Parser<'a> {
+    /// Builds a new parser after tokenizing the input string `text`.
+    pub fn new(text: &'a str) -> Result<Self, Error> {
+        Ok(Self {
+            tokens: Tokenizer::new(text).tokenize()?
+        })
+    }
+
+    /// Cleans a string from the string syntax allowed by DBus. This includes concatenating
+    /// things like `''\'''` to `'`. DBus strings sort of work like in a POSIX shell and
+    /// concatenation is implied. There is only one escape sequence and that is in an unquoted
+    /// substring a backslash may escape an ASCII apostrophe (U+0027).
+    /// This method is the only one within the parser that allocates and in theory could be
+    /// rewritten to taking a `&mut str` instead of returning a `String` since all
+    /// strings are |output| <= |buf.len()|.
+    fn clean_string(&self, buf: &str) -> String {
+        let mut quoted = false;
+        let mut escape = false;
+        let mut outbuf = String::with_capacity(buf.len());
+
+        for c in buf.chars() {
+            match c {
+                '\'' if !escape => {
+                    quoted = !quoted;
+                }
+                '\\' if !quoted => {
+                    escape = true;
+                    continue;
+                }
+                c if c.is_whitespace() && !quoted => {
+                    continue;
+                }
+                c => {
+                    outbuf.push(c);
+                }
+            }
+        }
+
+        outbuf
+    }
+
+    /// Parses key-value-pair tokens into a MatchRule
+    pub fn parse(&self) -> Result<MatchRule<'a>, Error> {
+        let mut match_rule = MatchRule::new();
+
+        for &(key, raw_value) in &self.tokens {
+            let value = self.clean_string(raw_value);
+            match key {
+                "type" => {
+                    match_rule = match_rule.with_type(MessageType::try_from(value.as_str()).map_err(|_| Error::UnknownType)?);
+                    Ok(())
+                }
+                "interface" => {
+                    match_rule.interface = Some(Interface::new(value).map_err(Error::BadConversion)?);
+                    Ok(())
+                }
+                "sender" => {
+                    match_rule.sender = Some(BusName::new(value).map_err(Error::BadConversion)?);
+                    Ok(())
+                }
+                "member" => {
+                    match_rule.member = Some(Member::new(value).map_err(Error::BadConversion)?);
+                    Ok(())
+                }
+                "path" => {
+                    match_rule.path = Some(Path::new(value).map_err(Error::BadConversion)?);
+                    Ok(())
+                }
+                "path_namespace" => {
+                    match_rule.path = Some(Path::new(value).map_err(Error::BadConversion)?);
+                    match_rule.path_is_namespace = true;
+                    Ok(())
+                }
+                "eavesdrop" => {
+                    match raw_value {
+                        "'true'" | "true" => {
+                            match_rule = match_rule.with_eavesdrop();
+                            Ok(())
+                        }
+                        "'false'" | "false" => {
+                            Ok(())
+                        }
+                        _ => {
+                            Err(Error::BadBoolean)
+                        }
+                    }
+                }
+                _ => {
+                    // Args and Destination are not supported yet.
+                    Err(Error::UnknownKey)
+                }
+            }?;
+        }
+
+        Ok(match_rule)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::message::parser::Error;
+    use crate::message::MatchRule;
+
+    #[test]
+    fn test_tokenizer() -> Result<(), Error> {
+        let mr = MatchRule::parse(r"interface='org.freedesktop.Notifications',member='Notify'")?;
+        assert_eq!(mr.match_str(), "interface='org.freedesktop.Notifications',member='Notify'");
+        let mr = MatchRule::parse(r"interface='org.mpris.MediaPlayer2.Player' , path= /org/mpris/MediaPlayer2,member='Notify', eavesdrop ='true'")?;
+        assert_eq!(mr.match_str(), "path='/org/mpris/MediaPlayer2',interface='org.mpris.MediaPlayer2.Player',member='Notify',eavesdrop='true'");
+        Ok(())
+    }
+
+    #[test]
+    fn test_malformed() {
+        assert!(MatchRule::parse(r"interface='org.freedesktop.Notifications',member=").is_err());
+    }
+
+    #[test]
+    fn test_spurious_comma() {
+        assert!(MatchRule::parse(r"interface='org.freedesktop.Notifications',").is_ok());
+    }
+}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/message/signalargs.rs
@@ -0,0 +1,103 @@
+use crate::arg;
+use crate::{Message, MessageType};
+use crate::message::MatchRule;
+use crate::strings::{BusName, Path, Interface, Member};
+
+/// Helper methods for structs representing a Signal
+///
+/// # Example
+///
+/// Listen to InterfacesRemoved signal from org.bluez.obex.
+///
+/// ```rust,no_run
+/// use dbus::blocking::Connection;
+/// use dbus::message::SignalArgs;
+/// use dbus::blocking::stdintf::org_freedesktop_dbus::ObjectManagerInterfacesRemoved as IR;
+/// use std::time::Duration;
+///
+/// let c = Connection::new_session().unwrap();
+/// // Add a match for this signal
+/// let mr = IR::match_rule(Some(&"org.bluez.obex".into()), None).static_clone();
+/// c.add_match(mr, |ir: IR, _, _| {
+///      println!("Interfaces {:?} have been removed from bluez on path {}.", ir.interfaces, ir.object);
+///      true
+/// });
+///
+/// // Wait for the signal to arrive.
+/// loop { c.process(Duration::from_millis(1000)).unwrap(); }
+/// ```
+
+pub trait SignalArgs {
+    /// D-Bus name of signal
+    const NAME: &'static str;
+
+    /// D-Bus name of interface this signal belongs to
+    const INTERFACE: &'static str;
+
+    /// Returns a message that emits the signal.
+    fn to_emit_message(&self, path: &Path) -> Message where Self: arg::AppendAll {
+        let mut m = Message::signal(path, &Interface::from(Self::INTERFACE), &Member::from(Self::NAME));
+        arg::AppendAll::append(self, &mut arg::IterAppend::new(&mut m));
+        m
+    }
+
+    /// If the message is a signal of the correct type, return its arguments, otherwise return None.
+    ///
+    /// This does not check sender and path of the message, which is likely relevant to you as well.
+    #[allow(clippy::if_same_then_else)]
+    fn from_message(m: &Message) -> Option<Self> where Self: Sized + arg::ReadAll {
+        if m.msg_type() != MessageType::Signal { None }
+        else if m.interface().as_ref().map(|x| &**x) != Some(Self::INTERFACE) { None }
+        else if m.member().as_ref().map(|x| &**x) != Some(Self::NAME) { None }
+        else {
+            arg::ReadAll::read(&mut m.iter_init()).ok()
+        }
+    }
+
+    /// Returns a match rule matching this signal.
+    ///
+    /// If sender and/or path is None, matches all senders and/or paths.
+    fn match_rule<'a>(sender: Option<&'a BusName>, path: Option<&'a Path>) -> MatchRule<'a> {
+        let mut m: MatchRule = Default::default();
+        m.sender = sender.cloned();
+        m.path = path.cloned();
+        m.msg_type = Some(MessageType::Signal);
+        m.interface = Some(Self::INTERFACE.into());
+        m.member = Some(Self::NAME.into());
+        m
+    }
+
+
+    /// Returns a string that can be sent to `Connection::add_match`.
+    ///
+    /// If sender and/or path is None, matches all senders and/or paths.
+    fn match_str(sender: Option<&BusName>, path: Option<&Path>) -> String {
+        Self::match_rule(sender, path).match_str()
+    }
+}
+
+#[test]
+fn intf_removed() {
+    use crate::blocking::LocalConnection;
+    use crate::blocking::stdintf::org_freedesktop_dbus::ObjectManagerInterfacesRemoved as IR;
+    use std::{time::Duration, cell::Cell, rc::Rc};
+    let c = LocalConnection::new_session().unwrap();
+
+    let mr = IR::match_rule(Some(&c.unique_name().into()), Some(&"/hello".into())).static_clone();
+    println!("Match: {:?}", mr);
+
+    let ir = IR { object: "/hello".into(), interfaces: vec!("ABC.DEF".into(), "GHI.JKL".into()) };
+    let ir_msg = ir.to_emit_message(&"/hello".into());
+    let done = Rc::new(Cell::new(false));
+    let done2 = done.clone();
+
+    c.add_match(mr, move |ir2: IR, _, _| {
+        assert_eq!(ir2.object, ir.object);
+        assert_eq!(ir2.interfaces, ir.interfaces);
+        done2.set(true);
+        false
+    }).unwrap();
+    use crate::channel::Sender;
+    c.send(ir_msg).expect("Failed to send message");
+    while !done.get() { c.process(Duration::from_millis(1000)).unwrap(); }
+}
--- a/third_party/rust/dbus/src/methoddisp.rs
+++ b/third_party/rust/dbus/src/methoddisp.rs
@@ -101,21 +101,21 @@ impl MethodErr {
 impl<T: Into<ErrorName<'static>>, M: Into<String>> From<(T, M)> for MethodErr {
     fn from((t, m): (T, M)) -> MethodErr { MethodErr(t.into(), m.into()) }
 }
 
 /// Result containing the Messages returned from the Method, or a MethodErr.
 pub type MethodResult = Result<Vec<Message>, MethodErr>;
 
 /// A MethodType that wraps an Fn function
-pub struct MethodFn<'a>(Box<Fn(&Message, &ObjectPath<MethodFn<'a>>, &Tree<MethodFn<'a>>) -> MethodResult + 'a>);
+pub struct MethodFn<'a>(Box<dyn Fn(&Message, &ObjectPath<MethodFn<'a>>, &Tree<MethodFn<'a>>) -> MethodResult + 'a>);
 /// A MethodType that wraps an FnMut function. Calling this recursively will cause a refcell panic.
 pub struct MethodFnMut<'a>(Box<RefCell<FnMut(&Message, &ObjectPath<MethodFnMut<'a>>, &Tree<MethodFnMut<'a>>) -> MethodResult + 'a>>);
 /// A MethodType that wraps an Fn+Send+Sync function, so it can be called from several threads in parallel.
-pub struct MethodSync(Box<Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static>);
+pub struct MethodSync(Box<dyn Fn(&Message, &ObjectPath<MethodSync>, &Tree<MethodSync>) -> MethodResult + Send + Sync + 'static>);
 
 impl<'a> fmt::Debug for MethodFn<'a> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Fn>") }
 }
 
 impl<'a> fmt::Debug for MethodFnMut<'a> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<FnMut>") }
 }
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/nonblock.rs
@@ -0,0 +1,604 @@
+//! Async version of connection.
+//!
+//! This module requires the `futures` feature to be enabled.
+//!
+//! Current status:
+//!  * Basic client functionality is up and running, i e, you can make method calls and
+//!    receive incoming messages (e g signals).
+//!  * As for server side code, you can use the `tree` module with this connection, but it does not
+//!    support async method handlers.
+//!
+//! You're probably going to need a companion crate - dbus-tokio - for this connection to make sense.
+//! (Although you can also just call read_write and process_all at regular intervals, and possibly
+//! set a timeout handler.)
+
+
+use crate::{Error, Message};
+use crate::channel::{MatchingReceiver, Channel, Sender, Token};
+use crate::strings::{BusName, Path, Interface, Member};
+use crate::arg::{AppendAll, ReadAll, IterAppend};
+use crate::message::{MatchRule, MessageType};
+
+use std::sync::{Arc, Mutex};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::{task, pin, mem};
+use std::cell::RefCell;
+use std::time::Duration;
+use crate::filters::Filters;
+use std::future::Future;
+use std::time::Instant;
+use std::collections::HashMap;
+
+
+#[allow(missing_docs)]
+mod generated_org_freedesktop_standard_interfaces;
+mod generated_org_freedesktop_dbus;
+
+
+/// This module contains some standard interfaces and an easy way to call them.
+///
+/// See the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces) for more information about these standard interfaces.
+///
+/// The code was created by dbus-codegen.
+pub mod stdintf {
+    #[allow(missing_docs)]
+    pub mod org_freedesktop_dbus {
+        pub use super::super::generated_org_freedesktop_standard_interfaces::*;
+        #[allow(unused_imports)]
+        pub(crate) use super::super::generated_org_freedesktop_dbus::*;
+
+        #[derive(Debug, PartialEq, Eq, Copy, Clone)]
+        pub enum RequestNameReply {
+            PrimaryOwner = 1,
+            InQueue = 2,
+            Exists = 3,
+            AlreadyOwner = 4,
+        }
+
+        #[derive(Debug, PartialEq, Eq, Copy, Clone)]
+        pub enum ReleaseNameReply {
+            Released = 1,
+            NonExistent = 2,
+            NotOwner = 3,
+        }
+
+    }
+}
+
+
+type Replies<F> = HashMap<Token, F>;
+
+/// A connection to D-Bus, thread local + async version
+pub struct LocalConnection {
+    channel: Channel,
+    filters: RefCell<Filters<LocalFilterCb>>,
+    replies: RefCell<Replies<LocalRepliesCb>>,
+    timeout_maker: Option<TimeoutMakerCb>,
+    waker: Option<WakerCb>,
+    all_signal_matches: AtomicBool,
+}
+
+/// A connection to D-Bus, async version, which is Send but not Sync.
+pub struct Connection {
+    channel: Channel,
+    filters: RefCell<Filters<FilterCb>>,
+    replies: RefCell<Replies<RepliesCb>>,
+    timeout_maker: Option<TimeoutMakerCb>,
+    waker: Option<WakerCb>,
+    all_signal_matches: AtomicBool,
+}
+
+/// A connection to D-Bus, Send + Sync + async version
+pub struct SyncConnection {
+    channel: Channel,
+    filters: Mutex<Filters<SyncFilterCb>>,
+    replies: Mutex<Replies<SyncRepliesCb>>,
+    timeout_maker: Option<TimeoutMakerCb>,
+    waker: Option<WakerCb>,
+    all_signal_matches: AtomicBool,
+}
+
+use stdintf::org_freedesktop_dbus::DBus;
+
+macro_rules! connimpl {
+     ($c: ident, $cb: ident, $rcb: ident $(, $ss:tt)*) =>  {
+
+type
+    $cb = Box<dyn FnMut(Message, &$c) -> bool $(+ $ss)* + 'static>;
+type
+    $rcb = Box<dyn FnOnce(Message, &$c) $(+ $ss)* + 'static>;
+
+impl From<Channel> for $c {
+    fn from(x: Channel) -> Self {
+        $c {
+            channel: x,
+            replies: Default::default(),
+            filters: Default::default(),
+            timeout_maker: None,
+            waker: None,
+            all_signal_matches: AtomicBool::new(false),
+        }
+    }
+}
+
+impl AsRef<Channel> for $c {
+    fn as_ref(&self) -> &Channel { &self.channel }
+}
+
+impl Sender for $c {
+    fn send(&self, msg: Message) -> Result<u32, ()> {
+        let token = self.channel.send(msg);
+        if self.channel.has_messages_to_send() {
+            // Non-blocking send failed
+            // Wake up task that will send the message
+            if self.waker.as_ref().map(|wake| wake().is_err() ).unwrap_or(false) {
+                return Err(());
+            }
+        }
+        token
+    }
+}
+
+impl MatchingReceiver for $c {
+    type F = $cb;
+    fn start_receive(&self, m: MatchRule<'static>, f: Self::F) -> Token {
+        self.filters_mut().add(m, f)
+    }
+    fn stop_receive(&self, id: Token) -> Option<(MatchRule<'static>, Self::F)> {
+        self.filters_mut().remove(id)
+    }
+}
+
+impl NonblockReply for $c {
+    type F = $rcb;
+    fn send_with_reply(&self, msg: Message, f: Self::F) -> Result<Token, ()> {
+        let token = {
+            // We must hold the mutex from moment we send the message
+            // To moment we set a handler for the reply
+            // So reply can't arrive before we set handler
+            let mut replies = self.replies_mut();
+            self.channel.send(msg).map(|x| {
+                let t = Token(x as usize);
+                replies.insert(t, f);
+                t
+            })
+        };
+        if self.channel.has_messages_to_send() {
+            // Non-blocking send failed
+            // Wake up task that will send the message
+            if self.waker.as_ref().map(|wake| wake().is_err() ).unwrap_or(false) {
+                return Err(());
+            }
+        }
+        token
+    }
+    fn cancel_reply(&self, id: Token) -> Option<Self::F> { self.replies_mut().remove(&id) }
+    fn make_f<G: FnOnce(Message, &Self) + Send + 'static>(g: G) -> Self::F { Box::new(g) }
+    fn timeout_maker(&self) -> Option<TimeoutMakerCb> { self.timeout_maker }
+    fn set_timeout_maker(&mut self, f: Option<TimeoutMakerCb>) -> Option<TimeoutMakerCb> {
+        mem::replace(&mut self.timeout_maker, f)
+    }
+    fn set_waker(&mut self, f: Option<WakerCb>) -> Option<WakerCb> {
+        mem::replace(&mut self.waker, f)
+    }
+}
+
+
+impl Process for $c {
+    fn process_one(&self, msg: Message) {
+        if let Some(serial) = msg.get_reply_serial() {
+            if let Some(f) = self.replies_mut().remove(&Token(serial as usize)) {
+                f(msg, self);
+                return;
+            }
+        }
+        if self.all_signal_matches.load(Ordering::Acquire) && msg.msg_type() == MessageType::Signal {
+            // If it's a signal and the mode is enabled, send a copy of the message to all
+            // matching filters.
+            let matching_filters = self.filters_mut().remove_all_matching(&msg);
+            // `matching_filters` needs to be a separate variable and not inlined here, because if
+            // it's inline then the `MutexGuard` will live too long and we'll get a deadlock on the
+            // next call to `filters_mut()` below.
+            for mut ff in matching_filters {
+                if let Ok(copy) = msg.duplicate() {
+                    if ff.2(copy, self) {
+                        self.filters_mut().insert(ff);
+                    }
+                } else {
+                    // Silently drop the message, but add the filter back.
+                    self.filters_mut().insert(ff);
+                }
+            }
+        } else {
+            // Otherwise, send the original message to only the first matching filter.
+            let ff = self.filters_mut().remove_first_matching(&msg);
+            if let Some(mut ff) = ff {
+                if ff.2(msg, self) {
+                    self.filters_mut().insert(ff);
+                }
+            } else if let Some(reply) = crate::channel::default_reply(&msg) {
+                let _ = self.channel.send(reply);
+            }
+        }
+    }
+}
+
+impl $c {
+    fn dbus_proxy(&self) -> Proxy<&Self> {
+        Proxy::new("org.freedesktop.DBus", "/org/freedesktop/DBus", Duration::from_secs(10), self)
+    }
+
+    /// Get the connection's unique name.
+    ///
+    /// It's usually something like ":1.54"
+    pub fn unique_name(&self) -> BusName { self.channel.unique_name().unwrap().into() }
+
+    /// Request a name on the D-Bus.
+    ///
+    /// For detailed information on the flags and return values, see the libdbus documentation.
+    pub async fn request_name<'a, N: Into<BusName<'a>>>(&self, name: N, allow_replacement: bool, replace_existing: bool, do_not_queue: bool)
+    -> Result<stdintf::org_freedesktop_dbus::RequestNameReply, Error> {
+        let flags: u32 =
+            if allow_replacement { 1 } else { 0 } +
+            if replace_existing { 2 } else { 0 } +
+            if do_not_queue { 4 } else { 0 };
+        let r = self.dbus_proxy().request_name(&name.into(), flags).await?;
+        use stdintf::org_freedesktop_dbus::RequestNameReply::*;
+        let all = [PrimaryOwner, InQueue, Exists, AlreadyOwner];
+        all.iter().find(|x| **x as u32 == r).copied().ok_or_else(||
+            crate::Error::new_failed("Invalid reply from DBus server")
+        )
+    }
+
+    /// Release a previously requested name on the D-Bus.
+    pub async fn release_name<'a, N: Into<BusName<'a>>>(&self, name: N) -> Result<stdintf::org_freedesktop_dbus::ReleaseNameReply, Error> {
+        let r = self.dbus_proxy().release_name(&name.into()).await?;
+        use stdintf::org_freedesktop_dbus::ReleaseNameReply::*;
+        let all = [Released, NonExistent, NotOwner];
+        all.iter().find(|x| **x as u32 == r).copied().ok_or_else(||
+            crate::Error::new_failed("Invalid reply from DBus server")
+        )
+    }
+
+    /// Adds a new match to the connection, and sets up a callback when this message arrives.
+    ///
+    /// If multiple [`MatchRule`]s match the same message, then by default only the first will get
+    /// the callback. This behaviour can be changed for signal messages by calling
+    /// [`set_signal_match_mode`](Self::set_signal_match_mode).
+    ///
+    /// The returned value can be used to remove the match.
+    pub async fn add_match(&self, match_rule: MatchRule<'static>) -> Result<MsgMatch, Error> {
+        let m = match_rule.match_str();
+        self.add_match_no_cb(&m).await?;
+        let mi = Arc::new(MatchInner {
+            token: Default::default(),
+            cb: Default::default(),
+        });
+        let mi_weak = Arc::downgrade(&mi);
+        let token = self.start_receive(match_rule, Box::new(move |msg, _| {
+            mi_weak.upgrade().map(|mi| mi.incoming(msg)).unwrap_or(false)
+        }));
+        mi.token.store(token.0, Ordering::SeqCst);
+        Ok(MsgMatch(mi))
+    }
+
+
+    /// Adds a new match to the connection, without setting up a callback when this message arrives.
+    pub async fn add_match_no_cb(&self, match_str: &str) -> Result<(), Error> {
+        self.dbus_proxy().add_match(match_str).await
+    }
+
+    /// Removes a match from the connection, without removing any callbacks.
+    pub async fn remove_match_no_cb(&self, match_str: &str) -> Result<(), Error> {
+        self.dbus_proxy().remove_match(match_str).await
+    }
+
+    /// Removes a previously added match and callback from the connection.
+    pub async fn remove_match(&self, id: Token) -> Result<(), Error> {
+        let (mr, _) = self.stop_receive(id).ok_or_else(|| Error::new_failed("No match with that id found"))?;
+        self.remove_match_no_cb(&mr.match_str()).await
+    }
+
+    /// If true, configures the connection to send signal messages to all matching [`MatchRule`]
+    /// filters added with [`add_match`](Self::add_match) rather than just the first one. This comes
+    /// with the following gotchas:
+    ///
+    ///  * The messages might be duplicated, so the message serial might be lost (this is
+    ///    generally not a problem for signals).
+    ///  * Panicking inside a match callback might mess with other callbacks, causing them
+    ///    to be permanently dropped.
+    ///  * Removing other matches from inside a match callback is not supported.
+    ///
+    /// This is false by default, for a newly-created connection.
+    pub fn set_signal_match_mode(&self, match_all: bool) {
+        self.all_signal_matches.store(match_all, Ordering::Release);
+    }
+}
+
+
+    }
+}
+
+connimpl!(Connection, FilterCb, RepliesCb, Send);
+connimpl!(LocalConnection, LocalFilterCb, LocalRepliesCb);
+connimpl!(SyncConnection, SyncFilterCb, SyncRepliesCb, Send);
+
+impl Connection {
+    fn filters_mut(&self) -> std::cell::RefMut<Filters<FilterCb>> { self.filters.borrow_mut() }
+    fn replies_mut(&self) -> std::cell::RefMut<Replies<RepliesCb>> { self.replies.borrow_mut() }
+}
+
+impl LocalConnection {
+    fn filters_mut(&self) -> std::cell::RefMut<Filters<LocalFilterCb>> { self.filters.borrow_mut() }
+    fn replies_mut(&self) -> std::cell::RefMut<Replies<LocalRepliesCb>> { self.replies.borrow_mut() }
+}
+
+impl SyncConnection {
+    fn filters_mut(&self) -> std::sync::MutexGuard<Filters<SyncFilterCb>> { self.filters.lock().unwrap() }
+    fn replies_mut(&self) -> std::sync::MutexGuard<Replies<SyncRepliesCb>> { self.replies.lock().unwrap() }
+}
+
+/// Internal callback for the executor when a timeout needs to be made.
+pub type TimeoutMakerCb = fn(timeout: Instant) -> pin::Pin<Box<dyn Future<Output=()> + Send + Sync + 'static>>;
+
+/// Internal callback for the executor when we need wakeup a task
+pub type WakerCb = Box<dyn Fn() -> Result<(), ()> + Send + Sync +'static>;
+
+/// Internal helper trait for async method replies.
+pub trait NonblockReply {
+    /// Callback type
+    type F;
+    /// Sends a message and calls the callback when a reply is received.
+    fn send_with_reply(&self, msg: Message, f: Self::F) -> Result<Token, ()>;
+    /// Cancels a pending reply.
+    fn cancel_reply(&self, id: Token) -> Option<Self::F>;
+    /// Internal helper function that creates a callback.
+    fn make_f<G: FnOnce(Message, &Self) + Send + 'static>(g: G) -> Self::F where Self: Sized;
+    /// Set the internal timeout maker
+    fn set_timeout_maker(&mut self, f: Option<TimeoutMakerCb>) -> Option<TimeoutMakerCb>;
+    /// Get the internal timeout maker
+    fn timeout_maker(&self) -> Option<TimeoutMakerCb>;
+    /// Set the wakeup call
+    fn set_waker(&mut self, f: Option<WakerCb>) -> Option<WakerCb>;
+}
+
+
+/// Internal helper trait, implemented for connections that process incoming messages.
+pub trait Process: Sender + AsRef<Channel> {
+    /// Dispatches all pending messages, without blocking.
+    ///
+    /// This is usually called from the reactor only, after read_write.
+    /// Despite this taking &self and not "&mut self", it is a logic error to call this
+    /// recursively or from more than one thread at a time.
+    fn process_all(&self) {
+        let c: &Channel = self.as_ref();
+        while let Some(msg) = c.pop_message() {
+            self.process_one(msg);
+        }
+    }
+
+    /// Dispatches a message.
+    fn process_one(&self, msg: Message);
+}
+
+/// A struct used to handle incoming matches
+///
+/// Note: Due to the lack of async destructors, please call Connection.remove_match()
+/// in order to properly stop matching (instead of just dropping this struct).
+pub struct MsgMatch(Arc<MatchInner>);
+
+struct MatchInner {
+    token: AtomicUsize,
+    cb: Mutex<Option<Box<dyn FnMut(Message) -> bool + Send>>>,
+}
+
+impl MatchInner {
+    fn incoming(&self, msg: Message) -> bool {
+        if let Some(ref mut cb) = self.cb.lock().unwrap().as_mut() {
+            cb(msg)
+        }
+        else { true }
+    }
+}
+
+impl MsgMatch {
+    /// Configures the match to receive a synchronous callback with only a message parameter.
+    pub fn msg_cb<F: FnMut(Message) -> bool + Send + 'static>(self, f: F) -> Self {
+        {
+            let mut cb = self.0.cb.lock().unwrap();
+            *cb = Some(Box::new(f));
+        }
+        self
+    }
+
+    /// Configures the match to receive a synchronous callback with a message parameter and typed
+    /// message arguments.
+    ///
+    /// # Example
+    ///
+    /// ```ignore
+    /// let mr = MatchRule::new_signal("com.example.dbustest", "HelloHappened");
+    /// let incoming_signal = connection.add_match(mr).await?.cb(|_, (source,): (String,)| {
+    ///    println!("Hello from {} happened on the bus!", source);
+    ///    true
+    /// });
+    /// ```
+    pub fn cb<R: ReadAll, F: FnMut(Message, R) -> bool + Send + 'static>(self, mut f: F) -> Self {
+        self.msg_cb(move |msg| {
+            if let Ok(r) = R::read(&mut msg.iter_init()) {
+                f(msg, r)
+            } else { true }
+        })
+    }
+
+    /// Configures the match to receive a stream of messages.
+    ///
+    /// Note: If the receiving end is disconnected and a message is received,
+    /// the message matching will end but not in a clean fashion. Call remove_match() to
+    /// stop matching cleanly.
+    pub fn msg_stream(self) -> (Self, futures_channel::mpsc::UnboundedReceiver<Message>) {
+        let (sender, receiver) = futures_channel::mpsc::unbounded();
+        (self.msg_cb(move |msg| {
+            sender.unbounded_send(msg).is_ok()
+        }), receiver)
+    }
+
+    /// Configures the match to receive a stream of messages, parsed and ready.
+    ///
+    /// Note: If the receiving end is disconnected and a message is received,
+    /// the message matching will end but not in a clean fashion. Call remove_match() to
+    /// stop matching cleanly.
+    ///
+    /// # Example
+    ///
+    /// ```ignore
+    /// let mr = MatchRule::new_signal("com.example.dbustest", "HelloHappened");
+    /// let (incoming_signal, stream) = conn.add_match(mr).await?.stream();
+    /// let stream = stream.for_each(|(_, (source,)): (_, (String,))| {
+    ///    println!("Hello from {} happened on the bus!", source);
+    ///    async {}
+    /// });
+    /// ```
+    pub fn stream<R: ReadAll + Send + 'static>(self) -> (Self, futures_channel::mpsc::UnboundedReceiver<(Message, R)>) {
+        let (sender, receiver) = futures_channel::mpsc::unbounded();
+        (self.cb(move |msg, r| {
+            sender.unbounded_send((msg, r)).is_ok()
+        }), receiver)
+    }
+
+    /// The token retreived can be used in a call to remove_match to stop matching on the data.
+    pub fn token(&self) -> Token { Token(self.0.token.load(Ordering::SeqCst)) }
+}
+
+/// A struct that wraps a connection, destination and path.
+///
+/// A D-Bus "Proxy" is a client-side object that corresponds to a remote object on the server side.
+/// Calling methods on the proxy object calls methods on the remote object.
+/// Read more in the [D-Bus tutorial](https://dbus.freedesktop.org/doc/dbus-tutorial.html#proxies)
+#[derive(Clone, Debug)]
+pub struct Proxy<'a, C> {
+    /// Destination, i e what D-Bus service you're communicating with
+    pub destination: BusName<'a>,
+    /// Object path on the destination
+    pub path: Path<'a>,
+    /// Some way to send and/or receive messages, non-blocking.
+    pub connection: C,
+    /// Timeout for method calls
+    pub timeout: Duration,
+}
+
+impl<'a, C> Proxy<'a, C> {
+    /// Creates a new proxy struct.
+    pub fn new<D: Into<BusName<'a>>, P: Into<Path<'a>>>(dest: D, path: P, timeout: Duration, connection: C) -> Self {
+        Proxy { destination: dest.into(), path: path.into(), timeout, connection }
+    }
+}
+
+struct MRAwait {
+    mrouter: MROuter,
+    token: Result<Token, ()>,
+    timeout: Instant,
+    timeoutfn: Option<TimeoutMakerCb>
+}
+
+async fn method_call_await(mra: MRAwait) -> Result<Message, Error> {
+    use futures_util::future;
+    let MRAwait { mrouter, token, timeout, timeoutfn } = mra;
+    if token.is_err() { return Err(Error::new_failed("Failed to send message")) };
+    let timeout = if let Some(tfn) = timeoutfn { tfn(timeout) } else { Box::pin(future::pending()) };
+    match future::select(mrouter, timeout).await {
+        future::Either::Left((r, _)) => r,
+        future::Either::Right(_) => Err(Error::new_custom("org.freedesktop.DBus.Error.Timeout", "Timeout waiting for reply")),
+    }
+}
+
+impl<'a, T, C> Proxy<'a, C>
+where
+    T: NonblockReply,
+    C: std::ops::Deref<Target=T>
+{
+
+    fn method_call_setup(&self, msg: Message) -> MRAwait {
+        let mr = Arc::new(Mutex::new(MRInner::Neither));
+        let mrouter = MROuter(mr.clone());
+        let f = T::make_f(move |msg: Message, _: &T| {
+            let mut inner = mr.lock().unwrap();
+            let old = mem::replace(&mut *inner, MRInner::Ready(Ok(msg)));
+            if let MRInner::Pending(waker) = old { waker.wake() }
+        });
+
+        let timeout = Instant::now() + self.timeout;
+        let token = self.connection.send_with_reply(msg, f);
+        let timeoutfn = self.connection.timeout_maker();
+        MRAwait { mrouter, token, timeout, timeoutfn }
+    }
+
+    /// Make a method call using typed input argument, returns a future that resolves to the typed output arguments.
+    pub fn method_call<'i, 'm, R: ReadAll + 'static, A: AppendAll, I: Into<Interface<'i>>, M: Into<Member<'m>>>(&self, i: I, m: M, args: A)
+    -> MethodReply<R> {
+        let mut msg = Message::method_call(&self.destination, &self.path, &i.into(), &m.into());
+        args.append(&mut IterAppend::new(&mut msg));
+        let mra = self.method_call_setup(msg);
+        let r = method_call_await(mra);
+        let r = futures_util::FutureExt::map(r, |r| -> Result<R, Error> { r.and_then(|rmsg| rmsg.read_all()) } );
+        MethodReply::new(r)
+    }
+}
+
+enum MRInner {
+    Ready(Result<Message, Error>),
+    Pending(task::Waker),
+    Neither,
+}
+
+struct MROuter(Arc<Mutex<MRInner>>);
+
+impl Future for MROuter {
+    type Output = Result<Message, Error>;
+    fn poll(self: pin::Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> {
+        let mut inner = self.0.lock().unwrap();
+        let r = mem::replace(&mut *inner, MRInner::Neither);
+        if let MRInner::Ready(r) = r { task::Poll::Ready(r) }
+        else {
+            *inner = MRInner::Pending(ctx.waker().clone());
+            return task::Poll::Pending
+        }
+    }
+}
+
+/// Future method reply, used while waiting for a method call reply from the server.
+pub struct MethodReply<T>(pin::Pin<Box<dyn Future<Output=Result<T, Error>> + Send + 'static>>);
+
+impl<T> MethodReply<T> {
+    /// Creates a new method reply from a future.
+    fn new<Fut: Future<Output=Result<T, Error>> + Send + 'static>(fut: Fut) -> Self {
+        MethodReply(Box::pin(fut))
+    }
+}
+
+impl<T> Future for MethodReply<T> {
+    type Output = Result<T, Error>;
+    fn poll(mut self: pin::Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Result<T, Error>> {
+        self.0.as_mut().poll(ctx)
+    }
+}
+
+impl<T: 'static> MethodReply<T> {
+    /// Convenience combinator in case you want to post-process the result after reading it
+    pub fn and_then<T2>(self, f: impl FnOnce(T) -> Result<T2, Error> + Send + Sync + 'static) -> MethodReply<T2> {
+        MethodReply(Box::pin(async move {
+            let x = self.0.await?;
+            f(x)
+        }))
+    }
+}
+
+#[test]
+fn test_conn_send_sync() {
+    fn is_send<T: Send>() {}
+    fn is_sync<T: Sync>() {}
+    is_send::<Connection>();
+    is_send::<SyncConnection>();
+    is_sync::<SyncConnection>();
+    is_send::<MsgMatch>();
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/nonblock/generated_org_freedesktop_dbus.rs
@@ -0,0 +1,209 @@
+// This code was autogenerated with `dbus-codegen-rust -d org.freedesktop.DBus -p /org/freedesktop/DBus -m none -c nonblock -g -i org.freedesktop. --dbuscrate crate --filter DBus -o dbus/src/nonblock/generated_org_freedesktop_dbus.rs`, see https://github.com/diwic/dbus-rs
+#![allow(missing_docs)]
+use crate as dbus;
+use crate::arg;
+use crate::nonblock;
+
+pub trait DBus {
+    fn hello(&self) -> nonblock::MethodReply<String>;
+    fn request_name(&self, arg0: &str, arg1: u32) -> nonblock::MethodReply<u32>;
+    fn release_name(&self, arg0: &str) -> nonblock::MethodReply<u32>;
+    fn start_service_by_name(&self, arg0: &str, arg1: u32) -> nonblock::MethodReply<u32>;
+    fn update_activation_environment(&self, arg0: ::std::collections::HashMap<&str, &str>) -> nonblock::MethodReply<()>;
+    fn name_has_owner(&self, arg0: &str) -> nonblock::MethodReply<bool>;
+    fn list_names(&self) -> nonblock::MethodReply<Vec<String>>;
+    fn list_activatable_names(&self) -> nonblock::MethodReply<Vec<String>>;
+    fn add_match(&self, arg0: &str) -> nonblock::MethodReply<()>;
+    fn remove_match(&self, arg0: &str) -> nonblock::MethodReply<()>;
+    fn get_name_owner(&self, arg0: &str) -> nonblock::MethodReply<String>;
+    fn list_queued_owners(&self, arg0: &str) -> nonblock::MethodReply<Vec<String>>;
+    fn get_connection_unix_user(&self, arg0: &str) -> nonblock::MethodReply<u32>;
+    fn get_connection_unix_process_id(&self, arg0: &str) -> nonblock::MethodReply<u32>;
+    fn get_adt_audit_session_data(&self, arg0: &str) -> nonblock::MethodReply<Vec<u8>>;
+    fn get_connection_selinux_security_context(&self, arg0: &str) -> nonblock::MethodReply<Vec<u8>>;
+    fn reload_config(&self) -> nonblock::MethodReply<()>;
+    fn get_id(&self) -> nonblock::MethodReply<String>;
+    fn get_connection_credentials(&self, arg0: &str) -> nonblock::MethodReply<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>>;
+    fn features(&self) -> nonblock::MethodReply<Vec<String>>;
+    fn interfaces(&self) -> nonblock::MethodReply<Vec<String>>;
+}
+
+impl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> DBus for nonblock::Proxy<'a, C> {
+
+    fn hello(&self) -> nonblock::MethodReply<String> {
+        self.method_call("org.freedesktop.DBus", "Hello", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn request_name(&self, arg0: &str, arg1: u32) -> nonblock::MethodReply<u32> {
+        self.method_call("org.freedesktop.DBus", "RequestName", (arg0, arg1, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn release_name(&self, arg0: &str) -> nonblock::MethodReply<u32> {
+        self.method_call("org.freedesktop.DBus", "ReleaseName", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn start_service_by_name(&self, arg0: &str, arg1: u32) -> nonblock::MethodReply<u32> {
+        self.method_call("org.freedesktop.DBus", "StartServiceByName", (arg0, arg1, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn update_activation_environment(&self, arg0: ::std::collections::HashMap<&str, &str>) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus", "UpdateActivationEnvironment", (arg0, ))
+    }
+
+    fn name_has_owner(&self, arg0: &str) -> nonblock::MethodReply<bool> {
+        self.method_call("org.freedesktop.DBus", "NameHasOwner", (arg0, ))
+            .and_then(|r: (bool, )| Ok(r.0, ))
+    }
+
+    fn list_names(&self) -> nonblock::MethodReply<Vec<String>> {
+        self.method_call("org.freedesktop.DBus", "ListNames", ())
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn list_activatable_names(&self) -> nonblock::MethodReply<Vec<String>> {
+        self.method_call("org.freedesktop.DBus", "ListActivatableNames", ())
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn add_match(&self, arg0: &str) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus", "AddMatch", (arg0, ))
+    }
+
+    fn remove_match(&self, arg0: &str) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus", "RemoveMatch", (arg0, ))
+    }
+
+    fn get_name_owner(&self, arg0: &str) -> nonblock::MethodReply<String> {
+        self.method_call("org.freedesktop.DBus", "GetNameOwner", (arg0, ))
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn list_queued_owners(&self, arg0: &str) -> nonblock::MethodReply<Vec<String>> {
+        self.method_call("org.freedesktop.DBus", "ListQueuedOwners", (arg0, ))
+            .and_then(|r: (Vec<String>, )| Ok(r.0, ))
+    }
+
+    fn get_connection_unix_user(&self, arg0: &str) -> nonblock::MethodReply<u32> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionUnixUser", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn get_connection_unix_process_id(&self, arg0: &str) -> nonblock::MethodReply<u32> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionUnixProcessID", (arg0, ))
+            .and_then(|r: (u32, )| Ok(r.0, ))
+    }
+
+    fn get_adt_audit_session_data(&self, arg0: &str) -> nonblock::MethodReply<Vec<u8>> {
+        self.method_call("org.freedesktop.DBus", "GetAdtAuditSessionData", (arg0, ))
+            .and_then(|r: (Vec<u8>, )| Ok(r.0, ))
+    }
+
+    fn get_connection_selinux_security_context(&self, arg0: &str) -> nonblock::MethodReply<Vec<u8>> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionSELinuxSecurityContext", (arg0, ))
+            .and_then(|r: (Vec<u8>, )| Ok(r.0, ))
+    }
+
+    fn reload_config(&self) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus", "ReloadConfig", ())
+    }
+
+    fn get_id(&self) -> nonblock::MethodReply<String> {
+        self.method_call("org.freedesktop.DBus", "GetId", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+
+    fn get_connection_credentials(&self, arg0: &str) -> nonblock::MethodReply<::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>> {
+        self.method_call("org.freedesktop.DBus", "GetConnectionCredentials", (arg0, ))
+            .and_then(|r: (::std::collections::HashMap<String, arg::Variant<Box<dyn arg::RefArg + 'static>>>, )| Ok(r.0, ))
+    }
+
+    fn features(&self) -> nonblock::MethodReply<Vec<String>> {
+        <Self as nonblock::stdintf::org_freedesktop_dbus::Properties>::get(&self, "org.freedesktop.DBus", "Features")
+    }
+
+    fn interfaces(&self) -> nonblock::MethodReply<Vec<String>> {
+        <Self as nonblock::stdintf::org_freedesktop_dbus::Properties>::get(&self, "org.freedesktop.DBus", "Interfaces")
+    }
+}
+
+#[derive(Debug)]
+pub struct DBusNameOwnerChanged {
+    pub arg0: String,
+    pub arg1: String,
+    pub arg2: String,
+}
+
+impl arg::AppendAll for DBusNameOwnerChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+        arg::RefArg::append(&self.arg1, i);
+        arg::RefArg::append(&self.arg2, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameOwnerChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameOwnerChanged {
+            arg0: i.read()?,
+            arg1: i.read()?,
+            arg2: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameOwnerChanged {
+    const NAME: &'static str = "NameOwnerChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
+
+#[derive(Debug)]
+pub struct DBusNameLost {
+    pub arg0: String,
+}
+
+impl arg::AppendAll for DBusNameLost {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameLost {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameLost {
+            arg0: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameLost {
+    const NAME: &'static str = "NameLost";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
+
+#[derive(Debug)]
+pub struct DBusNameAcquired {
+    pub arg0: String,
+}
+
+impl arg::AppendAll for DBusNameAcquired {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.arg0, i);
+    }
+}
+
+impl arg::ReadAll for DBusNameAcquired {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(DBusNameAcquired {
+            arg0: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for DBusNameAcquired {
+    const NAME: &'static str = "NameAcquired";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/dbus/src/nonblock/generated_org_freedesktop_standard_interfaces.rs
@@ -0,0 +1,153 @@
+// This code was autogenerated with `dbus-codegen-rust -m none -c nonblock -g -i org.freedesktop.DBus --dbuscrate crate --file ./data/standard_interfaces.xml -o ../dbus/src/nonblock/generated_org_freedesktop_standard_interfaces.rs`, see https://github.com/diwic/dbus-rs
+use crate as dbus;
+#[allow(unused_imports)]
+use crate::arg;
+use crate::nonblock;
+
+pub trait Properties {
+    fn get<R0: for<'b> arg::Get<'b> + 'static>(&self, interface_name: &str, property_name: &str) -> nonblock::MethodReply<R0>;
+    fn get_all(&self, interface_name: &str) -> nonblock::MethodReply<arg::PropMap>;
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> nonblock::MethodReply<()>;
+}
+
+impl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> Properties for nonblock::Proxy<'a, C> {
+
+    fn get<R0: for<'b> arg::Get<'b> + 'static>(&self, interface_name: &str, property_name: &str) -> nonblock::MethodReply<R0> {
+        self.method_call("org.freedesktop.DBus.Properties", "Get", (interface_name, property_name, ))
+            .and_then(|r: (arg::Variant<R0>, )| Ok((r.0).0, ))
+    }
+
+    fn get_all(&self, interface_name: &str) -> nonblock::MethodReply<arg::PropMap> {
+        self.method_call("org.freedesktop.DBus.Properties", "GetAll", (interface_name, ))
+            .and_then(|r: (arg::PropMap, )| Ok(r.0, ))
+    }
+
+    fn set<I2: arg::Arg + arg::Append>(&self, interface_name: &str, property_name: &str, value: I2) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus.Properties", "Set", (interface_name, property_name, arg::Variant(value), ))
+    }
+}
+
+#[derive(Debug)]
+pub struct PropertiesPropertiesChanged {
+    pub interface_name: String,
+    pub changed_properties: arg::PropMap,
+    pub invalidated_properties: Vec<String>,
+}
+
+impl arg::AppendAll for PropertiesPropertiesChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.interface_name, i);
+        arg::RefArg::append(&self.changed_properties, i);
+        arg::RefArg::append(&self.invalidated_properties, i);
+    }
+}
+
+impl arg::ReadAll for PropertiesPropertiesChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(PropertiesPropertiesChanged {
+            interface_name: i.read()?,
+            changed_properties: i.read()?,
+            invalidated_properties: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for PropertiesPropertiesChanged {
+    const NAME: &'static str = "PropertiesChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.Properties";
+}
+
+pub trait Introspectable {
+    fn introspect(&self) -> nonblock::MethodReply<String>;
+}
+
+impl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> Introspectable for nonblock::Proxy<'a, C> {
+
+    fn introspect(&self) -> nonblock::MethodReply<String> {
+        self.method_call("org.freedesktop.DBus.Introspectable", "Introspect", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+}
+
+pub trait Peer {
+    fn ping(&self) -> nonblock::MethodReply<()>;
+    fn get_machine_id(&self) -> nonblock::MethodReply<String>;
+}
+
+impl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> Peer for nonblock::Proxy<'a, C> {
+
+    fn ping(&self) -> nonblock::MethodReply<()> {
+        self.method_call("org.freedesktop.DBus.Peer", "Ping", ())
+    }
+
+    fn get_machine_id(&self) -> nonblock::MethodReply<String> {
+        self.method_call("org.freedesktop.DBus.Peer", "GetMachineId", ())
+            .and_then(|r: (String, )| Ok(r.0, ))
+    }
+}
+
+pub trait ObjectManager {
+    fn get_managed_objects(&self) -> nonblock::MethodReply<::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>>;
+}
+
+impl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> ObjectManager for nonblock::Proxy<'a, C> {
+
+    fn get_managed_objects(&self) -> nonblock::MethodReply<::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>> {
+        self.method_call("org.freedesktop.DBus.ObjectManager", "GetManagedObjects", ())
+            .and_then(|r: (::std::collections::HashMap<dbus::Path<'static>, ::std::collections::HashMap<String, arg::PropMap>>, )| Ok(r.0, ))
+    }
+}
+
+#[derive(Debug)]
+pub struct ObjectManagerInterfacesAdded {
+    pub object: dbus::Path<'static>,
+    pub interfaces: ::std::collections::HashMap<String, arg::PropMap>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesAdded {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesAdded {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesAdded {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for ObjectManagerInterfacesAdded {
+    const NAME: &'static str = "InterfacesAdded";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
+
+#[derive(Debug)]
+pub struct ObjectManagerInterfacesRemoved {
+    pub object: dbus::Path<'static>,
+    pub interfaces: Vec<String>,
+}
+
+impl arg::AppendAll for ObjectManagerInterfacesRemoved {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.object, i);
+        arg::RefArg::append(&self.interfaces, i);
+    }
+}
+
+impl arg::ReadAll for ObjectManagerInterfacesRemoved {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(ObjectManagerInterfacesRemoved {
+            object: i.read()?,
+            interfaces: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for ObjectManagerInterfacesRemoved {
+    const NAME: &'static str = "InterfacesRemoved";
+    const INTERFACE: &'static str = "org.freedesktop.DBus.ObjectManager";
+}
--- a/third_party/rust/dbus/src/prop.rs
+++ b/third_party/rust/dbus/src/prop.rs
@@ -23,52 +23,52 @@ impl<'a> Props<'a> {
         }
     }
 
     /// Get a single property's value.
     pub fn get(&self, propname: &str) -> Result<MessageItem, Error> {
         let mut m = Message::method_call(&self.name, &self.path,
             &"org.freedesktop.DBus.Properties".into(), &"Get".into());
         m.append_items(&[self.interface.to_string().into(), propname.to_string().into()]);
-        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
-        let reply = try!(r.as_result()).get_items();
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        let reply = r.as_result()?.get_items();
         if reply.len() == 1 {
             if let &MessageItem::Variant(ref v) = &reply[0] {
                 return Ok((**v).clone())
             }
        }
        let f = format!("Invalid reply for property get {}: '{:?}'", propname, reply);
        return Err(Error::new_custom("InvalidReply", &f));
     }
 
     /// Set a single property's value.
     pub fn set(&self, propname: &str, value: MessageItem) -> Result<(), Error> {
         let mut m = Message::method_call(&self.name, &self.path,
             &"org.freedesktop.DBus.Properties".into(), &"Set".into());
         m.append_items(&[self.interface.to_string().into(), propname.to_string().into(), Box::new(value).into()]);
-        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
-        try!(r.as_result());
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        r.as_result()?;
         Ok(())
     }
 
     /// Get a map of all the properties' names and their values.
     pub fn get_all(&self) -> Result<BTreeMap<String, MessageItem>, Error> {
         let mut m = Message::method_call(&self.name, &self.path,
             &"org.freedesktop.DBus.Properties".into(), &"GetAll".into());
         m.append_items(&[self.interface.to_string().into()]);
-        let mut r = try!(self.conn.send_with_reply_and_block(m, self.timeout_ms));
-        let reply = try!(r.as_result()).get_items();
+        let mut r = self.conn.send_with_reply_and_block(m, self.timeout_ms)?;
+        let reply = r.as_result()?.get_items();
 
         (|| {
             if reply.len() != 1 { return Err(()) };
             let mut t = BTreeMap::new();
-            let a: &[MessageItem] = try!(reply[0].inner());
+            let a: &[MessageItem] = reply[0].inner()?;
             for p in a.iter() {
-                let (k, v) = try!(p.inner());
-                let (k, v): (&String, &MessageItem) = (try!(k.inner()), try!(v.inner()));
+                let (k, v) = p.inner()?;
+                let (k, v): (&String, &MessageItem) = (k.inner()?, v.inner()?);
                 t.insert(k.clone(), v.clone());
             }
             Ok(t)
         })().map_err(|_| {
             let f = format!("Invalid reply for property GetAll: '{:?}'", reply);
             Error::new_custom("InvalidReply", &f)
         })
     }
@@ -83,36 +83,36 @@ pub struct PropHandler<'a> {
 impl<'a> PropHandler<'a> {
     /// Create a new PropHandler from a Props.
     pub fn new(p: Props) -> PropHandler {
         PropHandler { p: p, map: BTreeMap::new() }
     }
 
     /// Get a map of all the properties' names and their values.
     pub fn get_all(&mut self) -> Result<(), Error> {
-        self.map = try!(self.p.get_all());
+        self.map = self.p.get_all()?;
         Ok(())
     }
 
     /// Get a mutable reference to the PropHandler's fetched properties.
     pub fn map_mut(&mut self) -> &mut BTreeMap<String, MessageItem> { &mut self.map }
 
     /// Get a reference to the PropHandler's fetched properties.
     pub fn map(&self) -> &BTreeMap<String, MessageItem> { &self.map }
 
     /// Get a single property's value.
     pub fn get(&mut self, propname: &str) -> Result<&MessageItem, Error> {
-        let v = try!(self.p.get(propname));
+        let v = self.p.get(propname)?;
         self.map.insert(propname.to_string(), v);
         Ok(self.map.get(propname).unwrap())
     }
 
     /// Set a single property's value.
     pub fn set(&mut self, propname: &str, value: MessageItem) -> Result<(), Error> {
-        try!(self.p.set(propname, value.clone()));
+        self.p.set(propname, value.clone())?;
         self.map.insert(propname.to_string(), value);
         Ok(())
     }
 }
 
 
 /* Unfortunately org.freedesktop.DBus has no properties we can use for testing, but PolicyKit should be around on most distros. */
 #[test]
--- a/third_party/rust/dbus/src/strings.rs
+++ b/third_party/rust/dbus/src/strings.rs
@@ -1,19 +1,24 @@
-// CString wrappers.
+//! This module contains strings with a specific format, such as a valid
+//! Interface name, a valid Error name, etc.
+//!
+//! (The internal representation of these strings are `Cow<str>`, but with a \0 byte
+//! at the end to use it libdbus calls without extra allocations. This is usually nothing
+//! you have to worry about.)
 
 use std::{str, fmt, ops, default, hash};
 use std::ffi::{CStr, CString};
 use std::borrow::{Borrow, Cow};
 use std::os::raw::c_char;
 
 #[cfg(not(feature = "no-string-validation"))]
-use Error;
+use crate::Error;
 #[cfg(not(feature = "no-string-validation"))]
-use ffi;
+use crate::ffi;
 
 macro_rules! cstring_wrapper {
     ($t: ident, $s: ident) => {
 
 impl<'m> $t<'m> {
     #[cfg(feature = "no-string-validation")]
     fn check_valid(_: *const c_char) -> Result<(), String> { Ok(()) }
 
@@ -23,51 +28,69 @@ impl<'m> $t<'m> {
         let b = unsafe { ffi::$s(c, e.get_mut()) };
         if b != 0 { Ok(()) } else { Err(e.message().unwrap().into()) }
     }
 
     /// Creates a new instance of this struct.
     ///
     /// Note: If the no-string-validation feature is activated, this string
     /// will not be checked for conformance with the D-Bus specification.
-    pub fn new<S: Into<Vec<u8>>>(s: S) -> Result<$t<'m>, String> {
-        let c = try!(CString::new(s).map_err(|e| e.to_string()));
-        $t::check_valid(c.as_ptr()).map(|_| $t(Cow::Owned(c)))
+    pub fn new<S: Into<String>>(s: S) -> Result<$t<'m>, String> {
+        let mut s = s.into();
+        s.push_str("\0");
+        unsafe { $t::check_valid(CStr::from_bytes_with_nul_unchecked(s.as_bytes()).as_ptr() as *const c_char)?; }
+        Ok(Self(Cow::Owned(s)))
     }
 
     /// Creates a new instance of this struct. If you end it with \0,
     /// it can borrow the slice without extra allocation.
     ///
     /// Note: If the no-string-validation feature is activated, this string
     /// will not be checked for conformance with the D-Bus specification.
-    pub fn from_slice(s: &'m [u8]) -> Result<$t<'m>, String> {
-        if s.len() == 0 || s[s.len()-1] != 0 { return $t::new(s) };
+    pub fn from_slice(s: &'m str) -> Result<$t<'m>, String> {
+        let ss = s.as_bytes();
+        if ss.len() == 0 || ss[ss.len()-1] != 0 { return $t::new(s) };
         $t::check_valid(s.as_ptr() as *const c_char).map(|_| {
-            let c = unsafe { CStr::from_ptr(s.as_ptr() as *const c_char) };
-            $t(Cow::Borrowed(c)) 
+            unsafe { Self::from_slice_unchecked(s) }
         })
     }
 
     /// This function creates a new instance of this struct, without checking.
     /// It's up to you to guarantee that s ends with a \0 and is valid.
-    pub unsafe fn from_slice_unchecked(s: &'m [u8]) -> $t<'m> {
-        debug_assert!(s[s.len()-1] == 0);
-        $t(Cow::Borrowed(CStr::from_ptr(s.as_ptr() as *const c_char)))
+    pub unsafe fn from_slice_unchecked(s: &'m str) -> $t<'m> {
+        let ss = s.as_bytes();
+        debug_assert!(ss[ss.len()-1] == 0);
+        $t(Cow::Borrowed(s))
     }
 
     /// View this struct as a CStr.
-    pub fn as_cstr(&self) -> &CStr { &self.0 }
+    ///
+    /// Note: As of dbus 0.9, this is made private to be able to make it easier for a potential
+    /// native implementation using "str" instead of "cstr".
+    pub (crate) fn as_cstr(&self) -> &CStr {
+        unsafe {
+            CStr::from_bytes_with_nul_unchecked(self.0.as_bytes())
+        }
+    }
+
+    #[allow(dead_code)]
+    pub (crate) fn as_ptr(&self) -> *const c_char { self.as_cstr().as_ptr() }
 
     /// Makes sure this string does not contain borrows.
     pub fn into_static(self) -> $t<'static> {
         $t(Cow::Owned(self.0.into_owned()))
     }
 
     /// Converts this struct to a CString.
-    pub fn into_cstring(self) -> CString { self.0.into_owned() }
+    pub fn into_cstring(self) -> CString {
+        // Change this when https://github.com/rust-lang/rust/issues/73179 is on stable.
+        let mut x: Vec<u8> = self.0.into_owned().into();
+        x.pop();
+        CString::new(x).unwrap()
+    }
 }
 
 /*
 /// #Panics
 ///
 /// If given string is not valid.
 /// impl<S: Into<Vec<u8>>> From<S> for $t { fn from(s: S) -> $t { $t::new(s).unwrap() } }
 */
@@ -75,130 +98,141 @@ impl<'m> $t<'m> {
 /// #Panics
 ///
 /// If given string is not valid.
 impl<'m> From<String> for $t<'m> { fn from(s: String) -> $t<'m> { $t::new(s).unwrap() } }
 
 /// #Panics
 ///
 /// If given string is not valid.
-impl<'m> From<&'m String> for $t<'m> { fn from(s: &'m String) -> $t<'m> { $t::from_slice(s.as_bytes()).unwrap() } }
+impl<'m> From<&'m String> for $t<'m> { fn from(s: &'m String) -> $t<'m> { $t::from_slice(s).unwrap() } }
 
 /// #Panics
 ///
 /// If given string is not valid.
-impl<'m> From<&'m str> for $t<'m> { fn from(s: &'m str) -> $t<'m> { $t::from_slice(s.as_bytes()).unwrap() } }
+impl<'m> From<&'m str> for $t<'m> { fn from(s: &'m str) -> $t<'m> { $t::from_slice(s).unwrap() } }
 
-impl<'m> From<$t<'m>> for CString { fn from(s: $t<'m>) -> CString { s.0.into_owned() } }
+/// #Panics
+///
+/// If given string is not valid.
+impl<'m> From<&'m CStr> for $t<'m> {
+    fn from(s: &'m CStr) -> $t<'m> {
+        let x = str::from_utf8(s.to_bytes_with_nul()).unwrap();
+        $t::from_slice(x).unwrap()
+    }
+}
+
+impl<'m> From<$t<'m>> for CString { fn from(s: $t<'m>) -> CString { s.into_cstring() } }
 
 
 /// #Panics
 ///
 /// If given string is not valid.
 impl<'m> From<Cow<'m, str>> for $t<'m> {
-    fn from(s: Cow<'m, str>) -> $t<'m> { 
+    fn from(s: Cow<'m, str>) -> $t<'m> {
         match s {
             Cow::Borrowed(z) => z.into(),
             Cow::Owned(z) => z.into(),
         }
     }
 }
 
 impl<'inner, 'm: 'inner> From<&'m $t<'inner>> for $t<'m> {
     fn from(borrow: &'m $t<'inner>) -> $t<'m> {
         $t(Cow::Borrowed(borrow.0.borrow()))
     }
 }
 
 impl<'m> ops::Deref for $t<'m> {
     type Target = str;
-    fn deref(&self) -> &str { str::from_utf8(self.0.to_bytes()).unwrap() }
+    fn deref(&self) -> &str { self.0.split_at(self.0.len()-1).0 }
 }
 
 impl<'m> fmt::Display for $t<'m> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        let s: &str = &self;
-        (&s as &fmt::Display).fmt(f)
+        <str as fmt::Display>::fmt(&*self, f)
     }
 }
 
+/*
+As of dbus 0.9, this has been removed to prepare for a potential native implementation.
 impl<'m> AsRef<CStr> for $t<'m> {
     fn as_ref(&self) -> &CStr { &self.0 }
 }
+*/
 
 impl<'m> hash::Hash for $t<'m> {
     fn hash<H: hash::Hasher>(&self, state: &mut H) {
         self.0.hash(state);
     }
 }
 
 }}
 
 /// A wrapper around a string that is guaranteed to be
-/// a valid (single) D-Bus type signature. Supersedes TypeSig.
+/// a valid (single) D-Bus type signature.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct Signature<'a>(Cow<'a, CStr>);
+pub struct Signature<'a>(Cow<'a, str>);
 
 cstring_wrapper!(Signature, dbus_signature_validate_single);
 
 impl Signature<'static> {
-    /// Makes a D-Bus signature that corresponds to A. 
+    /// Makes a D-Bus signature that corresponds to A.
     pub fn make<A: super::arg::Arg>() -> Signature<'static> { A::signature() }
 }
 
 /// A wrapper around a string that is guaranteed to be
 /// a valid D-Bus object path.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct Path<'a>(Cow<'a, CStr>);
+pub struct Path<'a>(Cow<'a, str>);
 
 cstring_wrapper!(Path, dbus_validate_path);
 
 // This is needed so one can make arrays of paths easily
 impl<'a> default::Default for Path<'a> {
-    fn default() -> Path<'a> { Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"/\0".as_ptr() as *const c_char)})) }
+    fn default() -> Path<'a> { Path(Cow::Borrowed("/\0")) }
 }
 
 /// A wrapper around a string that is guaranteed to be
 /// a valid D-Bus member, i e, a signal or method name.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct Member<'a>(Cow<'a, CStr>);
+pub struct Member<'a>(Cow<'a, str>);
 
 cstring_wrapper!(Member, dbus_validate_member);
 
 /// A wrapper around a string that is guaranteed to be
 /// a valid D-Bus interface name.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct Interface<'a>(Cow<'a, CStr>);
+pub struct Interface<'a>(Cow<'a, str>);
 
 cstring_wrapper!(Interface, dbus_validate_interface);
 
 /// A wrapper around a string that is guaranteed to be
 /// a valid D-Bus bus name.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct BusName<'a>(Cow<'a, CStr>);
+pub struct BusName<'a>(Cow<'a, str>);
 
 cstring_wrapper!(BusName, dbus_validate_bus_name);
 
 /// A wrapper around a string that is guaranteed to be
-/// a valid D-Bus bus name.
+/// a valid D-Bus error name.
 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
-pub struct ErrorName<'a>(Cow<'a, CStr>);
+pub struct ErrorName<'a>(Cow<'a, str>);
 
 cstring_wrapper!(ErrorName, dbus_validate_error_name);
 
 #[test]
 fn some_path() {
-    use std::os::raw::c_char;
     let p1: Path = "/valid".into();
     let p2 = Path::new("##invalid##");
-    assert_eq!(p1, Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"/valid\0".as_ptr() as *const c_char) })));
+    assert_eq!(p1, Path(Cow::Borrowed("/valid\0")));
     #[cfg(not(feature = "no-string-validation"))]
     assert_eq!(p2, Err("Object path was not valid: '##invalid##'".into()));
     #[cfg(feature = "no-string-validation")]
-    assert_eq!(p2, Ok(Path(Cow::Borrowed(unsafe { CStr::from_ptr(b"##invalid##\0".as_ptr() as *const c_char) }))));
+    assert_eq!(p2, Ok(Path(Cow::Borrowed("##invalid##\0"))));
 }
 
 #[test]
 fn reborrow_path() {
     let p1 = Path::from("/valid");
     let p2 = p1.clone();
     {
         let p2_borrow: &Path = &p2;
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.toml":"023c46a92caf2fc7a31fba3e7d4428a287e1fbdef822ed7e9a8f91284a30b387","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"322fadd63e558e5a10caf980cbedf83ac1546ba40fd992f54492e21ce54205af","rust-toolchain":"58bea07cb6d97f9cfcd5c8f98b1feca0fb81cce5b0bf29a8e70ed2641956e9a6","src/lib.rs":"c7dca30b651c91590ff46370bdaa10214062b9456395fb4bd549dedbf457c695","src/tcplistener.rs":"c6e2db06d4265fa0956851e1c965336d60c53ab21573729aae76ecfe0ccc84c3","src/tcpstream.rs":"38a17de54213faf9de217f6146ff86ee75b67d4404a532b1419903269200936b"},"package":"62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/Cargo.toml
@@ -0,0 +1,44 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "hermit-abi"
+version = "0.1.19"
+authors = ["Stefan Lankes"]
+description = "hermit-abi is small interface to call functions from the unikernel RustyHermit.\nIt is used to build the target `x86_64-unknown-hermit`.\n"
+documentation = "https://hermitcore.github.io/rusty-hermit/hermit_abi"
+readme = "README.md"
+keywords = ["unikernel", "libos"]
+categories = ["os"]
+license = "MIT/Apache-2.0"
+repository = "https://github.com/hermitcore/libhermit-rs"
+[package.metadata.docs.rs]
+default-target = "x86_64-unknown-hermit"
+features = ["docs"]
+[dependencies.compiler_builtins]
+version = "0.1"
+optional = true
+
+[dependencies.core]
+version = "1.0.0"
+optional = true
+package = "rustc-std-workspace-core"
+
+[dependencies.libc]
+version = "0.2.51"
+default-features = false
+
+[features]
+default = []
+docs = []
+rustc-dep-of-std = ["core", "compiler_builtins/rustc-dep-of-std", "libc/rustc-dep-of-std"]
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/LICENSE-APACHE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+	http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/README.md
@@ -0,0 +1,22 @@
+# hermit-abi
+
+[![Crates.io](https://img.shields.io/crates/v/hermit-abi.svg)](https://crates.io/crates/hermit-abi)
+[![Documentation](https://img.shields.io/badge/docs-latest-blue.svg)](https://hermitcore.github.io/rusty-hermit/hermit_abi/)
+[![License](https://img.shields.io/crates/l/hermit-abi.svg)](https://img.shields.io/crates/l/hermit-abi.svg)
+
+This is small interface to call functions from the unikernel [RustyHermit](https://github.com/hermitcore/libhermit-rs).
+
+Please read the README of [RustyHermit](https://github.com/hermitcore/libhermit-rs) for more information.
+
+## License
+
+Licensed under either of
+
+* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
+* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
+
+at your option.
+
+## Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/rust-toolchain
@@ -0,0 +1,1 @@
+nightly
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/src/lib.rs
@@ -0,0 +1,490 @@
+//! `hermit-abi` is small interface to call functions from the unikernel
+//! [RustyHermit](https://github.com/hermitcore/libhermit-rs).
+
+#![no_std]
+#![allow(clippy::missing_safety_doc)]
+#![allow(clippy::result_unit_err)]
+
+extern crate libc;
+
+pub mod tcplistener;
+pub mod tcpstream;
+
+use libc::c_void;
+
+// sysmbols, which are part of the library operating system
+
+extern "Rust" {
+	fn sys_secure_rand64() -> Option<u64>;
+	fn sys_secure_rand32() -> Option<u32>;
+}
+
+extern "C" {
+	fn sys_rand() -> u32;
+	fn sys_srand(seed: u32);
+	fn sys_get_processor_count() -> usize;
+	fn sys_malloc(size: usize, align: usize) -> *mut u8;
+	fn sys_realloc(ptr: *mut u8, size: usize, align: usize, new_size: usize) -> *mut u8;
+	fn sys_free(ptr: *mut u8, size: usize, align: usize);
+	fn sys_init_queue(ptr: usize) -> i32;
+	fn sys_notify(id: usize, count: i32) -> i32;
+	fn sys_add_queue(id: usize, timeout_ns: i64) -> i32;
+	fn sys_wait(id: usize) -> i32;
+	fn sys_destroy_queue(id: usize) -> i32;
+	fn sys_read(fd: i32, buf: *mut u8, len: usize) -> isize;
+	fn sys_write(fd: i32, buf: *const u8, len: usize) -> isize;
+	fn sys_close(fd: i32) -> i32;
+	fn sys_sem_init(sem: *mut *const c_void, value: u32) -> i32;
+	fn sys_sem_destroy(sem: *const c_void) -> i32;
+	fn sys_sem_post(sem: *const c_void) -> i32;
+	fn sys_sem_trywait(sem: *const c_void) -> i32;
+	fn sys_sem_timedwait(sem: *const c_void, ms: u32) -> i32;
+	fn sys_recmutex_init(recmutex: *mut *const c_void) -> i32;
+	fn sys_recmutex_destroy(recmutex: *const c_void) -> i32;
+	fn sys_recmutex_lock(recmutex: *const c_void) -> i32;
+	fn sys_recmutex_unlock(recmutex: *const c_void) -> i32;
+	fn sys_getpid() -> u32;
+	fn sys_exit(arg: i32) -> !;
+	fn sys_abort() -> !;
+	fn sys_usleep(usecs: u64);
+	fn sys_spawn(
+		id: *mut Tid,
+		func: extern "C" fn(usize),
+		arg: usize,
+		prio: u8,
+		core_id: isize,
+	) -> i32;
+	fn sys_spawn2(
+		func: extern "C" fn(usize),
+		arg: usize,
+		prio: u8,
+		stack_size: usize,
+		core_id: isize,
+	) -> Tid;
+	fn sys_join(id: Tid) -> i32;
+	fn sys_yield();
+	fn sys_clock_gettime(clock_id: u64, tp: *mut timespec) -> i32;
+	fn sys_open(name: *const i8, flags: i32, mode: i32) -> i32;
+	fn sys_unlink(name: *const i8) -> i32;
+	fn sys_network_init() -> i32;
+	fn sys_block_current_task();
+	fn sys_wakeup_task(tid: Tid);
+	fn sys_get_priority() -> u8;
+}
+
+/// A thread handle type
+pub type Tid = u32;
+
+/// Maximum number of priorities
+pub const NO_PRIORITIES: usize = 31;
+
+/// Priority of a thread
+#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
+pub struct Priority(u8);
+
+impl Priority {
+	pub const fn into(self) -> u8 {
+		self.0
+	}
+
+	pub const fn from(x: u8) -> Self {
+		Priority(x)
+	}
+}
+
+pub const HIGH_PRIO: Priority = Priority::from(3);
+pub const NORMAL_PRIO: Priority = Priority::from(2);
+pub const LOW_PRIO: Priority = Priority::from(1);
+
+/// A handle, identifying a socket
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
+pub struct Handle(usize);
+
+pub const NSEC_PER_SEC: u64 = 1_000_000_000;
+pub const CLOCK_REALTIME: u64 = 1;
+pub const CLOCK_MONOTONIC: u64 = 4;
+pub const STDIN_FILENO: libc::c_int = 0;
+pub const STDOUT_FILENO: libc::c_int = 1;
+pub const STDERR_FILENO: libc::c_int = 2;
+pub const O_RDONLY: i32 = 0o0;
+pub const O_WRONLY: i32 = 0o1;
+pub const O_RDWR: i32 = 0o2;
+pub const O_CREAT: i32 = 0o100;
+pub const O_EXCL: i32 = 0o200;
+pub const O_TRUNC: i32 = 0o1000;
+pub const O_APPEND: i32 = 0o2000;
+
+/// returns true if file descriptor `fd` is a tty
+pub fn isatty(_fd: libc::c_int) -> bool {
+	false
+}
+
+/// intialize the network stack
+pub fn network_init() -> i32 {
+	unsafe { sys_network_init() }
+}
+
+/// `timespec` is used by `clock_gettime` to retrieve the
+/// current time
+#[derive(Copy, Clone, Debug)]
+#[repr(C)]
+pub struct timespec {
+	/// seconds
+	pub tv_sec: i64,
+	/// nanoseconds
+	pub tv_nsec: i64,
+}
+
+/// Internet protocol version.
+#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
+pub enum Version {
+	Unspecified,
+	Ipv4,
+	Ipv6,
+}
+
+/// A four-octet IPv4 address.
+#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
+pub struct Ipv4Address(pub [u8; 4]);
+
+/// A sixteen-octet IPv6 address.
+#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
+pub struct Ipv6Address(pub [u8; 16]);
+
+/// An internetworking address.
+#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
+pub enum IpAddress {
+	/// An unspecified address.
+	/// May be used as a placeholder for storage where the address is not assigned yet.
+	Unspecified,
+	/// An IPv4 address.
+	Ipv4(Ipv4Address),
+	/// An IPv6 address.
+	Ipv6(Ipv6Address),
+}
+
+/// determines the number of activated processors
+#[inline(always)]
+pub unsafe fn get_processor_count() -> usize {
+	sys_get_processor_count()
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn malloc(size: usize, align: usize) -> *mut u8 {
+	sys_malloc(size, align)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn realloc(ptr: *mut u8, size: usize, align: usize, new_size: usize) -> *mut u8 {
+	sys_realloc(ptr, size, align, new_size)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn free(ptr: *mut u8, size: usize, align: usize) {
+	sys_free(ptr, size, align)
+}
+
+#[inline(always)]
+pub unsafe fn notify(id: usize, count: i32) -> i32 {
+	sys_notify(id, count)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn add_queue(id: usize, timeout_ns: i64) -> i32 {
+	sys_add_queue(id, timeout_ns)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn wait(id: usize) -> i32 {
+	sys_wait(id)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn init_queue(id: usize) -> i32 {
+	sys_init_queue(id)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn destroy_queue(id: usize) -> i32 {
+	sys_destroy_queue(id)
+}
+
+/// read from a file descriptor
+///
+/// read() attempts to read `len` bytes of data from the object
+/// referenced by the descriptor `fd` into the buffer pointed
+/// to by `buf`.
+#[inline(always)]
+pub unsafe fn read(fd: i32, buf: *mut u8, len: usize) -> isize {
+	sys_read(fd, buf, len)
+}
+
+/// write to a file descriptor
+///
+/// write() attempts to write `len` of data to the object
+/// referenced by the descriptor `fd` from the
+/// buffer pointed to by `buf`.
+#[inline(always)]
+pub unsafe fn write(fd: i32, buf: *const u8, len: usize) -> isize {
+	sys_write(fd, buf, len)
+}
+
+/// close a file descriptor
+///
+/// The close() call deletes a file descriptor `fd` from the object
+/// reference table.
+#[inline(always)]
+pub unsafe fn close(fd: i32) -> i32 {
+	sys_close(fd)
+}
+
+/// sem_init() initializes the unnamed semaphore at the address
+/// pointed to by `sem`.  The `value` argument specifies the
+/// initial value for the semaphore.
+#[inline(always)]
+pub unsafe fn sem_init(sem: *mut *const c_void, value: u32) -> i32 {
+	sys_sem_init(sem, value)
+}
+
+/// sem_destroy() frees the unnamed semaphore at the address
+/// pointed to by `sem`.
+#[inline(always)]
+pub unsafe fn sem_destroy(sem: *const c_void) -> i32 {
+	sys_sem_destroy(sem)
+}
+
+/// sem_post() increments the semaphore pointed to by `sem`.
+/// If the semaphore's value consequently becomes greater
+/// than zero, then another thread blocked in a sem_wait call
+/// will be woken up and proceed to lock the semaphore.
+#[inline(always)]
+pub unsafe fn sem_post(sem: *const c_void) -> i32 {
+	sys_sem_post(sem)
+}
+
+/// try to decrement a semaphore
+///
+/// sem_trywait() is the same as sem_timedwait(), except that
+/// if the  decrement cannot be immediately performed, then  call
+/// returns a negative value instead of blocking.
+#[inline(always)]
+pub unsafe fn sem_trywait(sem: *const c_void) -> i32 {
+	sys_sem_trywait(sem)
+}
+
+/// decrement a semaphore
+///
+/// sem_timedwait() decrements the semaphore pointed to by `sem`.
+/// If the semaphore's value is greater than zero, then the
+/// the function returns immediately. If the semaphore currently
+/// has the value zero, then the call blocks until either
+/// it becomes possible to perform the decrement of the time limit
+/// to wait for the semaphore is expired. A time limit `ms` of
+/// means infinity waiting time.
+#[inline(always)]
+pub unsafe fn sem_timedwait(sem: *const c_void, ms: u32) -> i32 {
+	sys_sem_timedwait(sem, ms)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn recmutex_init(recmutex: *mut *const c_void) -> i32 {
+	sys_recmutex_init(recmutex)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn recmutex_destroy(recmutex: *const c_void) -> i32 {
+	sys_recmutex_destroy(recmutex)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn recmutex_lock(recmutex: *const c_void) -> i32 {
+	sys_recmutex_lock(recmutex)
+}
+
+#[doc(hidden)]
+#[inline(always)]
+pub unsafe fn recmutex_unlock(recmutex: *const c_void) -> i32 {
+	sys_recmutex_unlock(recmutex)
+}
+
+/// Determines the id of the current thread
+#[inline(always)]
+pub unsafe fn getpid() -> u32 {
+	sys_getpid()
+}
+
+/// cause normal termination and return `arg`
+/// to the host system
+#[inline(always)]
+pub unsafe fn exit(arg: i32) -> ! {
+	sys_exit(arg)
+}
+
+/// cause abnormal termination
+#[inline(always)]
+pub unsafe fn abort() -> ! {
+	sys_abort()
+}
+
+/// suspend execution for microsecond intervals
+///
+/// The usleep() function suspends execution of the calling
+/// thread for (at least) `usecs` microseconds.
+#[inline(always)]
+pub unsafe fn usleep(usecs: u64) {
+	sys_usleep(usecs)
+}
+
+/// spawn a new thread
+///
+/// spawn() starts a new thread. The new thread starts execution
+/// by invoking `func(usize)`; `arg` is passed as the argument
+/// to `func`. `prio` defines the priority of the new thread,
+/// which can be between `LOW_PRIO` and `HIGH_PRIO`.
+/// `core_id` defines the core, where the thread is located.
+/// A negative value give the operating system the possibility
+/// to select the core by its own.
+#[inline(always)]
+pub unsafe fn spawn(
+	id: *mut Tid,
+	func: extern "C" fn(usize),
+	arg: usize,
+	prio: u8,
+	core_id: isize,
+) -> i32 {
+	sys_spawn(id, func, arg, prio, core_id)
+}
+
+/// spawn a new thread with user-specified stack size
+///
+/// spawn2() starts a new thread. The new thread starts execution
+/// by invoking `func(usize)`; `arg` is passed as the argument
+/// to `func`. `prio` defines the priority of the new thread,
+/// which can be between `LOW_PRIO` and `HIGH_PRIO`.
+/// `core_id` defines the core, where the thread is located.
+/// A negative value give the operating system the possibility
+/// to select the core by its own.
+/// In contrast to spawn(), spawn2() is able to define the
+/// stack size.
+#[inline(always)]
+pub unsafe fn spawn2(
+	func: extern "C" fn(usize),
+	arg: usize,
+	prio: u8,
+	stack_size: usize,
+	core_id: isize,
+) -> Tid {
+	sys_spawn2(func, arg, prio, stack_size, core_id)
+}
+
+/// join with a terminated thread
+///
+/// The join() function waits for the thread specified by `id`
+/// to terminate.
+#[inline(always)]
+pub unsafe fn join(id: Tid) -> i32 {
+	sys_join(id)
+}
+
+/// yield the processor
+///
+/// causes the calling thread to relinquish the CPU. The thread
+/// is moved to the end of the queue for its static priority.
+#[inline(always)]
+pub unsafe fn yield_now() {
+	sys_yield()
+}
+
+/// get current time
+///
+/// The clock_gettime() functions allow the calling thread
+/// to retrieve the value used by a clock which is specified
+/// by `clock_id`.
+///
+/// `CLOCK_REALTIME`: the system's real time clock,
+/// expressed as the amount of time since the Epoch.
+///
+/// `CLOCK_MONOTONIC`: clock that increments monotonically,
+/// tracking the time since an arbitrary point
+#[inline(always)]
+pub unsafe fn clock_gettime(clock_id: u64, tp: *mut timespec) -> i32 {
+	sys_clock_gettime(clock_id, tp)
+}
+
+/// open and possibly create a file
+///
+/// The open() system call opens the file specified by `name`.
+/// If the specified file does not exist, it may optionally
+/// be created by open().
+#[inline(always)]
+pub unsafe fn open(name: *const i8, flags: i32, mode: i32) -> i32 {
+	sys_open(name, flags, mode)
+}
+
+/// delete the file it refers to `name`
+#[inline(always)]
+pub unsafe fn unlink(name: *const i8) -> i32 {
+	sys_unlink(name)
+}
+
+/// The largest number `rand` will return
+pub const RAND_MAX: u64 = 2_147_483_647;
+
+/// The function computes a sequence of pseudo-random integers
+/// in the range of 0 to RAND_MAX
+#[inline(always)]
+pub unsafe fn rand() -> u32 {
+	sys_rand()
+}
+
+/// The function sets its argument as the seed for a new sequence
+/// of pseudo-random numbers to be returned by `rand`
+#[inline(always)]
+pub unsafe fn srand(seed: u32) {
+	sys_srand(seed);
+}
+
+/// Create a cryptographicly secure 32bit random number with the support of
+/// the underlying hardware. If the required hardware isn't available,
+/// the function returns `None`.
+#[inline(always)]
+pub unsafe fn secure_rand32() -> Option<u32> {
+	sys_secure_rand32()
+}
+
+/// Create a cryptographicly secure 64bit random number with the support of
+/// the underlying hardware. If the required hardware isn't available,
+/// the function returns `None`.
+#[inline(always)]
+pub unsafe fn secure_rand64() -> Option<u64> {
+	sys_secure_rand64()
+}
+
+/// Add current task to the queue of blocked tasl. After calling `block_current_task`,
+/// call `yield_now` to switch to another task.
+#[inline(always)]
+pub unsafe fn block_current_task() {
+	sys_block_current_task();
+}
+
+/// Wakeup task with the thread id `tid`
+#[inline(always)]
+pub unsafe fn wakeup_task(tid: Tid) {
+	sys_wakeup_task(tid);
+}
+
+/// Determine the priority of the current thread
+#[inline(always)]
+pub unsafe fn get_priority() -> Priority {
+	Priority::from(sys_get_priority())
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/src/tcplistener.rs
@@ -0,0 +1,13 @@
+//! `tcplistener` provide an interface to establish tcp socket server.
+
+use crate::{Handle, IpAddress};
+
+extern "Rust" {
+	fn sys_tcp_listener_accept(port: u16) -> Result<(Handle, IpAddress, u16), ()>;
+}
+
+/// Wait for connection at specified address.
+#[inline(always)]
+pub fn accept(port: u16) -> Result<(Handle, IpAddress, u16), ()> {
+	unsafe { sys_tcp_listener_accept(port) }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/hermit-abi-0.1.19/src/tcpstream.rs
@@ -0,0 +1,109 @@
+//! `tcpstream` provide an interface to establish tcp socket client.
+
+use crate::{Handle, IpAddress};
+
+extern "Rust" {
+	fn sys_tcp_stream_connect(ip: &[u8], port: u16, timeout: Option<u64>) -> Result<Handle, ()>;
+	fn sys_tcp_stream_close(handle: Handle) -> Result<(), ()>;
+	fn sys_tcp_stream_read(handle: Handle, buffer: &mut [u8]) -> Result<usize, ()>;
+	fn sys_tcp_stream_write(handle: Handle, buffer: &[u8]) -> Result<usize, ()>;
+	fn sys_tcp_stream_set_read_timeout(handle: Handle, timeout: Option<u64>) -> Result<(), ()>;
+	fn sys_tcp_stream_get_read_timeout(handle: Handle) -> Result<Option<u64>, ()>;
+	fn sys_tcp_stream_set_write_timeout(handle: Handle, timeout: Option<u64>) -> Result<(), ()>;
+	fn sys_tcp_stream_get_write_timeout(handle: Handle) -> Result<Option<u64>, ()>;
+	fn sys_tcp_stream_peek(handle: Handle, buf: &mut [u8]) -> Result<usize, ()>;
+	fn sys_tcp_stream_set_nonblocking(handle: Handle, mode: bool) -> Result<(), ()>;
+	fn sys_tcp_stream_set_tll(handle: Handle, ttl: u32) -> Result<(), ()>;
+	fn sys_tcp_stream_get_tll(handle: Handle) -> Result<u32, ()>;
+	fn sys_tcp_stream_shutdown(handle: Handle, how: i32) -> Result<(), ()>;
+	fn sys_tcp_stream_peer_addr(handle: Handle) -> Result<(IpAddress, u16), ()>;
+}
+
+/// Opens a TCP connection to a remote host.
+#[inline(always)]
+pub fn connect(ip: &[u8], port: u16, timeout: Option<u64>) -> Result<Handle, ()> {
+	unsafe { sys_tcp_stream_connect(ip, port, timeout) }
+}
+
+/// Close a TCP connection
+#[inline(always)]
+pub fn close(handle: Handle) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_close(handle) }
+}
+
+#[inline(always)]
+pub fn peek(handle: Handle, buf: &mut [u8]) -> Result<usize, ()> {
+	unsafe { sys_tcp_stream_peek(handle, buf) }
+}
+
+#[inline(always)]
+pub fn peer_addr(handle: Handle) -> Result<(IpAddress, u16), ()> {
+	unsafe { sys_tcp_stream_peer_addr(handle) }
+}
+#[inline(always)]
+pub fn read(handle: Handle, buffer: &mut [u8]) -> Result<usize, ()> {
+	unsafe { sys_tcp_stream_read(handle, buffer) }
+}
+
+#[inline(always)]
+pub fn write(handle: Handle, buffer: &[u8]) -> Result<usize, ()> {
+	unsafe { sys_tcp_stream_write(handle, buffer) }
+}
+
+#[inline(always)]
+pub fn set_read_timeout(handle: Handle, timeout: Option<u64>) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_set_read_timeout(handle, timeout) }
+}
+
+#[inline(always)]
+pub fn set_write_timeout(handle: Handle, timeout: Option<u64>) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_set_write_timeout(handle, timeout) }
+}
+
+#[inline(always)]
+pub fn get_read_timeout(handle: Handle) -> Result<Option<u64>, ()> {
+	unsafe { sys_tcp_stream_get_read_timeout(handle) }
+}
+
+#[inline(always)]
+pub fn get_write_timeout(handle: Handle) -> Result<Option<u64>, ()> {
+	unsafe { sys_tcp_stream_get_write_timeout(handle) }
+}
+
+#[inline(always)]
+pub fn set_nodelay(_: Handle, mode: bool) -> Result<(), ()> {
+	// smoltcp does not support Nagle's algorithm
+	// => to enable Nagle's algorithm isn't possible
+	if mode {
+		Ok(())
+	} else {
+		Err(())
+	}
+}
+
+#[inline(always)]
+pub fn nodelay(_: Handle) -> Result<bool, ()> {
+	// smoltcp does not support Nagle's algorithm
+	// => return always true
+	Ok(true)
+}
+
+#[inline(always)]
+pub fn set_nonblocking(handle: Handle, mode: bool) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_set_nonblocking(handle, mode) }
+}
+
+#[inline(always)]
+pub fn set_tll(handle: Handle, ttl: u32) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_set_tll(handle, ttl) }
+}
+
+#[inline(always)]
+pub fn get_tll(handle: Handle) -> Result<u32, ()> {
+	unsafe { sys_tcp_stream_get_tll(handle) }
+}
+
+#[inline(always)]
+pub fn shutdown(handle: Handle, how: i32) -> Result<(), ()> {
+	unsafe { sys_tcp_stream_shutdown(handle, how) }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"CHANGELOG.md":"1e68c96d2407d76c47f9e238dd48bde35ee3742e32f3c3ac20b35ac0ca2885a5","Cargo.lock":"4535f7fbc231c450241d5facee636701a69139e102c1009467d71ee8936355c0","Cargo.toml":"16656784f6cbda9df98d95dd56f676a6b1f08decdd145695329a666b8ad9da8d","README.md":"c25846ed66decef7e58bbbad52779eb8c806b1ba18f75e6b07812a8dea58a28b","UNLICENSE":"7e12e5df4bae12cb21581ba157ced20e1986a0508dd10d0e8a4ab9a4cf94e85c","build.rs":"47a71e744297c709a883ec3cc33d673e7cfb5188895fba2f048ab88fa10e3924","dbus_interfaces/DBusMenu.xml":"86a8bf3e60a93000073481fd8f2c365350062636e5c3d0efb7e68237a967042b","dbus_interfaces/StatusNotifierItem.xml":"0ae1294932445ca77c9b376019f01c4c0bf57fa5cf3478cfc51b66fe8bcab8ee","dbus_interfaces/StatusNotifierWatcher.xml":"19df7f185c6be476134d80ec886fcecbd80ff5b377d5349b84b951119d3eab49","examples/example.rs":"f148630408b0788147570f186dfc89370f264342066b9d0739deb343f2643014","examples/screenshot_of_example_in_gnome.png":"10c422275bd39d426c26a187988d1105599ecc13d9e112255113439082168de1","src/dbus_ext.rs":"0e2e3a8b5fb4fde4706807ec8db00f8552177e11a43f761b3f082d2317f6e998","src/dbus_interface.rs":"31b53ddbc2f25fc34055cff14b01ee8626a168ffa8f234ee5c993c29f5cdd6e5","src/error.rs":"4e9e0c196e9c9573f4e9a12893728250ea776d89697f16578ddd458c37da4ca2","src/freedesktop.rs":"1d86493413e40ed662dfab682d9c44a09582e8959308d4aaba084ddd9b8dfc1d","src/lib.rs":"544eb1cb18b3e4ea034a9a61435d59ba6167a04513f4bf62fa2ed85acaace09d","src/menu.rs":"a86472253dacb06a1caae48c2e6750c8a27e9e6190bc13c05ea0bf058b9e8ff1","src/service.rs":"b4fe1de31767432b73fb1c12a7e37816f540de5bd349dcd1bee25f430566ab2e","src/tray.rs":"d21d9b0749bf2e5f03e0586e0daf700fd4ec258c30c403c13f0e6837a4f4223d"},"package":"4934310bdd016e55725482b8d35ac0c16fd058c1b955d8959aa2d953b918c85b"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/CHANGELOG.md
@@ -0,0 +1,8 @@
+# 0.2.2 (2024-04-27)
+
+## New methods:
+
+  - `TrayService::run_without_dbus_name`
+  - `TrayService::spwan_without_dbus_name`
+
+See https://github.com/iovxw/ksni/pull/25 for details
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/Cargo.lock
@@ -0,0 +1,225 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "ansi_term"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "winapi",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "clap"
+version = "2.34.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
+dependencies = [
+ "ansi_term",
+ "atty",
+ "bitflags",
+ "strsim",
+ "textwrap",
+ "unicode-width",
+ "vec_map",
+]
+
+[[package]]
+name = "dbus"
+version = "0.9.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bb21987b9fb1613058ba3843121dd18b163b254d8a6e797e144cbac14d96d1b"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "winapi",
+]
+
+[[package]]
+name = "dbus-codegen"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a49da9fdfbe872d4841d56605dc42efa5e6ca3291299b87f44e1cde91a28617c"
+dependencies = [
+ "clap",
+ "dbus",
+ "xml-rs",
+]
+
+[[package]]
+name = "dbus-tree"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f456e698ae8e54575e19ddb1f9b7bce2298568524f215496b248eb9498b4f508"
+dependencies = [
+ "dbus",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "ksni"
+version = "0.2.2"
+dependencies = [
+ "dbus",
+ "dbus-codegen",
+ "dbus-tree",
+ "thiserror",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.153"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06085512b750d640299b79be4bad3d2fa90a9c00b1fd9e1b46364f66f0485c72"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.78"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "strsim"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
+
+[[package]]
+name = "syn"
+version = "2.0.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "unicode-width",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.57"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "unicode-width"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"
+
+[[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "xml-rs"
+version = "0.8.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/Cargo.toml
@@ -0,0 +1,41 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.58"
+name = "ksni"
+version = "0.2.2"
+authors = ["iovxw <iovxw@outlook.com>"]
+description = """
+A Rust implementation of the KDE/freedesktop StatusNotifierItem specification
+"""
+readme = "README.md"
+keywords = [
+    "systray",
+    "linux",
+    "gui",
+]
+categories = ["api-bindings"]
+license = "Unlicense"
+repository = "https://github.com/iovxw/ksni"
+
+[dependencies.dbus]
+version = "0.9"
+
+[dependencies.dbus-tree]
+version = "0.9"
+
+[dependencies.thiserror]
+version = "1.0"
+
+[build-dependencies.dbus-codegen]
+version = "0.9"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/README.md
@@ -0,0 +1,145 @@
+# ksni 
+
+[![Build Status](https://github.com/iovxw/ksni/workflows/Rust/badge.svg)](https://github.com/iovxw/ksni/actions?query=workflow%3ARust)
+[![Crates](https://img.shields.io/crates/v/ksni.svg)](https://crates.io/crates/ksni)
+[![Documentation](https://docs.rs/ksni/badge.svg)](https://docs.rs/ksni)
+[![MSRV](https://img.shields.io/badge/msrv-1.58.0-blue)](https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field)
+
+A Rust implementation of the KDE/freedesktop StatusNotifierItem specification
+
+## Example
+
+```rust
+use ksni;
+
+#[derive(Debug)]
+struct MyTray {
+    selected_option: usize,
+    checked: bool,
+}
+
+impl ksni::Tray for MyTray {
+    fn icon_name(&self) -> String {
+        "help-about".into()
+    }
+    fn title(&self) -> String {
+        if self.checked { "CHECKED!" } else { "MyTray" }.into()
+    }
+    // NOTE: On some system trays, `id` is a required property to avoid unexpected behaviors
+    fn id(&self) -> String {
+        env!("CARGO_PKG_NAME").into()
+    }
+    fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
+        use ksni::menu::*;
+        vec![
+            SubMenu {
+                label: "a".into(),
+                submenu: vec![
+                    SubMenu {
+                        label: "a1".into(),
+                        submenu: vec![
+                            StandardItem {
+                                label: "a1.1".into(),
+                                ..Default::default()
+                            }
+                            .into(),
+                            StandardItem {
+                                label: "a1.2".into(),
+                                ..Default::default()
+                            }
+                            .into(),
+                        ],
+                        ..Default::default()
+                    }
+                    .into(),
+                    StandardItem {
+                        label: "a2".into(),
+                        ..Default::default()
+                    }
+                    .into(),
+                ],
+                ..Default::default()
+            }
+            .into(),
+            MenuItem::Separator,
+            RadioGroup {
+                selected: self.selected_option,
+                select: Box::new(|this: &mut Self, current| {
+                    this.selected_option = current;
+                }),
+                options: vec![
+                    RadioItem {
+                        label: "Option 0".into(),
+                        ..Default::default()
+                    },
+                    RadioItem {
+                        label: "Option 1".into(),
+                        ..Default::default()
+                    },
+                    RadioItem {
+                        label: "Option 2".into(),
+                        ..Default::default()
+                    },
+                ],
+                ..Default::default()
+            }
+            .into(),
+            CheckmarkItem {
+                label: "Checkable".into(),
+                checked: self.checked,
+                activate: Box::new(|this: &mut Self| this.checked = !this.checked),
+                ..Default::default()
+            }
+            .into(),
+            StandardItem {
+                label: "Exit".into(),
+                icon_name: "application-exit".into(),
+                activate: Box::new(|_| std::process::exit(0)),
+                ..Default::default()
+            }
+            .into(),
+        ]
+    }
+}
+
+fn main() {
+    let service = ksni::TrayService::new(MyTray {
+        selected_option: 0,
+        checked: false,
+    });
+    let handle = service.handle();
+    service.spawn();
+
+    std::thread::sleep(std::time::Duration::from_secs(5));
+    // We can modify the tray
+    handle.update(|tray: &mut MyTray| {
+        tray.checked = true;
+    });
+    // Run forever
+    loop {
+        std::thread::park();
+    }
+}
+```
+
+Will create a system tray like this:
+
+![screenshot_of_example_in_gnome.png](examples/screenshot_of_example_in_gnome.png)
+
+(In GNOME with AppIndicator extension)
+
+## Todo
+ - [X] org.kde.StatusNotifierItem
+ - [X] com.canonical.dbusmenu
+ - [X] org.freedesktop.DBus.Introspectable
+ - [X] org.freedesktop.DBus.Properties
+ - [X] radio item
+ - [ ] documents
+ - [ ] async [diwic/dbus-rs#166](https://github.com/diwic/dbus-rs/issues/166)
+ - [X] mutable menu items
+
+## License
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <http://unlicense.org/>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/build.rs
@@ -0,0 +1,56 @@
+use std::env;
+use std::fs::File;
+use std::io::prelude::*;
+use std::path::Path;
+
+use dbus_codegen::{generate, GenOpts, ServerAccess};
+
+fn generate_code(interfaces: &[(&str, GenOpts)], outfile: &str) {
+    let mut code = String::new();
+    for (n, (file, opts)) in interfaces.iter().enumerate() {
+        let mut f = File::open(file).unwrap();
+        let mut xml = String::new();
+        f.read_to_string(&mut xml).unwrap();
+        code.push_str(&format!("mod n{} {{\n", n));
+        code.push_str(&generate(&xml, &opts).unwrap());
+        code.push_str(&format!("\n}}\npub use n{}::*;\n", n));
+    }
+    let out_dir = env::var("OUT_DIR").unwrap();
+    let path = Path::new(&out_dir).join(outfile);
+    let mut f = File::create(path).unwrap();
+    (&mut f as &mut dyn Write)
+        .write_all(code.as_bytes())
+        .unwrap();
+}
+
+fn main() {
+    generate_code(
+        &[
+            (
+                "dbus_interfaces/StatusNotifierWatcher.xml",
+                GenOpts {
+                    methodtype: None,
+                    skipprefix: Some("org.kde.".into()),
+                    ..Default::default()
+                },
+            ),
+            (
+                "dbus_interfaces/StatusNotifierItem.xml",
+                GenOpts {
+                    serveraccess: ServerAccess::AsRefClosure,
+                    skipprefix: Some("org.kde.".into()),
+                    ..Default::default()
+                },
+            ),
+            (
+                "dbus_interfaces/DBusMenu.xml",
+                GenOpts {
+                    serveraccess: ServerAccess::AsRefClosure,
+                    skipprefix: Some("com.canonical.".into()),
+                    ..Default::default()
+                },
+            ),
+        ],
+        "dbus_interfaces.rs",
+    );
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/dbus_interfaces/DBusMenu.xml
@@ -0,0 +1,437 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+A library to allow applications to provide simple indications of
+information to be displayed to users of the application through the
+interface shell.
+
+Copyright 2009 Canonical Ltd.
+
+Authors:
+    Ted Gould <ted@canonical.com>
+    Aurélien Gâteau <aurelien.gateau@canonical.com>
+
+This program is free software: you can redistribute it and/or modify it 
+under the terms of either or both of the following licenses:
+
+1) the GNU Lesser General Public License version 3, as published by the 
+Free Software Foundation; and/or
+2) the GNU Lesser General Public License version 2.1, as published by 
+the Free Software Foundation.
+
+This program is distributed in the hope that it will be useful, but 
+WITHOUT ANY WARRANTY; without even the implied warranties of 
+MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR 
+PURPOSE.  See the applicable version of the GNU Lesser General Public 
+License for more details.
+
+You should have received a copy of both the GNU Lesser General Public 
+License version 3 and version 2.1 along with this program.  If not, see 
+<http://www.gnu.org/licenses/>
+-->
+<node name="/" xmlns:dox="http://www.canonical.com/dbus/dox.dtd">
+    <dox:d><![CDATA[
+    @mainpage
+
+    The goal of DBusMenu is to expose menus on DBus.
+    
+    Main interface is documented here: @ref com::canonical::dbusmenu
+    ]]></dox:d>
+	<interface name="com.canonical.dbusmenu">
+		<dox:d><![CDATA[
+		A DBus interface to expose menus on DBus.
+
+		Menu items are represented with a unique numeric id and a dictionary of
+		properties.
+
+		To reduce the amount of DBus traffic, a property should only be returned
+		if its value is not the default value.
+
+		Available properties are:
+
+		<table>
+		<tr>
+			<th>Name</th>
+			<th>Type</th>
+			<th>Description</th>
+			<th>Default Value</th>
+		</tr>
+		<tr>
+			<td>type</td>
+			<td>String</td>
+			<td>Can be one of:
+			- "standard": an item which can be clicked to trigger an action or
+			  show another menu
+			- "separator": a separator
+
+			Vendor specific types can be added by prefixing them with
+			"x-<vendor>-".
+			</td>
+			<td>"standard"</td>
+		</tr>
+		<tr>
+			<td>label</td>
+			<td>string</td>
+			<td>Text of the item, except that:
+			-# two consecutive underscore characters "__" are displayed as a
+			single underscore,
+			-# any remaining underscore characters are not displayed at all,
+			-# the first of those remaining underscore characters (unless it is
+			the last character in the string) indicates that the following
+			character is the access key.
+			</td>
+			<td>""</td>
+		</tr>
+		<tr>
+			<td>enabled</td>
+			<td>boolean</td>
+			<td>Whether the item can be activated or not.</td>
+			<td>true</td>
+		</tr>
+		<tr>
+			<td>visible</td>
+			<td>boolean</td>
+			<td>True if the item is visible in the menu.</td>
+			<td>true</td>
+		</tr>
+		<tr>
+			<td>icon-name</td>
+			<td>string</td>
+			<td>Icon name of the item, following the freedesktop.org icon spec.</td>
+			<td>""</td>
+		</tr>
+		<tr>
+			<td>icon-data</td>
+			<td>binary</td>
+			<td>PNG data of the icon.</td>
+			<td>Empty</td>
+		</tr>
+		<tr>
+			<td>shortcut</td>
+			<td>array of arrays of strings</td>
+			<td>The shortcut of the item. Each array represents the key press
+			in the list of keypresses. Each list of strings contains a list of
+			modifiers and then the key that is used. The modifier strings
+			allowed are: "Control", "Alt", "Shift" and "Super".
+
+			- A simple shortcut like Ctrl+S is represented as:
+			  [["Control", "S"]]
+			- A complex shortcut like Ctrl+Q, Alt+X is represented as:
+			  [["Control", "Q"], ["Alt", "X"]]</td>
+			<td>Empty</td>
+		</tr>
+		<tr>
+			<td>toggle-type</td>
+			<td>string</td>
+			<td>
+			If the item can be toggled, this property should be set to:
+			- "checkmark": Item is an independent togglable item
+			- "radio": Item is part of a group where only one item can be
+			  toggled at a time
+			- "": Item cannot be toggled
+			</td>
+			<td>""</td>
+		</tr>
+		<tr>
+			<td>toggle-state</td>
+			<td>int</td>
+			<td>
+			Describe the current state of a "togglable" item. Can be one of:
+			- 0 = off
+			- 1 = on
+			- anything else = indeterminate
+
+			Note:
+			The implementation does not itself handle ensuring that only one
+			item in a radio group is set to "on", or that a group does not have
+			"on" and "indeterminate" items simultaneously; maintaining this
+			policy is up to the toolkit wrappers.
+			</td>
+			<td>-1</td>
+		</tr>
+		<tr>
+			<td>children-display</td>
+			<td>string</td>
+			<td>
+			If the menu item has children this property should be set to
+			"submenu".
+			</td>
+			<td>""</td>
+		</tr>
+		<tr>
+			<td>disposition</td>
+			<td>string</td>
+			<td>
+			How the menuitem feels the information it's displaying to the
+			user should be presented.
+			- "normal" a standard menu item
+			- "informative" providing additional information to the user
+			- "warning" looking at potentially harmful results
+			- "alert" something bad could potentially happen
+			</td>
+			<td>"normal"</td>
+		</tr>
+		</table>
+
+		Vendor specific properties can be added by prefixing them with
+		"x-<vendor>-".
+		]]></dox:d>
+
+<!-- Properties -->
+		<property name="Version" type="u" access="read">
+			<dox:d>
+			Provides the version of the DBusmenu API that this API is
+			implementing.
+			</dox:d>
+		</property>
+
+		<property name="TextDirection" type="s" access="read">
+			<dox:d>
+			Represents the way the text direction of the application.  This
+			allows the server to handle mismatches intelligently.  For left-
+			to-right the string is "ltr" for right-to-left it is "rtl".
+			</dox:d>
+		</property>
+
+		<property name="Status" type="s" access="read">
+			<dox:d>
+			Tells if the menus are in a normal state or they believe that they
+			could use some attention.  Cases for showing them would be if help
+			were referring to them or they accessors were being highlighted.
+			This property can have two values: "normal" in almost all cases and
+			"notice" when they should have a higher priority to be shown.
+			</dox:d>
+		</property>
+
+		<property name="IconThemePath" type="as" access="read">
+			<dox:d>
+			A list of directories that should be used for finding icons using
+			the icon naming spec.  Idealy there should only be one for the icon
+			theme, but additional ones are often added by applications for
+			app specific icons.
+			</dox:d>
+		</property>
+
+<!-- Functions -->
+
+		<method name="GetLayout">
+			<dox:d>
+			  Provides the layout and propertiers that are attached to the entries
+			  that are in the layout.  It only gives the items that are children
+			  of the item that is specified in @a parentId.  It will return all of the
+			  properties or specific ones depending of the value in @a propertyNames.
+
+			  The format is recursive, where the second 'v' is in the same format
+			  as the original 'a(ia{sv}av)'.  Its content depends on the value
+			  of @a recursionDepth.
+			</dox:d>
+			<arg type="i" name="parentId" direction="in">
+				<dox:d>The ID of the parent node for the layout.  For
+				grabbing the layout from the root node use zero.</dox:d>
+			</arg>
+			<arg type="i" name="recursionDepth" direction="in">
+				<dox:d>
+				  The amount of levels of recursion to use.  This affects the
+				  content of the second variant array.
+				  - -1: deliver all the items under the @a parentId.
+				  - 0: no recursion, the array will be empty.
+				  - n: array will contains items up to 'n' level depth.
+				</dox:d>
+			</arg>
+			<arg type="as" name="propertyNames" direction="in" >
+				<dox:d>
+					The list of item properties we are
+					interested in.  If there are no entries in the list all of
+					the properties will be sent.
+				</dox:d>
+			</arg>
+			<arg type="u" name="revision" direction="out">
+				<dox:d>The revision number of the layout.  For matching
+				with layoutUpdated signals.</dox:d>
+			</arg>
+			<arg type="(ia{sv}av)" name="layout" direction="out">
+				<dox:d>The layout, as a recursive structure.</dox:d>
+			</arg>
+		</method>
+
+		<method name="GetGroupProperties">
+			<dox:d>
+			Returns the list of items which are children of @a parentId.
+			</dox:d>
+			<arg type="ai" name="ids" direction="in" >
+				<dox:d>
+					A list of ids that we should be finding the properties
+					on.  If the list is empty, all menu items should be sent.
+				</dox:d>
+			</arg>
+			<arg type="as" name="propertyNames" direction="in" >
+				<dox:d>
+					The list of item properties we are
+					interested in.  If there are no entries in the list all of
+					the properties will be sent.
+				</dox:d>
+			</arg>
+			<arg type="a(ia{sv})" name="properties" direction="out" >
+				<dox:d>
+					An array of property values.
+					An item in this area is represented as a struct following
+					this format:
+					@li id unsigned the item id
+					@li properties map(string => variant) the requested item properties
+				</dox:d>
+			</arg>
+		</method>
+
+		<method name="GetProperty">
+			<dox:d>
+			  Get a signal property on a single item.  This is not useful if you're
+			  going to implement this interface, it should only be used if you're
+			  debugging via a commandline tool.
+			</dox:d>
+			<arg type="i" name="id" direction="in">
+				<dox:d>the id of the item which received the event</dox:d>
+			</arg>
+			<arg type="s" name="name" direction="in">
+				<dox:d>the name of the property to get</dox:d>
+			</arg>
+			<arg type="v" name="value" direction="out">
+				<dox:d>the value of the property</dox:d>
+			</arg>
+		</method>
+
+		<method name="Event">
+			<dox:d><![CDATA[
+			This is called by the applet to notify the application an event happened on a
+			menu item.
+
+			@a type can be one of the following:
+
+			@li "clicked"
+			@li "hovered"
+			@li "opened"
+			@li "closed"
+
+			Vendor specific events can be added by prefixing them with "x-<vendor>-"
+			]]></dox:d>
+			<arg type="i" name="id" direction="in" >
+				<dox:d>the id of the item which received the event</dox:d>
+			</arg>
+			<arg type="s" name="eventId" direction="in" >
+				<dox:d>the type of event</dox:d>
+			</arg>
+			<arg type="v" name="data" direction="in" >
+				<dox:d>event-specific data</dox:d>
+			</arg>
+			<arg type="u" name="timestamp" direction="in" >
+				<dox:d>The time that the event occured if available or the time the message was sent if not</dox:d>
+			</arg>
+		</method>
+
+		<method name="EventGroup">
+			<dox:d>
+				Used to pass a set of events as a single message for possibily several
+				different menuitems.  This is done to optimize DBus traffic.
+			</dox:d>
+			<arg type="a(isvu)" name="events" direction="in">
+				<dox:d>
+					An array of all the events that should be passed.  This tuple should
+					match the parameters of the 'Event' signal.  Which is roughly:
+					id, eventID, data and timestamp.
+				</dox:d>
+			</arg>
+			<arg type="ai" name="idErrors" direction="out">
+				<dox:d>
+					I list of menuitem IDs that couldn't be found.  If none of the ones
+					in the list can be found, a DBus error is returned.
+				</dox:d>
+			</arg>
+		</method>
+
+		<method name="AboutToShow">
+			<dox:d>
+			This is called by the applet to notify the application that it is about
+			to show the menu under the specified item.
+			</dox:d>
+			<arg type="i" name="id" direction="in">
+				<dox:d>
+				Which menu item represents the parent of the item about to be shown.
+				</dox:d>
+			</arg>
+			<arg type="b" name="needUpdate" direction="out">
+				<dox:d>
+				Whether this AboutToShow event should result in the menu being updated.
+				</dox:d>
+			</arg>
+		</method>
+
+		<method name="AboutToShowGroup">
+			<dox:d>
+				A function to tell several menus being shown that they are about to
+				be shown to the user.  This is likely only useful for programitc purposes
+				so while the return values are returned, in general, the singular function
+				should be used in most user interacation scenarios.
+			</dox:d>
+			<arg type="ai" name="ids" direction="in">
+				<dox:d>
+					The IDs of the menu items who's submenus are being shown.
+				</dox:d>
+			</arg>
+			<arg type="ai" name="updatesNeeded" direction="out">
+				<dox:d>
+					The IDs of the menus that need updates.  Note: if no update information
+					is needed the DBus message should set the no reply flag.
+				</dox:d>
+			</arg>
+			<arg type="ai" name="idErrors" direction="out">
+				<dox:d>
+					I list of menuitem IDs that couldn't be found.  If none of the ones
+					in the list can be found, a DBus error is returned.
+				</dox:d>
+			</arg>
+		</method>
+
+<!-- Signals -->
+		<signal name="ItemsPropertiesUpdated">
+			<dox:d>
+			Triggered when there are lots of property updates across many items
+			so they all get grouped into a single dbus message.  The format is
+			the ID of the item with a hashtable of names and values for those
+			properties.
+			</dox:d>
+			<arg type="a(ia{sv})" name="updatedProps" direction="out" />
+			<arg type="a(ias)" name="removedProps" direction="out" />
+		</signal>
+		<signal name="LayoutUpdated">
+			<dox:d>
+			Triggered by the application to notify display of a layout update, up to
+			revision
+			</dox:d>
+			<arg type="u" name="revision" direction="out" >
+				<dox:d>The revision of the layout that we're currently on</dox:d>
+			</arg>
+			<arg type="i" name="parent" direction="out" >
+				<dox:d>
+				If the layout update is only of a subtree, this is the
+				parent item for the entries that have changed.  It is zero if
+				the whole layout should be considered invalid.
+				</dox:d>
+			</arg>
+		</signal>
+		<signal name="ItemActivationRequested">
+			<dox:d>
+			  The server is requesting that all clients displaying this
+			  menu open it to the user.  This would be for things like
+			  hotkeys that when the user presses them the menu should
+			  open and display itself to the user.
+			</dox:d>
+			<arg type="i" name="id" direction="out" >
+				<dox:d>ID of the menu that should be activated</dox:d>
+			</arg>
+			<arg type="u" name="timestamp" direction="out" >
+				<dox:d>The time that the event occured</dox:d>
+			</arg>
+		</signal>
+
+<!-- End of interesting stuff -->
+
+	</interface>
+</node>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/dbus_interfaces/StatusNotifierItem.xml
@@ -0,0 +1,96 @@
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node>
+  <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-->
+    <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>
+
+    <signal name="NewToolTip">
+    </signal>
+
+    <signal name="NewStatus">
+      <arg name="status" type="s"/>
+    </signal>
+
+  </interface>
+</node>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/dbus_interfaces/StatusNotifierWatcher.xml
@@ -0,0 +1,42 @@
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+<node>
+  <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>
+</node>
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/examples/example.rs
@@ -0,0 +1,110 @@
+use ksni;
+
+#[derive(Debug)]
+struct MyTray {
+    selected_option: usize,
+    checked: bool,
+}
+
+impl ksni::Tray for MyTray {
+    fn icon_name(&self) -> String {
+        "help-about".into()
+    }
+    fn title(&self) -> String {
+        if self.checked { "CHECKED!" } else { "MyTray" }.into()
+    }
+    // **NOTE**: On some system trays, [`Tray::id`] is a required property to avoid unexpected behaviors
+    fn id(&self) -> String {
+        env!("CARGO_PKG_NAME").into()
+    }
+    fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
+        use ksni::menu::*;
+        vec![
+            SubMenu {
+                label: "a".into(),
+                submenu: vec![
+                    SubMenu {
+                        label: "a1".into(),
+                        submenu: vec![
+                            StandardItem {
+                                label: "a1.1".into(),
+                                ..Default::default()
+                            }
+                            .into(),
+                            StandardItem {
+                                label: "a1.2".into(),
+                                ..Default::default()
+                            }
+                            .into(),
+                        ],
+                        ..Default::default()
+                    }
+                    .into(),
+                    StandardItem {
+                        label: "a2".into(),
+                        ..Default::default()
+                    }
+                    .into(),
+                ],
+                ..Default::default()
+            }
+            .into(),
+            MenuItem::Separator,
+            RadioGroup {
+                selected: self.selected_option,
+                select: Box::new(|this: &mut Self, current| {
+                    this.selected_option = current;
+                }),
+                options: vec![
+                    RadioItem {
+                        label: "Option 0".into(),
+                        ..Default::default()
+                    },
+                    RadioItem {
+                        label: "Option 1".into(),
+                        ..Default::default()
+                    },
+                    RadioItem {
+                        label: "Option 2".into(),
+                        ..Default::default()
+                    },
+                ],
+                ..Default::default()
+            }
+            .into(),
+            CheckmarkItem {
+                label: "Checkable".into(),
+                checked: self.checked,
+                activate: Box::new(|this: &mut Self| this.checked = !this.checked),
+                ..Default::default()
+            }
+            .into(),
+            StandardItem {
+                label: "Exit".into(),
+                icon_name: "application-exit".into(),
+                activate: Box::new(|_| std::process::exit(0)),
+                ..Default::default()
+            }
+            .into(),
+        ]
+    }
+}
+
+fn main() {
+    let service = ksni::TrayService::new(MyTray {
+        selected_option: 0,
+        checked: false,
+    });
+    let handle = service.handle();
+    service.spawn();
+
+    std::thread::sleep(std::time::Duration::from_secs(5));
+    // We can modify the handle
+    handle.update(|tray: &mut MyTray| {
+        tray.checked = true;
+    });
+    // Run forever
+    loop {
+        std::thread::park();
+    }
+}
new file mode 100644
index 0000000000000000000000000000000000000000..b73d5d1c17648fc7e330937160eeb5a7943fe24e
GIT binary patch
literal 59644
zc$@%0K)=6<P)<h;3K|Lk000e1NJLTq008~~00FZI1^@s64=1Wu000`xdQ@0+Qek%>
zaB^>EX>4U6ba`-PAZ2)IW&i+q+O3*tmLw^5h5xe(Edh9p%V9i6JJ9m=UEC`xGrOu=
zEh(}p!o$Pd4Bl`Dz@7j4&+Gn!uVSsZlxr)!6wg=csmH;K=09JbpTVd1{e9i@{ag6;
zeK+m<GV;^-X`ero?+3!*{ru+#YWluEe|_K8^?4E7_eS48aO3x7da_>c?;yW7viNyF
ze1CWS`+-q@n$GwCxW2dj-u(C9QzaNXb3cnN9t-B*_xO2|F$(K8_^I#Fnl3csb>=Vn
zZvPlRr{8-1>j3_E^;`V>A0x9r!{I)W{a#Rhi_`c0kbisMemo}rGNKTFJURY6qCG<O
zKY#rczk7GPuNIiZNYqhJ<vXcArt)5K;Ut`&XcYcc{?ELw?_cL%^TRK)wwda5e)3BX
zk%-@r!VV+caNf@q7DG(&#LCYYSG4zDvl@F`FDXg?!j09DnQe`%EHY=j9e<1^yytd3
zkB2p$yaQLpz|F|<um9ZdZ~Sln{c@vwRpuf1_K6c^!MLL8i(x2p`p#7(B;0RI^NVkA
zpCA7BFD2H<V18k4OmO)5xy8)k&)Tw=XY<){Y4V?b33Y#OK!|vDW-!6XfG@#vD8bhl
zYY4=#k)OfHqop{>K*%n~%_w6sD<p?*;MshphIehu@$)wDLL#yitE7h3Az3NqROq)x
z2@RJmr<`-iHMiXJC{|L*rIcEPQ=?i<HP=#WZME0YtfiJ)X|=W1+vu?yFqT~}z4q37
zAA^UEG`QE``oSABPMc}wS!SJW_Bj^iv(n0|th(CjYwWmf0|9QAU3c4kj}s21bkfPE
zoO;^nXIyIS+D$j#a_eok-|-`B;oG*qWbOCN{qwAaZ`R^Vl&-6PW{tON{o@uvaFUfX
zG8R)H<5d};prdl;TSzG?bIO_T(VSV1j4~@ZJ1AphFr5(d4L@@CXXgGkZ;t5xyLpR$
zl{u%>{eNW6DRn<(?jQ5^7g^im!R?30)P=+pgf!ak5Xq5azkT#tPVC7qX0!X6#Go^n
z!o8VzOY{urZ;c=@yWPtPx6I~f-rNR|d3!np!B<=U?3+{Iv$6LDP)%|*h{&2XbYEw<
zDH<>K%Eq*EZr#Pu>8G}5UDLN&J85cl-O%Dl{?rlRRKM<Epch6z!;f=kCq16h8AP%+
zUOSNBa@nR_$lqBtFYXXGmjeE4^W<{(9*pAnz3;I^ZZy$S2~8JVg}k@xC#@4w90-X>
zLH5)9O`dB_iL`i58u!4dw=^Rw<;Dfb+)92)xDTs@P4`bPCcUZHK0T&g+A4f>*Hq@2
zl?KckFiCfxIaBvB&(?i`mgj0PLuy7940CI)nrxTp@64s;duFd;w9Ln9OsUU9qGs9_
z?z}OyP44Qbcdosd&JDyf_v)xQMon9-oiB8hw=H9?+>)Z3i*W42fEZP--Ji7w;burH
zsGaFB(i+vYsn=C(R?Q}aLq!uh3W&bvH9S<ir7A*5`;<cQ4pBLw5wqUR3=TcvTHm{@
zLJ_T7>1`4S`j!eK_8rOWP6UBp!lKd_w>$o%aPBq=YG(?{a=F<>Vn!bv1`}qfO^89&
z$F%6;5^YWkibSIbJ-Iz`9HY=jp%LOdEuT#fWjF7p%t#TlE4?cnfDm(Gz&nuuE=+fs
zK5R5kxzo}-c_o_sfIhr=_NwmCo0F82-F2!F8K7ob=^$1MVWd<m`8_lbg>FX9ebY0-
z&12>|4^OVOxN1NlG?!KYW&G?!5Nt3;c|Bb}GB^|gZ*F`EG(CF&nh9jp$e&9C73wa|
zz^q9w773nvAYpP1dx9Xdk;3iiBh;Vq_>zw*_NFuGXnq}SQUnL21!{BK47HA%v#!d=
z+RAYXBqogLZv)i;jALN#CfrG?#zOB1I;zE=b4nY_ok&5n5*vXluLW~4Mhy;==_GBI
z0+p20HHw>Br%wD@z``i=avS1FI9*~ybaIhE4~K`3K@WBsK7__S@~Mon!UdVGyBj*s
zl;ou$ZyKZKK29q+IAr2R4bF2zSts5Almw8SI$H<uQ{z%C2H2iVbt<WS*%%v~pJlBD
zDxR1f83Ni2pqLv50Dt0`b)W3(8F9t~eNawR?~F$0EQ?7*Q}(2`6SYGloZTJJP-sJo
z0TAdO9;dbW>xp)9suwi9YqSf!5Rk~Q(m3Z<!WGL{>*h{hBoH!!gwz-qZ|!A{CcQl)
z%xb9myl!)0BHk>WXZLn@9=0hfpBP6DwW5y%Co3FgS9fnDX-wvGP@Q^E1BLNn>vLzk
z(NFhA1-!d6ky(nHWRd1${uMA`a`Ud0Vp|7(SUD{s0F3bQym|y*V?UmIpZe>l-H%}#
zn7pBP>X9-)N7M2)A%G-t<+s8bN`(g2FVhX5P`VdOV6yEHPm7gSryLvEA#tgjhzkY*
zqQmO->N!wW{fDW#Kj-Stm>!^tvx4EB2F-CT*@TF)NB4Io0-C>Wfzim_VtDkMhUfmc
z4L#1>iCdV^S}Nd8U{b<Jpb^0A6*fRe>>S8c+hZ$Ee$e9W#O4O{AdYLkjl?xv9x9Y#
zae)fA2zIU!uj7|gObLztS&>oO>;ovE1Ir5T4Nsgz+EFV|qi?#9mLPO%5r3jHuYoBS
z`v~JuW;<kR76^c+=mTiMrA?3L)EZD&%59;bxeBvEjWc=#5P_}-^d|vyFv);+>-WAB
zZ9x^$dM@ui?V^07Rc?o_NKrZBr_1O=2ELFzzuh1<B+`%3QMH|^oyPnBlWYI>(n)^Y
zUQ%jh5a$U|Q`vi>cHyJQV0{+|f+-!^Eb+jA2U_k0LME|Ka#9n^rUMy{Jw~Eft`;<?
zug~M>oD|t3pt*0KzA8$SW`(CAaJ=TS+W6><+oACqqNdf%rQo$Xm_bo1)H;|Vfkq4o
zT0&#c*q9r{Pc14h;!kPwv|U{S>DyUoU1lR>>l9}{Qf?BWTm&SH1$|{XX7HNS1z}A-
z-A?g~*N8TEr~?%mtuxAN{cRG64Q>!UY^FDhfSo*oLK895QR-c4jqWJS4x?%A);xg_
z6zE-3WlrTTva}zpgX>iFWk{6&M#&;qbC}Ya@!-1aQFkG$iW8xFR6R`srP;m&vTro>
zcSJHCurdE-EzJDwODH?@V<PP#T1Wy(GS`H4GFgzUfWjvB9E@cyyxs^~fdhJDbSM=G
zQ|Tx-1cr=bV^@%_C|}~(rGHSRw7gMG7q^cPu#pQ!7Ia%n%0mLVz%>;u5nM-~(P2><
zZzi%s5hh8Wf!L1N=lmr4X8b&y$Hzb|%EX&N|1iOlDy=TSo`(C%)EE!}pTHy_dL=mw
zCKl;IgeL+FH4N30f{?ijh{K~#nnZ)raMH&7$`tS;m%v^G-%6;sz;q(aos<RK_lZy<
zNL@X?C`9Z)He3#r0PtjYjIO)9L&jl@bsOb6aFK}B4i@2a+BM7+3LVwOjTa1nR)a1t
zTnyVAaJ3yXV_Lv<MhwB<j2{%8DFS%Z2?BR{o(dBBU}*u9-%q{|0*-jWOH(>bi8MVH
z2YY}LE0ggBd=Ld@i6kJr@MVLf(T8|9(iG;U*bmw_;k4jiIKfd>%mSHDiU2Z<5@PhC
zfnJ~0dWGXZO=ai}&wHOseq7-G?uvisCc41=Uv84ox)=GL+AR(|p)^whDGVM1FR9tk
z)u?E5T8G=F7Gs?g+^Y*Q+K~oQojA9%2#pN<a5xvF8SRob{e)J-w)z9L72ZHnVUIIC
z1kL3FTjK+W<wI|5J3#u7mYQ_Zpa^H=YNgu2b(G-&R5QvNvOB@^B9*k#5a(eDK$wcF
z1i!l>{43>1+8uroDGCsSfnfmDhw<knYPhr=**#5lUl5#AZmq-}k)n(cgG!m9eA=AB
zX&G-K$>kzt4u%KPA=lEWb=r<6#Mt&h4PcqZL@6U{kk8!moIESKH5FX;uncGb2<nIp
zqfonW08JAZk@T^LvG}hFp>T0v18y94%@li0fDIF}<MPCRv?y0|QSON3ONE|^Oy)Yo
zAxuW0Ga{nF#1V}Z)C0T~E;a1J45a4Z81ysN2Zsc93?4&`)5w^Tfj&0i)}yYe8We+|
z?3b7Px9~M_IU5N@b%%O1B1}P{g9WKI;mSZ$kBDoXMnk(WV_*);k8qhJAGM75S*8+(
zX?KJ{Kyi$OmN4-JBJM1$V-RvJ8&IskZ-aS&N@2bbqwsC)FbNy_$K{O3gI;iXlhUIy
z%Qx7(K$1_nEKq^22IhduD4M<jXcD#|3@GTEuvxN=2Ng!)75%l)GOf)qDJl)FVi+iK
zk^+TOga!Q#r7;*pY`C@I8td)O19Fomm<VDK6%;``>8+uJE*H>X35r0`84`Sewl{pa
zA_Gm)Ab?bqIWF`g;fH(*2<X97GDmfjM*ha*Py!DV7zG*v5JjgL#hC!MokT0}S|Iir
z&z+F{&^evSzpbY8j2d^jkfWq*0O>i<riL{dh@?d30M-)m53N+{2!W-=Gn={59&>3@
z_-VWtRq?TRTS!i4tz?B*^+k(hE%8wJcyMX}f-I;Rt;QT_x}E!Oa?)_kh@BTj<WKoU
zUeF+9PSWXJLXBv#7>L5TxjuZSH3kHE0{%3Pr9Bq(5qAxL`RUU@yB9M6gg8)2p}VaB
zLabdz%i9|k^?>9;jB6Pk$AUZxh9Jv5f(r3Dk%mcxV2514Rv=uR1TvxU2WlL}ch9B=
z(Ise}NXT)-OPd&42vGIs*<u$AV(x5GP>>Z3tqm4(UEu!m<P8noi|3xr09HUx%hkKs
z>!$>m+yOu~wAmnhQS7!RkuirLB!QsBtxIc<;&`%$Qo;0iO0B@!GP$%H?j?*gae@E}
z>9khRewgY|mqRx+p16?(%w+_Sr=smpfXAz>>5m?@%&N)rzgCe@d`PO*2)PzeWZ<}w
zmb3!e6LNqQVgPJVSY!#?U%(CKNwMS6Xb_ZV(*N34ihZm7rgrcEE%#6V`p^D|2E6zq
z`eBpL;9dzKb|ZL#WF)#|L4A?ll-AaqE;Z0fCxCKrS`PM6eA*i&4*Fr{V39pW$rD8e
z^uvapcu*LE_mftkQV=n;HBtm={-oVpJx47C4=of@uO!vQ@m99BmTr*cCqj{8Jy2#1
zn(&}Ji<spss2_kviGc?xJ{Zv^-bPWb=8&IgO^6<#OZkH_No(=M;z?S=ybvVjEX^bL
zB@-eTdzR~upZGOOj>n;!pFy)DAtsIpzyFl^Kzu|h1W68W9gx0d5KUsVTLj~9QAuTY
z8%04eRzdF|FIcoqKP|Lw43r_dm8KX2v>F>VP3hs0_r{B~N)qvQTFOQYi<faRm0Q2T
z#k--;vlgXxkU}_h>@Gb6$saI>SmBLBc2G%>m*%>vbz$@$S~Sk{@E|IFT4=)WUo_9q
zzQXLt)QNMi+0<Wz|KLTkx|3c+*`jn9t<SRnX~<E`2wn$8u+phmuc!?(?1<K^h!_n-
zF0>)h&vt6j1uig;){!Q326LoifMSesKN#(a@xqk%r3J%*%#gm)np9H_Z>T`P_7;Cv
zEm|&M3_M8ddhy+>wxq>+4<^wh)R8uB<Y7JBJ9n}x`?R@zc4k_H7xI+1cd*;jQy_+J
zj~}g&5UK_N5(JRinFN1>8oR5Pe4;_xfFS9})3gK!7%+ZmLXdKXf%H2?h|zJ<!1>XV
zdbKdMdYd4rY=gqLt-V|a@9LwC>K{|}Obcsy7Z}0BQB1TegQ;2oR~B+TvILOh(J~!T
z5Ax_pKM84^3&w>9buC*>Q7@S)r?%ZHnP#pPI!nH3b#+OIUjrn)c0cgvXka%{Em}L!
zZcdJ9u6&s#`n69;A7{r$sBtESQ^}2{qmEKX4Uzt6JkNsmc^sl@YT1CaQzJo(QL*eI
zO`-z^bP?Xk-cIk^7UK5EgLIM~O=~0r-4zk0PI@(IuG&wdYl%Zc@l$+A2@EIM(YlHJ
zLwk)rbbjKupMV#b9p&)@jX|m7MuXI2DIRM|jEKaB(=x`Ol0gFHpZGu~0)$a4M$ehH
zGs>U%DDP#WCo~cig=bA~0UB{*5?ZI+1dSP8XW{ARx0Fq~d%>@vK&cI+$>U@U!CR~d
zTI(|i5#0kwA<*d(8W;C7Q1)`W+BV;!9<I4AYaip#hle`t7=xkR6~?!{<R>_dOnWc|
zWhMmMkcC)p#WY-_*Wkc;t7|FP^Q`oL(QXS$>TO|0P(;fU1g9FeAxi~!T?|Se?_3Bu
zt&lO#OqLyjdeeSXDmoclBWFkF8WtpRK3<L4R-ch3v|iX}Fz|plqflvugjfbylGBPP
za!{GdQhKsCd{FWiRN6o*O-LJCL9$_m4|YWpRHg<l@NJhO;~bchar$S-f@L}7I#($L
z5lC68d?y+iS1pDzX&W3tWSp`cPa>oIa>qh=2%&42=j~>8>Jtd`HJqCymoF~~{-Ow~
zY0sn}n@qFu+EMDFQBs2y1*wh^TYsTV;95D3QQDKXVvtyQ27nYnc26xLcevJ&I&Uo)
z;Fkjp)m4O%7396FSg&=HC}dyKs*kqGv0{l1zULzIY2zy$e?L?gf1*kED_@HHDH;^5
z)+VJN8YqA^(^l=<kEUA${Q2$BG4B#-><#y4!<OLLs~VNTpcg33j`%`q6Bt?+47su%
zy~r6L@ecZ6@o4!<vUpXYuJ$ohCIp{2q~(KX5p{0>4R#2%1LKmuUcnb_#%uw+El3dK
zwo-~*fzZOPBRuYc!(^NK<BkBN8~`k85ebb4zk}T4>qlr&HA}<IYgkkt#00O+sh!<W
zP>!X^y$v}wQ2@;bdNRlAwSi4y={`Ut(eM!)hNfj=(MmtpL6SPogGkWYU+0n(=%RNJ
z4H1RESP%~E!7Ffo<C*W(&WYD{)r{0Ib57t<>x+9+j^cORA+i|z30ZYnGq2S-bSsJ#
z5dhTi*Jt(--H|`$nvo624+r0+qS|g6Vi6}Utx#&4mSH2}W?CQ~^Vili1*(k~t--c;
zV4z{7wdU-&h4$_e-ISUy;a}tP&WJq75_d|i*(p4zA^jFQymQy2<$3H(w$HNABozwZ
z2|{M6sj4l>8=x7ct^*mnpA{+`S=MnFQhKp8xEA52W%z3zBqn9#tZ;h_8?3qzb__Kn
zj7U@`@AJxo_PXk-w^IX#KWjU*_`G#$f>;2o0}qKe?LS?EDT^0dahet!wxKGnd}DLL
zq=(TmWDbP`De2(M+bjS@D}V0Vt;7URBvBl_Lw(ER83E}fK|=Ci2Zs}qC56~|o(uqz
zbA`7NKYa(gAUDbcDfIRMP^!2|!!7i;5l<DPw$1`Z=u4~-O2?P-jyF+?z}ysyL7DhA
zEl>dKKnlD8-{2tc!Ww#X4|Lfj9D?(elA<)VdvqIr3$UUGmXMYpq2hi}IP?yko3z<a
z1s?Ph0KwoiF>N>wHyX04gbj9+I4B?WtIey_B%vVW$W>q|@&QGR5JqNt=(xQDIHUrx
zLOsNH+#?*VhxSA#BE+a3wFE-}_;W<v@`xV1&{_U_hPT+N69kmOqinj-{k>m6S$p~k
z+o6?T(@}tdDGNcNU$C_GXT)1Um<CiWEH3lTLvf)Lp4ea^E%>X}*KXF117BVzkz|Ic
zTZ9|-62aeecmz?^U8rcIEzv;xdkS3amP>t>8<nQRGW4LNHi4OCfH7Afat5iO*nt$h
zmpQGKqwPJKR=`23;V%>j+`CgMAkqn1+=E8)oD#n}LxB$9K4)ZRi)SHBj-*n^(CE-U
z)Z2}Mvkbi#wbUVpTA+MwU?%N~hxQiti4-IYltU6sJj+3Dt&YfjpfJNgZZwAF5kXPA
zs{v9W(~|q(J&+eylATrEE^VhEX$X>5*pFQ0*3ynzqDh_3jbFSvK`9sFwfheZX#*r9
z7^GVefpaDV2l5D|L9nw<h8)^{>ZAyYq&-#WmBNCkM~rH9kIn)R3t)TEu_io~^OOZM
z>H4=%8|Pb09a><qsq>kGZ**(XE^6>s0upiG){v~%4tjpR6+XimLB-6<ef(a@33XQ}
z9|HG|5xuhz+`X0GNd3ppQDrR&bw;L{gMZ(GO_Wkc(1_QPHpg`Yq=*VO6gIc^|1cfH
z-e))IqQ*gAPfJ<`vuz(O-BMa!(caAX9cn;@3goATUxPsKtwm;PTI;%%xatiAu}%;`
z*)#=nZz_+lwB|vRYTK+v7_;pJ9|kO)%n9s+64XMT-lF=4NMA=|QK1e>>0sWX5yqDA
zBcD0J_u4AeIXEr+!6FjbR~z11g9odbU^VTaW~vJz;TGt<-y&wwQUt_`A0LBiwi3z)
z?bbK}Phb4j`4W7)j^qVoniqQzL%Mi(hbBUNT9xqESzX8t3%WlG+1Pw-f74eZBeB~Q
zx@x7m=s?IO7!VJZ;*90Ebsa!(x2wGo1x4$+N$Uwk=h>ue0R>s)GzOesRghQv{@S2y
zUut%L%gr4IP8%S@e{Ncf_FOtu<)29q3JjgX!O`zATXd-^sB)lLhD9esWVz6@^J)ck
zBVTQ9x@O=3Nte`lY&C16SOW*E(7eaZ`_6@-wx!J%zv`HU786j46=Y-Bv^??G;v;h7
zg6u&Dnz~#hu{0eVi4Hqi=r%yrw9kSX)nU%02K5M;w-X8~(yjxcrV~IEHU5E;#)G{x
zW?6m;bBsF?S)stZcoF(WEXJT6*o~Y*{DWh-c5Ge`S_zP%eZn<yqthsjdXEcvoaNzD
zl9}ILw3d3y(uyBMsKcFbp-z=8>H`Icd(*)?z7gXDo9}^}TJFxbgPtj>MrJ%-1L`Us
zsXnmOTHcA;F4i(3;uO9`<#=rrp<L%_j7kd(6JG1cpo)1T+>|LQMw=PnKWx~*X)p;H
z<8_ROVZ?T?y)gj>Fp?(*NFD_H+meHjbV`qK51p0?z?qgEt$#kLr8j-{g8e!Or0wY+
z?^5{M25?AGFf)N)XtGE0$oii?3}OO#fpP32UH=WlJ*5w=IS5TCG;#mD2;ZZ_RU_rw
zKkJM5F0H=tcul*_o8QQ_o3a5OKma`NI#N&Iye)G8&wi_qGR<45okKg6%oOVh`o*QC
z)(L6}2($zb0-~Vc-oA3tX#{N=;zdwCq?;n`Al}x-A{i1xb@$(y8cG`rM0I2U00D$)
zLqkwWLqi~Na&Km7Y-Iodc$|HaJxIeq9K~N#r7D#Ub`a^1p*mR+6>-!m6rn<>6<T#L
zx%3N~G$bi5j)H5!!H>nNgNw7S4z7YA_yOYL>ZIr*CH^lhw21NGxF7HCJ?`ECLcPp1
zt7{z4blXfN;$kMdDh6KBiwHs(Lr7+pF(*k$c#f}o`1pDk<5}M4{v7>k&SHR1B%Wo4
zX%lY{PjA`==Y8TZE6OVIIq|4T7bJe<y3*t~&IOkRo*6dNsd?fsu~_I}rGr_~)QG2u
zqpGG;zL06M%6W^kR<5$vJ^2fRIelfB>og-sU=d4@AVNVEC6r+!MypPWg%s__J^Vwi
zUm}-6t`ZnI7Epl(+4Y0}!S8OZ{NzM4DHsR3UmWLS7zpeFjhf?pA3ILt1n@rtS9;rD
zsRJ{gq}SS7^au!T0~gnAP1yr3cYwhsLpEhs^3xRZdEotwz9|a~+yZ@T&E8u3IDG)p
z)K&5ZI5-4G3Y5L>@$R0^-u^w)>hA}FO>(W|ZpUQ+000JJOGiWi{{a60|De66lK=n!
z32;bRa{vG?BLDy{BLR4&KXw2B00(qQO+^Re2^<eIHR4~d^Z)=L07*naRCwC#y?LB9
zSy|`#ea;dQ_vZ3$RZt+7C<20vwmRb0+BB%`0xBYV0i`Hzt*uzNAUe*7wvA{zjw_%n
zg@`2}BFd=1xQw>z*zSO0H>hm2yh|?kM#MSinLo~nxN$S{U8)LRuscsxe&Wr%dGp3{
zp8fay9{J>_ev=AHZ5#$gL;$b~B7%qlK*~oI#fSj|f`EVs5I_M<N+c10l;4Pwf5)g|
z6s#ni3QoX@!O&A%Wn=D{*A3n|i~)ntcY)<{$<E#$s!Cl~RNfK#7ALT=(NI+tnhc7N
zl47jE+KLOiyPQA2LmwlE1#1ywQH7|Wsvv^FKmq}bkpD5Rd=<leQOVbNaHaJ(9a@^w
z`0wFwQH}zL=C4EVll3E%^PU_*(0uk>ZYc-etL5yC8K2crpDV1+6;|ge2hZuy`_1@z
z5>OQsMG;i<`KSnOPq~KGm52dbp2_fRY~D@C@LW(-6)Se~v=lA(Vz}Pn`6vRaq~WuN
z`yj$yUwPA{OZ^SK)cX_G$R&Si^{kJ0w?Hgc8dH(O@j;j(zWL6W@^d$yxRgI$1YXO{
zR#wNg&8Vw;l|LlEH;uRYBDY8cK_>S(A!6wIC3dM8$*<L>!dio!IjX8+(YC}Gi*iYb
zfRvl1s#&oZi!tDw$68NQH!P}_*mk6(5EDruspNAM$s1U7+)l%FPamodTk`Jgjk~a}
z_UCcLv%brJM-QL>^lu;DTe^0~%Z3~ec6?T=eRPyCm?HcFBwcAI(eeqZNABr==}Q@8
zZ`iGp)%bAJ#AKl_8rxw6N%<z3VmXXvEdq)ZtEh5VF(xz%@u*w1Xd9jAT1KxxSUo%$
zJqiI5&N)<-5F*JXqDlF8jKNrov!0X^DJCL<ku2n@5JJQ|pS8XnG@N3L!8wQN14&c<
z3PodyJt*M}XDtY3qTsaL7yUp>+!YAB-sO#<m-t+{OM)O1%ddxo+Z=s?M<@c(i6=2R
zn&D9$^_O(mPx*PRbcL>t6Kkoe<9QALlF5eFtD#Zv+KX5Ad{s%sfT2p7DAYk_2cOd@
zI1tq6D8!&71fxn4$;v?Wz{48<B%;|$>k)U)Ox$9N8U0zKLx>>bgROiG+GkCbl)mo?
zMd>)}%f%H}-XyHGfD%GNP^?wNT8y#8lt?LIjAcICz&OwO^Sh`<7_9wxy<~5oSawq`
zBaYXT6;pOu^$1&a_icw>;iK0N@UEO*5yfI3X}R^%=Q|bXL7A<E21h6hBQh9xMpawf
ztYMExQBiWhgPevfBH2Zd!Qu@*L@Iw=SAwwe?&LCl>c0SsKi-2Z^l5m2M%EP_kVK2C
zFN4dxvg(6aBw4oyieV)t`Cn0|_Hg1}Ot*CTJ4SOJ!3?pkfM5tQAeyawFfnVdlq0iX
zln@iDSxA$Dh((En5VOl~3>b^8Dl`PTz9$K|rlRqd3p;z`)={#u8p4$E#)y#0)s8W}
zmaA1kMG?J-;7f6}l8!$YGx3MyunRA15#n$!j<)<$<(uSa*ZPtx>7kJ8uv#$}b=$|Z
zgkDSw>BQMSpav#ZK~&ZRUNl=GE06|vUQ0Mg_CgJZy-hQ^NJSY;Up$bPIC#Pbul;I>
zyj(VipzjyqPcl(}69tzvjrUPeoEjNZDmqE-trAA5JOVA+HQ(5zx)%RR&fZP5>uS@B
z=$PCSF_VN@{{BAqx(A>6$)CW3?tec{pFR!1*>h)k+u!{?fA|M~!n@!5o-Fu--cRev
zBx?-DI6{o1zN7C0ySsaIT~7k~7zinnR7dwcm7IjEx%7vVRbxU(asZ$uUdjSs#spR(
z5&NDm{=7%<x&QXF`1Lpc4zK(5H(|X$umO*L<WsA7F?av&ZjIaC_iifbsJuV&^;Rw0
zXYP5)IQ{PA4Td<|Omvaz;2D|{Ug;?0W0G%3x(=>?vFe8etNiSRKm2`s<uktvGlruS
zB@8-o?d48*TbEl&J~S-9DT;Koy)yN(R$AK$X1v*>MU*l08x?>i8H01xAyyjRl@oL_
z2$L~mKp-Vt7!rC$^TRYERL=3FFZlxg)q@|vZ~gus@RC>F!tJ-+4oSK8n$vvjgFc35
zeC3V&#b5q4uX)|C5@J9_CK+MD8cS6*1eE=~9lEZk>pJ%Lm-I29D)cGfT@6MM?CA2T
z3S!LYF6ON<#Qx?$23<xEhf<wbi=Z{JY+FA65f9^QzUf)~<bQr1x4iDxm>Ij4a}b$k
zMGjm1qe4DCl+``_{woO+&fWeVUiGpc=db?et)OY`^$)xEb*L&g|NN^sdw%CgWz)7T
z=UU5&(`Sy_a)(lMN4-8eo@#RbsCZr0tg_Lo3WAjTmG_kyOjOxJIuUr2HNwj8FjAC?
z9H?f<S{`66P`j(b`ymn~SY$0xItH@`%2lF@)8c+jV;-GYouY?Vt}of;9Zmm%63!TE
z45g}3bC(Aw`E<N<Jo6b(;lhPozWaGUO1s>{8G~pd#>nCy|Cx8c>)rhB|N93#?y-;N
zYoGBI{Pc@nLf3Vr43kI#-dd`<W*K_UpFhve&TdW+s$!kPS2eZqEV~YCEygLLC0r3x
zA``n-T2VElS<-SNl7LY&ZsPoX8ZTTE^j(W{j<^5AKj6KmZ<iP`yzIxH55SGz_-**A
zI?~lV%ChPe?yqSn?~)ma64H5RkW&5{6pHtr?d>hT`5V6alAG%ZU;QjjoIbPep<L{I
z<;n#`rt$XVZ=2#K3>M5Bl@gPcPj$bK{0PpTyO7m}tRi=rC<Q&jWB8Z8Y_arcQ2@n2
zN~xviJe-b-z^Q_2!WbFdFEeNkSygsLWKEOg64)wf5K=6@fvm+egL{`_3>`E4PyUiG
z;QWPMUi6ArAsP`3DMfzb`Tr4s|8UcHkbp(o^3t1so*SR~WWMN;pU*3Q@ilnk0E0CK
z=R6>sIdvK%mdaJMrSunKr0;uDQci4bu`%Dscz~2${;unBrlMW$=W>Vj7-v^iapO=U
zV_sp{D~9|{&;*+AP>4Ci0I<H|3m$g^8=KqgFZKa=<P)C8iPP6$tLn%YIvoz`*91r>
z<|x6%YtK3fU8YBqt*0@D2Yt)~_?0)jiT(Y>__n|J>$hEzlBtbw`@7!Bsq3yEy}7}n
zruCw4{y!CiBI{w(s<dk+`6V4AbD75JLcx>hx(6XEh4J7AJ%Fb?_KVO2FZ;#Uk_v7@
zr%98cvNXgDlkBq*y|lZ2DMg{feK2>?VJNvF(KRJ@XWV<0Y@$blC6Ys1&AGCi6gN1V
z@0+_=ykd?l^2j8ke=v$mqlHNaN-#!1V;}*>818egd-917egNO`pZ-sjl-;qEiaSyO
z2HuxzFo?h{ulZ%Z<6FLw-}{3<;?`SlUDe?wyK~-Ht~qs@)7vN5+h1_@>{%}C>`*&T
z)y%m6M}IWddCp%rkBG%NN87ci!ro%Rt+(G!7b5L)0b*#H4KNTwAclnVJ|{_wa*Tb;
zi+}X{*Y3h2pLpYV?!R`+%X!>a{d@Z5a+35Mx81r$mQ@+?un8<rLDQk6;99~k9k#S<
z#{>KJ)vx{~p8SL_yVINWhR1vX&8*=^UieBr@_`RoeFoEWo$QekTg%1bnBjY)lSJU;
zPF#UyR^Wy&`yzh&rN6-2|JystIju_2s#+}I<Rd;rTy#ZAA@I4M{z)kC#^3*AjB|Hh
z_*p5+Bp_)bvjbQy1i<2~!O0pDM=nug)FXdB`T!;Sl5}G2r<&UsY>Cev_Rvq{H-GOB
zY1<Al`J|dzgER1L|NHkNDPfHvrG#q8=%Wz%{XhB>KI79K%CG$D8xTpkG-wP)42#`8
zs=8)gH&oW6eLzD%M3~Pv*gboes-7Wzz<YzufgrQloHHj+aP2i`xUjd!t+(CIg`M4E
zSF<Lz&Q9_jS%WV2vnBuRM?MAw-uNr8W?8KJa92`V*}#AQjIZG3zx1mGh9(!?1k>c|
z>amoEcLlrQNTKHl#G%3?9{yPvb9pPZySvBc=EmC3e&{D}E~TOag<dV1KFNW4`nupB
zycR14)wEXco5tWj`@_$@?0J6MH+<D)f9Gk>{O(cf>MFSVpbGs1uD=&IKITyXyz`&_
znYX?3U5ADLGF1UtE2=3erlK^9XC5MAfRI2<w)jTwOf7l^tJDK(VE{zv!BSO;w~Z!@
zDi3+U{rIVu|Kgb1RTSqv-oOuh*S7=ktnd6DLI|VFW}M}3-}*M5^w>x9dNT<pBzpv^
zk$%}CNvSH&$?Ywi5!$XtM7Z_V_tDfdVhlLvF~$&6Wc$PkHnz60M%bLq=r%Xm-PxsG
zF7d@Hud13p#EC#h`q<|4vMa#}eFwlpKk*azg2z9V`R3-h@l%Y%7z)a8t@v5|rQzY}
z8a$Yi;JPfZN7gg(2aluHFUxyR2$8BfTJU2^-13XB<=21X&Ft>&v9-0yzx$kr^Vl!@
zVyrPkab@lKt4!+Qvf8j(l5eRbcMrSNvbL|axG1Zdd|qGi%;&6(N;!^5z2Xs#3Q{ND
zsemTor9b?=2l7xWz|Ymr$}38Wk<*(E-};QF6<i8D>lrulZU5;<IJ>*Z5c4}*U5JrK
zKJ3%E;n81s$=`G402K02{dFxy(gR|DuuhqSIuRKYhGQ%@gfIx#oIc5IXU`$V;7m3U
zi^V>1B19=AR8rPb7($HPdfRQBJaHlmkIC_Bfr8_mCxk%PElbYA;GCiD63b=FM$-V$
z$4CI2bA-@y;rzM$*}!~ji+NqsRGtu)1q7Hq4<;6OdgZhE=8;1AYrpU^9{W|_uy#E$
zq+CfjDs4Xq_n<hZ*?&Ev_<tzg*GpP`JpfVh-qH6xRdsY}?*%V<DQ|l7?~LE??CkQY
z*SwAk7j}5YS3VWQ<j`$;4mx;6OsswOa0V!MDz4|6(3fN_Q|$c2haG-)C076PweIP2
z)GN;9>t$@A+)1ZFQ=&4;cYgiT*_wD$Tbmm^`|F<0v!DNC^l9j!xcq4j*A!FamB0LY
zcF&*XYi_*Z$lv{$n|}^>l+YWUmh%q$b<r!vteMGg#2D6m1QEen!5V`#u-IFITYX?i
zVf=ML%lqq9xuztlL?CITi{Pz8jL?Oi7z2F>M2%p;Sc`WKS9??=NuiI4K6FHlRCR+<
zrJ2v!+}NP&6V^F2k$VI*XG-%HUUeiGyDDoA8#MHNzUB}Lpl2u_rt)PDLuUq0U~(Lq
zh{pHJMI$cOdT#XaG3t79%sNYqk*7WV>)G4ezvQNR_`^PvM}EQQa?7iKnK!=qw|M+x
zzodk9x)P*`$=0bqqXQ7EB>VJe>xb&3Kzua#<>@zl_ay`~tpQmmZ9F>hoNj)8vG}sO
zVLIGbuAa$PO{CEA%x64>``qiEhhD$Wy{_Y%zx+x3zzbf6`05J4KdX?%*bH%h#cN*6
za&L!k`ueY3`<<VB;fuKCmtVgEK&?QLmxvz@Dgj-+C$Y*Nk3Lud?hN~)Ao;oNj&qzj
zb%GdU&X^~~SUIE-RTG+YbobAkKE=6n=SqW)89SQ#6iJ$}br$R(iDlmsNSMlEYmZv6
zji;VBh&Kc+=s;1#3MmE_i+xfIcxTZRh<%U7P+aqp9W5^NAkaxy+3czCefF0=VN?;r
z&yp$;B^~%r57g9Evrr|~lIJMc>moRb)z|p5p%>vIUphf%0$5|mzkRv&h=+d`*I$1h
z9`;$EK}yQmbLS>rgqFsa{9n>EDy>w2QmK6Q*o`-I=S>2IloBCjMP2R+=?LNendko>
zC>%Qe?DL<Cs^+7>i+||3DDbi$dM-CV|GDcLX9&O0i*{RnAYJ?z0#E(o&*Kvw@}P_U
z-X}cd!93-QKaUvtl?Ql<uSCjac4MjL8*HAwhF^I78~EWL{ju?H{=`qekY9N1uW;>k
z_rk%@oHKnCGQnx;0atd_p38yEy{KH&O|sS^Y9J>5^6%cx$35r)yz^b}MpI7kSuyKL
z7BOpKhKTU74|*VPd;34+GLj59WI<CRYM_rj8kF6=J(kO5Zu}9UZCk3UqTk;q^ntcr
z;;hXUU6q&=C6c-h?+hFBIo>*!ArMrs#!Z?YgoGJ!3TX|`y7Fe;_?lPp=&$(twKAL*
z=x;jWK3QW(nli>frcQKDdZlSbKo3{yFDt*gZk7AK$9c!U`<#dK+SmOWBEt0_ejon(
zJKo9W<_0k)7K>c&d%@4Vj8Fg6hw|IM^LuP<Zt`LGzE?&+uBFG#>K>FXPaW}~>*dG;
zK}y+oam`;C0AI>_OZ1mN>p39s<<I(Vl*ElUeHWnIc++!Gfv4T{96)%=P5Jk3xam6&
zB%^h#Tul>v9~dD&%GxV2^!(`0yo~Stf#<Q<IZq7zn219J>pb(V6P&pAo@|{ugYiBm
zxaH!=j-d%jL@?en+uBAo@v1lc2F6;Ny5=>%`s>{L!>?yH-@s|gZm;u(gI(oQ=TO8P
zx`1gy$*7s2*>uu~p<}U61dJ7a>yQ78Z~w}t@TULr$1K|pGxQ@*c5l70LAzX#V!}GZ
zyl(i{pYkcZ;3Y4`7Vn_zV}9Kzu6A_G1u-S8$uVr#2f7dmF|o71gY~Z91rjDfV;q&M
zGln54v)L@efkPy89cnDi#+>teEp9d&^Bz$wY3OqngY%xxeZq}gd(Z1eECj&z_BQWb
zEJsDA;!xvIv4<XDmvmJy)x)ruHCZn%^wg!Utjl=>O)DI1@iH_iR@OJlvTbSVnkPT;
z%ee1Hd^mj{_{`7zG=A|_zsx6n;>Yuz_r8z+>&IU}O3FLl@sGUY9sh_ihG%}$*Wta-
z+y|zBxyT)!!}CuvbT{VQPEMSqBQw+k9DE432M<w2OYMFY-vkmj|6nemKINuobMy1R
zpBrv^HZOnv_jAKd-^t6L|9w39rswc;&wuWC9M+R>dd`}`8oYZs6rLPi)so9rzDi@P
z94+{1)gVvO$Zx#jMOUOezVz#!mGAX|W(lJ@t=Zw7qYr^Z%we>5)EgU|y!M{F{>{J5
zyqR&&d)=GOjV+vWI6o#2(vdo9CHU!po?gR6Oi*oyqyIFXXpWHI`R@1fr+@txzWmF+
zn4kE$TZn*7vPM=BV!?8k5ajV+_Gte6um76cZo3`pY-#dgEpE)HO@l}(_<12l=%ZqM
zRZ5M3aj3$w?TJzG)>79MF$CJhk`yD(7`g%g5^G9SZ$_x-Xz@{`s;IGi$A9=*Ui^w%
zP~gR{xP@={@+b4{-<MH)Km5}#;na2a&gXSR%x2b%xvVVo)KU)~*rZ2b08wg54i4_L
zXwHFn1I7u9{k?IMcU_M$8Os3h8K3?sD`ei|9u2_#Kl-D%_r0#;O~3VfyzjQ#x%a*9
z$s_*FXYdi%-)9oyFzJt9HycSNmURt1sB6(>8XKNvg%Xj~rBACI2t4ImpFL*cZ+O;s
zpeRqi>Deg4lZtR3JYHcw{6IzgN|#*H+UpV3@TAJ;Jn1WF_xB;iQnpMh*%84QmtFRg
zrw@IGQ9b-gIsrUQurPjmo6XHlHtL$nd7Q}rHRtR)CjF4WAJlvY0)Ls5qs%4lOHv(A
zSW#|%-5dDUuY4+Bcf;fO*;{^zuxJrYeD$-wi@L5xfo|%Wr#${KY;J6D%WGbPG3!te
zF{Y3%3_6!07#Xb;QY6L*s>GC&g3jA9d#)-N=jhuG*VG`I2|&CfEO)>fn)w!ON|UQy
z`9g2F`DX$6!l!)=4}QS?c+U6#Am97#&*a(P_k;ZMqaQ^K8O>ME=U7*P9KErIRtPfz
zP#t}o5Q9v>5{s_Q+yzCEYf}2Yg&2Xv>60fpTh}a?Er0u#w{hQ(xX)#`^!+~SzTEGl
z?tAFxx88aiakvgWxcLue%JslO4n`fT=C6w;!&Wce{Jd=OZ+O;s@bVx0kC#0EC*AZM
zUQw+6ol^qu2ghD6^13M2J7$|(RCP0wjR>jqE(}V}V!g*ZpSu*-aui4GpHfYuBwUjw
z5QDEAm9x~wjXe*lin9!Dd&<E!5S7Eu%-!ieFA*z>(Ds4nz364!@Tkw@dEfR;yy^G;
z3xD}nZ{@Z-?!Z~gb!X1-;E(xe{>`U-3V;4rf5R`l`n9ERewEc{Amp&n#R!^+NeNNu
zLnIc)o!rdhMjA0KTFM9`aYxP@<bPM*vc0`YuZjJrq!=(rv0}NDXuabRk9h(y1*+K`
z5zpWL-P?K0qduSSdft!l_(wmAzj@o=W1Zu3p7fP$Y;I#KpDp90o^1|PRR#-r@TkSw
zCpmzi9QKpVK&G*cB1H_~oW&YPZ7uh^{{#8S7rm6Xzx}`Q4PX28yYvj-`@UQG-=6z}
z-18&vU*OnsIpeqHD(i$8Vp;~4E5y%_7QYC8{<m3mZXO~0S7x{6k{12_)vqrixT?ZC
zpYaVPpO*VR(i#R2OfhWcPzXJB^9Mz5q=a83X={*7L+4yhpcjB0s>mb0>RW~i>O~cb
z9t?;MXkh_tGGl*Ml64JNkOietCyfj@f?!0s{+{>X;Sc>pKK6kh&6!iD0J!7qS>Ez@
zZ|4vG<j=V6)>}y_;;g}2gRz2@-09{@EkA^wsKv^ML?0p{B|^-~fYKS4YwC(ILQ~h&
zb&a>#C3dB$!8(WaHG5spyKlRl+je%TW*a0-0i+~S*U>I_NHKu1#Heh~W_-&tZscPh
zcz^!tEpOw8UhoojmL0yC;j0E)RTwdc05+NMuPBv^0B}rk2FF&@N&BS$CM85up%;r-
zfx7a{>V~HF?CxG*<|{(q^4@=XCr#~e*5Rzhh!A6<@;;N0#E4jnI7{0H_LfT$!nvJ2
z_M>p^hu<$V8<lg;=VuOufd`!4_3&PFoyTwJ<v2oFOfCK0T^CaX>m91o7tBR{;B}Wa
z9gU%w2<G(q&7=b{3w|umUk-#EazyK}j-knL-ZAFZV=dsTlybOQIZNd{5@RkIr`%N`
zpZ!(etVv6Jc$s=(nqqs75d1^f!D&d4Rz3Iz8T+e^C{~qP!HM9EEe%82blDQ`b#06H
zj;4@pW|ucX%B7zW`>`|_lM*%mJC(|N-^URhl~VrqY&NH98k`ZT0sU1#6ZL#f6wCYW
zILCYLxC3lO60-_G$1+?*5&AB&*xRGs+a-p8b&h&tli9`=uBx-<z9>9)tT<n^yY4_<
zuUOlmT~#rCVCEh3rlGEDoCqmJV!<?Y%O%FHz%oVzUxc2d%<7u?Y)<Gp7Hvzlv4P**
z<hI>i-hIa%^eQCDl^MYl<|Um}eavOt--DKZwRwyVO7GHj{G*J{<t+XcFLM#MMdiR}
zet-m@IA(CCTn~qR?n%{t#X&|4xpJ0eA)+bboyA#;Hx^RN&n)G#s1p=1icb5Zk4#)1
zpgcP0CJC2p5LY?kQr6ggO5eV$E>h9r-s=RYk}qs%2FW)x(Z^NEYfPRQDZSf*_rjFG
zDXOw)TlyGrM%ZlXtelb(QqO+Z<La8K_MAC&irdfc6tvnvJYw>fu_%H=nHh(xYEq0D
zFjO~K=Mig<%%iN|%=PU3#g2owH*(0SBAS@hj_s!5<kmKu8=DBqVt=3WJLg%p%M3J1
zN-~0TRc0{OMCt=*!d8yh?i0J7F7)&*gudnWy*>693v4qVvGX}rT2Wic<v|~7xgnXb
zGMOvzpa)RXhy1z}eD9D)vCc)7CJ-1sDvhq@kbBRROV7v(;!SRb8~7h$jM#yNS2CA`
zlY)#hvdR`8*_Jc$H;&Bx3midFyLOU^+$+2$`8tX3WKvuy;GIYoM(-<(K!{3={pbV@
z7Z^*%NW?PG<4MYYg93y}DIsF9He2q#4;hu`95UOW?H6>*mXHF*80N;}XESEv;QY>b
zj%k3?%0M=15C_g!tn;j>x6GAoSe26WOGmR#t|9VtolT|OI%5r8=s17j0*n2<j0=c~
z*ad`4RvJtk?Mz6C*k^E3Rn>GcU}BFZ#Z?Y5hGn~;>sqXp2^&vgS(5cMr@6wU*VKGW
zh2Bieq5g~Om4E-7Z<=6Y4*l7w(92;Y#8F<7A@fb7lrqG9l1FmFG&`?riHw7dByv%U
zz9QW?%)oMmH$^CHx|SGAV~(|;LL#!gy^Zr0L0B%A?CtFl`ws6tb?tDzV%fE0ray!%
z)Yj(CI!%gmxz^ov9mctwy|)(cGktfv?1(91j3r5~b+<9n7kHPLETEaYJa_F`fj$JR
zuL|bK-nECG;$=!nm*9UlLR&(fK6Ti>@X?n<pBS5Q7y}AWa+AC@j>>zg+TkjpZ5Oor
z3u+^r*xI7m+#<?ZZrj<(-kFy90LEk*^qelrxCm#~la0j~n9^2#knv}=ZHK%|y0j-g
z36l;h(*YE9*S&(M@n}dimuKNMEBAE*fLoV`;rirI>O%|St~4*}fPQ3T5S~`AjB`ZI
zd)PXM^EG|w$98X{V64kkElo($b*w@;M>o)6jkRfAxnkxB1u%Fm|KuL_fl;2*s@W>J
z2|GtTkAc&oJ3`mk@-?j7qr)f1-@q8V=BlQYSoSef0u;QzqJ$XeyN<m@n``FcvDQH$
z=g1pIGgbEo)82^CYtCo*(cP1guOOf2gjZ3`q`szTRGjrhS5di`yBAXqk*qP)u4cBe
zMH>=*7YQkhRs>_PC5+Gm^<^3IFhgFtATFiw77mI?^@GcCdv{^G*-gKjOv}S?m%=|d
zD9SAKL%&GQ{;T8!p2mnuPY3~T{E^Xx97?ffzupa0TuEisR;x$kH&pMe4gV1J%Ce=-
z)sr+@sTg7w6eF3htuXP%7<0R=^Jt7<4T49k$@qZ874@`#U>!}Ni)H9UDFF?Zc4+k-
zF!Z?vHDx#3XtCIlopTp5{diD}&7P$<maW+)#?<s;NCuKoVlpcvy(#R(DXvkkPaTvY
z=G2r?YouvzAdO1uL&9OdXsCLzIL#&XQ2+oS07*naRCmP*c&L(f5tiSh9AYD8?5oHg
zPJzHD9ZPkgFzJZ3c<)NnSmvEPD)L_cbe&8UQrts6^)m?wK`rSJ!Q`Z$S=XtF?muNM
zSChH&2jI+FId2%<lc}@qB&%;rdC#G28o{JQRaMMpGo-jPgS)=i+Zp@wtIDylvB7*k
z9~onJcK2EK9mM=Qnj)JUGiI|HAp~~MUtqsoV$3H|)w4p)m9W<1y(jkhX8S5{Uu%W!
ztqoL#TW>$d?Ym1lG3;WA)?n*-{+tl;*4=I4AMzGg0%AF8g%I%8GB=hD<7vd;1*|4i
zBT)m9P^i|ma3g>h!HJ=37kGijdS<g3^?ZXCINSDI2!XTvea`G7L@iYfn};~$N)4+q
zYo&&4%Lq1u;G9ELvvSGfjEbet7=1D3lAHsVzQ3lNlex<lzfb)|27#C(v;5Q7g@mM1
zKazo_oi!eX(bd-j#k!$f>rJMK>pP4HwX;|wq_(H;drq7<!J=!k;5$o1h$#_D3}3st
zK<5WbUzB^1KQ$}RnIYlaL<@-M8UtyX_AR3mEcO9?CcuQS@~BMhI5}q+cQv6(mcoIT
zCSRgT7kZY<C8~<I4s0T($bQ?=C#8#t?Tt;ErolHg%f2I}Je9}Uin^}Znr~!mf9SDR
z^39DsIe{OMB&a%^&6~@LfJ7SaII%IKt{XO*nvHY2obLne`3tmN%<+|Rgc3)YyJ@iE
zWjC!}78qg>EZLnl3Q}tNiHM4#rp#H>gq5t^NJ>nhD8P!QYB1Jves7=i%LV7U$b}GC
zVo>X`#^(g;5Ed59xEqt2lv#E<CYY=UXvB)a8jtY?(MSk^5VYV1<Z5=te#jLAG(?;V
z7@L)1A&hkh&O5sOy^J4;O6&#a>+G&8VBHmk5<|^jRdHTd0D*MCs+bbP%7LVkWu39a
z90-z*(%jP_8n#$`5n1a)N0qMYO7=a&ZBs!NN-8n9%bU(vOGuIP`@8Jy@8P{?u~=YH
zn!3tXSaV5AlW_9nHd}Fn^XGTi+1)MfQE5$0p<vrHZr@mgHA)IgjI&f0uDiz>W_{0Y
z3@px`!xFL96~^IsAfa#<%E)?mSYV1E8^s#IN-6*;MN>eDM4KCmq6SimrP<3O3Na?4
zf(O()q6qtop1r=OHA1w4t!5w&O_KREe05lp?fbVPN;fFoNO!k%gLH#*x5P;42Bo_@
zrF%$@9^Eit0+ORU-aX&<`0d~AzOVDT&ht~-eGJ`PQrS5Q*TTbiwdM{nEaiOwS3G05
zykfw|tKi=<jr`bG7u=u3+i{9aq+iK5{Cvs@g4Wcv38r+heI=J@7@G749Qnrm)`VBB
zz=05JmldI!$xRvgBfIO$a}}gI3H6)>E+TKj3@SMl3sI5dKBGEI07HbJZxfa!8K>;#
z^-bIPp6)B@>kX&c*27~E`l3ONcL}gOvEldNo`xnu=TCX#k?)3VaTvS-5UDX8n-1l{
zy4}B{$vh+;H#axPR9`2V;=*?unHzwVoZB1%G$qrG%dyMTGt65w*$Z)#!%#Fp#W}g*
z7X|lo=Wu4W51C3k3+!|R(cgUM2aU{mK4znvf6p;6Q?jG~Ojp|XZX6r(liEkl20fQ|
zFhv03ZG<f9w0n?47upqzEjL+LTXt-<j3SrEg!Ge8pG6~(wd{?RWD?P8_3Qh%-=x);
zzVqmR!Z?L0jYfpFY2#eaL-C?@l7m@sc_Ad>nf11ZF()f=);ezX4$0Q7eN$89FkgtD
zorNT=bxM`2;|6J!;)ucdH{O%cH*8H683d_bTvoQj92fFSJkGPRE}M=milPQsmpGZ~
z+<W%`Nn&+Zm&e%GL~;KChn3~k9hKg@%cmo`07k5ru*f7H>`?RC@kJR#j1C7(1s~Ws
z@N<g#vc$J~r%L5SPY>ki=OHm5yhkc=oVWYnJppL2^WZ@&exF2iVKJ6yE@92>df=L0
zMt%oULKsz&hMZ#SbZEz{RM4(ZLMVWoimao4)(m;#*DfsyP2LaBYUSS*MSR6ANhJu@
zit_01{hRGq|7l9|ehtrKqrF*8;Jd2uCPZ`ULbN!ya*fGC$cqu2;;%bHPPr3L^-sWW
zcRPNkvYY9WQ&1@?Tj(PEG4{O^q>y@0>KTRkrF&rWr#_Y_JAx-L30ew$olUJmDgdFM
z`~&p*#0%z;+s&ifUts^Xi`+?x_Vw{nD6A9RXq^0RJJs0JGBi4gk+o`$b93wUYn94P
z;qa3!evMNFYQw=uKa1uU*c}Ss$~cCGD&cv_^kERDF#J0|<?CUgzDGTwSC}@@Fur`D
z{9cM_d=}3)BZ+2$RR?a;rty=Uq3EIpISpD8-0j++yRN5E7hvApl2J0AlF9(&c}cu9
z@fY{)i>r}Bo}C7ZtGPq=T)A2S<1Aac9!xI+af*6)chg&?*;sDrmQr$;Ic?l42ccQd
zYcQiC`vYghm?5<&BVrsw{B>r{fKXK@HIvq*pfT!kOKkT_4-KK-U|xp#2Nb)6a=iN&
z+IZUdjDC5ZI38Lny;A!ZgKdWIgC|(%5~B?EVYVqbMX}Nv&cs|>?_1Tat9&Ng15iWN
zsk<H)Q8!WP+xR+euI!j>^p8(*AK!aw&N&Q=vfSLX|L&4%Gr~2O<WUpB9i?Q~6gbVr
zshMm-mJY-2^3N@O?N{tC(u-eC`FHEJe39UnC)Sr4FPOdQo|tTC)Fe3IV7|XDxHlzv
zs9>z7xnJTi8zzv>iApt1?@n410Zbe$A#8Y`)l<h(4$|(AC+PQh=w$Uk3L|9`MEmf7
zZ)*YKy2%*Zsm>XX3P|)4Z6R#!-Y!1%jF^k3s9z$XY8GXbwQh<4q7C-Hx9b`AAd^&^
z{^1$1+@iH<b*6Q`FeGj6xB?MP9L99OGwzbxWmz)z#>%QP4{AtPYUac0Eu9F8!wX_o
zVTpNz8TuS2Cw}TD#QB{tsR0_-9{d&*_uS`|8pmuAKUiactVwDc=dM7FCh07~F>v)!
zMLtGP-G1MW2^92P3)x~1+*irz*dz8Ioi=o+-1pc#U+gV4Wb1f&p$Hug<Ns_^$4{)9
zzihq8(|i)*@oCDUo1Tc9s4<PAnm43Dkp8E635+HnMh|-CnW`Sd`OQ%bROYTPcOzN}
z<D>>4sNJt_Y(S4YE}IMKiISC=J!O~*N4}8q`1~HAj0z?RBEZ93{5tMB@+6ykRc&Km
zagoYJ^Mm^Xj3w0@U|qoU`Gcx10e3PznqZeXxoWAIR7%dkS;DHIeLh|m=ZCb75Rd(-
z?dq6&N7-GGmfLxic+LnQmVjv|jRs;ol%ZLXWfOIZY17a?y|=9tX`m!(VPvspdty{G
zCj<O1{qZ<YG*TfLpsA^ypugd2{wV#y)ouh|+w%7>H?I;>k~_R6_a$^IUh5sAjTY#e
zThhHRnBkQpUqaKyrss_~-4*P*Evhpcv~_b<YHUS#Hk&#c`iA}A(e2lC)`5JL=Jm3M
z5g2z-BRvwv42d103qvdJm^6D?Klz0@E1X~$W^>!SOyj$5Hg+^bH>3?UTJ;)Jry5S$
zV2>7NPJYm*YtoBFpI^gSVwT3WXBqgORQNbv!5U-kI_eSZ{ie3WOtD6uszYx^ZGTj-
zvR&gn$=58Ts!nr1iz(R4EHhv&|CPw*)GbkYMMQtfpsoYd(*4Z-lJbnU?=xtTC%?;V
z4r%D>8t<Oce_U~l*jO7Nl;Rp1Wn^385FE~!t-upnZKV&(x&K78)%Q!^xJfjB&PT4-
zX!`Ud<jaXji>DO}&O}wrNm(JpaQcM(r>w2NOvb!w?Jv)grV(N;r(8C_vDjLfZ=Q}O
z3aFp$@-TDE71oJJTc-uyE8F%RMHNz1HuI|SH-4~p@mTnLWqUEP?{RpDxcFzq<C8$Z
zA>x!S;X4&>C|n-zI=2ICT=sikFS}edb~C!qNcAq#r5dsX+B`5F2wDitdFWknn2ubh
z+%5(c;s~c;$Bn&Rp~Ldr`8e3~dR6!6P%`f5<7-yGjikDx=+7jDv;)$42%(E9tVVXj
z{q0<1Pjz&1+<i617)gw`9Q^sa-APRHBZd=DTcgSDEY8dRd*LZ_6|YJaZRjD9XR6<p
z6r`a?a6HdtVoaH!=q*o@B=Eyb6i#**3$Jx^rMK49oF`dJzMJ_YzOgb(x{_DAC^f*#
zk`xKcdYqjP)<mg@+F_KV)Q*Dl8|%3U6sU$R^_A*l+;+wd#o2bau5-aYg@82_ah<vK
z3X^0~M@?huAF=E3w=vnu8naU}7yqGHz`o&Ynx>7aX|pUd^@KG>8*qQ)=~Dbj6zgd@
zk-jYN`Po<_Y7ifp%91ws7w6!}RKiZpR!*Ov)UNT3H0no6ds2x#oo^0e79NWn)grj>
zWbwF7IrI7FH`AA^&BP!jb@oM)OJ26fg5Q{<6}fq)t+{R+qs;-I>B4Zys*#CYHOr8d
z#vn?>Z#9bqe^%v6Xnc9ZJP}q#Z^w82B2zRQH4`OES1RU#Y}-#1=^b(JA5r#I2oEFv
z_HIm5Khi~{Ts5~}h$`%dN5o036CeNnV1`~R+Rcqu6elHTq#@s~B3gjjaazu@qX1|1
z@}})_*5rykaqAwps<RVZ1xL+Y5{F(wayN`0fFQz1Hv*=Jg6N)IY8M@g1I=$loytX7
zZxO=q>E|N8Te5ys2zTBv#zidgt>oP9v?o}?xz+m`e%~RKZQ-P_g~McFS5wZHpopI=
z#N)}bN*93qp07H5amt!5&HS{4#ht3kHm;;j<}qQFIF2D;Dde-Yipnlap+mHBWP_wJ
z@ArU_P*bm4c>}`S50cAVyz;0NR{014s8(fCgT$lmzXmODbXBScHxLmy!g4#b`BVt4
zpr|>2zJd~<kB+0=dMYK$+%EPt2m#=upgmBB>tk(>NWfvE6)|T7_fpPw!fj8s?(=ct
zrHoqlFTe&R^)U>#Pn$ogwE_4(9n&>M*eBE{sHA<rzPL7j6~M4n5NCWgMa_wwhSs@>
z^Z0{5t*ovhe*E;)hv;Cy!j@Y8uz?y>#M@|jv@Xr1@q$slF8G@yy(3a|4Z8OC@8?7|
z{iWx_4t8==r46`^C2XN??xF8n#sMhInAH&gZ8MEB+@nr9szDaQMQbg+V-#aUay^xQ
z!jg`hdaZnX|121?5gwfTYGHn#ymLImDjeq%a&yB-{)l?!8j4y_-=M^kEgAbIt&$ve
z4in0KdS{$X{|PkR)Z3Qa$7YVR|4-v@tH=H_da!1>DmCAJNRH=x3y1~PcT$oI!B{-P
zjWL9*wuwq{EVz$Ok)lJodk3tUi@D2ihs$Gu8S`eP?;Q<R6-U->2cDD@YYUG5TQ?`C
zsehrrk9}94-*ZYdrY*M>OtTxze{>o8%T6OTk}kiIRPYw+URvRvwrW`Oc@+rK%^TVj
z%L?O@{y3f>ePi8arL=ITVWpmg%DJ~J#;q?G$I4x;#B;1exb2QhQyxfsf9+9%t<&<{
z(B>QNIlG(~N?$`@Z|Vzq{DK-hF9Bf%%qf}3clClsHOo)6oNne1=8kiOLDeP~b0RO*
zz=-(C<nJ3vgpdB5@9#^kqDp_|2-G-!rgoj$jmYWeZZl$Afk5boqxjRt48x=q-`a$C
z+EoOEgW^O^9#4{hiS73}nwNs9o)bnxey0LTHnjVMmXx2#A`w!kaH}%~QLvMBrpYEj
z$LApJR)C~iK?6uQx%P)Q&lEI%NU;^yaH!}uz_P)$`4R15dbc}9QjaY<ppw9lZYa;W
zL3(g@;>eNJTnRPP<9A|kU3z!0`rhW(g@ky0Og!QvB1&{(!yR*^1=J&zDGJIGe7MUR
zKYbCSZ{t5${Zn+Lpum-ArVK~ZwY!Aza&(G(jA%ex3GAH?lYI2**hm^a+FBB0o+VT5
zXgaws(Gu~OvUf_#g{_U|iWbQUro)y;D<GrJ@57eNE@bh4)wM9`hQqk~Yw8sB(hJn&
zC$<*@>bgD>*h+ynzx}T1(<NsousH=_6dEJw17iALUc`*o_NG=+49l5e(J7g@;ks@*
z3xoJ>Mbe|L_N;hSH9tHxSOOXM4MIt{GJza@Q8n1Up=*xc2H#a%f1PY@FmIP=C}?Lg
zZQvXig(xXBH`u_Aow^T7#Y0;nlEba`RSUDFm&H6|Hgd_FUm9K~=6cVwSHuEvRmeFb
z#2BNIWuqC*xr@kcST=VH$rx{FC(i>;Smw1q`UiK`HDopNd4DwJp{31fy5hus$TQ)d
zORTit1MXZciZK7ej&2;oR2z2#n3##+K8Vm(C=Y9=3Bsh37$a3=3#*9jT{0hqy6j6y
z597ZX-^k{0`&hWio>PC%E##RCX4>S{(oWTnQ|wMRFEW-^-lZJsPbrzmLN(RBGPbk{
zN>oJW`_TVlA}hbDylxvCId^hGoeOtE(H%SL!sD{Wg`ABmJk5N529E(sQ0vSs9@(k<
zu24KfZhwyU&c5icu@X7s#Xx)`&Gb$8Qk6{Y(T{hPWqNVx9f)7-Q*Se0`1Smg@f~&q
zq|E+I#P0PPrZ;A>FCEM4Y3C5;jP6f6@@T23aOc|)x+?P+tKka-JRlMd6dCWtHMV7g
zhja;2al{TEu;{NvIX`z2w!7YtnspQyvz^JFk@K~-3ApVbs(i9F-0go!svru^9CH-W
zL~ksqK{if}H;EH%z`~~1A$Y7by|{yMTD=1(X#GeJld7QIeoHS{>^v&DBkhJd#gGv8
z$!b8?N86spaglfJ5`!4#T9xB>D}I^H9!RBa+|<(I+4cipJ2#r`<)3#@`lI+=-^AW!
z@PSyU9cpDcl_n;CxbFy&Qm>;v%MEfs+XI=Q(cWy6OQ|v_`d6Kk(lF#Vq_x^#a;&t!
zp-uFANk)aE4q+;%4~;-_*KW=vKBM*YpR7wVSxrG%qcKZz*~=bpS+}G$`kr9TwQNVN
zyfG45S&g<YQh($>;|d17tS?WPDHZ?X6l_xmD9z0~;=7n-q-NN)QI`IhI>lVf;!>t<
z>hpnBRvk0KiO!BGlK&$f-sfGvyn6M6RXSp>D5kXF_#%xmDv}#7?~F-nLJQlqXUQ@R
z!bFYM3)OF8`Raa&QDzo=79Jj<WBSCf%9^2~60yJTu60SDazqGOPunA;<je;feMO;s
zm$&yBqfF=q-6a`z5GC7|9!{G*vUpB`(RP%X41ySGbK6Ri$c6-EeTrx*Tys-bs(_nA
z4O%Zz&g&s=FRjfl6czq;Bge+eyH6dLw#q!(;ofP(x)avCo7z#H0<b>8kFj)JU49)r
z&Rjs#5isZzmSu5Whu0%*{P^QK<49Z2RXRRye6oh_)QSu<n`uGIdjSg%9tyl@^n8^e
zQEhEyE&<(C#B2?1g2|d4QJ6mx`|~dfa|e&)mEqw>4270uh>eX+B)!=4fzhk_ZFt6T
z;G2Xub3QIJUkSZO`)%Whnjo!T@dc9;0nOfpH;R?h#Hp%4L{Ymz5yUVny<KtlMHAVi
zpKn{2K`ew$BWAxi0qegABBS}}Ur^<vH3|v0>Q#(WKO{^Px=3^Xicrs~wOtDwoQ|y_
zbSUA#7u-h<aNZ^b);oT*=e_qW87#0XU}XkFR$`_-^(!8aFMN~5nZv&P^Idi3H0ko@
z-Q33<eoH#vdP2<VGjAuQrt@dfQogl;4+<VHP$5`0Z6?B|!G4fm^4v90yfHvCtFe}M
zo1(YvpnqSh2Q<ZC8ZDlgZuh;}+}~zzRdz_I<mvO_+w+hgo9ei{ilu8>iJQEa{p@#Q
z&<%zqX4$T#$t>+Xf9`OfnXtY$xcPL&xKnMUiWwjWWg&jYX@5$u@Yl7dDszFHJ_1|l
zrwF55oK3k?2ehB9D|RA>hr!Px636r2KZhG&jR;VS#CC0&)c?1N-&UzC(SWW(u=1P>
zJ~}Q-GdWJtIQ^$Y1sPPmk8FD)=zR`)WwLScgXjSpr`#SUh_WvFVD-G&U>qFhm&$x%
z#+t;X^9Kq~B8&Dt^4l%6-hXI-GbyozA@}^A9??!dzj{OZR_>m(y_Yy_gw>X5Z(56C
zw#CB9^~v16Z|8i5POQo~L;<OIo*!);)lnD!a(+dj4ylsB>)v&Fi81ZkC2-7N-W#av
zeW_ZHv*v?t-gbb`>jX?*HEX;Ywo>_fL+C{p&dhFm*p0gqX|48{`KnMI+=t%Audpt}
z+2G?;?Yxc9c<^Y!lg3C@5hSTaO~XyZ6kV7;fz=x=_oe>$6}}tq;v)*Lu@VAKd-fr#
zho&x38rBDG)Sq2Lp5iB%)wEGIcN4^HFjD#T_BnwC^h)I}$eE^``mx>^s>o0+LnF*Y
zZp3xv<>9ba7-y-CF<P%k(s0eyNgEJWrT+l+?0&KN_!1PjFTCO?GW@ga%JusOu6A~h
zTXJ%h1kDt_qMrpejBA(g1OI#?9+#x72k2*l$MUq%$BfVM?r{{uE9dDnN+KqpBcGli
z9Ysd0@iV@6Fv&>G-zbAjpRK+mGk)XXm5dT~cEnH>(5z^D2$pm@##6;3&No_>P^Q|Q
z@Odu4)>2SU%pX1%GSSt%lagcE5=fe)`^LGfLBus2@_rwEIMYa*(~efr)8K5UFr}lJ
zXGfmt&4v~+w`7KLu@y^x*e`|a|4zoUWw8<Mit3WbKsY5RwdAczG$9(+yARcAom1K!
zgyTN7*s0j7A%+yPQbSx)suk5lK(FJI6RTsMYG3gm)%I1)TTep&+sNzU)Tw#M8<l0m
zCVSZpt*927?Fn~r3zV#~(e^L|884#Tk9LQExBOoeGj)Vy+>>Rt6*PGXHId23D55!W
zO2q?l;de0}vZ|#}aClqOCch0y4rv-?^RJw*BoZc(`NO+eIF<eug?TWM+gf>#$O5@i
zDk?L0$kM)$=VF!ubobxYlM7nc4?Mdek|!2~R$LhGRM2+ZN?vgL>?lx`+a@M)vd<Sv
z+ct^w-vfWQb9h~1kOh2faetysSUT^FanM;xZaBysW*%177bD{m;;_c}dTrKG_T@h3
zdN-btU;po0H`_5X8xj>MmfAMP;UYoQgAbsPpzeevZR5&sE@S>NK-hsIdsLNmXM6D0
zFmgalG4+=|WADjK5zEGL(dCB3L9VAi?d$E7e41vS0csG>?}d{XELP~AB59BCk*Yg1
zU`vPgwjc-QpnqPNb@KhWVSn}^CxSc&6qAIWX*_RWzu%yJimIV`_V_s&Q$Sb#aRlT;
z3Z;NIQF{q{T+`@T?;k9u$w8XB^0&mOgzET^`P<eZa})z3e}`%8LfB7yl<<NgwE$;L
zy32odMDgFzSB2rNW2$dy*ajG7F`fq0wGO%Uv;Dm}<n4nP9~YTd7#TBEyXOMuc7yxg
zt+Y@Wy%tb4jg@FwC;zu-cb!3$c%~+yc7vFOU4-J=$a}XxlN3jHbr%(i*3y~E_Y=6_
z5u;Vm4|OTUx6zGR-uyx&t~WPpiTNY{jjhy~6(t%$4sxuQeoZeaAcqa7uhi^ksD3=k
zSkM&yOM_&E`h98yBTaBTCv;xx$K=Tgl-?bF+DJYpr^nbDq?~*RfUK)v-k*oc?*q>e
zNf|XcmZsu41DTqRT9k$2s|4I=6-vaK{PYn0Wic^IL*NA`EG=-|TMZgaL;x}*c|Tu&
zK3lKc!aDE0Y?X{FyuqN7p)Nf8n~qROOgY_V{5cC9B_4-$fHoW*=YLo=?pe5F!fHkl
z4F0t0yfIr3%tQ`gI=P8)@DC^MGaUcZkQkD@z9^^sg`D5Yh&+j~xu}x#+A*S{QM{6o
z{J--OJ9F>=N>Jm~$*Qn?j9oAqk5&?oKQGVwL9$oQjDiu3uVMCg)X3lb0#WmvKwHxS
zV=%?`Fssv!Yso)oy~N|cNo%>&meG>Qp)Uz*JH=M^z7xW~eOGtX7)zN-6_JPiVDy2Z
z+b^mwW)vEui^qdZ^{rC`;(yyeb)GB$-+_I^9pkPEkwqoCma{A^wE{A+4u}D;^V^y-
z4=+726R%rpt#CU3?VkY1Y-Easzk-&w%o6)AO6b)R5Qc-Jnj_%(e^_yGi9GOsgA;rE
zQC*5cSU%+X!#uX6a3Dq0RRc3kbDW?%vW(aJ3ow%RO96?S%^u`GqUqjr;p=Tb2^VC3
zZ$5HnMCNz?o-R$ol{1L_-Y>njyN5-8@9aTqIr04~oR_dRvqJuT5X@=)iz!a=*N@{u
zume;T{pwEPeg^sfphHsoS1xCB!f+RQhGp8SbzIY8(N!m0LB-bky_UQpGB6PSne&G&
z<d^wXtliE7uHmg73MK#IEsExUa<!r8<nV_6w@eIYf{MVv*(@RS-z?U42d6b@o?!QB
z&ba4ONhHY)7Mr1UVi1GDokM*`M7h|#g8vifnLP&{Kh|LFq5Q!6*X>>L*D;I4zdp}c
z9S=Z?jhnt6idEOz77G!V+R`c}Nxg<kcr0LjQCB8IO7}QTqWXiR{a89e|5~3v2zh>9
zyI*VTP7S&~rvPc@T}e-ww*NUYd94O@{q@->-L2UL-uA$(f?%y{&d~MyOWo`B56(SQ
zf!=skwSBb|e_QJurgDWr?j1SPJBCPJsTeso=a|sn+Nt<Eg@iOx2$NQ+!$`gxZlIOd
z{2u<qMwYHa?p}}6yS+~q)_-$&Ew$~w;7We{MnY8(-oWWKr?NKeWNE=d^UnOY<68tn
zTz8aJbgot+blD;q3o6>IAzKc;!&W*LH0**(t<tKAv9XB^lWreqE==$R+U-ZfMOTba
z7&S3}zZgR>R~<Fh?hR=Ii}}3<K27#s&OTfsu^I1}zHZ%KhU|+&J^**sD2%K|_j}I3
z=ia~vmuEH8%fa1o|7ZSy%U`d(xuSk)fxTcyK4>(3-WO(>^0~qV`wjdqKpuDY<e3N-
zh;x`YZ+~0I?^dx8s<WFA!-0NOzaez(Azbs2|J=QQK@had?g10Morc}M^*Bzd{l8}c
z{&@-AoVNHYcJJD}zWYOu{sKky{c&>QWVB@E>6vQXH2Tf^w(RAJDZzNDbiux`rEKnC
z>oKqe?0vM*<*TSw{nS^*=1h#x?)he`J@Ja%_v|fs;E96|Jm=p7DekB~guZ>f?R`b@
zTQU%H>I=$|Fnu3L3c{D^8y@~p2jw77{FI>EDAtK5Ip1fBKh)=D(zMde$lK0)hL!)G
z9P@$c%q7y}3GBPr^i$*F^!5pp;%Pe4wk7Mvxy64q<h4DNykNum9X7~qL&&tJqfV)O
zu9Ep)MtuuF4m~GqS;lRz2**s<DB#5n#zxc5Q|yy+=np?INnK4xqe(EFdx35Z?|pn@
zdcX8SeBzb8@4wh|l52n8jQINU5@mXSZ7P2AnvO@WI{(%L|GljWHsUq4i4#~9Eafoi
zBl3Bi%OYAgP1fobujPJY%wO!a{Y$U0&eQ8d-tC!E??tu$%qL(J`+d=;OH;@*c@YCO
zx};y5!HaSSSqS+zE35E(e^pYDJfmHkfjnb0Gy{I-NwkG)CyhX$sy9`1TXVCte%gdJ
z_xgb7UF5sR#pai@qbkv`qfXD3Gl3a{OP9c7&^^ES4fJNJ*<W_rmM25Cyu?niX@wSi
zDI_Zjrim#MYRR9p{@!KW&q0ffF!u-g_@WZtQ#EFqZPUqCcNDn(@_GhpRTwrGH24r2
zEZBQXI!0|HkiY#X_8geVZ8P;1|Gl4|-!TjZAF;#X+}%=b;`k5FL6u7SY097RjKEZm
zch_!T(yS(EGzE{p3;E1euf0}9=d+B<&(52m#O@+1%%$w6(viMZ$Dgr9H0tq9l_S6B
z=-I>t18zKgUM|J5`@W6b-0*#ZbwpwXo`rVr_x7Ye!g@b>i{)#k(Me$Y=UD5u?4(;M
zbZr3bQpNpWT<EV@(u&otgTu}1Xk(~nMWm<*(LZ!QdT$Oyia%|Ke~FBQKCrN7bHAQ!
zh-$7gk0-%l@Zr@Sb_y^dyIUaNarFS3F`C8>xqs)$R!QMg)k(N=MUY5JEdfYu`7*F(
zOi?#~yaR%Z6UD|#mC}D|a1o+o4!c($26~E7Aif2{mV(J-)Stf!)PSAJZ{VeX(B2s_
zezE%*(s#}36=9)e@*Cd0@{OU?&v+w^aYYRBNntwGL$*9zvxbqWf>m~T_7tYIXWGes
zwi9~nOT|yCfI}CVvU&TqONAp`MYOw>lVsNFs#|{2`U>4`a=)yRF~)nuj;fVv@<oC_
z#^mO*dgOSwqt!DV(<w-1mHh>%s^eetOxHd>+6#Yc&`U^oe&$ppnArFDJSXTkfHLc{
z#fvb@La&0mb5E+9<@=>+rDV>IlQ>gW<aRN@cVS1j^io@*e#LPyUl&r1(Ax-W&|{Gs
zxS2{gSbo=hW&8a>fOTXp<@|dbJ*6$rSDE0CU+pJp5=HubM9S8jpqr}&@A!|rwEZ5c
zq$-H}7SNoY?MePC!)r)wF2k!!$)yxLie{s5ku*uNl%f3j4vtTPtq#m`)!Z*aXPdV#
zm~hb9h+SsNIyNOiD{rp!(+X4iFS`w-dWpw-TI|Y`p5A7te7=c+7xkrUX?L~~Nf2;>
z549VdqTPFlC%f_TMh?N&&1yF>FtD<-i+<kzu`db(*p@~WccA!FA*$mqRQt8S#Jl@-
zX#%uo>V1t%q3;(zubB&?TF)`sfb+^{9Em?Uf_5zuMf+^I=(1GYXq%<-b&BI*nf;HK
z`H!TZ=Qx-0JFRc-76LbJpF4$2-+R#=6{i#}9W4Z#I$_N6(8W;umDn_pawZ?7(AOK6
zGoV_#4g05s%!Zjo9et@Lm_BVrM!+gXHCm#(diOPpHj@I`O^fl>46tb^URObm9BFgI
z`f+@wp^M*=W1WBKPUC9|<xfPQ(w2hJTLm5)Q>(!_oZRX16?B~0`M>MdO@L%n8+Cly
zLJQ6u&C<u>nSW&{Jp&rXA7giIiQ;AD8Bqp40}2UG)Nmwm5HWmfKjblgwNli#wAF=n
z;?|-zvrYa~ZCe|1BfSuz*S}j|3iNf=gax*g_j<A{nKzKKhW7oCtyW2MNTQVx!mRsl
z%Zu>PgE<+I$c#Vvr*sa}j#uhJq<qHqcjGJ%2%xQW>MusGkd%$kqqr{$t_Gh4K;Um;
zBlgWTLK^j0f?Bo89aAR*GC$n`L)p+~1%}gOtji_J=ZZG$;nbo?(A@tao^r6Z>Rvm`
zly|Sa&QEh-YTIk0ic;_T&6<Zld`}17e(1Myv;fJb6=`JKFg6X_oqK$BYn}ikW68W!
zfnY>hJM|<m&3fNvp2EQ=@!yIYSg;MO+e2N5(%e<6`bvwQ*qlHUP*o@&2RT{`bsHsY
zgz++t(s3GDWN!}nZH}<V$6BKpqhK%jSyEkA^F;vh$^-rELYp0M$o&d2PpWsLh=oVs
zYXxbkA}J%|SlmH-$=b=RohMGenHax)w_RE?f#AjOsZEO8j}cU6gp0|3+U5BkBc1zR
z`|SQN`{%9s0JQoC5X2frI!+d!l4RYa&_uAQ<x*{~=@7pUK$Q5BRTd{pQ^a6!d`+O{
zS5qg{Rey6E8R_Hf-I<FCIlF%S`Kk9G+A*0$2QxzqI>eh1RiVy3X9%Yo_Sn4Uv>N~U
z*}0w#!8b3mipx`*eA$xX_(Gg>K^>BtaTs(S+xx$(+x>SH*h~amV8r8OYQ;F%5n^sR
zxHhqIe(DZr13#1L)v~^^$JK1kUU1oEC6zIjiZ$;9HNFvB@4k%Qq@d5A`24sO2<7i+
z=ujY~_kX<=bNuf{;KM^E4aJB7D&KB~K^r0kQtnLU<;!;-q^3*{&p<b@n{mkzHcx+f
z{vl-Q@lMS;Ik$`v765@==!1RJdMsGfve#BV8y5de2;KWbpqomE8REmYZ;ub{WZQ5~
zxBiv9H!K0V6qy6Reh-@2ZhA1BdxEOo)~dAb&NU_i<DDA4y}WE&3}iLg)iPDfht<nx
zq#1|&#mZM4-4Ev(AD+eRvNZ5zPFnWUtn6kzOU1W;t1eWVrtN|h>~#H}*QiK-^R1+*
zA+=SjcvUZ$^JN#NDD09QEKPd#m?Xx2VsGr~8b5VSqy@)?q~Tk-S+g`_BAuH7PO4(^
zt%v}5cr41?E-ka2WHEklI&q)x3tCU;kiedHZi{D4qiAey))3yojFeK%6&mVEKmG69
zJ`hDv4nqub$Pd|KGa--aKa;b~<ein$d`uDv_P+JL99qeM$RWW*Jcnc_!LhAgGRMZ)
z?vjnetqw6aQam4zevT3b)YjHkLU5T;yK8W2D#3rw*pkbPFPk$LJaKhmwmo5A${y37
z^89J&hoUJ(g|=@aOEvhCd8QY-le}V?FBp(j|1kENy1Tn86LCffc~F6jAc;Sjz0A41
z+W6@j=6Rh#*!Wh=2-((azi|*=0B>K|3>;QZ_>xyr7*u=?E6aVh_XFABq-o{il9-!I
zcJtv~=SCfh|Br9y%@t*rRr6wC59=oVlL2F^cM3_Ar8Sz7(7*7N+1XjotxO-19<Iyz
zRNd{Nv_CNX$Md7shCX+(@apTlNh)F>#EgssS?K8MqGZSWW_bzax<iLCHeX+E@nmp1
zSEqEv8NeQJh#+6Fx?TKL2%-EI6qLWQVcbME(&$SLxfBt~#bjn?2AQlsTJo&~UG-sI
zB(cAu!X4)+@#+biMrWAW$iss|+C#v+B!f2(5ncq<`1tr=z!XUAhLb$#$<1h~6mmq=
z+hY$gx!>m{#(-C%Z(=fh8xTTSuwdWN)}~v3apFY+xz#r?DB5tw12y#EejLY{b>ve~
znZiIG2r;RbBL$Vjvfi2fS~p5<_A_o2s7$;zD&#4!<I84YXK!k341qm*#=rpN^r|@(
zewT1B4S~Vyn6yq70TZErxKV^loP66_ttZbckCl~Y>Wr;?*V;~@jmVcEI~2M<SVo<l
zqaJzB%J3P;P$@&!-ZANX4U8#*mp5bAiY>{J4`#e1U2+>qPC0kYr&Z81G^xDB1SD}y
zx?hNZk{5-+=7NeBB13LG3GB9>BoliU#I+ybK+`Pev*jVS40mhy3i<I3kZDpq1Wgp5
z@)zPZ&$iN+tR#$=ZP}8oUMN~|Ork~6Pvgv0%>?gX|1!l!gwu60ZvBwCAo0zOm%hGf
z@eDF!OpZQ}OeF%?<1FA46^~5XVz~zp#=S|AG>ju@yMFJVpb-Nvk4I&+5gp`a+qU*y
zh%AJX5?$)Q&}Pd6hvD1dsQRqQwvcSNCURve+cp~>!>~I1@44!ZW}RD?mzTc<1oW^i
zg4~qTtmGLp|7UK~($bW*;Zv}<w6wCeMw4K%cPTh`kh1M656?&&&TvMVJD7j!mo3J8
zs_Fy5RgMgLo&g^^6_BHo(~NUO`{c*G{ROhNrj@u+OAVzx{%jQ;9UTGBLwsja5PWo2
zG|Lr|!g_i{t6rWDqd5uDqoD0NJC!<jRjErK;5yNa{^1=w<@BeP>6#KY#Pg`EKp^!N
zx{3<rb7owb(?{25B4Dj+n<k<JC<h@r!+4Tvc_{3WRzXAULQCi&S2fbPEp{JpeQQ{|
z*ua0L$C7V{Of}77@Grao2N9VH-hu0xM@PQu((|RoMdd#B@#T#T(dh*W%t&}`(RlRo
zbIm6A%!2ufOG?Onj(jvR)NghKtc7w{navtVsh$HVN|lmmsZ=af>*^OWz4g<Y4OrnW
z{tbNH(o#CvV)fkj?Q3gmC3a&PZF0pkl;|qi)hS6j)iU~N*LUzhf-fVXjt|!<c=kDF
z&sfxp9lAKMI(qO7nWk6K^oNwLIVG3bi3aGh&Mrh770>(!&1&6xTo5N5V(kOlKW#*h
z^y4BQ9bH`TWM)*jZ?&@^_ALxCAuQu?`mU*|*%H7^9vvj#*JlC!2G#qsS7$ysw<%#G
zTIvt`i`8Se-rU~8yE<?wl9rw>=(dCC3?Ih116S}pn#lPep2*7`^i7VCXAJxrQV={W
z)fshY9C?-6jm4Aj!@YMS%fYqp|G+h2$pydecW0-8%@z<wg0wM2*aH;^Gt;A()O{9o
zhF2~?>hA88>j&#eUs%v?Ui`1NPPWVY91-x5$FsevDRSTGDVwmcuvelB-0#7+rc)if
z-(I31z3I3h=DXmv?v|6Cb;6WH+b8O=hYr^f5V>F6<7rpoT)7$vSv^a2ZNuZU7#J|+
z@$b73T$0eGTHD$f$CKb(>PN?tMkCFLw=8Ktr+##2sqdBSCA(ll6IQTxviUc7Taghi
za@GT|PHA;5v|H_0oQ#NIdxmd9xk>wiKv)wH=-hJ&zk_u^KrTFJt&;Y^PEU6LCMV9?
zo(nq3ZJ*dpYDzE08hI)M7k;JFMyqdq-w;}WN5kXeW9$ej_*U-yr!2WDZ$IvX^KGoG
zhW;1cI2pTV2K7u#$~F!Ijnp?SKg2Y$z{@@OZs7gY;YK=l@O`=4i)_i$j)#~hd(s!R
zo*0A?@?*vEzrK0iR*40!b-;}=tA1Jo5I8kFntUZ>9P(RXAvxJfzb8t!x;G^WzUtmy
z8H&Fqt*zTR(C^6lMYdQXS{BXLQ}{bsWO<%%44g9d0dS+^uH7h3G{+Qcv9#U<w{#WF
zocou8xvJ&PO-P3)K1sB9Ks9*oO|XFbR)^xA?X=E6Xhue03z1BYOy!9Zu%uPF{U%X7
zhzHK?I=VQL9OQ`#O>r|m6PufP|D*CG+US{~e+)?i7JTuCIuCHL7cp?9>1#Ch^r#R<
z47$Z>jQP6&oWe_Y36exC@&?gC#lAeZztc>bRxAa`In^e9Pr)GyM)J_!#0jeDz1x2k
zF@5yzjR?9RtA8n}k_bv#GGLKY(GEJgeGHrY(8=>wloWGiW207Wvx?OZU&d31vUKp|
z=7GnMwXufMk<T?Cks(^4u{jOwMH)F{8Mm0VyKCj!L+)fZ?`1QSW6RfD`zl{+om~I8
z+6$7xGAe4YRd{LgsU31Rx&sOVV~a+3=47l-fmubKq~$sTI*K#4Jcp=3>i8quwi7p}
zKelc20ghT;Eqcqg4QIo6)@m~+w{Ujd>KFY480OCFD@CH<*fbh%^G*!x+OXy!J_q;i
zn?7X%7tICPs@&E@z#U#ES)4O^gx-AFD#Y=!8_pCFW&y*!4Gn#vSYlCr_oL;m#`@#7
zsQ}eV-dWGD8Rxx{jLkZOa9q}^ct!Xj=E)T=NFoezmOs=TT`UAaU$>g_Z`W5pKYj{4
zPrqY_1@gaH6Bd5D0zZkXRkz%!T^PjfwpUo5mhv<l2|5SJnvQNc)VgSlpbq?mn<3Ra
zk!az>VwvIu^=Z#AX#v~=0RfEyrEoU1lA{p(xN^-Mo<0vFU!?&5CG=McdKvZKEj^Q1
z-RF@CO)21@Z8X6BI4}W}?-N3joqfaBu$~%h%6KHtIGWV_vV7V7V9TzeISl0_AtCX}
zlf##Z1^6!^;kyxU+l4dJD*j-ml@ur-=wPzDdpqk9AD#x=p&ZdxAm8^)JafCq?!8{S
z2KC;J_x8v3p2@8HfkpYwSiM=b6IIml;S>Xxhkv(^JjC$^cI8<U@V?m|vp3%vg_kiX
zBJ>7Bvpl{O;tO09!1&YuRdM|O_f7{PhJ|}LYwCQ>(p#8J?DbMC9f{4jXw7c!$O{Ew
zP0zB!@AmFXz(d-;tYQ~KjIS1u>Fgc|hU)^@V@JS5&lUv<jQ6kcO`MEZi*8g=1sk^3
zhpay;Y@KjZOV*UEN*K}o!uy)@dINl&5`KZ0TEfkq%PW0-vv=ffoeX36QD=*0%g3a?
zZ+}itoj3e6d$h5l4jHgGn7RxyL_^DJY<#MpC9kn7^2ir9ch0bcohN(z*h~sGoG+VP
z0t}yd;|Y)&);CB${;3qJ>%6UU`f}Z4zf~8btq)lD?lOi?l4zS@PX*Vs0O{YzNuDaC
zAvZ4Kcso9lCw9{(neW16FHieH<on><t^?l99f*36zpdCk>~$mkf;Z@~I)BlDHEqpq
zLEO<a$fvIk0T?r5A7pxc-X)2Q7$O3es7QP))b{;a`jq<1S{?ryC_(PA1zBGIYXf=k
z@LzbnNqw5Ee}LToi4+^82-pg}zD-Y0yZc2EXz_fH^*j!Hw?z>MWsYk(8$$*B60e0L
zx@|5ds9pROF8~(A*FYb*WfQ1~h5^Wer^|khnnZ-E0}+th;rBw^zbr8!2j3O5%4`{Z
z2E?EDMWFiNM%@APd!EZ}tiYd3z?-$BZ)qAKLh?uAGltsf)m))NG4=mE4LpTRPoT`+
z>jQp~EaUc~^}f_2sBUmI8>{uZH)%7hKU)~s`kevi9vT(RBwGEFhlg)_VoI|Hd2));
zZ!UOf;_<R3Kl`5FgL;M&b`4lSxKA32F-075-y=mhswPB`5lBJ*MF`?}xT&xb%4O5>
z$56nB3S!n;H>DkFD{_)2u9#MMX&L^o|I^EKwgT`UKauuC(00;>Ef$DBxvY^nE_t?B
zsVrTJaAz?qFN)=Z;hs#^7mX1cb;>!X2y&P~6|gkq61Ep9z^0JIk*j+23`{|C>XFe|
zC4jiE6}0Thy)5)nv!enpyLz+FE!}lL^nS#&OTtDZ&tqmpYgq<MrKL*G)U<Zrb{7O<
zdvzJp)Z5JZ5A9u(9NQk6n7Yig@W;~Zxk=YAajOwg>Y^H_;s3RiQMG#qanDBV(TG9&
z#CCQm{(9*T8Nj+6)9r~_kz_k{rUu7nr%wMIWK?7h`6K5bKZg%;i<?Z-n6SoyJ927W
z{0_-fO1doPuF;M;8@<CDd#foP1-KKlbd#h(W^Bw6nVcXOA1`FUF@RDdmx%7Su8Z|y
zou##Phl@Xjif@^ApL&Lw`7Cvaw)B4trbybqFIskf(3dSnv8o(x49U%XJFtx$EXAYt
z6*UC`bnfa`%SXSY=IV8gIOA`kwz>;YO`;V*BdQxSaezy__50Od?Z_hAl*Wb&ZR>o$
zOoQ(B_<J+cd!Keio;sJ#$spIpCHh`VHBVR~XV{X=pXYFZuwPav#pge1rw;d;Rvcy1
z2s}e`VMu=gs#(_U`ozi7++t5N0i>8WXDq~TjFxySyBAYrf|->1DGMMll9hZ8X?Z&r
zf$<ZZ+qRk)@rPpZv9`dYwu>y-i!<=CrM{MV%UcKt!}DP?+ro)>Yw%|%_ER*qW+K`E
z+!GB=O|d14Jyc{CEF|eP!JTe9AgQsVW7Lt0{_H7KA-}r<>!}p`y2PY@!wl|MuCF~;
zPrNq3E)DB-m9Hd_J6V(aG2M$pc&lK5JG1%1gf`(+dUn%7$kDWOSc#joNm@-!Ej(gN
zx2+9%s&JbSW?A$!a=h-r-K^#x7f)en^})l3EW6E7wD0)pUjo?vDQGev`{$c<NtMs_
z;Uvwt=Ch1X$M$Z!20=FM(kw9CwFA3}Q#4{Ip86>M3in<L19sa2NFev%mld+0`E*(w
z3)HM_p#+)?wel#cA4LoHg<7NjV(_#B7fSM-i(Tg9lM~LoKi^!CDnA{l8+?@39}`hw
zn7*6*`Etl*GnKoWhjd!La58PnH>1IkrP|)mGP*d$r;vtgpsqOXq^geZ54#Oyr(ayW
zt8;n15e^*sq`^&i%teYh(ijGJnBOM=FaLexx=^hvpA<zKy}Z6|2>{p?suji~sMRSp
zHhxLpLt!wEKI)REif&A?v>~BF1Z0KGh6VmPoaL%!X7<Sg`HSrj-=y_4v9yWmr=52$
z^&~8H@9}nD7y`qC?nA|WK#S#jmnaHC7VYdAQ#S|f?09s;(~Fk~7u0m)c%2(;J*T+(
zY157oSH7ZC`QnLd_TCB?Ma~1-vD7AIEsST3bAQ=+qQ;CYgs7O&ND&p1NW1p(hAzG<
z%%#BY^I+T8^+BSLhZx;6De<QPZ_6|9Rh2R7!V#`U7P?W*n8rajBO$U#N?W*dwXMxm
zmP4k3>r!jChg>qF-7kuXd9>g!<cQsfa-q@%<4GFKWtT+BD=A#!*nfZPo#GcU?C{nD
zFtEg*I39~}Tmr`pPuu5TUmjsL9+yJN+dmKdB~xUP<#zn20C`l1K6$Yk!z_3e#=n(P
zp;JYO4IH4Ku{+%#O0Y-lSLFu$h2H(~AXQ|XDYbihWsJ3Sd%R)UQJkUtx%*+Eeh<UN
z=banrrH4z<BN@Td(a}+foibN86?Je5TLN^kP7odyyt+d70e3(!NbCl&tE($)n-?BV
ze@Y5i+6A-mR537KhH#CKHpPi3C=_SV#@MwOG-s<6LyVcU)I+#X^VRWJgh$;$aMHbR
zd%b~NT%`9LCkQ9yfh}fv=)q{pVr;)=-y+&&ab_xKs_xS&$f`52iJ#N**SWaeN7Dn2
zXFzVTMPF?3t`NdQ1u~92C;a4)$$ifxidJ$qHjHJ9aT1^z>c+LviTaLn=J#{ITU&>j
zP0mqYt`nb-Sq^o*$EsW&PK-s^Dbexu^|u~2sj`pbPFQKW1@pl~=n<bSZbfzkhCIVV
zDL(uiMMsfmbS<$Mc4i)BrOH$(!`Dxkp0?-FH`TX-gPI|x-S;`GCzi$AXu9|1x_-Yr
zXwSxHZ4HuO6g9oh=#!TS3-@sjrF;`ZN=1hdzE2zwfAD>3bCVo?XwvG+*og9#%Hwq!
zF#-waMo7VuG>lpb`u6UHzkW>r?&we`UnpC!ZvZxq1>A0cRu7rd*-fp*GFRbeCwCsf
z-yNLqKbP&ZCcLR$J-@DB`I5sBqi`A5IG++;HqU5~&F5E~io=f1W8S&pTw6|6I_Oyv
znU<uyFHjc>yGyZ3m`=iTsJ`klPGYbw9uf37<WW*mO3_zM8(#N0WYQ;f+xr_WypwoM
zXL@B0JlHh_j{~=}mp51L^MR*yrWZp`yS-PXMj}CZ=a&8Tufr}Ei}^uaPAb4yJyX;D
z{mqw~cLCADEN8{GQ<`eVGKxs0iv1C4q$Jyhj8qBM_%eML?)j9+goz;Qn_>RiZs%SI
z(x)5HBYr2PCSBEhyGC+)j3lEG1p2o!xtUnSVp2F){UcGlY$)6WcW#_IJ<Hj*8TeoF
z2fhOb?s3DDS<tZqh40y0;4vNhw#|S4)98Q51P0tR-KV)c$woXrJ`D#wu##}L2}_>6
zh~K>nJV*~bC}Z!1lEJphgC5FV9t=F~J?Xv9J%z|rbA@EG_K#06Ff(mKQsy=8&x^oi
z5LmWv?mjW#i6Q3eEX%89Oc9SFxm6xFDW*b^U|ou`tVNbY6il#v*7iua?jTmD4e%<}
zwr1Ae3vTN<)b75gf7zgTTul_YPzRo9Lrm&Vdpn-jMD|y}d*SRp!5B}%)Ti%F9~;v*
zN(6i7VVB9`Hx}JjrR+U|cd+RKBt3oo!VPClhM~PZ3^)`x@nX?RbAPXJm=Nj9t6MA6
zU%sPKZAS4wu_cuwUNCZs@c6EeOULOZ0>Z&HPV-4ns>Ydi<U@J>VO%gW2alE>#_9Es
zUF^Farg!`BTbp@%r{_O+w4EEi-siqqUtZsld)-j`Jr5JF&G&Xt6wgz(<s;#%I{i_A
zq+ICCX;2q@{(WrxWk!65KJXZHXQ)4nBzE>TiFRA{bde%n*0vTUTLsPs%ji;LvxL@v
z0SPe^qDJ^KPMO9B79VAT4U62u?6xF`Djh+bvxfR<g-SC2kOUGAmh$O1FM0ZKkjA?`
zCe$X27}|jyqYfso9Cle3MZI^Qe0JOXxf4Ym7?$dcUsHl!xG8+2AOM)3ljVj)pK1MH
z?d*HYesQ1saRBr-NF4l{1K!RL1bMH|G@ga_y`k!mR@(f(X8{n8fNIqXJHbd4B@9gl
zEc7wdMGVvl7BneGKQxGI@fDekE@`J*?Bz<ki;a@s$|K54=={YuC?xwtCDG}8GC}1M
znzh9KdRV_e(R;lQnKJbqRq{ETEmaddGd&Xo@Auz(bU*Ocx2StYz7I;BD(2O2fX6EK
z=gxZJWe6l#re`457#p$W&FSGGQ&y4y-=r7xoUk-yX4>1>!ry}-*^>+;A<rELMOCOQ
z9Pwy$r&6y$Yv#a0gm|C7gG70-APO|HP^mRpyh_29%H*kteJc}7RJwl6%5GGPTYMq^
zz7}$a@pRYw%4pq`8DAkRil%q>rQn*Zr&qi?Js-Ru2cqfzBcn*u#!H?E7cYM^e+!Yz
zq)vK}8|iu@%S?C~Ej{wns!F-WI^!7nlIJG^i9}qPw9h{d5OC{4s}tLFdvPM3&aj@8
zUdFp11K_8~w#KHe@qzk)$?_|1GSGIH$+g=3v>f^N(hJmO`CkV~NKnHA<Uj(etO{b^
zf=rBI-DLO7kpZ@d7%&UK(seTmAosD}_96ot$E~MTNK%zH36Rw6T?Qy(kP1C{8zE8g
zC^|IHQYN(31RcCQ9(Z*={mtI=|61^f@7NfQ{RDLhe4ht9e-^)zCE@ix;@iS3n;mgs
zC4b}h=!ZD@BiSTWlDV}GLK#CnJ9vCK+3t*Ga}IuOk9vk?X*DmV7%Tt*k%`I)$vw|h
zwK~bY59z&eCiS3C0o$?dw>v}GCYmaY+7!CH7(ZMd<k<I*Ui+37@?QsfUt2_uGQnFI
zuS>TyB}TUC;oh~(vAa_=3b=K~UBhr6Lv(yXMVd}KMTB{~LUPPatO9q|6J<CGNi3_L
zbl>c~>lRlhwyVaTF8+`k9);3N>5~PfRGBD+bA*e31wF{Mdz}c0-<R=U{ulY~{Y)>t
z@1Di)qylemA*Mk=o>t-c&j<YQO6C(^8QugzU!RC?<Y*R`7VWdQ;ZgK2^Xr4@yDe7n
z>tz1ty!zKNm%Zrm^b=znK`;0#PTT~as>Cvgi!R0jE|>$)Z|Ba#M8IdHNZ?-ubapvg
z3P|FvI9R>+D#Xg-z<Js6qrK)4|2k=_K8GnpGOFp=h&NQcuZP0Dk;&z1Ys}^i{#h%X
zfw>g-+Y}W6tff#KIwJjF?C5-47c5ehAv((ib53)1%_FfXs!c;<V@ZObbmBpCnI(Jm
zJM6<UPMMCg-Pu*G%lE`o%CeNHJ%k^})n^^~I^1_r|HJ!<Di*(^dXXFUk1xy(gv;l4
zd<KXTKPcL3>S`LB=ea8bQ%|x(%JmSR`hYL4nqku40$UAy4#+Iu|MzQg#-w$#0V|x2
z<Y#k6UF9p|4L(X{;`kQ2ail(rDCq0!m(3k)1Kv{D`0B!7pO|~UWPXUM(wEaQ{4o&D
zW_Z=8mw*eoMG5&~QZLutqm=bGCH5}WfF}Hp8?75@Q<p=Sn{Y1X8#hv#mc<m?<~MW%
z_UGhZJemZ9Eoc6+)8&bXOxdzFv!oUOoj*wa?*Ws{xT86y0C|}T+&{U>pN+a6@aGQZ
zbH-BX^pkedP!VHhxi40b!<&!;K~Fr0TOCsp4s{=zaiC$LNa6qe1aaC0BTq|z>^?Gv
z?TGeXigo7F$wKV{u0(Q`8JbcaPkYkAFUR{AagpSdSt|Dfx36!lGP6q!-u*u|-YP80
z@B0H)1W73o5QnZoI)njfqz0)$iJ`l@TUxq7K)OUEq`Nz$grPefV1S|X4By}RU!3PT
z7hDaq=iO_s{fT$2y$c~EK(H?4NAFE<+8wihHCdODAedjE-VqRna*ht`J@Z{$`QeBg
zERs8=40B<mgx*o$j`LV6*%4rHejW!7F9qrX_K#VmUeE^bd8tK~HS^2*O8Z&Q`#X45
zgs>lKvB?e^xDSLx?tpx+*~+aUzG4pY8|VjMrA*;LDFTs>`FV<1v3rmw0NF*>_T}cV
z*`DYUoF5`S_%;axpMsGAEn1Q;L{jzLzi+S-q0_D6zf{)0HSah1G8A?C`<<f=Lnkq^
z=pD6Rq-b0}ijL^$mq~AT=&7#>O|zU17g=W1H7x5hA~%Geuuq@`r_k_GgcDPQf3O6G
z=<FYF<-S{KsZhV4Gcl_8+UtbA=_#T0mLi&oj6-LW;9)mb{ME0ra;NisORpt<d4Q^k
zU^%mv7Sx=Nf;(IBn-X(Fq59eDHZ%YqG|gcKno|QMK_dY>13NWvy=^{IZ`9j6ABaS5
z*%|OZmh+<LpCDP=ZinL`RkhX9`Fm4`HNfG(g9F6~;o><wOMa;YKFMU60NCfq2KHLP
zp(!lhGUgAyR6sr%4{xH?f8)Pf2Z?Q5AFEhQiQL-S8R!9HbI#@-f1E`l=bHP2+hj|L
z5}2@&bHQv%yBG5wF;crXF3q}=e7)?+*q4%fy}x4i?&Gn*q<1%w`s!3TZk2alq{EK!
z1w^S8!ha485+Ne7OPOzU+K)-d#`MKY1Fw9B96;h0qo|eB)Yt8G1XQsZ3uPL)I7QRf
zX`Q|EnAG~X#7-E<H*62xBB;1^gH9U>LYtPDqGg`ZqPJgoBQ`P-KFkCnr-Yn-6Oj&p
zFl&tpngDM^W9p2gmA6nP4+TM*EU%8U59UucN1gt!7AZ2(Qx-A9UfcIGUn(?wnoqUa
zWQS0{J~ubF))x)O3zNG4r+>xzUBo+u3-9V~<-s@0=S2Rnafj+p=6l=@6s$(0Yh;ld
zM}tE(u_RWn<X*^Uscc^59gGR1cX9nvyYGG`%zwz9l5Z|V>AW@c61C|znmAH9md1>!
zeUnNxDiTaz?~G-c`npbA?1#~+lKif!l5F?4Bf5+Pmj4Rgl++Nzi}GvxODIibs>N}B
zh1tmwoFn|{wEDk>p>uwelvueCbX{jaT#q66oGzhLdoH^dHx1>(C|Pf+HEC6=si$Y=
z>N*WX1b)B@VFoZ1af;#jTxW6&4-e<Odprm-s`zr>)y@BhqyB<oTdz~ncOlp3D+G$-
z7uPKh?GIF0=03+>tyD`&WM#GSLmCk%nQVjLp@<$t-sYIX97pxq*rG5sR7tkQ-YVn)
zp;5c(AkK-i#WoZ^cnKYFcxFvm)g9k`A!}L1u(7w}1{@?ZV5636<zny5E7)*gW`;Cz
z5WSxu$~_BPFZx5yr{5|I?BA4RJ|J04wGwtb*_Bv=Wh`1XkIC%29^a+Oh9_}AKr)}Y
zU0F^NFsXgwfDs=1zxx{;4}{*ldBc}syN&!d$3_>UHm?_CmLFXjM?=F24knT7=heL`
z%p3S<x`ONun%1R8Zz0|Ws4P8|1k7B|I|=-*sR@SQV0PM2OxV_u$DAJnQWXe9J8XDN
z`CezRUw27c2va4J3T7cz-=bS!h6GOX9X@H8ly2(tl){q8+OaS^KgY51<e(K_qMLPW
zHY}@PcYmYx-O=fQL8C%A9Fjih6AEu)&{C>c+Wwm+nrV^77yTOVxl3x3h2=k2l!EM?
z{)C@@D48oY4W^U?>d=z8X&Dh6u~9w2?DyERZClrdTMz4oO`6CL`A}6idS>F1jjef7
z#UP0Kxh>P_f^#M;98Nanlim&@qZq;mtNuo9rLTTY^7`!$GaEz5S$;S#C>THrO-|E&
z`FGJT9Q!b6Q`HI8*FNL`^ydO`o(EBu>$fYBjDeiD@rso)e-<|AzzTsp|5du<O<!xJ
zu*V=tjT<Eaa+ZPs$lopT;nJ$faop&;w_C7vk1&^eKK{AKI5JP!@TZNMMaj^2khkE_
ze$D$jXcG9px+X>0-JpqNdJ!l_iad0{3QIO%Z!EPBC}pjvN6MfzBpjo%d;QelSItO}
zc&>fqr-xMkGg!mPW}=Oq?J>&Cz1LoNFYK{5$?Rim>U+o9eouWsY0^l~G8DxZ>8P9P
z)~r}PR{+F0zZiAQN=gtOL%B1ZcE3z(So!bj>TVMr+F>4@aB<v?-a<eCbEa2qYGm??
z<M-a7w%I98QI3iF=&JLn+QGURSW0t1r-68isf~>dSEf=tgeUFew~tJ}%F0mj&Y$?Y
z=Q4uYS)N(!|J-EwS6oT=TFEYxB1zhos}#cFRG-eY_7hok+ZGDLclPE@9#?G%HRsE=
zu|3{5J&xJY(J!dH_qnsY{;|}|prUksey$1qH(|l|M0a@2JIj5%(H*sn33SW~YLk4@
z<{^%~t-bQa&;tTNbE=!X2N#>Fva{MPyF4)BX-aA;N-Wc0p&ZlN?G-Y~bkKl{Mm|A^
z?q~0qtF8{r^;ozb|8O3y8The-EsOZ`{P$NFAv`QW&;fgD_f_h;!TX1mJF2XQmK`TV
zZ{+Ry`<2h_MOAJ0%qz$L=C7N)oaULRhBIZzufNcZDXfFcM6>gg*8i5MeHZi3LfKx5
z=;x`NVlgx6$;qbMNWrWf$GdA+lw6k}UsytmR>#S85h>eYUuKqvWFyF|a_e`#g-M!L
zxa#=uWY}2y+BPmUIBgB(nbr23obWtW%Sm7r`Y4WDyAj>_lWFYgng)u|($y{D)nB=A
ztj@~;Iuj@70|Kfm2PeO9D4cY;Y{}D(Pm)|0KsHS!8jt=u+XdmQEG!@6wj5BlA7Qs&
z^lS~cY!0_~EwiUIhg!q3^4JvqWQQd(!(QWu{Z~%1C_@2|ix6efTh#K}*xLSXY57>c
zP&l=>Y9_6e`)X33d>`j2IKMV;oI;lhwEamLcTLWvBucRkz0m2u!ZAYxT_8<|BVcH<
z;3lZ^%bLSuTYyC^w7_x*l_A}0ad&sLC`dx((W)m^)p$f6n*__tP3drs;U@1fXB|ng
zoN0@^TBhNV-(S#uVBN|1(&=;mH4i|*{QUe;+ID~`_!)5cq=@~>M-=4=Bl0wBmZ(Q|
znm;eto<;vO)vyqcxL#Do3ivsB-)l{|;&Q`con`(Tz{1MPio$T5F(hgy1{)@F;XU@x
zOjs<EBsv0MvYuKgDA3@5&=eY<AAYu~cm<4xFhbKN7C|xbS;Hs`SdQQ($NTp-m&0}y
zMTX(nUa@mFb-RC^wNON2Y8vui8-*N;>JZky0?R;nlUWkX(SZ?P(qf43U8WbC*IDkL
zC*uxlBbG|v=T|2S6->1HyjLz(9=l28)9Hq~{ws3tUEK6IJ|5C;Lu`2JvDd$N?4*eZ
zR4VRnbl#a=p<Z?o+DU2bB4YFuHZ`^lF{>U#{cqwPy8l`WQ7EndU4`H47zB6rnCI!g
zmkb-UFG{rZ^>-HccyG@$?lW5{NQa5yi(X5DYM_)aD-vTT_FOFZC~6jLukS=-HsW^#
zN6ivZL!QB5jed8}tLO0Qr>%%UM;Q927{TQQK$3-K?Zt-Qy*B)vFNtA9xBdt(GC9R~
zRx>2Fq@{Z5&FOrm*UvGd-+&ine^z9*Qlk1dLYm4;+DFZJhpKume0^4!$DAkmOi^-!
z9Pex1z*pN)L%FF}D(QZAiSSaL7LWL{GFvLoQzAQ^6%)R6u2@JF5A!f?5=VSYWTaG`
zn2C9feMNAuQ}72>$<k>f+XHmu)%T@Nep4+K5)98Qm=R#(_}iR~y7J)`ZaZE*n*t95
z_2sziZXMc;vQ1^nBC|XX3EFG)%b1+MXtb0%8XN_61%jdjkfC0|HWb8Z#)Mw9BHRVN
z&+#sn+{IW~tw*+B4)Ijfo|TgLdwQm!76C=d|24=c<WF=cBBO+1BgmxAPmZpY_1^}Z
zfx`e=002fGO`KoJ3fL$MLnjHKSDpNHma4A4|LV7<=;%n1TDeZ+h>H*%UNnXqiL{*M
zC-<LjH&$N!W20S*@UvaFW*NPOkE_WAT9T`RpeAus3`vEk<`i)<L5Xqk5;WZutlap?
zcLZpKzz>!cp{PjkrBmJHi-=zDhV8ltMaf8^q}8)#;&t-ae%I#5))W{#?Pr^0eofc0
z?-2mZu2P8pB8Ka2bAt*ABha?MD_AB8hn-LI|N0m-wGl6+iI5gOKBBoR`gC~RQ2PoX
zPWmX5wYBwSn{xA#9?%$flJA|jPgy6@hs4S-#qjyzSr_lHqsR$gw=)2+^0bg80xd}f
z9I)Z_e?4SowzeS?79U6$zc68;31#9#;Z2|G=WHeq+>V7~TU$j?Q2#X#t9}IcZK+L-
zjHPb<4R$WDz;R4MXfxdlO29(2&Gp1)C#%<~;A62`Xt&{#XnXtP!4q?Hb4;!#3J5r`
zL(}ZP8r9jePFLOftd2wnnvzjkSKY#Y6<Ta58_ZY~1(tR(|C~Z*ib{$j7P_ZuvUXHc
z3W;X5e3o2;8PqT!>C?@?hzzv0>r3^uq3+nH&C94AK72BXz5atnVdqN+^1Ii!a_Dg~
zq`(qdzo)*E3R#D|-}#Y&*6J4krz;e!76Y7qu8izno<n(AIZ&-*Ox3taNgj|ViDSG;
zxJHre%u!F3B-l`sbDL>eU(S4o1Qc@{eC>QzsdN_-M9|v>8GdX8+xes4ffVlBc#XpR
zZUU2~T8#rlX-CB}wV$(jHA-yI>e3f)fXqJB<6KI<j>m_&60GYje&439PmFnN+mAOt
zz4297PkD`3$1?Pbw6~1H<L9)<n4;{;+Q$x8Lbi+Rks{;Z8LZEALm|)W;WQ#-1ryU6
z_2_M+2C+vdDZX>zhw%OW-aSUIqPr1kPO4jH=B-zDF0MP??6d{eU47<|eYN^b_;g&#
zXE#<<JiYJZHWBhFiH&vKGt^Bu*gA{2@1r(duq3?%Flr}e^b9rR=I>Zv^yt?OszWwY
zQ+$jOdGjo=8YG2jR`RR-I&I~hGPew!rX98m9Z)2q`<`n(^I=QZXE%siMox{=CFz&i
z9fVap|8qDgMN-u;N`v>b965`H9URz-o(veD5$Pr`?|9n%K}ZqoeVN2ST7Uulo1RKq
zDGjlrCq#CO4KmeB{b!1p%P870r01%FLg`6;+i3`$)(TvAMP@tdHDeNLYv0w?)v17A
zN3yX;6WXZ~U%qI{<S-m(NY5yu4CoF&i-snSEiF(x`I_U7*(b2_cGxev3Kwj|?Fd%=
z#ES?@e9vgbDzfj1%Fi0UH@47G{H!-|J%T@zf(?VtYNt^02nDinlb^1WA>T!Po5~NH
z%Ol~JRGB#eZn~cU8B{*BaWPVja=34Ye_0uFatrxj%KE$YiYfj4J-pF}+#l&vjW5Dz
z)yq~Z{)6%skC~-jIyyN?T&5nG$3>ShT2wu|Bk)bB_#@LxwP~1K0#EU)P(JN4=`+2=
zRGCQaCVa+u3q-ZWMo7k=n|E$(u;<^mfGkeZ<ot~nSvOBLq0qvC(c>i_QZ>q{dMG<u
zduKlNon~3ZiVc5!mup;kw{V0wP67OH^h4uY)vjMas5Q7yrJfJ%(~=)5({~+o$;Mth
zHqKR4yp(q4!<Y<ck^9KanU>3P>?2>|v^^0F+2TtVEq9?z*BfvV5@>d%9hqx|{OG->
z;lwe{Ji|V}fCd?BU!YWj(wQQGUyA978E+EDZUcM%FYS@E(ThPOiC7#ut;yB*vV+oK
z!<R5t$3(tft<w{s7-Jlta`*9Z1n869dr7RM4!&!E6=srKCu&ub?k1?@6HrSe9Z!TV
zT74yo;t3SeO!5^j*{S^up7Z%g2o}~S4krE(URo%Xn=6;#^==H=a(J8DFvpe;J|>_)
z@OcCr8`~wWkc&L=k_2EDdks&oqzkX1w>L_~aI_)RQW%%)Qc=EKR!pd;EU;m+&%MEP
z<b1{`YlemZ;$28$YMAN5mXdGcy%QSVDy?8g=s^<ly0qf@gmw7Wo(nj|^dnPZP>QbZ
z7>o+qsaTL<-2BfP0^yLkFW}F9Mlw%|3Q9iH*p$#S%+bR`DhY%1!z3ZX4d8HsFsEg$
z5bDeG4&7z4c4Vw=GZgH0N_)v%0UV^P!jZI3Xwl2zbo-8vGcZY;OV40$ESRv!Nv2Ue
z@nUNKd5h^6bnG$GH#o({$(iBlQx;ugrj>&E`9?}YUkoewLvo?u%u7ZKUoH#=+s`XT
zg7dG$DxT?Mg{fD|lJwR(l*5}gJ^%RF@tvd8EvHAPVAjpzPI_42-oRAtd%NT_7~1#9
zvCpc3nt%&S-$cJu<BA~Ea|~$nab29Bla`%}LNk1Q6MBAx5T8FI5dN~$D15b<2>iSb
zM$T%YAJHwfn_|Es^*5V1Vs>T@0m-7-RYKoMhvO59t`wtPq;rpMNlmr5GL*-`l~qkW
z|AvGNyLa}}kUfLn4-VLqI2<tWcPDFh{#lLXjGu@%DC1%UKJllWF0EyfC*GEi8o~uz
z#v)OH?IA(nBpGo>SbyNx={K~r3`g#8oUBTv9xZ-B2@2}V4osD%oTY#3SNP>Smq6Xs
zMl`L@yBNS+LbPCGswa}9SbJaMEU>$#2D%!Kl7{|Us}ESwF6gFOIkoGPcLYv|){Cm<
z_Xa|ll}$}D>6^lS2RN}J=Riq04!ss}!eCHL&nsXAn=DRP!aob802Ls~TeT$cnpXlS
zTD*zrB_UHg8Dw3MANB}QVEN)DyXrc(K;+I?byZaa0<&Q6?eOsM<59hZU*+Xb$Khw#
zflmra%7M6m8f+hS6)0_Ckc;?GNLnbzxOgsK5=DQ!oTW=kE!zL9&^On6z2}zR>3Wu>
z{2rxvJg0-wovyg|dsD@hd?>Pv*Z@WK8yn}o0-<51PVVosd<y4yRfYZ=>-L`xA?d4o
zou^xphy9%#m!!iJCu9#@k*{O>QQz9}{8-G3qH`<QcRoc+{tOWAl~2FpV=Irh_rh1l
zIA#**@JT8ep_c`$WciJZeZp!e>nI7buqAOHmKJL#Ye09SS~L=bG%Zn;sW)f+_WxH>
zESC_>AP<blQ`(En`@tL3Y0z<he=li@YY`^8!SEc`>kKG(QU+E70dZ6!*v8<_lKrkg
zGA1a8=G4c?t*>*7i{&GnsNk@eibN$o>f4vJ=qQmmVG%r&jvC8^r_&Lz$dFDa9M*B6
zDw!J@2zfoo-cMB1^<;%$bc$Z1Kss~=EnpBw<+YYo={4!FYE^r?eumMurxKvQcCvhi
zV&x)jY)7ZjDdg_Xw~CEE#(2mnx3tmCDVafWuy$fn4U%6gJ8My0SJ$`4Yp$uSoj+&e
z<coZ+EbN#zdZ0VWCvZOZEik*+NKhz&q0@DXt~C}lV;ZcF@VmSRGoCaDlzGep{*-oE
zIH<Gi^Bzp~W6^GY?{nE5%a!$UVCcJgwS4J9pDUwh{E67CHv%;Hljq^Vw@dNW`#+~9
zU2*8xc}C(-ds~2^*@r)^Wkv)mtY<&Be{<GU;VuJy(~#Dk310t4@iigM@Hvy)k8+O<
z!FDmb&x*?8p{m}`TM@8QeO}$^&%VuvzK4Q4f@8?59{GV3ZGl7z^4HYTo*YOdvSvZo
zOEtm$n1qCcjl%zSW7;z_df>)%9mJ%l7D!{@<dm>r*Bss0C<rc`9KUok?9Z}u^X`%F
z^Qn$bj>yrGZHxda?S|0uMtj;p{jEilRfw<c<4i+8naHtoNhc~vbmmQ3y^|oXYzz-Y
zU`lE4+b-0_o4!UNFWYcvnxE!srhD%+EUtiMo-=@u+}I+FyRU!-DYOcT4Ab?3fP<6d
zN`6BOr}2qm0|NtlCH8z+McivtYZl7<f?_C}w%A-ob;(a9u}+K17UCpnYn81|q700P
z3(z!Jf=NJ-RSXWxbbO3!jL<~}4V7I7)Eqhb3Oo~Z$;H<}N_K%$^%G72%rbYrzb^ol
zm;z|FAq=%~J&mK~e{qyIt#8b#!{yaF3~WPtzx<YxRT{XtwDnrG*~z?*oATH#DR$bW
z#pGSFaauYPIJ)AzW1iyW^}eGjhX>a7;6}Y&_W#q|u>Q03s>|Q+s={e;xTpwp<2knV
zgC5@;UT5obr@gXmo_e3x(1m+GK=T6`uLF5|1uP6(@N~=7lX=*|#G)P7ddoGt_~a#5
zUqaefz6cdbE`I(Yi&n{6h@^Em!V5hs2!hX~_;q8^|E9g&Y0d9}OYc5`%(?4#|4G`I
zf7ToOrZiJEweMH6{;M0**H7&IZrU9;6a^5|H!Z84V})d)-!JBnVX=4H_3g%Yp)dTC
zH_BmFEf){1i4RwU%7PcX*=w`j%ZVDTx28RgBNcvk8S8I3XJ4?qv!u8%ts`#ABwQf~
zrN8MAR<n+VSb<as>_{mXppu+8zfBrbQs4b$HC3;G_DNW)^9t$}LvXMF(TK*&avAdQ
z-z@yK1${@`cefIY@XHO4)jLH09H$?PbM*5k+I4nYC#)5l(G|WgIKA$*TK=8cFPi&y
zRQMgh{cDZ=H@m6(4(jdKZ#jL4z9?qYS333LWSw5}Ms{${(yM-pGsB+Qw07%v3`@8O
z5~u#PgDDW0X@<unFR?X<7N=P{4(1gU{1fqNxFlJ@Wr6*xlqBQvNs8zP|JGG2%)+I+
zdkNut$JmYLm39yE(`UbGzdwX<IxRDc_N|4LZC$^y+mu515{TXJjd>gm5^UzYE1mOL
zu=P1vRCexG6gX}%7mEzbzE^qj$Ky1=VYMsr@y}ytVR;A@eC@WoCB%zj1!ceWm!Lb^
zV%3W2hV6OltIfu2vxW16CqBEah_$MRJN-ldNnfp2t9KdoHrt6ie(Bcbt#0+k{*O_L
z<+wUlioLs?)IYlH&yuKx<WAd>X?S%ieR}&!cnp5CekE7(&Hi0lw)J?VBm><_2t917
zGHoysxw&1R4(e@6_-F#uSOXHsYMEtJ-~JQG=rBoA5XCIh>Fn7B@+*!*AQdxTn?$M@
zOs%dWP{H`6SDS#)^Esx<UT87J<*ly%1#L`#+cyw>2@^Tx6LmcFv{`7&WX|$rLU`P0
zd!8fpJBr610EINOwm;ihFAS^v|F0Kd%wt|naIIm(qhAm~8)KYxv2T9zr@lR!tnJiP
zD!bD=(?OW}=5OQ3$jH&D|F!J$WfSb^SM{Gi(eh+m+}xep?AmT#`{$z>PsypNInmk;
z1gb{31RI0tV}%pIg<U?SgQM`72^)U-Xo-tNpR`e~FZm?=E0>tG<3aesdvbXoCWV(i
z8XM|9armv3vczFJ)8CALsmrp;6Ze83xrLJ0oiFNtt?Y=cUT(x}MahaqjB3}N^m6Kp
zlStoGF2_g3Msu%xYwymUYx7P2Ju$I%@o;t**?8Ure+oiW?>J|_RNhQVRNlT3yIs>`
zeE8$D|GH)Sh5hEteba+4^)*)Z`wO+jon>bH;+@CjX}C(!e$ue}W@S?~)&s<v!nrZ?
z;*C4F=I_tx#b$@6nM#<}?9*0-4MVtY`O{X8HwX1odoEm?+<;=1dDjy4((XX25|XT$
zD?6POq6-Y?T9;Q~`6yzG67KLI!p1k|6wC(i+7NU$edh<f7A2Kww9!W3LgFn5_Cn0X
z-YRAP+NiyUNC1N1;hV3P!W-jn+1ch!PJwW{2E$k}UVfpWlrrs$%kQ-*))mb$uZB|(
zrV-k0Hm}hdOqXKb=vBZrLf_aMZAFNT`PJDi$dJoi-nF}~Ar9S|Ke4{Y^jN*YqP4gU
z&(P{zx%i|H9^4+yz}^7DMqHfW&5uX5Y#MI(EvBZS1d9A7Ry=upc~e$&yb3wG1;1<F
zAV<bVB+^wmHOMQX4WbQ<Y!Yg%35p>lL~is#2UM+kHL(E|$0GKZzO~S$9fI|`1p&vA
ziHnBrob2!4XDthsrbg)_E)Jh>pI<2Sa)c<zC+yc?G%UOb6=5bVHaFA!ZFHp+%dXo*
zV$IH5&D;A~uksCZrVH_K3i}(<Jv^&pkuhT<qrh5gm{SjtESIRLQp%Q>j|Aak{_XAp
zAr=8Cfxp48(im&ZiuXp8HWUVFSv8#29s8Y5?v(O~lQg+&lQ5Sa{BFDHsXO<Iv-(<N
z#Im*&Qa9e;q%6YSynT*`$;J=PQDGFihkLKApk~lara#iHES8DF>1L6O8h;<0_M7gl
zZc9P&#!vHm=J;YZ2TEhszWsS?_4dnANeTI}LROdGAQ81;R6}L;%U-FmcLMEql*Qj~
zJ2I)fJMNU$BUmf)77ku%cy`)F#l+yZA_HkUTy>KmQi&Omk`HC-`Oq>5N2;SP*~*0@
zpjd3W-$*f3QEF1@O+3@DZ{JsUjbqkVgJ6{=K2h=UL?4K`1w^_d3KcZ@1tmm)&aw3P
zJ43AH+ZyfH)1nVg_3!3k4|Lk5srM&5O7FKwmfim}U!Iza^-ufX($mws-mj^~u0L)l
zMSIT$C9#LU#lj(q+I0>~t}x^`S&;-9tjn#6dx0^`kIK&TECgmQCc%2M^mzG8Gb^dL
zm&`4jA?C<s0>5v2X|J=clbCr$c)PbW^juMs_7=N*8td27Er_DjHSLEpUHtbh?8+dd
zV+->81&M}7ClyLte^C99f?_T`i2b!fe}HlMRQ5GN-AVc=Q?yKwUPTzcWgr)K^qyym
zV$5%^GebbzIiY$PG{B9-v7%dNacg{<^~$(;u;>LmEqhL>j2}h2Qt^2`0TZzghzA6K
z>S2}_w80&_-ODMQfl@V&XVev2j1?Z!c4^0AI*u4)o_)OJZz#8#;1xSB?EQwh7VeiK
z{X0Zr1=EqDSB@NaTc$pj#?&hZ?!N1bNRL0f*`3-er_T!@xAz38$P|D7eo@Mc^Mk3D
z`%(L~t1(Z0>bs7c#)G;APXwk|4|RFNf676w7D`#S=GMIAH(f^Mwl1yup>+D+m>!ZY
zOD10e(Eq9QbI*d<wPWco!<K#L*lvOi)Y`6k;q&tH+ALJP?*GiDEflijspCBQ&Vu$>
zIM&KFY48}^%-r14b^g|0*_*T!Uuf6vIM?@)no!tAE7r8>AHn)#)vmwq41RSs#<^WJ
z%(1bZVQ;oq#e#}#rk=fKs@Q<Ui=xYC^*UeZV?bzk9hjno8aO)fs;n3_-nw}*auu-d
z2p!S)_WiGbvM*)1m(1jv-|z|v4gCw6;o=q0_#Pb?D7|^n{vZ;w;V>!BtV&Ipi&EVi
zqXN~IYIfOWwN%?roQgAbG7!7@vD>r8vC<ER1ntbx^q*2zy_MQW#?~#uxnH+!RN30a
zFe;?PY03pZDH#afYRa&q!;=bTGjYSkAx%VOw^yrPc}KM?>(tbgi%_Pa2GwTs$DpQf
zTzG<O!7m#wS`nGnhh@!oZVAAGbxh5Sct#e<z~WbF@*O51I3-iR>;z<D&qXdV7~CjB
z(K|9$Kc1!iJskDy1=Cij4^XIDJO$rQ|JJwaNd;z^<fEK9EVcxfsSl@OzY#cx-IYgf
zcmnqfY;c66ph5AZJn~G$ReT#oXKz@ps4M|fR<*mXk~%O`8xufUk9#S>!K(^iUB@kw
z#j>=FjNw||>%2FOxwah6*=ME5?-*xHedIG`+WmdeZ;&GXTbnojS_!lTL2yq^>q;gW
zmJnmg%GdO@6xsszx$5N(vH39)IGsJSphV-1+xv*&NM2Qy%CDzhtv+IU)<5muRm}2+
zf?~pWw9Dc6L86LkdB6(5i*CZqJ{Fd}%2*A#c=%ojktDQ+@Eb!B%xW?{dt;zB?4*a6
zTDJC6-{&jJB0>F6sjo=bm{ds)2p3eGzKy*3v5z0&`Me9zhA=K$qHQgVVi+d2F&m7M
z_`#sDApa6D)~QCw%)-mN0J<KaZ$KRPtDXU7mK-P#%py^MT;*ic0(yyo5jl{9Mt~xc
z5DCO-@$IuTVHW4thXHJ<NyG<OaimF=1(w01cwNvM`D0b!Ge>}PA3arXE5a2GELVQH
zMBQ*b#LAL7{7b7gqJ&Z5f0Nz}74SS-V3QI;o2K52Cyt`+%t`7x1I(A<OMcCTWvTOb
zs<OyeNYC0-`dm51h-{Pp+j<Mr_hzqOZVHe}saVyMrIey^7V!-+nfvPmSb0_gyeeG(
zh;kZqOx$s%p!xoEbVdeM;=H6DM?TAxwE-Qh`UR`Jn>)U81R5H9h(y9~7pJIv0`2a3
zDSYGUp=6JF2~!sSDB9slc`#`&2+I5JophrPBlu;K+aPeW7L~g1jugRwViWNC6}~+A
z+UD|kfuq=hJ#hg9r2(5%XZ;J&*o0t1?hUY3C6lWJY#)If*a59ir$iV4+$x$baMiDR
zm=3@BsH6m`fTd++jG8uN8d10B7;wkO$iz)xzjrYX*paJZlN6$uRz8oHBtJW0%DkTy
zmOHWx>Hv?I$GSaB;LD$auQgFAF!lX_!3!L_LSMZ3TAd{Rq-*_>3d$Na=%B0nzn!pf
z@MXNAT((h125UG)@r4RXs|C;CS)V5|NC@4Lzw$h?W@RAl41JM7^E+y$G)dtz0LC2k
z@?*mGv=`GDh1txw4L|U+6{ws}!B}X?%#jHPhcv!6j9RAjWnPHc-lQq;sUz`u{W05A
z^^`@~u`hKYNozwr@+(1{)^JMM0#P5abRue8mu{>TS1g}ww+e;Qsm^H%YhH?I8GkVC
zuFL#KWqZ~?A0#^IPR7GTzMEB#F52L(Twq^EG)oXxdJZ4(r6Yq4^)_FkcXF*_c2=;*
znWi*0K9?8Bo8IRUg7iC*C@}XA{#u)feq&La&Xx@gb>UkuH~%{MmFCEz7CJIQf+38`
z+6ael(7K4<#|+Bb(zIcej-afaiO8mp?7B+dgGb)I36_r{B(`>r*L`AJhGDHbUpRNj
zv+}Rfc7Y#U_+$(z4z|;BXPq%))2a#<zZv;xpFd}#Qu<kL@|#|9oIeLp^P^ppCFRSP
zFaQ2Dc4=-TKA)A#)Z@&Xv*G3b9Skk&YI*_Rby<*7jiDTDWs}nUIz>{#psB#TKM_gK
z(Z2rnAHAteUw^}PdZ}iW3o%RQnTSvsKME87zTGk`RFRPAT+hk;GS^5ta}8vfm^W>k
zW>Qp3snAiZhcOKk$AH$ce%0QdROu6j(oRDJ?f*F@6)jk8crgBYrD@HjZtzitdEYR-
zap(N9hd7VH6n<`rHpY153y{q%V8Fx0-bLAZ6DK1U`2-@=KKUXy@ix2PJ4-f!VPtgF
z@FNN>b4ilI@&HeS6i#9&13K{0b8cRV$)^}Ky*8XR_3=q+yn4<QlLny9*MX*UVnj)h
z@XtNQ8xAr+XBs60uX&0>6@n`*G~!LLr>Ymi^QdArR8D-G4&3Y<Injl}>11U4zcvvy
z!diQ=R3rm;S>4l<=K6$ZdIm;R%2LAf&@GYAfXPFcBbZL^wS#^GCB;X1JK4RFdiO)Q
z4|)=vltj`*j!AUa6yJnK>yM-49d*M{lrwqYmX@|0ibxGr6q(t6Av)hfbRhGr|HZ(-
z#a?tR`NtJAg&cI3X5AVR^cWd%=EJ(4T;V5~y=VDfb`C8PbvaT!_i*()CN4k`G*}U=
zO$HTlbjB))^q-eAivelw|FonAkxpu)iD=JPE{=r><n=6B`>oCviCIVAT=E(Ze3VQm
zy!y0KL{7_+Je&k()LD_D3C~Y*YgV-O%W9mvYwx3;HEBO_t=O5=*Xu)R{j2U*8b@{R
zoAhUqS^hJ2e+1k^9^LlswZOv#nb;w;c4&VQP~kn55n0-}%3+`~pO<<2fE5J6k2$YY
zk7IZbb*W~{*Q-z~ojxIV({(9>6irweMR&f9o<s|wt0pZ$k5RvJS#~BOw;_HhO~fQ0
z?xia^N6&quukmnbmDuVzO#0_;#QgQ^*DU2*fvrVTw(FqBDoh&QK<#Nrr6$iLh)&7K
zL?5eOheM4cHM|?Bu_$u=qg%7hB@pyal5_(rpn}nKC3oHX?=a)PWS%=>->RPR1GmTX
zFzL1wWu(Z_8NUY_^$O_VnZR;G{|@QA34zC~l=22|_Jgo_`>Cmp_uY$@jRX5a9S-Ck
zQtZ)XQ$L#Z<5^~rG+d4ri&(@}RIy0%O|}a$0<<I2a{I2Lo4ot|$~}M0ykYCR%0a(F
zT)hET*h<G6{fqQmG%JbDY^nN%(RZh{;tKM_?w0l2yEPd-hOvCuMC3Ioptp!A7?jpD
zt3UDO%U4+*+xZ?nQcBxYVdaK3n>@szk4eH-&{b$8X2X|1Y%!mLm%d(^WpK$`h7qYY
z`ODsl^)q>!nWZ2_y+x5oMJ2(j%~qxR%&S@6%Ux!%!Lm2}DBvPpzQ~PLDOGP6YgGo^
zFLp3BbBm2huUs<a)6;t&3}~wy6%$T&Qp9sMW++ZpD*UxG$iwG}><9(MuQ%hs;zvg9
zWN{R%h}ZdKSYNa*3lo6$KG-cZgezw76J6*UH!sCqU3oSgFwOA%MS!Q0*hWPfqq!S}
z5cfI<i_x}KxH#t_;o;a6)z!gE9BpvIes1}{^a@^bU@Ug|>Tjs8*4eLs$=$*d7Gm<p
zr=2j2@iNsDp|u}94``*N|F|_P<U@-V4ys&--5|7tGwW8-GmQ@Z<x95bH<;X&gKej&
zsR!J<4^aNOpg^oy_l*6(z~&*3))+aXF0LL&Koqx!#1}^TKag$nHzV)NzUF;ZDh{GW
zlv5sV2xJ`G-|J;`aMBhs#7N}<dmKsB)D#FMxp;UIRz6=Z>$GWfUEKMMzCHI}^}kq;
z^qd~n@2hV^>hjyqRZTg2TPL=T*Sg!=R#h}@Qy7FPp1ZeQw66bTyM!}eKoxls3Bz<5
zo|pIn`swBAyjnRH>TJ#7GwgC{v9~dBd<?<Dzq@+Pyr)x2d2#<Wc6|U3_Vh5ke7S)x
z(J>i5n5)u0LjgOBhv45eo(s5}XV~;Ro`8SdKT!75UcKZE3k+n}u8ZrVWg0yp%J#Ww
zo%lwN*Bq=GsDg7~(d8B__hKe6sWGEGE5mvf)EI5o2vB*;PK$*$f56|Wm)h7U*u_<#
zUb;5ulRfULTQfs$jMe?DU-}VpL_|gV$V7dYk8YgB?k9XwPWE>uXHBiEaty@(!tqkm
zEYsIL8NubU|J_|M!?9tU$fn(v1d7qBx1+R7$HTNbJ|@UEPGrb~mQ|XKQmB{fV07&7
zv$g8QLP{iC^~T^=A>uiqMt3vNs*wa!>|){ds4k}F90Q`+20sxpe`INQPAa6zWY4LO
ziFwzpnUBJGWMpI&lOqh^gyjf0=|<>({2u&4HOYPFGpnoFP7!w>&-?eX>1J5Dp=h^R
zWHc%scH)5kyAu1h88XSuEZv_fbL=Qu1dR2Q2f=rmUWfm-=+B3`Vg-JgnBWG;zC<_O
z-rlyTZ!WNm;(o3WDth);&61D8#oJZ~#u!1zZ$CeTdirwsx{zqrLLszl<Aza~vjchZ
z(a`UL3oAF`KjHXGr<F<HsTse_EUOqEO4JpYgeC?I;tFn!^Ri6}XH?Tc_Lr(?{+xc>
z^yzJGQkS)N_nuEHKRADaA;x)Qgl!m@%G!O>P6Jfs_#8$mf+?xqp0kPwcPf-g>ZzI6
z1t(jHCUDL|`!pvR7-Q(xL7M~gv2-!UU3PD{cDZ5(K8F6qmkXgr|0~<C*+$0+4$lLw
z+$2&2i-W^I<<uyr7cs~O4(2sahpEq+kS#9FHTkA1RiqNkOC&RlKJ%|st{|j&HGdoj
zHY{8HW_%bvYJ}R65r=19ShTxmO*K#?D5igR7dUN|Y*i-N`zf@@8;Yo0QoJ4&(lYza
z&;Flca$2x`BW}gSlrj!Ki-X1&G#(Yzk}7+9WJ#5f<RsB3;3Xy|GN=xqBH6U`Vj`ws
z&T`65Kt3Vrpn9PM21l3pvh%zF<$*xJJsQfi_i(1yC5jT@8X$!-O60v<IU6qzLTpc0
zm&1+XzOiwZDMw42JdZcApeKJrT|Dv4(9F-fZOMHjTENIAVgu;aif{O>0<KUvc{J?m
z+t=TZecQsUkA<?p1(s-7Rdgl#DwRKg*u?Rv^DwId`7HBcg}qE23ETl5sRR>H@)H)*
z<wSi^yjH(%p-H|%$XS3+dOuX57*+&GVUab}ffY|#Z!|vLa!RAYQUS*^$hXy!_4cL#
zftnx8itE+NXMm~0z{0P2NuM^GuD~owE`&2*xW5!m+t5qv{YZTsFf-2xOhqw(hu*SJ
zLXl<LV8y$b4MW=x6)-6{>5^VJv`l7o=VxZLOptnY<@j4v>Ox1gtZH#k0^6~cPWsE!
z#O-KMnqnN*Um99O<A+ub*pkP~`eiR%sAbq+&7tIY!;G>|P5O%!yRP&`$&ivyShvJl
z3EZu=p)|V*rmvlyc|R=a{imLZl(CcEF|=}sR4Ce@53%L~GT{jMa5ykHfbC^NdBN1)
zDyAtDQ}H-396cC<Wf;dlydcZ|Z6qNs-ZTZIRPu=rf`zjAC|nyJ#wcUKdxsh_ExNwk
z{HD&bC`GyY-)ik&rquYpR^bcMA|MNP;FA@{c;YUuUQW+nf|oQY9NK{?JYxep-VaW|
z(Pu^au>^gZO-mdQ@Gp53U8BH-5RK*4X2LxNO2h>d2D&wmE-nHTQZ5{lX!u`unP?^w
z7eAN9iAuoAm0KsLW!uX6P)L%4IqeZ7u6_zbhtLO0pC?-;GMJi~g|f-Jt1l95k3lNf
zfxrg%cZV+Q9?MX;$1lw~z?ge{TIU5I%KqyH`P_=x*rZ2;b*ky>EX1iIZ-DTov_DBP
z^$6Opjs)v}g_aTO5eXU;KTlCUrWVTaU+SZrlWI&P+~bpswMmKeH(^>%oiM%_E-gtW
zHm!v7>0HTQwFTjl1Xeys7Vj8tgR;(fyeLW~_NoyTb`7mYCyZJsyFVofy&r0*YEPsY
zN`zuFDH!m~kCJ8r`<!)xAvFuOzlhNFu#NFX)$`l8VZo{dBD0s6Q`wC>O^c0y)PtM#
zErBp#42s(r<Q)O2(6Ugj6u08f|8readz(MC96vbU@bMy%HQisKje+pguU?+oB5kps
zRL-A)17ZguO$X|t>pRw$Eqxjs7Dw@KEAWXWiTjCWu;vdqV0zx{0*emMHa0e*Vxy=C
zC$%v!{FQ?Z%fC?evmncu&W;_|8R#7-!G**z`SFmoCOc6JcW=H7MKklFIh45OtIR1i
z?{^W?$2HM3=3+Wf-Z9mq0ODzx%{95c=Up%(4AHfd=*%PT6=@QYub$|@33+7@(nBGY
zPH_vtc)VzHt?_BS{oF_IHi`PFzFCjB#YAtCsY-Q&=#F`xzxDjjaM7^c)=2e!XKJWa
zeyf497bJaSkZu+wS5R>}7LEnQ3|5hr>&ukt7}F!Fk6Es$pjs}XQ-})W0e+^3@rl-#
zch4hD9fEcr46>ea5wl_d#J!H)Wi$4tsGTTcy)L^otG(WhnnhCUIboCe-Mx8_%Zf7e
z;<V$EM#)7wC&vn+dW1CBj2AO<fmM>t_;Q_-rfLk1UyENE=ht>p=qGp^Y3?$got)?{
z_{)8XlPb*Y#54FJD4uZr_#5;DV&7$j_g&hYCSbFb$NYz$BNHvB(wruCb}`g<W3iE}
zEe5e3S^XW1Fl0-M6lV}f5#<P>6}&?H0dNd*WAZoICU$P=jg1E;mcf6j@Mw44x3Gf;
zWxcI${&3!@_Cs;`V;yL(>D!Vur|hxk$M9^b#{7;I!eSc#e@kmSsxG;6efkM-yM_Q*
z>)vSh#{Bh$Ex>z(`>|d@8ldkGhF3T492?ofEGBRCEAG?VcQXA<z|TVl@4^QM23#*)
ztg{YytKU~$YlhT5=l-^?jf;hT)!tlwN7i>8z{S|wJa2;7LuT0XvtUR#x{}=vcEF(Y
zm5s#er5LDbm8iUV-H8;Q>@gUK^s4&1dP!xxvC#mfK^jpmTudA7R=oSQ3$H)Z8m`pv
zmzA_%gWYf04>H|Q$x?cT`720t8We;H>uHbbkk@~D``g4R!pj%E@VjBXt=S6*Yt;xb
zx+zl%n*{V(9rdlrUZsP%@>GPbEQ>Y!+|#((8||t=lzKbtP5)fla4GwstFwgR{&iy~
zMm-rE0<MjKM0gbr?P^kvU8sO_YQ*0LjGoZM=3y0xvyibzb<8fFLr+;xg9l&-l3+HY
z%UOd{YEUn}9hR9`^VWUYtO?Beo!)gG+0ovZZ`L_SiarKLGk%{cNxYSOEwqpy+I<Fq
zmU%|m(j|pGt@=b$D;eIRL&h4O$gt91FGCYDXUpEs#YGx(-TVg&KUlZ8xmmFe5+TsC
zJ+0%tbatCVet>%ztX>-O8@qfGtLz6<p?;xgdM`mM2=Q4ZM%IiSEaZ_Dwqa4@<e-Zw
z*x-Okf7Lay$T6~upxwn>@WYgJLi~S95B2r@bGX?n+8O&H0nO**QjKRb+829=cM+*A
z<S^IE4p~vC&NPNQxOu5)Y7gbD_RhQ*<RzPz%>4Yal!~Pi7^JlKfe~2UgvNM|f9dyK
z<Gpb%J9pb0l2*<dJ1P7LZ*MXb{5@a$H{9Yp770KHodjl1MuFWkR70%#*Tjdu>#c6{
ziD8ROHw8D#VP0i@YS|~7OEy)?phJ+1tjv+Gef>)9IFt85ZWs>_PuJX-_o3*5i5Nm_
zY;!k1W_=0qU|{FJ>3!Lz;UYr1NV{a`e)+Be8^tH|uTUJ(sMB|LVk=6^K4T`w681;a
ztJ1FD%o`B?oNPtB(s<3rKsmhQZg6RW>1H(ue|@As>uJZ;j-OTWj^4?TMz!7D^<&*T
znn7ONB<{5f`6T?zL5CXVdh9DE&>3!=2b2KITeo5Nt$Rwex%l5Ktk{MS8dNV8o#V=S
zmYvzbZ$s4X9xg|iaUXq(w86&pS<BYvF$_E?P9Qk#_%~xzloF&gb~PETz`@e}{b?Qv
z?4nXerQ{R2hv~lnSc+zx2NX2KIkL_9eH(FI{m6`A8z3yh3CL=rC{qw+o)9tPbj&PY
zikELNiU#uEwdyf*&W-vz^vkt56zG#*HbeO0Nl5moySP4JMdmY<Zy4VBJTDI}*vD+}
z!zg$%Cq1<Ix>OX>ThPeRrq|%M;`+1wh^Z3(*N=<dLDxN2AS5s_u$^kjj;xGv=mM)d
z?pU6zkOZ=QeN`RJZwN4qv&eKmGL^SW+VHf?TGaklu%IU6Z%Ahk9IPE4T|N9@n5gUE
z-fu#q8x8lkY>V9hfxyO5wEHq2<RhN8babEH`NjIBryiv<Xsiwf`CM4ubgfcHoi>}D
zM059kMaeemS#C|%0da81jNSdWNx3q|yC-GuGL_ydk85W{y6?-)re(_9h<yIXj&~jM
zu)HL5i!y`ngM6=Pu#WD0-i*cLFfz=${_qejM?6aaDSl00NFA&vHFm?fT~cr+D@P)L
z4Uy>j5}oUhFIr3X)z~pS^u%j<A|UB}ibUXb){vQWkP>z`A(v*Zd^MXu$I^s_F~X&1
z#T8q{X6qFytSRi;GK~oW%W@_0U9^h4QSuJLWKo4vR@}S-V~ak|V596+WutNlCbCZU
z%JA#=P$U96q^+V-*$@>QyK#lzWx^mY1L$XvkN9h+AI+RQ@!kC9{58t5K`!dILV6v)
z`#CAkXBJ&~{~XkBIM6`%k?6c<#6lBZp^Y}ms|ia^=_we%TL&?KjnXrjv{F`YI7$Yu
z>E4r;u?z7w#>?no*U-;my268=XNi;@5cGK6p%xP}512c(M<`9?n4SX|v?&hYCY<})
z!I=*T(03bvL`I*$3TNU9axP3)^+5l~0#J)^S+j6p2rr|hPsHIoI`+*zK6XTFUsT?g
zCO7_;X?c$66pg^J7+fyhJcPD2Tl?kY<QO<UqZYSHh8?`eFU*mwg>05ik^EmT05jIm
zsaI>RSm+FeHG4TcxAu>M8&Wl+ndG+F>>d{-DNzg_roEr`4kVQ7GR&ipV1oV>&*;4Z
zdw#xa)yO&ZOAGS9>j+;WC8Aplj2klR1C>woifRC3xs9k9A6$**q#z!sRgFs}&tUzD
zi)d4ExWr1bzMJen;a->a9D`#b$($rKmakpptQcA;h(Di8KLh#)F$AY{M7+6{#;QyZ
z&mLmlUPo-|p|Zj_N`gh25FJ!5D-fkpE=9uhg#pjFX(?`R&$hr4+^Q!Fz9!aHEw5^>
zm^u>)cO*sW1f^A}wru^<SQTDU7$;FE?c*)vc?$=V`x&+k<q9MrHgi=WZpGnBlK~;>
zbyEXva0<Vizq}ShEHjs=*$}`U3;d{!!X4_=7&yZL{@Q{epd{CYWym(!wY^|(44)};
z5uyY$QlI6hQD5^LN*G-H_}N^ae{b)1WBrew{^stP;C+L!AY5>4eQxa1JnQ&xvD3dG
z<swLl!zi`$SQA0(g$TKI!&Qo_|MAM*PRm7R>-kISdzv!08)dI&B)7ifHhdn7^wdIt
zxI|E{&d(f5%(8cFi0vis@;}m`w}owg-6Tmuf(^g&`(|J=etFOJN3$X8L5+CvCc|9x
z&QkdHH0-f+qJymc_Epp%=rm3Wr}ax<yWp={2KmWsUxlXDv+nan8mu3m-Zsn|`ncfH
z8t!cp=LHcMp{Dk6%tne?E0mb7zP0AP%#AJ#5wtp2Tl64~eeX@>%oppqN$=4)tk=1}
zzkhW6;*C9Pc>-!^(!TuK*M=k$@U!bQzX|t0j^i=^SWUG1`ua3m%@~I@KIW<!588x6
zhzGNtdBR5Sx?XqaCm6@HVVY+-K1cXmcpsj4i=7QBZ^Kuv&y^(nWdYt}#vXsWsq18K
ztoj{2wx_cD1_>I(%Hb!&`gajyK8MI)L%v&^$0D#tPq$LBUa8~384O_(E0Ux0_PEV?
zxp&O}Sb^iZPr&nBOf2(ec}MhPRP1kGuk;F?(|3NiQ`rZn={H#(bjlu!#%bi#JJ)aQ
z*Izz3a@5<;*Yvlq{fVhwMHv4btFmb*OJ%-APy6lCG&n9Uh1EGbi)Bd8^Zva;0>c1<
z!eIM}z}&(?W4lY@pP$LBS1^H=EbEG9yX<AeY7oKt^?R<7#bi^3)RS=Mv4wo!#}~Y$
z!$m14CmQW3sqNRbzjWFH9~Z3~CVCaFy!sbY?CXWkYEa8&a>ZkJTHuwLbMb`+_&5~S
z7U~MO-wMR#q*GMmx1H;H|Ho5+(`SygVY6RsEt%67n^l8tWzThE!}vS0jo@fqqb))v
zzf%x#DIh$yu(9G`-mi63uUG-gN9hN<ddvESkrAaSD*<l)?*HyZ{`7Wh!8axd-h|5S
z^7eZ#zlWO@`VBrt#VNnxths!$Wqt3rh$aqu&#5<;o&Ne=u=cZq=G$v<AqraN*q<Q2
zQtO?FEqY9iHqU8ju)d-?9}hb!#BCe$sUAGvvury}u5fs`$wJ@E+En(s-MHFi7V90Y
z|7GlD7Mgv3JGtoR(P{2_j?7XhAvwy8^|QIWyx_QhT5mVoky57Jcm!WDfY;dq{ALZ`
zQ^I=1uI*=5yjZpC?KY&SZ$O&EsML6{>-T@0qI=w`HUHxkrW7x>cXn>5yeO;Kp5o1H
z54P|{hv!i()Y}&?*`fFk3++@~b(ma=NkTK4#2_Ba66xCBxIv_;S?Ry+yOyTx{g$`7
z+UGD*f4&$-F#oc+s7SN^zC2BxqozXdw~wGC*8N#@1+{2JGS&4Cdq#Q}Qpc|8D&@UT
zdzi>3EuijPCCm35*WKw)8O-YYNe-rCY<^6EdMQdfIfdm5Zj#Ewbi64`HOdzc8sESF
z6WH#HGT|kI9h$*tD;K}TQ%t+dTRVwqVvN07sUYAw`;{#7Gv_i9iJ$0NDMaSj^I#oz
z)vqm{%+)~4umF6T>u{&=)v@?_;gh3o!8_XG<4KKHv+Pv787Tj<+Z$#of8qA)75$Yn
z*hO{vffD8yjh6E>z6&mIVCrx)qnP_vL}|IvR>YR@A$RQd?R_-ck+0}cmh)w=Y5O`V
z;Y=3JE$<K5?c1g{zzM+x6_J&3|9fVNQBS<a#27b*tn6Xyn=Gj^s0^0G<9)uChEZ!p
zZ|n`dyu5yNv4+iGV&M_f4?NV88Y6LqyN%r9S5o*NuAMy}n=W?RPq&s5jNOy%{dU?P
z_wvqBt@Xu~$n*RM`HRL2s_d02SNJ&ojdE+hx9BBpmc#Z&1L_kDgM)b~6j1-y9|#YP
zM)8@*GRUngA9P#U?N)WTys*J`xllX>Ck~~RPcgcd6e<KK=jcdUg-8=8z5S)xnBE-=
zim>tx?v53X*iddDlcjQvr3`2<bvc)WeHTgIHq(q+<zT$fyA9l_cIu5-yXdEOXEQd=
zzdcG&xZfvOFBWT0($_g>UA`-KKPq4r&XOV!{8p%t>TvSxaEygO$g^UZUY@w^_`n|d
z%im9^pW0iwAnBu$65g}c35z56!woy9=nY%S|5MUcheh$V(G_WyP`W|sMq0YNLAsHy
z73l`)l5UoeQcCIW?(UG51?gCJfp7hN^E~tKJM-Q<_dVyl_sk5Zkz56V+ibvD-5LSx
zE~q*889u7#vp;4!diha%d}2bABh7pKEwyCFhuwe0LHgF5>!CU5K62f&&Gb-c${$s0
z^f$0{#fiJ&^B)cMQ*}z)o-H&bX5*!SE2LD<3;64NGf8{up(|2Ku=&6!U!~BIhFbew
zK=Ya6-L4qpM&hno^HKr>r4=waui>()p)b1ql=H5t;n7*VZEn}EiQ^Aw(LH~_==m{E
zq7&r~YzAd9NPm<Si}LDvekpQYukCYWUv~M8hdNRxW=+6()p_ki{bIkyRDmR-{Tyn`
z%`MhrY?Tn(d7+9}9yS26`=rEAw+2)D0f+5aRRm3yMpNvN#nZ<4+l88dygppvxFDZL
zi1z|yYZz*F|3)2F7PLo-Sc@5EKJ;B(@R*IjyEHwsiJYzT_ezr83qkGa0#6Vl1sHfj
zp!1Q^^cr6GuXAwrxE=ZTS`h20k+dRl2aPJB__9ibE=%KEa8ZynlWtPAyd}LOj%co0
zS=b>g4*Idb&g|BgwMv#XJheck^RDb6;32e~!)%Olq&=kVZ*RpPsM-5xHRoS1w+_X{
zZZ$WrdT`$fEN$nx2C+^BK4HZ$fDx3pd+-M0Gn8W*LhapR>}fMoJ$7_YS6p1&TrGaG
zjui@^r#!xSKQ}k`cr3<AeNjaqtmFMK=fzXLj2|G4z0BOgIPe!TD_l$*VSF9$dcHg)
z5)t3DF*wEXDEsOfK}))EaFxTgh`Mxoa7U3#FqN2R=kW%Z6C6RJ@ftA&#ti78o#VGi
z0>;Bl2f*}sGA&20$9~h~kHV)nwqZ3-R(@mj;!hYu{}9~&zVH6e6es(nxnz&nv=cu<
zN;X%I-QNr17hBDL|M)!(bJxmBMJ<l|y;iXni#EHSLQxc(;&3uSicL#l1fF^23cIp+
zCJN96ND5udkU7z*3(}K2H6^*ccoxj~)H2?B1BvC)*Qmw)+(w&!sL7J1-};$Zidkf;
zWUnPIejX%(n^LOJs$pm~n_0Uy_>DRLu<%MtH&%=6OGsxV6%uj_ky-l3Wwwc>TP@2H
z64b7h$m9)#b~OMUU}8Q2zoj-;$1alTIra+5LB%wee>cXfrq1fHq*=UBPdBJkv>%@Y
zoD3ghC5<_q)msw#fD)1WLl+mrg@XSX*lqp&a}Ax5>G?nuyG)W4jei=lWfbGmV;0-d
z244?C3B)IWB(a~a|7QDzT^jwQsm3nQp}HT`KMAc8S1jz-)~H=(Gwbx{`p5{BHkO};
zcpTNY_S=X4pfui+exsljR?M4lxC^6N^|&>4axd>v?`j^pEoo-*zeZ4M@{-)nQxj9L
z>ld16%ih`?fsKkxHsuH-zYbH}A<%gM@sbDW<Q5OxN+_mS*hbZjr+NU?26w+5p*Mp}
z5D1`FHb**YgZnz5WiLIJo8fK&Lhedp^;K)f$8<9<!}bvEdtRIC7=|Mr(YS=KqlMZ(
z3DCtQAP{-z<0F~C7?n&iY_#sB@TtOIW9pql16hfdeYx;Y?GcVli=#0UByn;vvGSue
z?qgzEL4?9Zu$z96N_OeDXoiypO~XAQL0W|FTN-h0*byuxmy;P`tBZ&Frvn~4d~<H(
z{S{4n-@a-Tk8bkOa{UV3^62M8LJ)n>Pr1GD&snGH`;ufKBN7E}^<ihQevlG@hh2ls
zRgO&d0YmoSH$f$uR5~@wWI<{BkPjRT$_jG?;eaX-1sXH`AjuBh8UB*t+Y*-l+P+1`
zkv46r4!{QAaNiQ3)NiyGgPw}BaTPP%sq?(qS5B+HNJ|J3b_-HRH$H^}rsfnZlKP?7
z8{ZU|NvjqrbXfYVC0`HtTu7J=iz_DQeJjI6%!}1`aN>G?2Cat94-c|<)I2p;lI=WC
z0b=)PZHI={gikOw>9zS}bZIh1^l>+xCi{rRY{M!!gz!)vSYM}LpF8$~D9-ZM99#u-
z{b!I;$ZsF>yA++W^7YL&t&y);dilw*%0++<=uTcGIgPt|T5{ORR5+uB4Le8k3YUDT
zMlm!#HHDjI^(|F_86z|}jaBc{I%tT{wy40Id+Gl1n{P7RwXY~bknZm8vKci3OXjEP
zy{07u6p%5K9RE66AR8p_pyGgD7lrqG@Pg8}0ESnp2Zv<d`SSn1PdtOw4@cwc``5Kl
zPXEZ8qx#<-WT6SQyy2G*G8R!7e*GYY+!CgtQ`}{w3W8P57<5IFgAFmX8q>aPKF8qp
z8&}w(v(sw5z2GQrDe0nNFPHUPsVV}Q2yF`s%wLUI%_NsHgDCJLXh9Uk^)x`~$_cP?
zGV+k-BTJXD5bM~x&m*{aNWK=a$%j1L+&$lQe@tu5IPo*1(SJ*ITKg5wrm7hCClQVr
zO%soQfOVH18Y&AuR?Zr;RsQ!AHFl#$nlCiyNXAQ)YNsYkjEbIulFTL3rw1Y+qPHdH
zo}THB)h!WKMopn3X~LpYV<pY0WQMo>pg3LMW<Cv_3qk_6C*Ca*65ff2PIUs=J`(JI
zEi$FUol2TlZ_KiV6T;L|sFalIi#5NiET8@?bXB5-L7+XnTbb=KuG6vLk1OZT|He+9
zVu*?UB0wNf`n15=bS8r=7Q*7cHTLmp+<f#5kDfNql-Q&y-H!JVbdvBUS2W88N7svZ
z+1ki)<e?4lUw{_lNqmpTS3!Y+R7(@WXJ7EF4WyFkS~~Mn^>dcinM$$@#X`hxoBiDW
zaB}oz0^7RT^*GRd9i2D9;;D<13qG|3|M~#n(g#rPt?1>uqoI$<bYCnK2xL>0=+imD
zmJSXvY-8w1iHHikw@25iRl&v0Em=I%PZN;^>&X;HKMoHi4|_#T;t3-lfLERS*zRyV
z!g*5u$chiDmA%v#;hd^tu83f7?mVmWy>a+ZWjGK+I2JLxy8nrE%j+rt9#1ZSvvj7#
zA`|2qh<Dw4`@G;QAWvCBP`xPp4hTys6ZsP@vTLutae84>HzF>2wc_>ga0kBPsBS)X
z=sX9Tp<dp~Rc?&j|0>v)kaV2r?-wjC_NZ*&U87vxSSN9x$mXMPAD>ZCRed$Y?e6Z*
zv_#tw@u5k&ZAsR(+4*gi4I1sd8+O-^<v}&aXA`H!FT+?!ILOtl2V_r=CWj}v;AQ2c
zuUqh2uS&CR?Yq!J(F{|PPn)(=oYlWVUnUq<4PNe#ky2Ba5Qn4x*?#D8dk#cA#nMpc
zxvkI)t>jXSJT){?;khHP<>)*lUs@@2mFy&e>uVID%7NRa+kUfQB*>KM-8a%a7ca0W
z3_(^pnzJ$gUS2;|b6`Db0WpvM^WJ7ap+4`}KooV(Yy2*)f8-E|&#G5#J(5iCw9%NQ
zRUwmIIzBmBR5Fh&nMJ4QUgP(+wwK0fGecZ|ET?npb{jUn3jfJQ&Vh|%{m*ZG6%5-*
z%;-93@G0uMgU%0$^%8gazxdCYedX-BFVOYKzV-C?&U>>CJkX~e#00PvdC)X=`z`zL
zl;tI$;QHKV!tc7NQv7N!x|5f71js)ztP;^bYsZ@j&e>IRtk6{|ptC2yFTo)DGmVWe
zQi9<pD#BUw@W(^yT~1L0RkmR%1LY*@mu1><TAZ%|{w4D+lMVLSNu|vHc4b8F_s~8K
zT2W0jbzYf?Jc6H+{wdUC>SybwJLokOTugvGpwqP-Oz%3asL4V*cKOR>=}yD&ZAvDu
z+SdSApcS?zCqrFJd!x>4RkI9b<wzwO1@?Z6)U!2mY0Im<MROhMi00w02TwmV<U5fA
zyUxI#3@_gkR^oto&Oj*AEbo3X7*5~{%Lw{?yC!h)Ra^b{K#ji#2!(Kc{}23Wc;`&1
zQzXL<0VR1}^9;;#=oBRvqkn6MC;wnMw^|NW=cP*(;Pr!|4$Ie7hHRM9magB(nqJIt
zqETS}HA;(Y$3s&&G7B6?gO9Ck21ZVqT@5)xp`3v|M$h~4?azJG7M`As&EK*9rZ>A(
z=OodAx?<Fm=rm0SmNI&&=Z_t$5b6Xm{zXiqjyGuOOKD2c<xBJvTC;5QF_)TKpsVC=
zivcQOM!=cNLTe5z9tff!)>H2>1<}Nvw<SYtz6JNM#(nsqs&QGabKD}#fjOj$9GF$G
z2ihmp)2>QG1plH*jE(x`W2cZZg=dywXR<Vo5ONh?hiPI~i$SB)rd)QZmwrl+SH*%^
zizSM>Z|^R2{7`HP3mim*pwqftcsmKD+TrQuJs~3}C%l8D-Yya?uWKD{Fb4<a%0EDW
zGVY>Nl1i${GV{lT>Fh>IEyg7a*;5`j?CBpI^OMisH8_P@CAOjMTBVGSkGt(J_%v<O
z<a9}Y@Us=zco`x}e+TI0l2RIBHM@P?c{|~H5$_rlX_X+BeJBda^1t5&FYo#}gYysS
zwW-FBhS57}<@M{Sh$$o}Jnswtd1HSpFlD?%Ah4U_rXBC_FW}VGC;L;E3`CMq4h=Do
z)_I6-Jr|MkV3@j47NNE>X-+N;y2vbBDY56#XG6gR>Fo8HaIgS?0{w)!MWB4$uXmS9
zc^l>rS=)NCopP8r#3+7g5%_SW+_Lliho@i7nJN6`zn#F`yOBiqKb)Mqebg{-P{SkT
z&#v3UyL4?ep>TTTbefN1=LgmAQEPQrKGrWHDsLS3yo0WdjZOIyBz0`x9}qMXYx=Q-
zE7yC6TVy-%j+QASD=&{;5lGJOw4E((D&MqLvVjRpH+W3iyv7Rrh6LPteiAV7n3fzM
z)YdrHv)O&Pfp2j>wbewD9w>UBaLskOVNl7wLU6>XtBCjhQt0(xiP(%m1B7&%85R3u
z_WU{PfiNNjIj~6ef(4Ux8f=#4)Ij1V?ymo9<3gd(z**6nG7v>a@pAQ+6fO|O-PYEY
zIpd!%aYt~|qHqCnv-}xmLpDKl>Y4L_RbUTa>+P4`6Pw(YY0WZpID#|N#S{fvn3$TZ
zK@5~i2)6Db-v*S;70%dAJ2a3`QVtj@SLhs*JJ3i3C*#D+rDP3?C?=c7|9j=-?N_a@
zncrMfCe%W@YAc)mwWKq%vPjiVOU6B}>&B-c;RyU{+jx3jYfGjQN;rXcL=BH0yL=z9
z(S9wor@+fb&Oi7I*ZrcWl@!(gJSfv_KP)3GC>{q@Za0K>oaC*Y+-o{bieEV$^U0(a
z`M5u=t#uY>31l6D{Ur)p9Y@Av;+g_n`)+PLVm1UOkd~INbZo%9PnFp{Ahbh36&cfR
zKsXa}a^sX*{?u%aT~V|tb->jPK5reSp)L)5VQh7`P>+9LI0S-H=`8uJkYGF4yd`({
z!8fGZsK>h#TbtiN+EFP>+<C1x;xE<D-w`$ACN-P?k7HtNENSv$98jkk&)4w1+j6Fw
z?R^`Pq%?W&%9S#DF4{h`9h{_aX%#Rk(H~+^piun%^J`?Pg+vwVhrg<K=0(w)=t7Jb
z?b=F`Bs8k!6F@_uqs5n(hK_>5kstUzpF&sg0O*peXPjKjTrUm%*g1Kf8Zm6pk)?2g
zRkk-}@H<|-(X#N&SA-wthBW|Rg`yXvVnhXn@9w^jA9x8sxp>%|T9L|bIc<a32_Dw!
zvuWYuQ05czqLV2R%zvh4$UbV&T5CLN<u93qp$dgmq}6Q3hI?|4L`oZUEF!z}3imoJ
z^f+MI70hn7C(;MdVan+qec<Q2(I!K0X*ESx0l}jge5(kI9Q|T*QW9}r=(BYL!Nq-U
zC+5Pa!)?e3!X%DD)=%D7o5c4u-6th-b2@g}n7X<s%yTb#$N=qt0{enNL=rZa45HgT
zURoh&(b5BzVN>61@$e;pW|3pTfYJ)W_qM+sAt-nu{FtaL*sE7zJcfcUl1kI_9_1*1
z+jWC67Ql8z0<v#@4TgN|Tc2m;X&ew27Y~ct-n-@?s;cR6&1T@b9i1A%+Rkrq&g_r{
z@TOXl6oaOD=Z@8RXL2lki&8UFzT3qfCXYX&o!zf*jG8wXN-RragbBwk?2vhw?C$O1
zh{4aLbMx|kuhf+_x3>0L3JqC$#5X!$Sdx9?nUQh*Vi`s;S?@!Ula|=#F3ae2H6u^`
z`}i2M3%-|<ibTS=O+`(;TP7Y5g)4RsU}S6p9Zqup&EFjSBox`usXR3>fWpC9Qzp!X
z2o?1wpkB3xJ75yNpD8@YkzPxQ##MtO+6w=?9@d9CG&ICDxV@VwKG@-RcYZ5;C&iff
zcD^B`f#?eQ`uTzSnQtQ+F(ngm)LCmfHm4mwr{uS`;KwOuyE{9tODil?(prz1K6c~W
zAOEPi7$7#=-tgKQ2t&g?Pl?3sb^?JwA+}TgFC^M>2US!NgEM=}ttcPEtalM)V~TcX
z+TIK(*scViQ!~gl9e;gy83popjNbBpFoGY<Z55rS>$4r`R}o1btAz0|W*>QI{pmZL
zuo@%Hu&N>b(k^_sLtgz17zhpQp?*52uP;q~VQrFQ2xZA82`Y*XJR$1s9zugjk+brr
zpi`ma$<Vpky~BGE<6qTz26*RDoQIfX`{Of~ukmrzCV*W(cRy3xOJ^UeD;3E^<V6oc
zOb`E34PHLDqqc}EA{;Od47(_C<T8ibt%jjvN=KZTAcyFq;m`-mAZrHf1n*+3BNi}q
z${;6-1l8^xnYfkzGfGa7=p!K{(7ii&maW>sVUT-9rY1zj8he@i>i5`LDwx~+(DARl
zSSF8;nBtJ5FOT4~QIm^BgMNXKVCLUR8T?0yd5(-`KVL7^*r7@N5&(%`d{lvyP+;aj
z19WB{Epx&qlP|LThr!~}l=#yv=QHY|t*t&g(cDHB;#Pvw$LKjGr!EqyAEkS)FV4!#
zg+zybnVhY)T?@U9isvKfjf>OylQI^)*kb;Wn6dq|*CP$@n7IdU!8!8-?>4~WA|25T
z585;(1b_3_d%ECP;=iY!PaY-5*zx*E!UOF(f)zeewJWW&?GU!S@Xw(_JDHJmtfTH3
zZ+^ZFX!kqY(3v4lk~uVHxtO5W$+sZzLvng!HBLhwJ?uq%K`Do>r>AFULwLMeM(Jg8
zSQb%>1;)+`&En3PaC4iMkeSxu`@1PTFd|%5d(wuDD2wKSeCj@!hK_C!;&B6r5y=Ye
zV&O=e*f-dgQ<bb^+Y7PT_gIdi3A4PaWS{Vs_N$sUduL`ezlS%sXYZbz01;PvYW`DS
zh->LKmy0hrY`FNr7}Dq*(Du1%h8J5+T^$6wb!H>N^1r(#J-9+?o$g~N`n<<n2z4y!
zIua*-PBK@zRejStq4umzGNCrVl%&_X>HB<jH6*`o2Hnc31{rC^KFd2V|9N`gyMY{^
zHHq8SNBt;OgKWDS+1&?Rt2#y$<N{)*8*qx4xLalwV8S@#QD?GqVi#JYqhnd#k3!EK
zHu&%$?a?_T_d&LqAyxE!4y+y_f#vCo+`w#f4L&{!VYWWFYZbw9YXtIOY{0N(G<V&Z
zQ7P+7ZM}+J4QsgPO3`<gt@3H1S}d2um&@@0radpLkFO1xQLNe}^s7E7l8{-M=XEXa
zJA~U#fnWaa=<Ac7_rQiAn=BPN8zFL^uM6vmw?@Z<w+cceFb6s3cz0K;KCt@3PMf?h
z_b^(k`z%+As>uZlL%KQmCOrptc0`~y>$vr+H-Yw>E~|P_*QpwJBL*X(vkq5gR&o#1
zK)An?2yBAS++UW3ZeT>he1GVeQ}$P3{jbKqR`6X?;lr{gA!6H$Wd;+jJ-@BYX36j0
zL$z2IZer1i!q3d8YAUH#Kf^_SaWzA;@!VghYL&m7)4FX5gcCFJFk>>kqLUjFP+N-t
z%Hoiv|18xko{s9`6W8NFHnQ!RGz$_stTcf}cXFU3I|><KwpK?V;XV!m07NhFs|=ik
z>U4DZ0QSWNxA7#2pbq^vo@$+cI;iUaG=0p<jw(5m^hRk?E*J6Ka1!lA?)?v?T`%JE
zYI5}irt4^j!ownn6t)NjtOuk9k%_QPAt{G;Zl*S<w1(sD_{-#W@Bosa!%(|@YVJC9
zN2a-^g9x(CVDHXLAFRWgte?YjpPOQJXMbrblUr$!zSLgOxInF~F-ZuO`|{dqb+XWr
z9sP-9(NK{5HC1Q@8b@HHhRwxrf!KRYl2;+sWOlU62^Lv}F{-xTS)5$*NH#HF(&&^9
zIy7Jc!5FnC?>}$QrKtNJPIjRNiSHcDWMLg-(wY!|DWD?!RnkZ~S8g9Bi_gogC~hh$
zaKoJS;9x6=2{>*IWDe2cFK5c?Tu+3YzAX;lS3O>~N%-Bi=}qldSG(T4m2ysa@-}Ga
z4HrZZ0Ki)P=LI-BGTOL{Qyoz<>f*FQ;-))qCyTE^nmZ)p%NJQXa2)rOju&sNl}Ux`
z)pVdtqEL%tdEG-uah|Vpv>1UshG$`Q?)EWXaa2-x0)4PAF6Xv;E9qOJB!1ACv%IAD
zt^F`5G~a+h2A=t;T>6n9d(^I+#?DxfBiu?j%C-QzFlTrV6fep#%M-NJvaM9ENo<i~
zChm_@BQKuj8|BS}9;$A7f8RzTZYhydf7kf<%lWK5ZtxBw$lEg}lU)eq?1N>s3<6%p
z1OtA#8Xo?Hy^BykfwYpBdJH{(WU@Va9W^qsEt&X)T{>4yE@VT-v1+=D+fDxm4n1Dw
z{DmF`lpv!)!6fSa)S@CNwd7&W`rF3)VEX(oz~@#OKg=rXOSl|6KI>D{Dj{z7I}9Sc
zOxl=j35{>t+Z%*cKnWHD4(PU4C^7E^g;M`B)v$S<@}OR!fwU9YMFqvmp-b#7xyU=C
z3ZX%Pa$vV;@^9F81%75yv!qq5^)-1?XR8y{vowbHnAB!yll$j1E0g#8hSjjE<nUEM
zu}5+~z4zhW1m1icjpg6LQd)uVATvwO;C5d(*Qo37n)r??yJv6p`R(hDc;pLrh#4Go
z<uX(Zlo&j_f-$Et^)jvi1hX`=+qPeuGIi@3Ak^^mA`NDToe(Y^<Q*DdU2mE35810V
z9ZZ&SAv`1s_xJh4xv9uZv2^oZK=jxt)wzQ2-|4oC7Mm7(KGgt}_S)-L2YW=D7Us`h
zu&0p(9VIz!g@LMJrB`Q`=NsUXj{3*UZ6?w+Rtm+gpjxkz`cIFK^t-Yu91??n`xpi}
zA7Lhoi6NJapBodg<lHy}aINqs_ui7E$lXv;Qd%rDxPg+wN{`+#Q$CtzKubYkOeNcu
z8!p*83)!y9P$`~pmoBQ{x_*ss=EIS&gIJU}?o2*x86U510Ztl`fQNZTg?iTdD(o;+
zA?{3W4@+L0-|a_huz@=U-_CB1zVO0NsFH?^&(%sKinf#zn4|ZTLz)GZ?}<_PqIeaU
z(Rmb@@dy-<7h6vj=g35yk5SbCOP=-<xmdl1%tw~m896?B%?<M$^u;#-5?oRq3wBS(
z<|eeh!L*)IpM(n`%mpnx8ND$Owc1!;JcwD?R<uvH>U)PP=cqVS;dvl+d3V7~RSZ#i
z(YuXB9<er4Qv1`xje#>?h%%v+9BQzcE~JC~U~gBRx&^Hr?(gi#{{4GzPmkn77o@eH
zS5vUPxm}{6c<!&*tdE(VC7U&$O^h#XPw~Y%g}DXl7jMAe&67}7_^4-A!c18#=r+VP
z@<O9v_1plX+%;y!wpmgpd?SDQq%n2!Z1-*x`C{uf%fw>q3=)$*llK#28umo=rs2Zy
zjy+?dFOQq5i~SR~%|+*lVOIaqsl!)z?>O^by<wIA$;v80k#ZqJ)eG4Xx{Y-B+b>VA
z_&s=0KMvgp|Ms|A_2cUqk^|#O0>ZmnvFec8ZB8G}&_W5jF(oE@qS0>PG*U0xqTuq~
zKbinVTugnkxs@$(257$3QLv0q_Qwy3MBz1Q1mgR=hCszWU%kQS`BN;WR~PX|9xk1h
z8}l1OGE}xM%)LIaprCo{K-pgUcY*nz@xx)uaCsd3ZI8e%ovGZ%bp;?CLNG8a*2J7;
zhqt4HS;V9qw#5NJ#SnRmp^#H#Df#xMyc66|GUGvsU{!J4f+8Ycv@l}_-mq)Mp@G3*
ztDpJ>_GCw+1rFI&$?iF3LHO}zAJD6FvI8iD1Ui6KVX?0U&;Vme7be5wb<r1Zy>$mK
zn6bdJ#MW*d$mp(s6glJ<xXJuF=vyeKXL!i5WIOb~DeA34e^=8n_qJ9%KO%Qe*s<9&
z*%p{+f^+QP-tCfm(T%a?h-73r!@`$%ItBjRv1UvpX7P01b<d-go{<J^@o{qV@5=Zy
z)M#Z+9Wr+i0ZiMyll-5c{`u2q)e!Tzp538D5M+^kJOc}U0lmtwgzJ4Yyu~UC^?0>T
zMEt8lWjbHVoHSxKlT?i@7s4l*=n7<yr4zDZprO+j3AR=wmLka9bp4*{D?u&@W{#s_
zOr&r>mzSm2z+K^<Z3U^2>i9voeQcHhxXXB3n*zsL4*n1Mq1%yMH(o6~@9@5?Tox_C
ztz2HpXpy*^NGp#TMKKzT1)--aSi|43-Ah*%Uf6J&XD9=@`yz2K?k}v2&CGV^)Wrv&
zP@#mxM2o6$ZU*ir*jZO1_!)j^myHU3{(a~DaI&%)XBH{|bNYJ!RO+UC-NLU3rBIyU
z3!1-IJE1|NeHR2w`g#5}?2^|tJyjZPJ2w!I-|$4zHMBG<cnMTKN2;hLP>47rTKTm1
zsCleca<O!l)y^BXX+3v_k2A?#nJcu9>PUF^;$!Fs)X}o>g|ezwAw7nt!`T#u&c8C~
zn=oRPN&`)n1jWP#i{%sDo}U7YO-*+Y1hj4is5)o<N(1EhIKMtOr;XrSB0iVMTmDxQ
zfENK-%g5E^xjgXlZkoKWPn(BYl0m47WBH&WgTI;hVVFw55Gk=PAU}3Im*nWTA`6=j
zmJTc9_sRBq$$zeZ?EN7a9j4e=b<|sD)^X%?{c${~sD9fFHb*4Ee%f~yVC35MvNP?5
zk7udYuR`!q>wqd3r}`+T`g0S#Rmi447Yx?<Dg*T^Q$o8&?d)`a=hT3=>$U<C8jW@e
zT-@$%DebC2{-2TG^g8kPjdW<wd&F~g!YRxGp(VEYZ<dlU(b8kClw0*zlv$mm)L{c3
zUZQRsyj4QY_bHg9uLTwXG%N6vxFn~CHg1OFtuIx`U%fz6oPx2mr)~@c7FD<@^rL?W
zPTpjR!gwcT#avo5$=ivsdtAOjFOjw9K6FP}{+?mp?7;WV;>mv&2vaF{W?_WmVB?IK
zQ{kWg{5--YjDKrE5c=xJi-%f%EDJlU`^OKKz+U9p7A>~A+lS3ePOEs*A%227I}x7;
zd7ahm%gfjDXxN*+FucR5{JvG3vNA>h_tQ?;koWbbbgr3c@C6PDtN-na?UBBQ05*%2
zTR=d3$}WDCRr8{4oW1k32PH>MhM?ek852D_BP<giR;eWQx(Ta6?m~w2>%l!Dq=GcH
zXzoQJ@UI^P^&cwmO5W)rvEefnV}BuF!&-hXL4qk}R5L3UW1$nCVC=eSOFlP<{pFpr
z{#_i&r?;2)0k5_8?~0D<#8?Vs!jC$Uw5QoVT1&js#`XIm1E}475hE^fAHDtMjw6)0
zp#=%{g(CUeV~1;OCqv=qiDdQ4CFF@r*#=fx6eFod5Q1z^zTj|ti@Pt|F#6T!0!fes
z$a?Zah`F>BztSThAAs@R5)Vtk2W7?x8B?XxB|lY-d5w9nhJcOdlcO2)rB(Ig8`SfZ
zhh8e0^EC1F1{c@Z;V{2yasr9ZCXr~ko8g+>URwcZ#e@g}<rV-%!rk(V5*LFJJwJ{m
zUIc+3aV8|=<rArXPj;+%gFxZ?pAsOfSWBMXn}*A}vBE=T<zz2CiPHEp7x)O!$;g6D
z5Lo!q!jkM1Pq(CDcFDpUwSqzXdD5IG(uog^`Uy)AJJZVh2kwH0!KM79V@D!eRxj34
zH-z+a@so);Sa8QU8go$^8NLG%T}HNE&3Caeh)aXGNG;qg!uu=mMjd@{0%!x_9V9}M
zuU4MElDu(WG1OSxFI{TguQ#M;3E;qxk0}|&kwRvd{f7C@@)0>U6GKJBjrtZ;D6k_W
z!{uQj-T&LcC%S1X5RG#(f7drKB&<|w!;XS#(k&1QY^XT@VHOlx)Ad9q4m-EKAK(lO
zSz{b>oBVyUgYtB`^^AYkaVPflaQ1|Ghlrp@ymY^FwIyBHt7jGvzH)-slwc!BgOV|z
z;};tyKl3~*Ft&y)AHe|uyh)L_c$E?#!JIHqL`dIeOgAbMpHzIA^EzyhWtrc;=*gy>
zcJoz`8G+b5Pf!AX7t5*+$)^-SC_~|8*>sc#eslVveH?V{=aPvj`1MAkNL_+NSZ(ba
tJ|LqDlX?Onm?qB9;*ooP5|%Re{F0q!c``*Qu^NCl6lK+9s-?_B{|EBa{Bi&Q
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/dbus_ext.rs
@@ -0,0 +1,38 @@
+use std::cell::Cell;
+use std::ptr::NonNull;
+
+use dbus::blocking::LocalConnection;
+
+thread_local! {
+    static CURRENT_DBUS_CONN: Cell<Option<NonNull<LocalConnection>>> = Cell::new(None);
+}
+
+#[derive(Debug)]
+pub struct NoCurrentErr;
+
+pub fn with_current<F: FnOnce(&LocalConnection) -> R, R>(f: F) -> Result<R, NoCurrentErr> {
+    CURRENT_DBUS_CONN
+        .with(|v| {
+            v.get().map(|conn| {
+                let conn = unsafe { conn.as_ref() };
+                f(conn)
+            })
+        })
+        .ok_or(NoCurrentErr)
+}
+
+pub fn with_conn<F: FnOnce() -> R, R>(conn: &LocalConnection, f: F) -> R {
+    CURRENT_DBUS_CONN.with(|v| {
+        let was = v.get();
+        struct Reset(Option<NonNull<LocalConnection>>);
+        impl Drop for Reset {
+            fn drop(&mut self) {
+                CURRENT_DBUS_CONN.with(|v| v.set(self.0));
+            }
+        }
+        let _reset = Reset(was);
+
+        unsafe { v.set(Some(NonNull::new_unchecked(conn as *const _ as *mut _))) }
+        f()
+    })
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/dbus_interface.rs
@@ -0,0 +1,1 @@
+include!(concat!(env!("OUT_DIR"), "/dbus_interfaces.rs"));
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/error.rs
@@ -0,0 +1,9 @@
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum Error {
+    #[error("dbus error: {0}")]
+    Dbus(#[from] dbus::Error),
+    #[error("service stopped")]
+    Stopped,
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/freedesktop.rs
@@ -0,0 +1,34 @@
+use dbus::arg;
+
+/// org.freedesktop.DBus.NameOwnerChanged
+///
+/// https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-name-owner-changed
+#[derive(Debug)]
+pub struct NameOwnerChanged {
+    pub name: String,
+    pub old_owner: String,
+    pub new_owner: String,
+}
+
+impl arg::AppendAll for NameOwnerChanged {
+    fn append(&self, i: &mut arg::IterAppend) {
+        arg::RefArg::append(&self.name, i);
+        arg::RefArg::append(&self.old_owner, i);
+        arg::RefArg::append(&self.new_owner, i);
+    }
+}
+
+impl arg::ReadAll for NameOwnerChanged {
+    fn read(i: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {
+        Ok(NameOwnerChanged {
+            name: i.read()?,
+            old_owner: i.read()?,
+            new_owner: i.read()?,
+        })
+    }
+}
+
+impl dbus::message::SignalArgs for NameOwnerChanged {
+    const NAME: &'static str = "NameOwnerChanged";
+    const INTERFACE: &'static str = "org.freedesktop.DBus";
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/lib.rs
@@ -0,0 +1,233 @@
+//! A Rust implementation of the KDE/freedesktop StatusNotifierItem specification
+//!
+//! See the [README.md](https://github.com/iovxw/ksni) for an example
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+
+mod dbus_ext;
+mod dbus_interface;
+mod error;
+mod freedesktop;
+pub mod menu;
+mod service;
+mod tray;
+
+#[doc(inline)]
+pub use menu::{MenuItem, TextDirection};
+pub use service::TrayService;
+pub use tray::{Category, Icon, Status, ToolTip};
+
+/// A system tray, implement this to create your tray
+///
+/// **NOTE**: On some system trays, [`Tray::id`] is a required property to avoid unexpected behaviors
+pub trait Tray: Sized {
+    /// Asks the status notifier item for activation, this is typically a
+    /// consequence of user input, such as mouse left click over the graphical
+    /// representation of the item.
+    /// The application will perform any task is considered appropriate as an
+    /// activation request.
+    ///
+    /// the x and y parameters are in screen coordinates and is to be considered
+    /// an hint to the item where to show eventual windows (if any).
+    fn activate(&mut self, _x: i32, _y: i32) {}
+
+    /// Is to be considered a secondary and less important form of activation
+    /// compared to Activate.
+    /// This is typically a consequence of user input, such as mouse middle
+    /// click over the graphical representation of the item.
+    /// The application will perform any task is considered appropriate as an
+    /// activation request.
+    ///
+    /// the x and y parameters are in screen coordinates and is to be considered
+    /// an hint to the item where to show eventual windows (if any).
+    fn secondary_activate(&mut self, _x: i32, _y: i32) {}
+
+    /// The user asked for a scroll action. This is caused from input such as
+    /// mouse wheel over the graphical representation of the item.
+    ///
+    /// The delta parameter represent the amount of scroll, the orientation
+    /// parameter represent the horizontal or vertical orientation of the scroll
+    /// request and its legal values are horizontal and vertical.
+    fn scroll(&mut self, _delta: i32, _dir: &str) {}
+
+    /// Describes the category of this item.
+    fn category(&self) -> Category {
+        tray::Category::ApplicationStatus
+    }
+
+    /// It's a name that should be unique for this application and consistent
+    /// between sessions, such as the application name itself.
+    fn id(&self) -> String {
+        Default::default()
+    }
+
+    /// It's a name that describes the application, it can be more descriptive
+    /// than Id.
+    fn title(&self) -> String {
+        Default::default()
+    }
+
+    /// Describes the status of this item or of the associated application.
+    fn status(&self) -> Status {
+        tray::Status::Active
+    }
+
+    // NOTE: u32 in org.freedesktop.StatusNotifierItem
+    /// It's the windowing-system dependent identifier for a window, the
+    /// application can chose one of its windows to be available through this
+    /// property or just set 0 if it's not interested.
+    fn window_id(&self) -> i32 {
+        0
+    }
+
+    /// An additional path to add to the theme search path to find the icons.
+    fn icon_theme_path(&self) -> String {
+        Default::default()
+    }
+
+    /// The item only support the context menu, the visualization
+    /// should prefer showing the menu or sending ContextMenu()
+    /// instead of Activate()
+    // fn item_is_menu() -> bool { false }
+
+    /// The StatusNotifierItem can carry an icon that can be used by the
+    /// visualization to identify the item.
+    fn icon_name(&self) -> String {
+        Default::default()
+    }
+
+    /// Carries an ARGB32 binary representation of the icon
+    fn icon_pixmap(&self) -> Vec<Icon> {
+        Default::default()
+    }
+
+    /// The Freedesktop-compliant name of an icon. This can be used by the
+    /// visualization to indicate extra state information, for instance as an
+    /// overlay for the main icon.
+    fn overlay_icon_name(&self) -> String {
+        Default::default()
+    }
+
+    /// ARGB32 binary representation of the overlay icon described in the
+    /// previous paragraph.
+    fn overlay_icon_pixmap(&self) -> Vec<Icon> {
+        Default::default()
+    }
+
+    /// The Freedesktop-compliant name of an icon. this can be used by the
+    /// visualization to indicate that the item is in RequestingAttention state.
+    fn attention_icon_name(&self) -> String {
+        Default::default()
+    }
+
+    /// ARGB32 binary representation of the requesting attention icon describe in
+    /// the previous paragraph.
+    fn attention_icon_pixmap(&self) -> Vec<Icon> {
+        Default::default()
+    }
+
+    /// An item can also specify an animation associated to the
+    /// RequestingAttention state.
+    /// This should be either a Freedesktop-compliant icon name or a full path.
+    /// The visualization can chose between the movie or AttentionIconPixmap (or
+    /// using neither of those) at its discretion.
+    fn attention_movie_name(&self) -> String {
+        Default::default()
+    }
+
+    /// Data structure that describes extra information associated to this item,
+    /// that can be visualized for instance by a tooltip (or by any other mean
+    /// the visualization consider appropriate.
+    fn tool_tip(&self) -> ToolTip {
+        Default::default()
+    }
+
+    /// Represents the way the text direction of the application.  This
+    /// allows the server to handle mismatches intelligently.
+    fn text_direction(&self) -> TextDirection {
+        menu::TextDirection::LeftToRight
+    }
+
+    /// The menu that you want to display
+    fn menu(&self) -> Vec<MenuItem<Self>> {
+        Default::default()
+    }
+
+    /// The `org.kde.StatusNotifierWatcher` is online
+    fn watcher_online(&self) {}
+
+    /// The `org.kde.StatusNotifierWatcher` is offine
+    ///
+    /// You can setup a fallback tray here
+    ///
+    /// Return `false` to shutdown the tray service
+    fn watcher_offine(&self) -> bool {
+        true
+    }
+}
+
+/// Handle to the tray
+pub struct Handle<T> {
+    tray_status: TrayStatus,
+    model: Arc<Mutex<T>>,
+}
+
+#[doc(hidden)]
+#[deprecated(note = "State is renamed to Handle")]
+pub type State<T> = Handle<T>;
+
+impl<T: Tray> Handle<T> {
+    /// Update the tray
+    pub fn update<R, F: FnOnce(&mut T) -> R>(&self, f: F) -> R {
+        let ret = f(&mut self.model.lock().unwrap());
+        self.tray_status.need_update();
+        ret
+    }
+
+    /// Shutdown the tray service
+    pub fn shutdown(&self) {
+        self.tray_status.stop();
+    }
+}
+
+impl<T> Clone for Handle<T> {
+    fn clone(&self) -> Self {
+        Handle {
+            tray_status: self.tray_status.clone(),
+            model: self.model.clone(),
+        }
+    }
+}
+
+#[derive(Clone, Default)]
+struct TrayStatus {
+    stop: Arc<AtomicBool>,
+    need_update: Arc<AtomicBool>,
+}
+
+impl TrayStatus {
+    fn need_update(&self) {
+        self.need_update.store(true, Ordering::Release);
+    }
+
+    fn stop(&self) {
+        self.stop.store(true, Ordering::Release);
+    }
+
+    fn take(&self) -> CurrentTrayStatus {
+        if self.stop.load(Ordering::Acquire) {
+            CurrentTrayStatus::Stop
+        } else if self.need_update.swap(false, Ordering::AcqRel) {
+            CurrentTrayStatus::NeedUpdate
+        } else {
+            CurrentTrayStatus::Idle
+        }
+    }
+}
+
+enum CurrentTrayStatus {
+    NeedUpdate,
+    Stop,
+    Idle,
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/menu.rs
@@ -0,0 +1,951 @@
+//! Types used to construct a menu
+
+use std::collections::HashMap;
+use std::fmt;
+use std::rc::Rc;
+
+use dbus::arg::{RefArg, Variant};
+
+// pub struct Properties {
+//     /// Tells if the menus are in a normal state or they believe that they
+//     /// could use some attention.  Cases for showing them would be if help
+//     /// were referring to them or they accessors were being highlighted.
+//     /// This property can have two values: "normal" in almost all cases and
+//     /// "notice" when they should have a higher priority to be shown.
+//     pub status: Status,
+//     /// A list of directories that should be used for finding icons using
+//     /// the icon naming spec.  Idealy there should only be one for the icon
+//     /// theme, but additional ones are often added by applications for
+//     /// app specific icons.
+//     pub icon_theme_path: Vec<String>,
+// }
+
+/// Direction of texts
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum TextDirection {
+    LeftToRight,
+    RightToLeft,
+}
+
+impl fmt::Display for TextDirection {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        let r = match *self {
+            TextDirection::LeftToRight => "ltr",
+            TextDirection::RightToLeft => "rtl",
+        };
+        f.write_str(r)
+    }
+}
+
+pub(crate) enum Status {
+    Normal,
+    Notice,
+}
+
+impl fmt::Display for Status {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        let r = match *self {
+            Status::Normal => "normal",
+            Status::Notice => "notice",
+        };
+        f.write_str(r)
+    }
+}
+
+/// All types of menu item
+///
+/// Do not use directly (except [`MenuItem::Separator`]), see examples in top level documents
+pub enum MenuItem<T> {
+    Standard(StandardItem<T>),
+    /// A separator
+    Separator,
+    Checkmark(CheckmarkItem<T>),
+    SubMenu(SubMenu<T>),
+    RadioGroup(RadioGroup<T>),
+}
+
+/// Menu item, the standard one
+pub struct StandardItem<T> {
+    /// Text of the item, except that:
+    /// -# two consecutive underscore characters "__" are displayed as a
+    /// single underscore,
+    /// -# any remaining underscore characters are not displayed at all,
+    /// -# the first of those remaining underscore characters (unless it is
+    /// the last character in the string) indicates that the following
+    /// character is the access key.
+    pub label: String,
+    /// Whether the item can be activated or not.
+    pub enabled: bool,
+    /// True if the item is visible in the menu.
+    pub visible: bool,
+    /// Icon name of the item, following the freedesktop.org icon spec.
+    pub icon_name: String,
+    /// PNG data of the icon.
+    pub icon_data: Vec<u8>,
+    /// The shortcut of the item. Each array represents the key press
+    /// in the list of keypresses. Each list of strings contains a list of
+    /// modifiers and then the key that is used. The modifier strings
+    /// allowed are: "Control", "Alt", "Shift" and "Super".
+    /// - A simple shortcut like Ctrl+S is represented as:
+    ///   [["Control", "S"]]
+    /// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
+    ///   [["Control", "Q"], ["Alt", "X"]]
+    pub shortcut: Vec<Vec<String>>,
+    /// How the menuitem feels the information it's displaying to the
+    /// user should be presented.
+    pub disposition: Disposition,
+    pub activate: Box<dyn Fn(&mut T)>,
+}
+
+impl<T> Default for StandardItem<T> {
+    fn default() -> Self {
+        StandardItem {
+            label: String::default(),
+            enabled: true,
+            visible: true,
+            icon_name: String::default(),
+            icon_data: Vec::default(),
+            shortcut: Vec::default(),
+            disposition: Disposition::Normal,
+            activate: Box::new(|_this| {}),
+        }
+    }
+}
+
+impl<T> From<StandardItem<T>> for MenuItem<T> {
+    fn from(item: StandardItem<T>) -> Self {
+        MenuItem::Standard(item)
+    }
+}
+
+impl<T: 'static> From<StandardItem<T>> for RawMenuItem<T> {
+    fn from(item: StandardItem<T>) -> Self {
+        let activate = item.activate;
+        Self {
+            r#type: ItemType::Standard,
+            label: item.label,
+            enabled: item.enabled,
+            visible: item.visible,
+            icon_name: item.icon_name,
+            icon_data: item.icon_data,
+            shortcut: item.shortcut,
+            disposition: item.disposition,
+            on_clicked: Rc::new(move |this, _id| {
+                (activate)(this);
+            }),
+            ..Default::default()
+        }
+    }
+}
+
+/// Menu item, a container of another menu tree
+pub struct SubMenu<T> {
+    /// Text of the item, except that:
+    /// -# two consecutive underscore characters "__" are displayed as a
+    /// single underscore,
+    /// -# any remaining underscore characters are not displayed at all,
+    /// -# the first of those remaining underscore characters (unless it is
+    /// the last character in the string) indicates that the following
+    /// character is the access key.
+    pub label: String,
+    /// Whether the item can be activated or not.
+    pub enabled: bool,
+    /// True if the item is visible in the menu.
+    pub visible: bool,
+    /// Icon name of the item, following the freedesktop.org icon spec.
+    pub icon_name: String,
+    /// PNG data of the icon.
+    pub icon_data: Vec<u8>,
+    /// The shortcut of the item. Each array represents the key press
+    /// in the list of keypresses. Each list of strings contains a list of
+    /// modifiers and then the key that is used. The modifier strings
+    /// allowed are: "Control", "Alt", "Shift" and "Super".
+    /// - A simple shortcut like Ctrl+S is represented as:
+    ///   [["Control", "S"]]
+    /// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
+    ///   [["Control", "Q"], ["Alt", "X"]]
+    pub shortcut: Vec<Vec<String>>,
+    /// How the menuitem feels the information it's displaying to the
+    /// user should be presented.
+    pub disposition: Disposition,
+    pub submenu: Vec<MenuItem<T>>,
+}
+
+impl<T> Default for SubMenu<T> {
+    fn default() -> Self {
+        Self {
+            label: String::default(),
+            enabled: true,
+            visible: true,
+            icon_name: String::default(),
+            icon_data: Vec::default(),
+            shortcut: Vec::default(),
+            disposition: Disposition::Normal,
+            submenu: Vec::default(),
+        }
+    }
+}
+
+impl<T> From<SubMenu<T>> for MenuItem<T> {
+    fn from(item: SubMenu<T>) -> Self {
+        MenuItem::SubMenu(item)
+    }
+}
+
+impl<T> From<SubMenu<T>> for RawMenuItem<T> {
+    fn from(item: SubMenu<T>) -> Self {
+        Self {
+            r#type: ItemType::Standard,
+            label: item.label,
+            enabled: item.enabled,
+            visible: item.visible,
+            icon_name: item.icon_name,
+            icon_data: item.icon_data,
+            shortcut: item.shortcut,
+            disposition: item.disposition,
+            on_clicked: Rc::new(move |_this, _id| Default::default()),
+            ..Default::default()
+        }
+    }
+}
+
+/// Menu item, checkable
+pub struct CheckmarkItem<T> {
+    /// Text of the item, except that:
+    /// -# two consecutive underscore characters "__" are displayed as a
+    /// single underscore,
+    /// -# any remaining underscore characters are not displayed at all,
+    /// -# the first of those remaining underscore characters (unless it is
+    /// the last character in the string) indicates that the following
+    /// character is the access key.
+    pub label: String,
+    /// Whether the item can be activated or not.
+    pub enabled: bool,
+    /// True if the item is visible in the menu.
+    pub visible: bool,
+    pub checked: bool,
+    /// PNG data of the icon.
+    pub icon_name: String,
+    /// PNG data of the icon.
+    pub icon_data: Vec<u8>,
+    /// The shortcut of the item. Each array represents the key press
+    /// in the list of keypresses. Each list of strings contains a list of
+    /// modifiers and then the key that is used. The modifier strings
+    /// allowed are: "Control", "Alt", "Shift" and "Super".
+    /// - A simple shortcut like Ctrl+S is represented as:
+    ///   [["Control", "S"]]
+    /// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
+    ///   [["Control", "Q"], ["Alt", "X"]]
+    pub shortcut: Vec<Vec<String>>,
+    /// How the menuitem feels the information it's displaying to the
+    /// user should be presented.
+    pub disposition: Disposition,
+    pub activate: Box<dyn Fn(&mut T)>,
+}
+
+impl<T> Default for CheckmarkItem<T> {
+    fn default() -> Self {
+        CheckmarkItem {
+            label: String::default(),
+            enabled: true,
+            visible: true,
+            checked: false,
+            icon_name: String::default(),
+            icon_data: Vec::default(),
+            shortcut: Vec::default(),
+            disposition: Disposition::Normal,
+            activate: Box::new(|_this| {}),
+        }
+    }
+}
+
+impl<T> From<CheckmarkItem<T>> for MenuItem<T> {
+    fn from(item: CheckmarkItem<T>) -> Self {
+        MenuItem::Checkmark(item)
+    }
+}
+
+impl<T: 'static> From<CheckmarkItem<T>> for RawMenuItem<T> {
+    fn from(item: CheckmarkItem<T>) -> Self {
+        let activate = item.activate;
+        Self {
+            r#type: ItemType::Standard,
+            label: item.label,
+            enabled: item.enabled,
+            visible: item.visible,
+            icon_name: item.icon_name,
+            icon_data: item.icon_data,
+            shortcut: item.shortcut,
+            toggle_type: ToggleType::Checkmark,
+            toggle_state: if item.checked {
+                ToggleState::On
+            } else {
+                ToggleState::Off
+            },
+            disposition: item.disposition,
+            on_clicked: Rc::new(move |this, _id| {
+                (activate)(this);
+            }),
+            ..Default::default()
+        }
+    }
+}
+
+/// Menu item, contains [`RadioItem`]
+pub struct RadioGroup<T> {
+    pub selected: usize,
+    pub select: Box<dyn Fn(&mut T, usize)>,
+    pub options: Vec<RadioItem>,
+}
+
+impl<T> Default for RadioGroup<T> {
+    fn default() -> Self {
+        Self {
+            selected: 0,
+            select: Box::new(|_, _| {}),
+            options: Default::default(),
+        }
+    }
+}
+
+impl<T> From<RadioGroup<T>> for MenuItem<T> {
+    fn from(item: RadioGroup<T>) -> Self {
+        MenuItem::RadioGroup(item)
+    }
+}
+
+/// Items of [`RadioGroup`]
+pub struct RadioItem {
+    /// Text of the item, except that:
+    /// -# two consecutive underscore characters "__" are displayed as a
+    /// single underscore,
+    /// -# any remaining underscore characters are not displayed at all,
+    /// -# the first of those remaining underscore characters (unless it is
+    /// the last character in the string) indicates that the following
+    /// character is the access key.
+    pub label: String,
+    /// Whether the item can be activated or not.
+    pub enabled: bool,
+    /// True if the item is visible in the menu.
+    pub visible: bool,
+    /// Icon name of the item, following the freedesktop.org icon spec.
+    pub icon_name: String,
+    /// PNG data of the icon.
+    pub icon_data: Vec<u8>,
+    /// The shortcut of the item. Each array represents the key press
+    /// in the list of keypresses. Each list of strings contains a list of
+    /// modifiers and then the key that is used. The modifier strings
+    /// allowed are: "Control", "Alt", "Shift" and "Super".
+    /// - A simple shortcut like Ctrl+S is represented as:
+    ///   [["Control", "S"]]
+    /// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
+    ///   [["Control", "Q"], ["Alt", "X"]]
+    pub shortcut: Vec<Vec<String>>,
+    /// How the menuitem feels the information it's displaying to the
+    /// user should be presented.
+    pub disposition: Disposition,
+}
+
+impl Default for RadioItem {
+    fn default() -> Self {
+        Self {
+            label: String::default(),
+            enabled: true,
+            visible: true,
+            icon_name: String::default(),
+            icon_data: Vec::default(),
+            shortcut: Vec::default(),
+            disposition: Disposition::Normal,
+        }
+    }
+}
+
+pub(crate) struct RawMenuItem<T> {
+    r#type: ItemType,
+    /// Text of the item, except that:
+    /// -# two consecutive underscore characters "__" are displayed as a
+    /// single underscore,
+    /// -# any remaining underscore characters are not displayed at all,
+    /// -# the first of those remaining underscore characters (unless it is
+    /// the last character in the string) indicates that the following
+    /// character is the access key.
+    label: String,
+    /// Whether the item can be activated or not.
+    enabled: bool,
+    /// True if the item is visible in the menu.
+    visible: bool,
+    /// Icon name of the item, following the freedesktop.org icon spec.
+    icon_name: String,
+    /// PNG data of the icon.
+    icon_data: Vec<u8>,
+    /// The shortcut of the item. Each array represents the key press
+    /// in the list of keypresses. Each list of strings contains a list of
+    /// modifiers and then the key that is used. The modifier strings
+    /// allowed are: "Control", "Alt", "Shift" and "Super".
+    /// - A simple shortcut like Ctrl+S is represented as:
+    ///   [["Control", "S"]]
+    /// - A complex shortcut like Ctrl+Q, Alt+X is represented as:
+    ///   [["Control", "Q"], ["Alt", "X"]]
+    shortcut: Vec<Vec<String>>,
+    toggle_type: ToggleType,
+    /// Describe the current state of a "togglable" item.
+    /// Note:
+    /// The implementation does not itself handle ensuring that only one
+    /// item in a radio group is set to "on", or that a group does not have
+    /// "on" and "indeterminate" items simultaneously; maintaining this
+    /// policy is up to the toolkit wrappers.
+    toggle_state: ToggleState,
+    /// How the menuitem feels the information it's displaying to the
+    /// user should be presented.
+    disposition: Disposition,
+    pub on_clicked: Rc<dyn Fn(&mut T, usize)>,
+    vendor_properties: HashMap<VendorSpecific, Variant<Box<dyn RefArg + 'static>>>,
+}
+
+impl<T> Clone for RawMenuItem<T> {
+    fn clone(&self) -> Self {
+        let vendor_properties = self
+            .vendor_properties
+            .iter()
+            .map(|(k, v)| (k.clone(), Variant(v.0.box_clone())))
+            .collect();
+
+        RawMenuItem {
+            r#type: self.r#type.clone(),
+            label: self.label.clone(),
+            enabled: self.enabled,
+            visible: self.visible,
+            icon_name: self.icon_name.clone(),
+            icon_data: self.icon_data.clone(),
+            shortcut: self.shortcut.clone(),
+            toggle_type: self.toggle_type,
+            toggle_state: self.toggle_state,
+            disposition: self.disposition,
+            on_clicked: self.on_clicked.clone(),
+            vendor_properties,
+        }
+    }
+}
+
+macro_rules! if_not_default_then_insert {
+    ($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident) => {
+        if_not_default_then_insert!($map, $item, $default, $filter, $property, (|r| r));
+    };
+    ($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident, $to_refarg: tt) => {{
+        let name = stringify!($property).replace('_', "-");
+        if_not_default_then_insert!($map, $item, $default, $filter, $property, name, $to_refarg);
+    }};
+    ($map: ident, $item: ident, $default: ident, $filter: ident, $property: ident, $property_name: tt, $to_refarg: tt) => {
+        if ($filter.is_empty() || $filter.contains(&&*$property_name))
+            && $item.$property != $default.$property
+        {
+            $map.insert(
+                $property_name.to_string(),
+                Variant(Box::new($to_refarg($item.$property))),
+            );
+        }
+    };
+}
+
+impl<T> fmt::Debug for RawMenuItem<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "Item {}", self.label)
+    }
+}
+
+impl<T> RawMenuItem<T> {
+    pub(crate) fn to_dbus_map(
+        &self,
+        filter: &[&str],
+    ) -> HashMap<String, Variant<Box<dyn RefArg + 'static>>> {
+        let item = self.clone();
+        let mut properties: HashMap<String, Variant<Box<dyn RefArg + 'static>>> =
+            HashMap::with_capacity(11);
+
+        let default: RawMenuItem<T> = RawMenuItem::default();
+        if_not_default_then_insert!(
+            properties,
+            item,
+            default,
+            filter,
+            r#type,
+            "type",
+            (|r: ItemType| r.to_string())
+        );
+        if_not_default_then_insert!(properties, item, default, filter, label);
+        if_not_default_then_insert!(properties, item, default, filter, enabled);
+        if_not_default_then_insert!(properties, item, default, filter, visible);
+        if_not_default_then_insert!(properties, item, default, filter, icon_name);
+        if_not_default_then_insert!(properties, item, default, filter, icon_data);
+        if_not_default_then_insert!(properties, item, default, filter, shortcut);
+        if_not_default_then_insert!(
+            properties,
+            item,
+            default,
+            filter,
+            toggle_type,
+            (|r: ToggleType| r.to_string())
+        );
+        if_not_default_then_insert!(
+            properties,
+            item,
+            default,
+            filter,
+            toggle_state,
+            (|r| r as i32)
+        );
+        if_not_default_then_insert!(
+            properties,
+            item,
+            default,
+            filter,
+            disposition,
+            (|r: Disposition| r.to_string())
+        );
+
+        for (k, v) in item.vendor_properties {
+            properties.insert(k.to_string(), v);
+        }
+
+        properties
+    }
+
+    pub(crate) fn diff(
+        &self,
+        other: Self,
+    ) -> Option<(HashMap<String, Variant<Box<dyn RefArg>>>, Vec<String>)> {
+        let default = Self::default();
+        let mut updated_props: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
+        let mut removed_props = Vec::new();
+        if self.r#type != other.r#type {
+            if other.r#type == default.r#type {
+                removed_props.push("type".into());
+            } else {
+                updated_props.insert("type".into(), Variant(Box::new(other.r#type.to_string())));
+            }
+        }
+        if self.label != other.label {
+            if other.label == default.label {
+                removed_props.push("label".into());
+            } else {
+                updated_props.insert("label".into(), Variant(Box::new(other.label)));
+            }
+        }
+        if self.enabled != other.enabled {
+            if other.enabled == default.enabled {
+                removed_props.push("enabled".into());
+            } else {
+                updated_props.insert("enabled".into(), Variant(Box::new(other.enabled)));
+            }
+        }
+        if self.visible != other.visible {
+            if other.visible == default.visible {
+                removed_props.push("visible".into());
+            } else {
+                updated_props.insert("visible".into(), Variant(Box::new(other.visible)));
+            }
+        }
+        if self.icon_name != other.icon_name {
+            if other.icon_name == default.icon_name {
+                removed_props.push("icon-name".into());
+            } else {
+                updated_props.insert("icon-name".into(), Variant(Box::new(other.icon_name)));
+            }
+        }
+        if self.icon_data != other.icon_data {
+            if other.icon_data == default.icon_data {
+                removed_props.push("icon-data".into());
+            } else {
+                updated_props.insert("icon-data".into(), Variant(Box::new(other.icon_data)));
+            }
+        }
+        if self.shortcut != other.shortcut {
+            if other.shortcut == default.shortcut {
+                removed_props.push("shortcut".into());
+            } else {
+                updated_props.insert("shortcut".into(), Variant(Box::new(other.shortcut)));
+            }
+        }
+        if self.toggle_type != other.toggle_type {
+            if other.toggle_type == default.toggle_type {
+                removed_props.push("toggle-type".into());
+            } else {
+                updated_props.insert(
+                    "toggle-type".into(),
+                    Variant(Box::new(other.toggle_type.to_string())),
+                );
+            }
+        }
+        if self.toggle_state != other.toggle_state {
+            if other.toggle_state == default.toggle_state {
+                removed_props.push("toggle-state".into());
+            } else {
+                updated_props.insert(
+                    "toggle-state".into(),
+                    Variant(Box::new(other.toggle_state as i32)),
+                );
+            }
+        }
+        if self.disposition != other.disposition {
+            if other.disposition == default.disposition {
+                removed_props.push("disposition".into());
+            } else {
+                updated_props.insert(
+                    "disposition".into(),
+                    Variant(Box::new(other.disposition.to_string())),
+                );
+            }
+        }
+        // TODO: vendor_properties
+        if updated_props.is_empty() && removed_props.is_empty() {
+            None
+        } else {
+            Some((updated_props, removed_props))
+        }
+    }
+}
+
+impl<T> Default for RawMenuItem<T> {
+    fn default() -> Self {
+        RawMenuItem {
+            r#type: ItemType::Standard,
+            label: String::default(),
+            enabled: true,
+            visible: true,
+            icon_name: String::default(),
+            icon_data: Vec::default(),
+            shortcut: Vec::default(),
+            toggle_type: ToggleType::Null,
+            toggle_state: ToggleState::Indeterminate,
+            disposition: Disposition::Normal,
+            //submenu: Vec::default(),
+            on_clicked: Rc::new(|_this, _id| Default::default()),
+            vendor_properties: HashMap::default(),
+        }
+    }
+}
+
+/// Vendor specific types/properties
+/// will be formatted to "x-<vendor>-<name>""
+#[doc(hidden)]
+#[derive(Debug, Hash, Eq, PartialEq, Clone)]
+pub struct VendorSpecific {
+    pub vendor: String,
+    pub name: String,
+}
+
+impl fmt::Display for VendorSpecific {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        write!(f, "x-{}-{}", self.vendor, self.name)
+    }
+}
+
+#[allow(dead_code)]
+#[derive(Debug, Eq, PartialEq, Clone)]
+enum ItemType {
+    /// An item which can be clicked to trigger an action or show another menu
+    Standard,
+    /// A separator
+    Separator,
+    /// Vendor specific types
+    Vendor(VendorSpecific),
+}
+
+impl fmt::Display for ItemType {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        use ItemType::*;
+        match self {
+            Standard => f.write_str("standard"),
+            Separator => f.write_str("separator"),
+            Vendor(vendor) => vendor.fmt(f),
+        }
+    }
+}
+
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+enum ToggleType {
+    /// Item is an independent togglable item
+    Checkmark,
+    /// Item is part of a group where only one item can be toggled at a time
+    Radio,
+    /// Item cannot be toggled
+    Null,
+}
+
+impl fmt::Display for ToggleType {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        use ToggleType::*;
+        let r = match self {
+            Checkmark => "checkmark",
+            Radio => "radio",
+            Null => "",
+        };
+        f.write_str(r)
+    }
+}
+
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+enum ToggleState {
+    Off = 0,
+    On = 1,
+    Indeterminate = -1,
+}
+
+/// Item disposition
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+pub enum Disposition {
+    /// A standard menu item
+    Normal,
+    /// Providing additional information to the user
+    Informative,
+    /// Looking at potentially harmful results
+    Warning,
+    /// Something bad could potentially happen
+    Alert,
+}
+
+impl fmt::Display for Disposition {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        use Disposition::*;
+        let r = match self {
+            Normal => "normal",
+            Informative => "informative",
+            Warning => "warning",
+            Alert => "alert",
+        };
+        f.write_str(r)
+    }
+}
+
+pub(crate) fn menu_flatten<T: 'static>(
+    items: Vec<MenuItem<T>>,
+) -> Vec<(RawMenuItem<T>, Vec<usize>)> {
+    let mut list: Vec<(RawMenuItem<T>, Vec<usize>)> =
+        vec![(RawMenuItem::default(), Vec::with_capacity(items.len()))];
+
+    let mut stack = vec![(items, 0)]; // (menu, menu's parent)
+
+    while let Some((mut current_menu, parent_index)) = stack.pop() {
+        while !current_menu.is_empty() {
+            match current_menu.remove(0) {
+                MenuItem::Standard(item) => {
+                    let index = list.len();
+                    list.push((item.into(), Vec::new()));
+                    // Add self to parent's submenu
+                    list[parent_index].1.push(index);
+                }
+                MenuItem::Separator => {
+                    let item = RawMenuItem {
+                        r#type: ItemType::Separator,
+                        ..Default::default()
+                    };
+                    let index = list.len();
+                    list.push((item, Vec::new()));
+                    list[parent_index].1.push(index);
+                }
+                MenuItem::Checkmark(item) => {
+                    let index = list.len();
+                    list.push((item.into(), Vec::new()));
+                    list[parent_index].1.push(index);
+                }
+                MenuItem::SubMenu(mut item) => {
+                    let submenu = std::mem::replace(&mut item.submenu, Default::default());
+                    let index = list.len();
+                    list.push((item.into(), Vec::with_capacity(submenu.len())));
+                    list[parent_index].1.push(index);
+                    if !submenu.is_empty() {
+                        stack.push((current_menu, parent_index));
+                        stack.push((submenu, index));
+                        break;
+                    }
+                }
+                MenuItem::RadioGroup(group) => {
+                    let offset = list.len();
+                    let on_selected = Rc::new(group.select);
+                    for (idx, option) in group.options.into_iter().enumerate() {
+                        let on_selected = on_selected.clone();
+                        let item = RawMenuItem {
+                            r#type: ItemType::Standard,
+                            label: option.label,
+                            enabled: option.enabled,
+                            visible: option.visible,
+                            icon_name: option.icon_name,
+                            icon_data: option.icon_data,
+                            shortcut: option.shortcut,
+                            toggle_type: ToggleType::Radio,
+                            toggle_state: if idx == group.selected {
+                                ToggleState::On
+                            } else {
+                                ToggleState::Off
+                            },
+                            disposition: option.disposition,
+                            on_clicked: Rc::new(move |this, id| {
+                                (on_selected)(this, id - offset);
+                            }),
+                            ..Default::default()
+                        };
+                        let index = list.len();
+                        list.push((item, Vec::new()));
+                        list[parent_index].1.push(index);
+                    }
+                }
+            }
+        }
+    }
+
+    list
+}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+    #[test]
+    fn test_menu_flatten() {
+        let x: Vec<MenuItem<()>> = vec![
+            SubMenu {
+                label: "a".into(),
+                submenu: vec![
+                    SubMenu {
+                        label: "a1".into(),
+                        submenu: vec![StandardItem {
+                            label: "a1.1".into(),
+                            ..Default::default()
+                        }
+                        .into()],
+                        ..Default::default()
+                    }
+                    .into(),
+                    StandardItem {
+                        label: "a2".into(),
+                        ..Default::default()
+                    }
+                    .into(),
+                ],
+                ..Default::default()
+            }
+            .into(),
+            StandardItem {
+                label: "b".into(),
+                ..Default::default()
+            }
+            .into(),
+            SubMenu {
+                label: "c".into(),
+                submenu: vec![
+                    StandardItem {
+                        label: "c1".into(),
+                        ..Default::default()
+                    }
+                    .into(),
+                    SubMenu {
+                        label: "c2".into(),
+                        submenu: vec![StandardItem {
+                            label: "c2.1".into(),
+                            ..Default::default()
+                        }
+                        .into()],
+                        ..Default::default()
+                    }
+                    .into(),
+                ],
+                ..Default::default()
+            }
+            .into(),
+        ];
+
+        let r = menu_flatten(x);
+        let expect: Vec<(RawMenuItem<()>, Vec<usize>)> = vec![
+            (
+                RawMenuItem {
+                    label: "".into(),
+                    ..Default::default()
+                },
+                vec![1, 5, 6],
+            ),
+            (
+                RawMenuItem {
+                    label: "a".into(),
+                    ..Default::default()
+                },
+                vec![2, 4],
+            ),
+            (
+                RawMenuItem {
+                    label: "a1".into(),
+                    ..Default::default()
+                },
+                vec![3],
+            ),
+            (
+                RawMenuItem {
+                    label: "a1.1".into(),
+                    ..Default::default()
+                },
+                vec![],
+            ),
+            (
+                RawMenuItem {
+                    label: "a2".into(),
+                    ..Default::default()
+                },
+                vec![],
+            ),
+            (
+                RawMenuItem {
+                    label: "b".into(),
+                    ..Default::default()
+                },
+                vec![],
+            ),
+            (
+                RawMenuItem {
+                    label: "c".into(),
+                    ..Default::default()
+                },
+                vec![7, 8],
+            ),
+            (
+                RawMenuItem {
+                    label: "c1".into(),
+                    ..Default::default()
+                },
+                vec![],
+            ),
+            (
+                RawMenuItem {
+                    label: "c2".into(),
+                    ..Default::default()
+                },
+                vec![9],
+            ),
+            (
+                RawMenuItem {
+                    label: "c2.1".into(),
+                    ..Default::default()
+                },
+                vec![],
+            ),
+        ];
+        assert_eq!(r.len(), 10);
+        assert_eq!(r[0].1, expect[0].1);
+        assert_eq!(r[1].1, expect[1].1);
+        assert_eq!(r[2].1, expect[2].1);
+        assert_eq!(r[3].1, expect[3].1);
+        assert_eq!(r[4].1, expect[4].1);
+        assert_eq!(r[5].1, expect[5].1);
+        assert_eq!(r[6].1, expect[6].1);
+        assert_eq!(r[7].1, expect[7].1);
+        assert_eq!(r[8].1, expect[8].1);
+        assert_eq!(r[9].1, expect[9].1);
+        assert_eq!(r[0].0.label, expect[0].0.label);
+        assert_eq!(r[1].0.label, expect[1].0.label);
+        assert_eq!(r[2].0.label, expect[2].0.label);
+        assert_eq!(r[3].0.label, expect[3].0.label);
+        assert_eq!(r[4].0.label, expect[4].0.label);
+        assert_eq!(r[5].0.label, expect[5].0.label);
+        assert_eq!(r[6].0.label, expect[6].0.label);
+        assert_eq!(r[7].0.label, expect[7].0.label);
+        assert_eq!(r[8].0.label, expect[8].0.label);
+        assert_eq!(r[9].0.label, expect[9].0.label);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/service.rs
@@ -0,0 +1,986 @@
+use std::cell::Cell;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::fmt;
+use std::hash::{Hash, Hasher};
+use std::rc::Rc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use dbus;
+use dbus::arg::{RefArg, Variant};
+use dbus::blocking::stdintf::org_freedesktop_dbus::PropertiesPropertiesChanged;
+use dbus::blocking::LocalConnection;
+use dbus::channel::{MatchingReceiver, Sender};
+use dbus::message::SignalArgs;
+use dbus::message::{MatchRule, MessageType};
+
+use crate::dbus_ext;
+use crate::dbus_interface;
+use crate::dbus_interface::{
+    DbusmenuItemsPropertiesUpdated, DbusmenuLayoutUpdated, StatusNotifierItemNewAttentionIcon,
+    StatusNotifierItemNewIcon, StatusNotifierItemNewOverlayIcon, StatusNotifierItemNewStatus,
+    StatusNotifierItemNewTitle, StatusNotifierItemNewToolTip, StatusNotifierWatcher,
+};
+use crate::error;
+use crate::freedesktop;
+use crate::menu;
+use crate::tray;
+use crate::{Handle, Tray};
+
+const SNI_PATH: &str = "/StatusNotifierItem";
+const MENU_PATH: &str = "/MenuBar";
+
+static COUNTER: AtomicUsize = AtomicUsize::new(1);
+
+/// Service of the tray
+pub struct TrayService<T> {
+    tray: Handle<T>,
+}
+
+impl<T: Tray + 'static> TrayService<T> {
+    /// Create a new service
+    pub fn new(tray: T) -> Self {
+        let tray_state = crate::TrayStatus::default();
+        TrayService {
+            tray: Handle {
+                model: Arc::new(Mutex::new(tray)),
+                tray_status: tray_state.clone(),
+            },
+        }
+    }
+
+    #[doc(hidden)]
+    #[deprecated(note = "state is renamed to handle")]
+    pub fn state(&self) -> Handle<T> {
+        self.tray.clone()
+    }
+
+    /// Get a handle of the tray
+    pub fn handle(&self) -> Handle<T> {
+        self.tray.clone()
+    }
+
+    fn service_loop(self, own_name: bool) -> Result<(), dbus::Error> {
+        let mut service = self.build_processor(own_name)?;
+        loop {
+            match service.turn(None) {
+                Err(error::Error::Stopped) => return Ok(()),
+                Err(error::Error::Dbus(r)) => return Err(r),
+                Ok(_) => (),
+            }
+        }
+    }
+
+    /// Run the service in current thread
+    pub fn run(self) -> Result<(), dbus::Error> {
+        self.service_loop(true)
+    }
+
+    /// Run the service in current thread, but not register new dbus name
+    ///
+    /// Which is required for some sandboxed environments (flatpak)
+    /// https://chromium-review.googlesource.com/c/chromium/src/+/4179380
+    pub fn run_without_dbus_name(self) -> Result<(), dbus::Error> {
+        self.service_loop(false)
+    }
+
+    /// Run the service in a new thread
+    pub fn spawn(self)
+    where
+        T: Send,
+    {
+        thread::spawn(|| self.run().unwrap());
+    }
+
+    /// Run the service in a new thread, but not register new dbus name
+    ///
+    /// Which is required for some sandboxed environments (flatpak)
+    /// https://chromium-review.googlesource.com/c/chromium/src/+/4179380
+    pub fn spawn_without_dbus_name(self)
+    where
+        T: Send,
+    {
+        thread::spawn(|| self.run_without_dbus_name().unwrap());
+    }
+
+    fn build_processor(self, own_name: bool) -> Result<Processor<T>, dbus::Error> {
+        let conn = LocalConnection::new_session()?;
+        let name = if own_name {
+            format!(
+                "org.kde.StatusNotifierItem-{}-{}",
+                std::process::id(),
+                COUNTER.fetch_add(1, Ordering::AcqRel)
+            )
+        } else {
+            conn.unique_name().to_string()
+        };
+
+        if own_name {
+            conn.request_name(&name, true, true, false)?;
+        }
+
+        let (menu_cache, prop_cache) = {
+            let state = self.tray.model.lock().unwrap();
+            (
+                RefCell::new(menu::menu_flatten(T::menu(&*state))),
+                RefCell::new(PropertiesCache::new(&*state)),
+            )
+        };
+        let inner = Rc::new(InnerState {
+            handle: self.tray,
+            menu_cache,
+            item_id_offset: Cell::new(0),
+            revision: Cell::new(0),
+            prop_cache,
+        });
+
+        let tray_service2 = inner.clone();
+        let tray_service3 = inner.clone();
+        let f = dbus_tree::Factory::new_fn::<()>();
+        let sni_interface = dbus_interface::status_notifier_item_server(&f, (), move |_| {
+            tray_service2.clone() as Rc<dyn dbus_interface::StatusNotifierItem>
+        });
+        let menu_interface = dbus_interface::dbusmenu_server(&f, (), move |_| {
+            tray_service3.clone() as Rc<dyn dbus_interface::Dbusmenu>
+        });
+        let tree = f
+            .tree(())
+            .add(
+                f.object_path(SNI_PATH, ())
+                    .introspectable()
+                    .add(sni_interface),
+            )
+            .add(
+                f.object_path(MENU_PATH, ())
+                    .introspectable()
+                    .add(menu_interface),
+            )
+            // Add root path, to help introspection from debugging tools
+            .add(f.object_path("/", ()).introspectable());
+        let mut rule = MatchRule::new();
+        rule.msg_type = Some(MessageType::MethodCall);
+        conn.start_receive(
+            rule,
+            Box::new(move |msg, c| {
+                dbus_ext::with_conn(c, || {
+                    if let Some(replies) = tree.handle(&msg) {
+                        for r in replies {
+                            let _ = c.send(r);
+                        }
+                    }
+                });
+                true
+            }),
+        );
+
+        let snw_object = conn.with_proxy(
+            "org.kde.StatusNotifierWatcher",
+            "/StatusNotifierWatcher",
+            Duration::from_secs(1),
+        );
+        match snw_object.register_status_notifier_item(&name) {
+            Err(ref e) if e.name() == Some("org.freedesktop.DBus.Error.ServiceUnknown") => {
+                if !inner.handle.model.lock().unwrap().watcher_offine() {
+                    inner.handle.tray_status.stop();
+                }
+            }
+            Ok(()) => inner.handle.model.lock().unwrap().watcher_online(),
+            r => r?,
+        };
+
+        let dbus_object = conn.with_proxy(
+            "org.freedesktop.DBus",
+            "/org/freedesktop/DBus",
+            Duration::from_secs(1),
+        );
+        let inner2 = inner.clone();
+        dbus_object.match_signal(
+            move |h: freedesktop::NameOwnerChanged, c: &LocalConnection, _: &dbus::Message| {
+                if h.name == "org.kde.StatusNotifierWatcher" {
+                    if h.new_owner.is_empty() {
+                        if !inner2.handle.model.lock().unwrap().watcher_offine() {
+                            inner2.handle.tray_status.stop();
+                        }
+                    } else {
+                        if h.old_owner.is_empty() {
+                            inner2.handle.model.lock().unwrap().watcher_online();
+                        }
+                        c.with_proxy(
+                            "org.kde.StatusNotifierWatcher",
+                            "/StatusNotifierWatcher",
+                            Duration::from_secs(1),
+                        )
+                        .register_status_notifier_item(&name)
+                        .unwrap_or_default();
+                    }
+                }
+                true
+            },
+        )?;
+
+        Ok(Processor { conn, state: inner })
+    }
+}
+
+/// A running TrayService, !Send + !Sync
+struct Processor<T> {
+    conn: LocalConnection,
+    state: Rc<InnerState<T>>,
+}
+
+impl<T: Tray + 'static> Processor<T> {
+    fn turn(&mut self, timeout: Option<Duration>) -> Result<(), error::Error> {
+        const PIECE: Duration = Duration::from_millis(50);
+        let now = Instant::now();
+        // Didn't find a better way to do the "select",
+        // just poll
+        loop {
+            use crate::CurrentTrayStatus::*;
+            match self.state.handle.tray_status.take() {
+                NeedUpdate => {
+                    dbus_ext::with_conn(&self.conn, || {
+                        self.state.update_properties();
+                        self.state.update_menu();
+                    });
+                }
+                Stop => {
+                    break Err(error::Error::Stopped);
+                }
+                Idle => {}
+            }
+            let wait = timeout
+                .map(|timeout| std::cmp::min(PIECE, timeout - now.elapsed()))
+                .unwrap_or(PIECE);
+            self.conn.process(wait)?;
+            if wait < PIECE {
+                break Ok(());
+            }
+        }
+    }
+}
+
+struct InnerState<T> {
+    handle: Handle<T>,
+    // A list of menu item and it's submenu
+    menu_cache: RefCell<Vec<(menu::RawMenuItem<T>, Vec<usize>)>>,
+    item_id_offset: Cell<i32>,
+    revision: Cell<u32>,
+    prop_cache: RefCell<PropertiesCache>,
+}
+
+impl<T: Tray + 'static> InnerState<T> {
+    fn update_immediately<F: Fn(&mut T)>(&self, f: F) {
+        {
+            let mut model = self.handle.model.lock().unwrap();
+            (f)(&mut model);
+        }
+        self.update_properties();
+        self.update_menu();
+    }
+
+    // TODO: macro?
+    fn update_properties(&self) {
+        let sni_dbus_path: dbus::Path = SNI_PATH.into();
+        let inner = self.handle.model.lock().unwrap();
+        let mut prop_cache = self.prop_cache.borrow_mut();
+        let mut dbusmenu_changed: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
+        let mut sni_changed: HashMap<String, Variant<Box<dyn RefArg>>> = HashMap::new();
+
+        let mut dbus_msgs = Vec::new();
+
+        if let Some(text_direction) = prop_cache.text_direction_changed(&*inner) {
+            dbusmenu_changed.insert(
+                "TextDirection".into(),
+                Variant(Box::new(text_direction.to_string())),
+            );
+        }
+
+        if let Some(tray_status) = prop_cache.status_changed(&*inner) {
+            let msg = StatusNotifierItemNewStatus {
+                status: tray_status.to_string(),
+            }
+            .to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+            let menu_status = match tray_status {
+                tray::Status::Passive | tray::Status::Active => menu::Status::Normal,
+                tray::Status::NeedsAttention => menu::Status::Notice,
+            };
+            dbusmenu_changed.insert("Status".into(), Variant(Box::new(menu_status.to_string())));
+        }
+
+        if let Some(icon_theme_path) = prop_cache.icon_theme_path_changed(&*inner) {
+            dbusmenu_changed.insert(
+                "IconThemePath".into(),
+                Variant(Box::new(icon_theme_path.to_string())),
+            );
+            sni_changed.insert(
+                "IconThemePath".into(),
+                Variant(Box::new(vec![icon_theme_path.to_string()])),
+            );
+        }
+
+        if !dbusmenu_changed.is_empty() {
+            let msg = PropertiesPropertiesChanged {
+                interface_name: "com.canonical.dbusmenu".to_owned(),
+                changed_properties: dbusmenu_changed,
+                invalidated_properties: Vec::new(),
+            }
+            .to_emit_message(&MENU_PATH.into());
+            dbus_msgs.push(msg);
+        }
+
+        if let Some(category) = prop_cache.category_changed(&*inner) {
+            sni_changed.insert("Category".into(), Variant(Box::new(category.to_string())));
+        }
+
+        if let Some(window_id) = prop_cache.window_id_changed(&*inner) {
+            sni_changed.insert("WindowId".into(), Variant(Box::new(window_id.to_string())));
+        }
+
+        if !sni_changed.is_empty() {
+            let msg = PropertiesPropertiesChanged {
+                interface_name: "org.kde.StatusNotifierItem".to_owned(),
+                changed_properties: sni_changed,
+                invalidated_properties: Vec::new(),
+            }
+            .to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+
+        // TODO: assert the id is consistent
+
+        if prop_cache.title_changed(&*inner) {
+            let msg = StatusNotifierItemNewTitle {}.to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+        if prop_cache.icon_changed(&*inner) {
+            let msg = StatusNotifierItemNewIcon {}.to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+        if prop_cache.overlay_icon_changed(&*inner) {
+            let msg = StatusNotifierItemNewOverlayIcon {}.to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+        if prop_cache.attention_icon_changed(&*inner) {
+            let msg = StatusNotifierItemNewAttentionIcon {}.to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+        if prop_cache.tool_tip_changed(&*inner) {
+            let msg = StatusNotifierItemNewToolTip {}.to_emit_message(&sni_dbus_path);
+            dbus_msgs.push(msg);
+        }
+
+        dbus_ext::with_current(move |conn| {
+            for msg in dbus_msgs {
+                conn.send(msg).unwrap();
+            }
+        })
+        .unwrap();
+    }
+
+    fn update_menu(&self) {
+        let new_menu = menu::menu_flatten(T::menu(&*self.handle.model.lock().unwrap()));
+        let mut old_menu = self.menu_cache.borrow_mut();
+
+        let mut props_updated = DbusmenuItemsPropertiesUpdated {
+            updated_props: Vec::new(),
+            removed_props: Vec::new(),
+        };
+        let default = crate::menu::RawMenuItem::default();
+        let mut layout_updated = false;
+        for (index, (old, new)) in old_menu
+            .iter()
+            .chain(std::iter::repeat(&(default, vec![])))
+            .zip(new_menu.clone().into_iter())
+            .enumerate()
+        {
+            let (old_item, old_childs) = old;
+            let (new_item, new_childs) = new;
+
+            if let Some((updated_props, removed_props)) = old_item.diff(new_item) {
+                if !updated_props.is_empty() {
+                    props_updated
+                        .updated_props
+                        .push((self.index2id(index), updated_props));
+                }
+                if !removed_props.is_empty() {
+                    props_updated
+                        .removed_props
+                        .push((self.index2id(index), removed_props));
+                }
+            }
+            if *old_childs != new_childs {
+                layout_updated = true;
+                break;
+            }
+        }
+
+        if layout_updated {
+            // The layout has been changed, bump ID offset to invalidate all items,
+            // which is required to avoid unexpected behaviors on some system tray
+            self.revision.set(self.revision.get() + 1);
+            self.item_id_offset
+                .set(self.item_id_offset.get() + old_menu.len() as i32);
+            *old_menu = new_menu;
+
+            let msg = DbusmenuLayoutUpdated {
+                parent: 0,
+                revision: self.revision.get(),
+            }
+            .to_emit_message(&MENU_PATH.into());
+            dbus_ext::with_current(move |conn| {
+                conn.send(msg).unwrap();
+            })
+            .unwrap();
+        } else if !props_updated.updated_props.is_empty() || !props_updated.removed_props.is_empty()
+        {
+            *old_menu = new_menu;
+
+            let msg = props_updated.to_emit_message(&MENU_PATH.into());
+            dbus_ext::with_current(move |conn| {
+                conn.send(msg).unwrap();
+            })
+            .unwrap();
+        } else {
+            *old_menu = new_menu;
+        }
+    }
+
+    // Return None if item not exists
+    fn id2index(&self, id: i32) -> Option<usize> {
+        let number_of_items = self.menu_cache.borrow().len();
+        let offset = self.item_id_offset.get();
+        if id == 0 && number_of_items > 0 {
+            // ID of the root item is always 0
+            return Some(0);
+        } else if id == offset {
+            // illegal id, bug in index2id or dbus peer
+            return None;
+        } else if id <= offset {
+            // expired id
+            return None;
+        }
+        let index: usize = (id - offset).try_into().expect("unreachable!");
+        if index < number_of_items {
+            Some(index)
+        } else {
+            None
+        }
+    }
+
+    fn index2id(&self, index: usize) -> i32 {
+        // ID of the root item is always 0
+        if index == 0 {
+            0
+        } else {
+            <i32 as TryFrom<_>>::try_from(index)
+                .expect("index overflow")
+                .checked_add(self.item_id_offset.get())
+                .expect("id overflow")
+        }
+    }
+
+    // Return None if parent_id not found
+    fn gen_dbusmenu_tree(
+        &self,
+        parent_id: i32,
+        recursion_depth: Option<usize>,
+        property_names: Vec<&str>,
+    ) -> Option<(
+        i32,
+        HashMap<String, Variant<Box<dyn RefArg + 'static>>>,
+        Vec<Variant<Box<dyn RefArg + 'static>>>,
+    )> {
+        let parent_index = self.id2index(parent_id)?;
+
+        // The type is Vec<Option<id, properties, Vec<submenu>, Vec<submenu_index>>>
+        let mut x: Vec<
+            Option<(
+                i32,
+                HashMap<String, Variant<Box<dyn RefArg>>>,
+                Vec<Variant<Box<dyn RefArg>>>,
+                Vec<usize>,
+            )>,
+        > = self
+            .menu_cache
+            .borrow()
+            .iter()
+            .enumerate()
+            .map(|(index, (item, submenu))| {
+                (
+                    self.index2id(index),
+                    item.to_dbus_map(&property_names),
+                    Vec::with_capacity(submenu.len()),
+                    submenu.clone(),
+                )
+            })
+            .map(Some)
+            .collect();
+        let mut stack = vec![parent_index];
+
+        while let Some(current) = stack.pop() {
+            let submenu_indexes = &mut x[current].as_mut().unwrap().3;
+            if submenu_indexes.is_empty() {
+                let c = x[current].as_mut().unwrap();
+                if !c.2.is_empty() {
+                    c.1.insert(
+                        "children-display".into(),
+                        Variant(Box::new("submenu".to_owned())),
+                    );
+                }
+                if let Some(parent) = stack.pop() {
+                    x.push(None);
+                    let item = x.swap_remove(current).unwrap();
+                    stack.push(parent);
+                    x[parent]
+                        .as_mut()
+                        .unwrap()
+                        .2
+                        .push(Variant(Box::new((item.0, item.1, item.2))));
+                }
+            } else {
+                stack.push(current);
+                let sub = submenu_indexes.remove(0);
+                if recursion_depth.is_none() || recursion_depth.unwrap() + 1 >= stack.len() {
+                    stack.push(sub);
+                }
+            }
+        }
+
+        let resp = x.remove(parent_index).unwrap();
+        Some((resp.0, resp.1, resp.2))
+    }
+}
+
+impl<T: Tray> fmt::Debug for InnerState<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        f.debug_struct(&format!("StatusNotifierItem")).finish()
+    }
+}
+
+impl<T: Tray + 'static> dbus_interface::StatusNotifierItem for InnerState<T> {
+    fn activate(&self, x: i32, y: i32) -> Result<(), dbus::MethodErr> {
+        self.update_immediately(|model| {
+            Tray::activate(model, x, y);
+        });
+        Ok(())
+    }
+
+    fn secondary_activate(&self, x: i32, y: i32) -> Result<(), dbus::MethodErr> {
+        self.update_immediately(|model| {
+            Tray::secondary_activate(&mut *model, x, y);
+        });
+        Ok(())
+    }
+
+    fn scroll(&self, delta: i32, dir: &str) -> Result<(), dbus::MethodErr> {
+        self.update_immediately(|model| {
+            Tray::scroll(&mut *model, delta, dir);
+        });
+        Ok(())
+    }
+
+    fn context_menu(&self, _x: i32, _y: i32) -> Result<(), dbus::MethodErr> {
+        Ok(())
+    }
+
+    fn item_is_menu(&self) -> Result<bool, dbus::MethodErr> {
+        Ok(false)
+    }
+
+    fn category(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::category(&*model).to_string())
+    }
+
+    fn id(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::id(&*model))
+    }
+
+    fn title(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::title(&*model))
+    }
+
+    fn status(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::status(&*model).to_string())
+    }
+
+    fn window_id(&self) -> Result<i32, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::window_id(&*model))
+    }
+
+    fn menu(&self) -> Result<dbus::Path<'static>, dbus::MethodErr> {
+        Ok(MENU_PATH.into())
+    }
+
+    fn icon_name(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::icon_name(&*model))
+    }
+
+    fn icon_theme_path(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::icon_theme_path(&*model))
+    }
+
+    fn icon_pixmap(&self) -> Result<Vec<(i32, i32, Vec<u8>)>, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::icon_pixmap(&*model)
+            .into_iter()
+            .map(Into::into)
+            .collect())
+    }
+
+    fn overlay_icon_name(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::overlay_icon_name(&*model))
+    }
+
+    fn overlay_icon_pixmap(&self) -> Result<Vec<(i32, i32, Vec<u8>)>, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::overlay_icon_pixmap(&*model)
+            .into_iter()
+            .map(Into::into)
+            .collect())
+    }
+
+    fn attention_icon_name(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::attention_icon_name(&*model))
+    }
+
+    fn attention_icon_pixmap(&self) -> Result<Vec<(i32, i32, Vec<u8>)>, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::attention_icon_pixmap(&*model)
+            .into_iter()
+            .map(Into::into)
+            .collect())
+    }
+
+    fn attention_movie_name(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::attention_movie_name(&*model))
+    }
+
+    fn tool_tip(
+        &self,
+    ) -> Result<(String, Vec<(i32, i32, Vec<u8>)>, String, String), dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::tool_tip(&*model).into())
+    }
+}
+
+impl<T: Tray + 'static> dbus_interface::Dbusmenu for InnerState<T> {
+    fn get_layout(
+        &self,
+        parent_id: i32,
+        recursion_depth: i32,
+        property_names: Vec<&str>,
+    ) -> Result<
+        (
+            u32,
+            (
+                i32,
+                HashMap<String, Variant<Box<dyn RefArg + 'static>>>,
+                Vec<Variant<Box<dyn RefArg + 'static>>>,
+            ),
+        ),
+        dbus::MethodErr,
+    > {
+        if let Some(menu_tree) = self.gen_dbusmenu_tree(
+            parent_id,
+            if recursion_depth < 0 {
+                None
+            } else {
+                Some(recursion_depth as usize)
+            },
+            property_names,
+        ) {
+            Ok((self.revision.get(), menu_tree))
+        } else {
+            Err(dbus::Error::new_failed("parentId not found").into())
+        }
+    }
+
+    fn get_group_properties(
+        &self,
+        ids: Vec<i32>,
+        property_names: Vec<&str>,
+    ) -> Result<Vec<(i32, HashMap<String, Variant<Box<dyn RefArg + 'static>>>)>, dbus::MethodErr>
+    {
+        let r = ids
+            .into_iter()
+            .filter_map(|id| self.id2index(id).map(|index| (id, index)))
+            .map(|(id, index)| {
+                (
+                    id,
+                    self.menu_cache.borrow()[index]
+                        .0
+                        .to_dbus_map(&property_names),
+                )
+            })
+            .collect();
+        Ok(r)
+    }
+
+    fn get_property(
+        &self,
+        id: i32,
+        name: &str,
+    ) -> Result<Variant<Box<dyn RefArg + 'static>>, dbus::MethodErr> {
+        let index = self
+            .id2index(id)
+            .ok_or_else(|| dbus::Error::new_failed("id not found"))?;
+        let mut props = self.menu_cache.borrow()[index].0.to_dbus_map(&[name]);
+        Ok(props.remove(name).unwrap())
+    }
+
+    fn event(
+        &self,
+        id: i32,
+        event_id: &str,
+        _data: Variant<Box<dyn RefArg>>,
+        _timestamp: u32,
+    ) -> Result<(), dbus::MethodErr> {
+        match event_id {
+            "clicked" => {
+                assert_ne!(id, 0, "ROOT MENU ITEM CLICKED");
+                let index = self
+                    .id2index(id)
+                    .ok_or_else(|| dbus::Error::new_failed("id not found"))?;
+                let activate = self.menu_cache.borrow()[index].0.on_clicked.clone();
+                self.update_immediately(|model| {
+                    (activate)(model, index);
+                });
+            }
+            _ => (),
+        }
+        Ok(())
+    }
+
+    fn event_group(
+        &self,
+        events: Vec<(i32, &str, Variant<Box<dyn RefArg>>, u32)>,
+    ) -> Result<Vec<i32>, dbus::MethodErr> {
+        let (found, not_found) = events
+            .into_iter()
+            .partition::<Vec<_>, _>(|event| self.id2index(event.0).is_some());
+        if found.is_empty() {
+            return Err(
+                dbus::Error::new_failed("None of the id in the events can be found").into(),
+            );
+        }
+        for (id, event_id, data, timestamp) in found {
+            self.event(id, event_id, data, timestamp)?;
+        }
+        Ok(not_found.into_iter().map(|event| event.0).collect())
+    }
+
+    fn about_to_show(&self, _id: i32) -> Result<bool, dbus::MethodErr> {
+        Ok(false)
+    }
+
+    fn about_to_show_group(&self, _ids: Vec<i32>) -> Result<(Vec<i32>, Vec<i32>), dbus::MethodErr> {
+        // FIXME: the DBus message should set the no reply flag
+        Ok(Default::default())
+    }
+
+    fn version(&self) -> Result<u32, dbus::MethodErr> {
+        Ok(3)
+    }
+
+    fn text_direction(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(Tray::text_direction(&*model).to_string())
+    }
+
+    fn status(&self) -> Result<String, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        Ok(match Tray::status(&*model) {
+            tray::Status::Active | tray::Status::Passive => menu::Status::Normal,
+            tray::Status::NeedsAttention => menu::Status::Notice,
+        }
+        .to_string())
+    }
+
+    fn icon_theme_path(&self) -> Result<Vec<String>, dbus::MethodErr> {
+        let model = self.handle.model.lock().unwrap();
+        let path = Tray::icon_theme_path(&*model);
+        Ok(if path.is_empty() {
+            Default::default()
+        } else {
+            vec![path]
+        })
+    }
+}
+
+struct PropertiesCache {
+    category: crate::Category,
+    title: u64,
+    status: crate::Status,
+    window_id: i32,
+    icon_theme_path: u64,
+    icon: u64,
+    overlay_icon: u64,
+    attention_icon: u64,
+    tool_tip: u64,
+    text_direction: crate::TextDirection,
+}
+
+impl PropertiesCache {
+    fn new<T: Tray>(tray: &T) -> Self {
+        PropertiesCache {
+            category: tray.category(),
+            title: hash_of(tray.title()),
+            status: tray.status(),
+            window_id: tray.window_id(),
+            icon_theme_path: hash_of(tray.icon_theme_path()),
+            icon: hash_of((tray.icon_name(), tray.icon_pixmap())),
+            overlay_icon: hash_of((tray.overlay_icon_name(), tray.overlay_icon_pixmap())),
+            attention_icon: hash_of((
+                tray.attention_icon_name(),
+                tray.attention_icon_pixmap(),
+                tray.attention_movie_name(),
+            )),
+            tool_tip: hash_of(tray.tool_tip()),
+            text_direction: tray.text_direction(),
+        }
+    }
+
+    fn category_changed<T: Tray>(&mut self, t: &T) -> Option<crate::Category> {
+        let v = t.category();
+        if self.category != v {
+            self.category = v;
+            Some(v)
+        } else {
+            None
+        }
+    }
+
+    fn title_changed<T: Tray>(&mut self, t: &T) -> bool {
+        let hash = hash_of(t.title());
+        self.title != hash && {
+            self.title = hash;
+            true
+        }
+    }
+
+    fn status_changed<T: Tray>(&mut self, t: &T) -> Option<crate::Status> {
+        let v = t.status();
+        if self.status != v {
+            self.status = v;
+            Some(v)
+        } else {
+            None
+        }
+    }
+
+    fn window_id_changed<T: Tray>(&mut self, t: &T) -> Option<i32> {
+        let v = t.window_id();
+        if self.window_id != v {
+            self.window_id = v;
+            Some(v)
+        } else {
+            None
+        }
+    }
+
+    fn icon_theme_path_changed<T: Tray>(&mut self, t: &T) -> Option<String> {
+        let v = t.icon_theme_path();
+        let hash = hash_of(&v);
+        if self.icon_theme_path != hash {
+            self.icon_theme_path = hash;
+            Some(v)
+        } else {
+            None
+        }
+    }
+
+    fn icon_changed<T: Tray>(&mut self, tray: &T) -> bool {
+        let hash = hash_of((tray.icon_name(), tray.icon_pixmap()));
+        self.icon != hash && {
+            self.icon = hash;
+            true
+        }
+    }
+
+    fn overlay_icon_changed<T: Tray>(&mut self, tray: &T) -> bool {
+        let hash = hash_of((tray.overlay_icon_name(), tray.overlay_icon_pixmap()));
+        self.overlay_icon != hash && {
+            self.overlay_icon = hash;
+            true
+        }
+    }
+
+    fn attention_icon_changed<T: Tray>(&mut self, tray: &T) -> bool {
+        let hash = hash_of((
+            tray.attention_icon_name(),
+            tray.attention_icon_pixmap(),
+            tray.attention_movie_name(),
+        ));
+        self.attention_icon != hash && {
+            self.attention_icon = hash;
+            true
+        }
+    }
+
+    fn tool_tip_changed<T: Tray>(&mut self, tray: &T) -> bool {
+        let hash = hash_of(tray.tool_tip());
+        self.tool_tip != hash && {
+            self.tool_tip = hash;
+            true
+        }
+    }
+
+    fn text_direction_changed<T: Tray>(&mut self, t: &T) -> Option<crate::TextDirection> {
+        let v = t.text_direction();
+        if self.text_direction != v {
+            self.text_direction = v;
+            Some(v)
+        } else {
+            None
+        }
+    }
+}
+
+fn hash_of<T: Hash>(v: T) -> u64 {
+    use std::collections::hash_map::DefaultHasher;
+    let mut hasher = DefaultHasher::new();
+    v.hash(&mut hasher);
+    hasher.finish()
+}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+    use crate::*;
+
+    /// gen_dbusmenu_tree should not return an empty tree when menu_cache is empty,
+    /// which was the old behavior before 421a8d9e5ac46f58ce13543df94ce3c9d85c7be2
+    #[test]
+    fn gen_dbusmenu_tree_empty() {
+        impl Tray for () {}
+        let handle = Handle {
+            tray_status: TrayStatus::default(),
+            model: Arc::new(Mutex::new(())),
+        };
+        let state = InnerState {
+            handle,
+            menu_cache: RefCell::new(Vec::new()),
+            item_id_offset: Cell::new(0),
+            revision: Cell::new(0),
+            prop_cache: RefCell::new(PropertiesCache::new(&())),
+        };
+        let r = state.gen_dbusmenu_tree(0, None, Vec::new());
+        assert!(r.is_none());
+        let r = state.gen_dbusmenu_tree(1, None, Vec::new());
+        assert!(r.is_none());
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/ksni/src/tray.rs
@@ -0,0 +1,105 @@
+use std::fmt;
+
+/// Category of this item.
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum Category {
+    /// The item describes the status of a generic application, for instance
+    /// the current state of a media player. In the case where the category of
+    /// the item can not be known, such as when the item is being proxied from
+    /// another incompatible or emulated system, ApplicationStatus can be used
+    /// a sensible default fallback.
+    ApplicationStatus,
+    /// The item describes the status of communication oriented applications,
+    /// like an instant messenger or an email client.
+    Communications,
+    /// The item describes services of the system not seen as a stand alone
+    /// application by the user, such as an indicator for the activity of a disk
+    /// indexing service.
+    SystemServices,
+    /// The item describes the state and control of a particular hardware,
+    /// such as an indicator of the battery charge or sound card volume control.
+    Hardware,
+}
+
+impl fmt::Display for Category {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        let r = match *self {
+            Category::ApplicationStatus => "ApplicationStatus",
+            Category::Communications => "Communications",
+            Category::SystemServices => "SystemServices",
+            Category::Hardware => "Hardware",
+        };
+        f.write_str(r)
+    }
+}
+
+/// Status of this item or of the associated application.
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum Status {
+    /// The item doesn't convey important information to the user, it can be
+    /// considered an "idle" status and is likely that visualizations will chose
+    /// to hide it.
+    Passive,
+    /// The item is active, is more important that the item will be shown in
+    /// some way to the user.
+    Active,
+    /// The item carries really important information for the user, such as
+    /// battery charge running out and is wants to incentive the direct user
+    /// intervention. Visualizations should emphasize in some way the items with
+    /// NeedsAttention status.
+    NeedsAttention,
+}
+
+impl fmt::Display for Status {
+    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+        let r = match *self {
+            Status::Passive => "Passive",
+            Status::Active => "Active",
+            Status::NeedsAttention => "NeedsAttention",
+        };
+        f.write_str(r)
+    }
+}
+
+/// Extra information associated to the item
+///
+/// That can be visualized for instance by a tooltip (or by any other mean the
+/// visualization consider appropriate.
+#[derive(Clone, Debug, Default, Hash)]
+pub struct ToolTip {
+    /// Freedesktop-compliant name for an icon.
+    pub icon_name: String,
+    /// Icon data
+    pub icon_pixmap: Vec<Icon>,
+    /// Title for this tooltip
+    pub title: String,
+    /// Descriptive text for this tooltip. It can contain also a subset of the
+    /// HTML markup language, for a list of allowed tags see Section Markup.
+    pub description: String,
+}
+
+impl From<ToolTip> for (String, Vec<(i32, i32, Vec<u8>)>, String, String) {
+    fn from(tooltip: ToolTip) -> Self {
+        (
+            tooltip.icon_name,
+            tooltip.icon_pixmap.into_iter().map(Into::into).collect(),
+            tooltip.title,
+            tooltip.description,
+        )
+    }
+}
+
+/// An ARGB32 image
+#[derive(Clone, Debug, Hash)]
+pub struct Icon {
+    pub width: i32,
+    pub height: i32,
+    /// ARGB32 format, network byte order
+    pub data: Vec<u8>,
+}
+
+impl From<Icon> for (i32, i32, Vec<u8>) {
+    fn from(icon: Icon) -> Self {
+        (icon.width, icon.height, icon.data)
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"CHANGELOG.md":"18e89ab18be7d22dd835924a38b1198651e870dfd0a2904a344120d341c4bc0e","Cargo.toml":"dd189fa732c00b7d1b036b43220253ef6ff2a0b1ff5ca7cf13f0669113a2055e","LICENSE":"1738b51502ae831fb59ffbeb22ebdd90bf17e5c72fe57c00b47552415f133fd8","README.md":"cfb01477df60cd0780ba59cbbc388f3f71d83bf51bab77e004fc7b811aff0efd","appveyor.yml":"b41eae9798a9bb250f6046509d9bbd6e63bac9ad2655d342b3d9c8975584f0c0","benches/benches.rs":"e277857c44afdc08b2acf35fc05be6226529c588eb9da397382b0a74c58615ab","dev":"5bd26dc2c86f777627abe96c5992b6c45e6b5dea52f42b7107fa5c106abe2ab4","src/lib.rs":"26a960216567e5dea46033b3383a69e7da498095c092e195e92c05faef52f915","tests/lib.rs":"de2b1181c379a0f55de7b86021a9afb77dbe81053a6acf99623bec3663f9b7c4"},"package":"8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/CHANGELOG.md
@@ -0,0 +1,123 @@
+# Change Log
+This project attempts to adhere to [Semantic Versioning](http://semver.org).
+
+## [Unreleased]
+
+## [0.8.0] - (2018-08-19)
+### Added
+- Normalized versions of Levenshtein and Damerau-Levenshtein (thanks [@gentoid](https://github.com/gentoid))
+
+## [0.7.0] - (2018-01-17)
+### Changed
+- Faster Levenshtein implementation (thanks [@wdv4758h](https://github.com/wdv4758h))
+
+### Removed
+- Remove the "against_vec" functions. They are one-liners now, so they don't
+  seem to add enough value to justify making the API larger. I didn't find
+  anybody using them when I skimmed through a GitHub search. If you do use them,
+  you can change the calls to something like:
+```rust
+let distances = strings.iter().map(|a| jaro(target, a)).collect();
+```
+
+## [0.6.0] - (2016-12-26)
+### Added
+- Add optimal string alignment distance
+
+### Fixed
+- Fix Damerau-Levenshtein implementation (previous implementation was actually
+  optimal string alignment; see this [Damerau-Levenshtein explanation])
+
+## [0.5.2] - (2016-11-21)
+### Changed
+- Remove Cargo generated documentation in favor of a [docs.rs] link
+
+## [0.5.1] - (2016-08-23)
+### Added
+- Add Cargo generated documentation
+
+### Fixed
+- Fix panic when Jaro or Jaro-Winkler are given strings both with a length of
+  one
+
+## [0.5.0] - (2016-08-11)
+### Changed
+- Make Hamming faster (thanks @IBUzPE9) when the two strings have the same
+  length but slower when they have different lengths
+
+## [0.4.1] - (2016-04-18)
+### Added
+- Add Vagrant setup for development
+- Add AppVeyor configuration for Windows CI
+
+### Fixed
+- Fix metrics when given strings with multibyte characters (thanks @WanzenBug)
+
+## [0.4.0] - (2015-06-10)
+### Added
+- For each metric, add a function that takes a vector of strings and returns a
+vector of results (thanks @ovarene)
+
+## [0.3.0] - (2015-04-30)
+### Changed
+- Remove usage of unstable Rust features
+
+## [0.2.5] - (2015-04-24)
+### Fixed
+- Remove unnecessary `Float` import from doc tests
+
+## [0.2.4] - (2015-04-15)
+### Fixed
+- Remove unused `core` feature flag
+
+## [0.2.3] - (2015-04-01)
+### Fixed
+- Remove now unnecessary `Float` import
+
+## [0.2.2] - (2015-03-29)
+### Fixed
+- Remove usage of `char_at` (marked as unstable)
+
+## [0.2.1] - (2015-02-20)
+### Fixed
+- Update bit vector import to match Rust update
+
+## [0.2.0] - (2015-02-19)
+### Added
+- Implement Damerau-Levenshtein
+- Add tests in docs
+
+## [0.1.1] - (2015-02-10)
+### Added
+- Configure Travis for CI
+- Add rustdoc comments
+
+### Fixed
+- Limit Jaro-Winkler return value to a maximum of 1.0
+- Fix float comparisons in tests
+
+## [0.1.0] - (2015-02-09)
+### Added
+- Implement Hamming, Jaro, Jaro-Winkler, and Levenshtein
+
+[Unreleased]: https://github.com/dguo/strsim-rs/compare/0.8.0...HEAD
+[0.8.0]: https://github.com/dguo/strsim-rs/compare/0.7.0...0.8.0
+[0.7.0]: https://github.com/dguo/strsim-rs/compare/0.6.0...0.7.0
+[0.6.0]: https://github.com/dguo/strsim-rs/compare/0.5.2...0.6.0
+[0.5.2]: https://github.com/dguo/strsim-rs/compare/0.5.1...0.5.2
+[0.5.1]: https://github.com/dguo/strsim-rs/compare/0.5.0...0.5.1
+[0.5.0]: https://github.com/dguo/strsim-rs/compare/0.4.1...0.5.0
+[0.4.1]: https://github.com/dguo/strsim-rs/compare/0.4.0...0.4.1
+[0.4.0]: https://github.com/dguo/strsim-rs/compare/0.3.0...0.4.0
+[0.3.0]: https://github.com/dguo/strsim-rs/compare/0.2.5...0.3.0
+[0.2.5]: https://github.com/dguo/strsim-rs/compare/0.2.4...0.2.5
+[0.2.4]: https://github.com/dguo/strsim-rs/compare/0.2.3...0.2.4
+[0.2.3]: https://github.com/dguo/strsim-rs/compare/0.2.2...0.2.3
+[0.2.2]: https://github.com/dguo/strsim-rs/compare/0.2.1...0.2.2
+[0.2.1]: https://github.com/dguo/strsim-rs/compare/0.2.0...0.2.1
+[0.2.0]: https://github.com/dguo/strsim-rs/compare/0.1.1...0.2.0
+[0.1.1]: https://github.com/dguo/strsim-rs/compare/0.1.0...0.1.1
+[0.1.0]: https://github.com/dguo/strsim-rs/compare/fabad4...0.1.0
+[docs.rs]: https://docs.rs/strsim/
+[Damerau-Levenshtein explanation]:
+http://scarcitycomputing.blogspot.com/2013/04/damerau-levenshtein-edit-distance.html
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/Cargo.toml
@@ -0,0 +1,28 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g. crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "strsim"
+version = "0.8.0"
+authors = ["Danny Guo <dannyguo91@gmail.com>"]
+description = "Implementations of string similarity metrics.\nIncludes Hamming, Levenshtein, OSA, Damerau-Levenshtein, Jaro, and Jaro-Winkler.\n"
+homepage = "https://github.com/dguo/strsim-rs"
+documentation = "https://docs.rs/strsim/"
+readme = "README.md"
+keywords = ["string", "similarity", "Hamming", "Levenshtein", "Jaro"]
+license = "MIT"
+repository = "https://github.com/dguo/strsim-rs"
+[badges.appveyor]
+repository = "dguo/strsim-rs"
+
+[badges.travis-ci]
+repository = "dguo/strsim-rs"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/LICENSE
@@ -0,0 +1,23 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Danny Guo
+Copyright (c) 2016 Titus Wormer <tituswormer@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/README.md
@@ -0,0 +1,69 @@
+# strsim-rs [![Crates.io](https://img.shields.io/crates/v/strsim.svg)](https://crates.io/crates/strsim) [![Crates.io](https://img.shields.io/crates/l/strsim.svg?maxAge=2592000)](https://github.com/dguo/strsim-rs/blob/master/LICENSE) [![Linux build status](https://travis-ci.org/dguo/strsim-rs.svg?branch=master)](https://travis-ci.org/dguo/strsim-rs) [![Windows build status](https://ci.appveyor.com/api/projects/status/ggue6i785618a39w?svg=true)](https://ci.appveyor.com/project/dguo/strsim-rs)
+
+[Rust](https://www.rust-lang.org) implementations of [string similarity metrics]:
+  - [Hamming]
+  - [Levenshtein] - distance & normalized
+  - [Optimal string alignment]
+  - [Damerau-Levenshtein] - distance & normalized
+  - [Jaro and Jaro-Winkler] - this implementation of Jaro-Winkler does not limit the common prefix length
+
+### Installation
+```toml
+# Cargo.toml
+[dependencies]
+strsim = "0.8.0"
+```
+
+### [Documentation](https://docs.rs/strsim/)
+You can change the version in the url to see the documentation for an older
+version in the
+[changelog](https://github.com/dguo/strsim-rs/blob/master/CHANGELOG.md).
+
+### Usage
+```rust
+extern crate strsim;
+
+use strsim::{hamming, levenshtein, normalized_levenshtein, osa_distance,
+             damerau_levenshtein, normalized_damerau_levenshtein, jaro,
+             jaro_winkler};
+
+fn main() {
+    match hamming("hamming", "hammers") {
+        Ok(distance) => assert_eq!(3, distance),
+        Err(why) => panic!("{:?}", why)
+    }
+
+    assert_eq!(3, levenshtein("kitten", "sitting"));
+
+    assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001);
+
+    assert_eq!(3, osa_distance("ac", "cba"));
+
+    assert_eq!(2, damerau_levenshtein("ac", "cba"));
+
+    assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001)
+
+    assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() <
+            0.001);
+
+    assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() <
+            0.001);
+}
+```
+
+### Development
+If you don't want to install Rust itself, you can run `$ ./dev` for a
+development CLI if you have [Docker] installed.
+
+Benchmarks require a Nightly toolchain. They are run by `cargo +nightly bench`.
+
+### License
+[MIT](https://github.com/dguo/strsim-rs/blob/master/LICENSE)
+
+[string similarity metrics]:http://en.wikipedia.org/wiki/String_metric
+[Damerau-Levenshtein]:http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
+[Jaro and Jaro-Winkler]:http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance
+[Levenshtein]:http://en.wikipedia.org/wiki/Levenshtein_distance
+[Hamming]:http://en.wikipedia.org/wiki/Hamming_distance
+[Optimal string alignment]:https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Optimal_string_alignment_distance
+[Docker]:https://docs.docker.com/engine/installation/
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/appveyor.yml
@@ -0,0 +1,13 @@
+install:
+  - ps: Start-FileDownload 'https://static.rust-lang.org/dist/rust-beta-x86_64-pc-windows-gnu.exe'
+  - rust-beta-x86_64-pc-windows-gnu.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust"
+  - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin
+  - rustc -V
+  - cargo -V
+
+build: false
+
+test_script:
+  - cargo build
+  - cargo test --verbose
+
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/benches/benches.rs
@@ -0,0 +1,84 @@
+//! Benchmarks for strsim.
+
+#![feature(test)]
+
+extern crate strsim;
+
+mod benches {
+    use super::*;
+
+    extern crate test;
+    use self::test::Bencher;
+
+    #[bench]
+    fn bench_hamming(bencher: &mut Bencher) {
+        let a = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGG";
+        let b = "CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGC";
+        bencher.iter(|| {
+            strsim::hamming(&a, &b).unwrap();
+        })
+    }
+
+    #[bench]
+    fn bench_jaro(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::jaro(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_jaro_winkler(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::jaro_winkler(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_levenshtein(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::levenshtein(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_normalized_levenshtein(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::normalized_levenshtein(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_osa_distance(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::osa_distance(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_damerau_levenshtein(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::damerau_levenshtein(&a, &b);
+        })
+    }
+
+    #[bench]
+    fn bench_normalized_damerau_levenshtein(bencher: &mut Bencher) {
+        let a = "Philosopher Friedrich Nietzsche";
+        let b = "Philosopher Jean-Paul Sartre";
+        bencher.iter(|| {
+            strsim::normalized_damerau_levenshtein(&a, &b);
+        })
+    }
+}
new file mode 100755
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/dev
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+# ./dev --help
+
+import argparse
+import os
+from subprocess import run
+import sys
+
+parser = argparse.ArgumentParser(prog='./dev')
+subparsers = parser.add_subparsers(metavar='<command>', title='commands')
+command = [
+    'docker', 'run', '-it', '--rm', '-v', os.getcwd() + ':/src:cached',
+    '-w=/src', 'rust:1.21.0'
+]
+
+def cargo(args, remaining):
+    sys.exit(run(command + ['cargo'] + remaining or []).returncode)
+
+parser_cargo = subparsers.add_parser('cargo', help='run a cargo command')
+parser_cargo.set_defaults(func=cargo)
+
+def sh(args, remaining):
+    sys.exit(run(command + ['bash']).returncode)
+
+parser_sh = subparsers.add_parser('sh', help='bring up a shell')
+parser_sh.set_defaults(func=sh)
+
+def test(args, remaining):
+    sys.exit(run(command + ['cargo', 'test']).returncode)
+
+parser_test = subparsers.add_parser('test', help='run tests')
+parser_test.set_defaults(func=test)
+
+if len(sys.argv) > 1:
+    args, remaining = parser.parse_known_args()
+    try:
+        args.func(args, remaining)
+    except FileNotFoundError:
+        sys.exit('Please install Docker.')
+else:
+    parser.print_help()
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/src/lib.rs
@@ -0,0 +1,786 @@
+//! This library implements string similarity metrics.
+
+use std::char;
+use std::cmp::{max, min};
+use std::collections::HashMap;
+
+#[derive(Debug, PartialEq)]
+pub enum StrSimError {
+    DifferentLengthArgs
+}
+
+pub type HammingResult = Result<usize, StrSimError>;
+
+/// Calculates the number of positions in the two strings where the characters
+/// differ. Returns an error if the strings have different lengths.
+///
+/// ```
+/// use strsim::hamming;
+///
+/// match hamming("hamming", "hammers") {
+///     Ok(distance) => assert_eq!(3, distance),
+///     Err(why) => panic!("{:?}", why)
+/// }
+/// ```
+pub fn hamming(a: &str, b: &str) -> HammingResult {
+    let (mut ita, mut itb, mut count) = (a.chars(), b.chars(), 0);
+    loop {
+        match (ita.next(), itb.next()){
+            (Some(x), Some(y)) => if x != y { count += 1 },
+            (None, None) => return Ok(count),
+            _ => return Err(StrSimError::DifferentLengthArgs),
+        }
+    }
+}
+
+/// Calculates the Jaro similarity between two strings. The returned value
+/// is between 0.0 and 1.0 (higher value means more similar).
+///
+/// ```
+/// use strsim::jaro;
+///
+/// assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() <
+///         0.001);
+/// ```
+pub fn jaro(a: &str, b: &str) -> f64 {
+    if a == b { return 1.0; }
+
+    let a_len = a.chars().count();
+    let b_len = b.chars().count();
+
+    // The check for lengths of one here is to prevent integer overflow when
+    // calculating the search range.
+    if a_len == 0 || b_len == 0 || (a_len == 1 && b_len == 1) {
+        return 0.0;
+    }
+
+    let search_range = (max(a_len, b_len) / 2) - 1;
+
+    let mut b_consumed = Vec::with_capacity(b_len);
+    for _ in 0..b_len {
+        b_consumed.push(false);
+    }
+    let mut matches = 0.0;
+
+    let mut transpositions = 0.0;
+    let mut b_match_index = 0;
+
+    for (i, a_char) in a.chars().enumerate() {
+        let min_bound =
+            // prevent integer wrapping
+            if i > search_range {
+                max(0, i - search_range)
+            } else {
+                0
+            };
+
+        let max_bound = min(b_len - 1, i + search_range);
+
+        if min_bound > max_bound {
+            continue;
+        }
+
+        for (j, b_char) in b.chars().enumerate() {
+            if min_bound <= j && j <= max_bound && a_char == b_char &&
+               !b_consumed[j] {
+                b_consumed[j] = true;
+                matches += 1.0;
+
+                if j < b_match_index {
+                    transpositions += 1.0;
+                }
+                b_match_index = j;
+
+                break;
+            }
+        }
+    }
+
+    if matches == 0.0 {
+        0.0
+    } else {
+        (1.0 / 3.0) * ((matches / a_len as f64) +
+                       (matches / b_len as f64) +
+                       ((matches - transpositions) / matches))
+    }
+}
+
+/// Like Jaro but gives a boost to strings that have a common prefix.
+///
+/// ```
+/// use strsim::jaro_winkler;
+///
+/// assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() <
+///         0.001);
+/// ```
+pub fn jaro_winkler(a: &str, b: &str) -> f64 {
+    let jaro_distance = jaro(a, b);
+
+    // Don't limit the length of the common prefix
+    let prefix_length = a.chars()
+                         .zip(b.chars())
+                         .take_while(|&(a_char, b_char)| a_char == b_char)
+                         .count();
+
+    let jaro_winkler_distance =
+        jaro_distance + (0.1 * prefix_length as f64 * (1.0 - jaro_distance));
+
+    if jaro_winkler_distance <= 1.0 {
+        jaro_winkler_distance
+    } else {
+        1.0
+    }
+}
+
+/// Calculates the minimum number of insertions, deletions, and substitutions
+/// required to change one string into the other.
+///
+/// ```
+/// use strsim::levenshtein;
+///
+/// assert_eq!(3, levenshtein("kitten", "sitting"));
+/// ```
+pub fn levenshtein(a: &str, b: &str) -> usize {
+    if a == b { return 0; }
+
+    let a_len = a.chars().count();
+    let b_len = b.chars().count();
+
+    if a_len == 0 { return b_len; }
+    if b_len == 0 { return a_len; }
+
+    let mut cache: Vec<usize> = (1..b_len+1).collect();
+
+    let mut result = 0;
+    let mut distance_a;
+    let mut distance_b;
+
+    for (i, a_char) in a.chars().enumerate() {
+        result = i;
+        distance_b = i;
+
+        for (j, b_char) in b.chars().enumerate() {
+            let cost = if a_char == b_char { 0 } else { 1 };
+            distance_a = distance_b + cost;
+            distance_b = cache[j];
+            result = min(result + 1, min(distance_a, distance_b + 1));
+            cache[j] = result;
+        }
+    }
+
+    result
+}
+
+/// Calculates a normalized score of the Levenshtein algorithm between 0.0 and
+/// 1.0 (inclusive), where 1.0 means the strings are the same.
+///
+/// ```
+/// use strsim::normalized_levenshtein;
+///
+/// assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001);
+/// assert!((normalized_levenshtein("", "") - 1.0).abs() < 0.00001);
+/// assert!(normalized_levenshtein("", "second").abs() < 0.00001);
+/// assert!(normalized_levenshtein("first", "").abs() < 0.00001);
+/// assert!((normalized_levenshtein("string", "string") - 1.0).abs() < 0.00001);
+/// ```
+pub fn normalized_levenshtein(a: &str, b: &str) -> f64 {
+    if a.is_empty() && b.is_empty() {
+        return 1.0;
+    }
+    1.0 - (levenshtein(a, b) as f64) / (a.chars().count().max(b.chars().count()) as f64)
+}
+
+/// Like Levenshtein but allows for adjacent transpositions. Each substring can
+/// only be edited once.
+///
+/// ```
+/// use strsim::osa_distance;
+///
+/// assert_eq!(3, osa_distance("ab", "bca"));
+/// ```
+pub fn osa_distance(a: &str, b: &str) -> usize {
+    let a_len = a.chars().count();
+    let b_len = b.chars().count();
+    if a == b { return 0; }
+    else if a_len == 0 { return b_len; }
+    else if b_len == 0 { return a_len; }
+
+    let mut prev_two_distances: Vec<usize> = Vec::with_capacity(b_len + 1);
+    let mut prev_distances: Vec<usize> = Vec::with_capacity(b_len + 1);
+    let mut curr_distances: Vec<usize> = Vec::with_capacity(b_len + 1);
+
+    let mut prev_a_char = char::MAX;
+    let mut prev_b_char = char::MAX;
+
+    for i in 0..(b_len + 1) {
+        prev_two_distances.push(i);
+        prev_distances.push(i);
+        curr_distances.push(0);
+    }
+
+    for (i, a_char) in a.chars().enumerate() {
+        curr_distances[0] = i + 1;
+
+        for (j, b_char) in b.chars().enumerate() {
+            let cost = if a_char == b_char { 0 } else { 1 };
+            curr_distances[j + 1] = min(curr_distances[j] + 1,
+                                        min(prev_distances[j + 1] + 1,
+                                            prev_distances[j] + cost));
+            if i > 0 && j > 0 && a_char != b_char &&
+               a_char == prev_b_char && b_char == prev_a_char {
+                curr_distances[j + 1] = min(curr_distances[j + 1],
+                                            prev_two_distances[j - 1] + 1);
+            }
+
+            prev_b_char = b_char;
+        }
+
+        prev_two_distances.clone_from(&prev_distances);
+        prev_distances.clone_from(&curr_distances);
+        prev_a_char = a_char;
+    }
+
+    curr_distances[b_len]
+
+}
+
+/// Like optimal string alignment, but substrings can be edited an unlimited
+/// number of times, and the triangle inequality holds.
+///
+/// ```
+/// use strsim::damerau_levenshtein;
+///
+/// assert_eq!(2, damerau_levenshtein("ab", "bca"));
+/// ```
+pub fn damerau_levenshtein(a: &str, b: &str) -> usize {
+    if a == b { return 0; }
+
+    let a_chars: Vec<char> = a.chars().collect();
+    let b_chars: Vec<char> = b.chars().collect();
+    let a_len = a_chars.len();
+    let b_len = b_chars.len();
+
+    if a_len == 0 { return b_len; }
+    if b_len == 0 { return a_len; }
+
+    let mut distances = vec![vec![0; b_len + 2]; a_len + 2];
+    let max_distance = a_len + b_len;
+    distances[0][0] = max_distance;
+
+    for i in 0..(a_len + 1) {
+        distances[i + 1][0] = max_distance;
+        distances[i + 1][1] = i;
+    }
+
+    for j in 0..(b_len + 1) {
+        distances[0][j + 1] = max_distance;
+        distances[1][j + 1] = j;
+    }
+
+    let mut chars: HashMap<char, usize> = HashMap::new();
+
+    for i in 1..(a_len + 1) {
+        let mut db = 0;
+
+        for j in 1..(b_len + 1) {
+            let k = match chars.get(&b_chars[j - 1]) {
+                Some(value) => value.clone(),
+                None => 0
+            };
+
+            let l = db;
+
+            let mut cost = 1;
+            if a_chars[i - 1] == b_chars[j - 1] {
+                cost = 0;
+                db = j;
+            }
+
+            let substitution_cost = distances[i][j] + cost;
+            let insertion_cost = distances[i][j + 1] + 1;
+            let deletion_cost = distances[i + 1][j] + 1;
+            let transposition_cost = distances[k][l] + (i - k - 1) + 1 +
+                                     (j - l - 1);
+
+            distances[i + 1][j + 1] = min(substitution_cost,
+                                      min(insertion_cost,
+                                      min(deletion_cost,
+                                          transposition_cost)));
+        }
+
+        chars.insert(a_chars[i - 1], i);
+    }
+
+    distances[a_len + 1][b_len + 1]
+}
+
+/// Calculates a normalized score of the Damerau–Levenshtein algorithm between
+/// 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same.
+///
+/// ```
+/// use strsim::normalized_damerau_levenshtein;
+///
+/// assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001);
+/// assert!((normalized_damerau_levenshtein("", "") - 1.0).abs() < 0.00001);
+/// assert!(normalized_damerau_levenshtein("", "flower").abs() < 0.00001);
+/// assert!(normalized_damerau_levenshtein("tree", "").abs() < 0.00001);
+/// assert!((normalized_damerau_levenshtein("sunglasses", "sunglasses") - 1.0).abs() < 0.00001);
+/// ```
+pub fn normalized_damerau_levenshtein(a: &str, b: &str) -> f64 {
+    if a.is_empty() && b.is_empty() {
+        return 1.0;
+    }
+    1.0 - (damerau_levenshtein(a, b) as f64) / (a.chars().count().max(b.chars().count()) as f64)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn hamming_empty() {
+        match hamming("", "") {
+            Ok(distance) => { assert_eq!(0, distance); },
+            Err(why) => { panic!("{:?}", why); }
+        }
+    }
+
+    #[test]
+    fn hamming_same() {
+        match hamming("hamming", "hamming") {
+            Ok(distance) => { assert_eq!(0, distance); },
+            Err(why) => { panic!("{:?}", why); }
+        }
+    }
+
+    #[test]
+    fn hamming_diff() {
+        match hamming("hamming", "hammers") {
+            Ok(distance) => { assert_eq!(3, distance); },
+            Err(why) => { panic!("{:?}", why); }
+        }
+    }
+
+    #[test]
+    fn hamming_diff_multibyte() {
+        match hamming("hamming", "h香mmüng") {
+            Ok(distance) => { assert_eq!(2, distance); },
+            Err(why) => { panic!("{:?}", why); }
+        }
+    }
+
+    #[test]
+    fn hamming_unequal_length() {
+        match hamming("ham", "hamming") {
+            Ok(_) => { panic!(); },
+            Err(why) => { assert_eq!(why, StrSimError::DifferentLengthArgs); }
+        }
+    }
+
+    #[test]
+    fn hamming_names() {
+        match hamming("Friedrich Nietzs", "Jean-Paul Sartre") {
+            Ok(distance) => { assert_eq!(14, distance); },
+            Err(why) => { panic!("{:?}", why); }
+        }
+    }
+
+    #[test]
+    fn jaro_both_empty() {
+       assert_eq!(1.0, jaro("", ""));
+    }
+
+    #[test]
+    fn jaro_first_empty() {
+        assert_eq!(0.0, jaro("", "jaro"));
+    }
+
+    #[test]
+    fn jaro_second_empty() {
+        assert_eq!(0.0, jaro("distance", ""));
+    }
+
+    #[test]
+    fn jaro_same() {
+        assert_eq!(1.0, jaro("jaro", "jaro"));
+    }
+
+    #[test]
+    fn jaro_multibyte() {
+        assert!((0.818 - jaro("testabctest", "testöঙ香test")) < 0.001);
+        assert!((0.818 - jaro("testöঙ香test", "testabctest")) < 0.001);
+    }
+
+    #[test]
+    fn jaro_diff_short() {
+        assert!((0.767 - jaro("dixon", "dicksonx")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_diff_one_character() {
+        assert_eq!(0.0, jaro("a", "b"));
+    }
+
+    #[test]
+    fn jaro_diff_one_and_two() {
+        assert!((0.83 - jaro("a", "ab")).abs() < 0.01);
+    }
+
+    #[test]
+    fn jaro_diff_two_and_one() {
+        assert!((0.83 - jaro("ab", "a")).abs() < 0.01);
+    }
+
+    #[test]
+    fn jaro_diff_no_transposition() {
+        assert!((0.822 - jaro("dwayne", "duane")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_diff_with_transposition() {
+        assert!((0.944 - jaro("martha", "marhta")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_names() {
+        assert!((0.392 - jaro("Friedrich Nietzsche",
+                              "Jean-Paul Sartre")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_both_empty() {
+        assert_eq!(1.0, jaro_winkler("", ""));
+    }
+
+    #[test]
+    fn jaro_winkler_first_empty() {
+        assert_eq!(0.0, jaro_winkler("", "jaro-winkler"));
+    }
+
+    #[test]
+    fn jaro_winkler_second_empty() {
+        assert_eq!(0.0, jaro_winkler("distance", ""));
+    }
+
+    #[test]
+    fn jaro_winkler_same() {
+        assert_eq!(1.0, jaro_winkler("Jaro-Winkler", "Jaro-Winkler"));
+    }
+
+    #[test]
+    fn jaro_winkler_multibyte() {
+        assert!((0.89 - jaro_winkler("testabctest", "testöঙ香test")).abs() <
+                0.001);
+        assert!((0.89 - jaro_winkler("testöঙ香test", "testabctest")).abs() <
+                0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_diff_short() {
+        assert!((0.813 - jaro_winkler("dixon", "dicksonx")).abs() < 0.001);
+        assert!((0.813 - jaro_winkler("dicksonx", "dixon")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_diff_one_character() {
+        assert_eq!(0.0, jaro_winkler("a", "b"));
+    }
+
+    #[test]
+    fn jaro_winkler_diff_no_transposition() {
+        assert!((0.840 - jaro_winkler("dwayne", "duane")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_diff_with_transposition() {
+        assert!((0.961 - jaro_winkler("martha", "marhta")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_names() {
+        assert!((0.562 - jaro_winkler("Friedrich Nietzsche",
+                                      "Fran-Paul Sartre")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_long_prefix() {
+        assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() <
+                0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_more_names() {
+        assert!((0.868 - jaro_winkler("Thorkel", "Thorgier")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_length_of_one() {
+        assert!((0.738 - jaro_winkler("Dinsdale", "D")).abs() < 0.001);
+    }
+
+    #[test]
+    fn jaro_winkler_very_long_prefix() {
+        assert!((1.0 - jaro_winkler("thequickbrownfoxjumpedoverx",
+                                    "thequickbrownfoxjumpedovery")).abs() <
+                0.001);
+    }
+
+    #[test]
+    fn levenshtein_empty() {
+        assert_eq!(0, levenshtein("", ""));
+    }
+
+    #[test]
+    fn levenshtein_same() {
+        assert_eq!(0, levenshtein("levenshtein", "levenshtein"));
+    }
+
+    #[test]
+    fn levenshtein_diff_short() {
+        assert_eq!(3, levenshtein("kitten", "sitting"));
+    }
+
+    #[test]
+    fn levenshtein_diff_with_space() {
+        assert_eq!(5, levenshtein("hello, world", "bye, world"));
+    }
+
+    #[test]
+    fn levenshtein_diff_multibyte() {
+        assert_eq!(3, levenshtein("öঙ香", "abc"));
+        assert_eq!(3, levenshtein("abc", "öঙ香"));
+    }
+
+    #[test]
+    fn levenshtein_diff_longer() {
+        let a = "The quick brown fox jumped over the angry dog.";
+        let b = "Lorem ipsum dolor sit amet, dicta latine an eam.";
+        assert_eq!(37, levenshtein(a, b));
+    }
+
+    #[test]
+    fn levenshtein_first_empty() {
+        assert_eq!(7, levenshtein("", "sitting"));
+    }
+
+    #[test]
+    fn levenshtein_second_empty() {
+        assert_eq!(6, levenshtein("kitten", ""));
+    }
+
+    #[test]
+    fn normalized_levenshtein_diff_short() {
+        assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_levenshtein_for_empty_strings() {
+        assert!((normalized_levenshtein("", "") - 1.0).abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_levenshtein_first_empty() {
+        assert!(normalized_levenshtein("", "second").abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_levenshtein_second_empty() {
+        assert!(normalized_levenshtein("first", "").abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_levenshtein_identical_strings() {
+        assert!((normalized_levenshtein("identical", "identical") - 1.0).abs() < 0.00001);
+    }
+
+    #[test]
+    fn osa_distance_empty() {
+        assert_eq!(0, osa_distance("", ""));
+    }
+
+    #[test]
+    fn osa_distance_same() {
+        assert_eq!(0, osa_distance("damerau", "damerau"));
+    }
+
+    #[test]
+    fn osa_distance_first_empty() {
+        assert_eq!(7, osa_distance("", "damerau"));
+    }
+
+    #[test]
+    fn osa_distance_second_empty() {
+        assert_eq!(7, osa_distance("damerau", ""));
+    }
+
+    #[test]
+    fn osa_distance_diff() {
+        assert_eq!(3, osa_distance("ca", "abc"));
+    }
+
+    #[test]
+    fn osa_distance_diff_short() {
+        assert_eq!(3, osa_distance("damerau", "aderua"));
+    }
+
+    #[test]
+    fn osa_distance_diff_reversed() {
+        assert_eq!(3, osa_distance("aderua", "damerau"));
+    }
+
+    #[test]
+    fn osa_distance_diff_multibyte() {
+        assert_eq!(3, osa_distance("öঙ香", "abc"));
+        assert_eq!(3, osa_distance("abc", "öঙ香"));
+    }
+
+    #[test]
+    fn osa_distance_diff_unequal_length() {
+        assert_eq!(6, osa_distance("damerau", "aderuaxyz"));
+    }
+
+    #[test]
+    fn osa_distance_diff_unequal_length_reversed() {
+        assert_eq!(6, osa_distance("aderuaxyz", "damerau"));
+    }
+
+    #[test]
+    fn osa_distance_diff_comedians() {
+        assert_eq!(5, osa_distance("Stewart", "Colbert"));
+    }
+
+    #[test]
+    fn osa_distance_many_transpositions() {
+        assert_eq!(4, osa_distance("abcdefghijkl", "bacedfgihjlk"));
+    }
+
+    #[test]
+    fn osa_distance_diff_longer() {
+        let a = "The quick brown fox jumped over the angry dog.";
+        let b = "Lehem ipsum dolor sit amet, dicta latine an eam.";
+        assert_eq!(36, osa_distance(a, b));
+    }
+
+    #[test]
+    fn osa_distance_beginning_transposition() {
+        assert_eq!(1, osa_distance("foobar", "ofobar"));
+    }
+
+    #[test]
+    fn osa_distance_end_transposition() {
+        assert_eq!(1, osa_distance("specter", "spectre"));
+    }
+
+    #[test]
+    fn osa_distance_restricted_edit() {
+        assert_eq!(4, osa_distance("a cat", "an abct"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_empty() {
+        assert_eq!(0, damerau_levenshtein("", ""));
+    }
+
+    #[test]
+    fn damerau_levenshtein_same() {
+        assert_eq!(0, damerau_levenshtein("damerau", "damerau"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_first_empty() {
+        assert_eq!(7, damerau_levenshtein("", "damerau"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_second_empty() {
+        assert_eq!(7, damerau_levenshtein("damerau", ""));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff() {
+        assert_eq!(2, damerau_levenshtein("ca", "abc"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_short() {
+        assert_eq!(3, damerau_levenshtein("damerau", "aderua"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_reversed() {
+        assert_eq!(3, damerau_levenshtein("aderua", "damerau"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_multibyte() {
+        assert_eq!(3, damerau_levenshtein("öঙ香", "abc"));
+        assert_eq!(3, damerau_levenshtein("abc", "öঙ香"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_unequal_length() {
+        assert_eq!(6, damerau_levenshtein("damerau", "aderuaxyz"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_unequal_length_reversed() {
+        assert_eq!(6, damerau_levenshtein("aderuaxyz", "damerau"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_comedians() {
+        assert_eq!(5, damerau_levenshtein("Stewart", "Colbert"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_many_transpositions() {
+        assert_eq!(4, damerau_levenshtein("abcdefghijkl", "bacedfgihjlk"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_diff_longer() {
+        let a = "The quick brown fox jumped over the angry dog.";
+        let b = "Lehem ipsum dolor sit amet, dicta latine an eam.";
+        assert_eq!(36, damerau_levenshtein(a, b));
+    }
+
+    #[test]
+    fn damerau_levenshtein_beginning_transposition() {
+        assert_eq!(1, damerau_levenshtein("foobar", "ofobar"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_end_transposition() {
+        assert_eq!(1, damerau_levenshtein("specter", "spectre"));
+    }
+
+    #[test]
+    fn damerau_levenshtein_unrestricted_edit() {
+        assert_eq!(3, damerau_levenshtein("a cat", "an abct"));
+    }
+
+    #[test]
+    fn normalized_damerau_levenshtein_diff_short() {
+        assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_damerau_levenshtein_for_empty_strings() {
+        assert!((normalized_damerau_levenshtein("", "") - 1.0).abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_damerau_levenshtein_first_empty() {
+        assert!(normalized_damerau_levenshtein("", "flower").abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_damerau_levenshtein_second_empty() {
+        assert!(normalized_damerau_levenshtein("tree", "").abs() < 0.00001);
+    }
+
+    #[test]
+    fn normalized_damerau_levenshtein_identical_strings() {
+        assert!((normalized_damerau_levenshtein("sunglasses", "sunglasses") - 1.0).abs() < 0.00001);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/strsim-0.8.0/tests/lib.rs
@@ -0,0 +1,49 @@
+extern crate strsim;
+
+use strsim::{hamming, levenshtein, normalized_levenshtein, osa_distance,damerau_levenshtein,
+             normalized_damerau_levenshtein, jaro, jaro_winkler};
+
+#[test]
+fn hamming_works() {
+    match hamming("hamming", "hammers") {
+        Ok(distance) => assert_eq!(3, distance),
+        Err(why) => panic!("{:?}", why)
+    }
+}
+
+#[test]
+fn levenshtein_works() {
+    assert_eq!(3, levenshtein("kitten", "sitting"));
+}
+
+#[test]
+fn normalized_levenshtein_works() {
+    assert!((normalized_levenshtein("kitten", "sitting") - 0.57142).abs() < 0.00001);
+}
+
+#[test]
+fn osa_distance_works() {
+    assert_eq!(3, osa_distance("ac", "cba"));
+}
+
+#[test]
+fn damerau_levenshtein_works() {
+    assert_eq!(2, damerau_levenshtein("ac", "cba"));
+}
+
+#[test]
+fn normalized_damerau_levenshtein_works() {
+    assert!((normalized_damerau_levenshtein("levenshtein", "löwenbräu") - 0.27272).abs() < 0.00001);
+}
+
+#[test]
+fn jaro_works() {
+    assert!((0.392 - jaro("Friedrich Nietzsche", "Jean-Paul Sartre")).abs() <
+            0.001);
+}
+
+#[test]
+fn jaro_winkler_works() {
+    assert!((0.911 - jaro_winkler("cheeseburger", "cheese fries")).abs() <
+            0.001);
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.toml":"a0e3c783725beb480b666d52d49da0ec69865c82e8bd5c8a76ba330158e954c1","LICENSE":"ce93600c49fbb3e14df32efe752264644f6a2f8e08a735ba981725799e5309ef","README.md":"9af1f6627e8c2e19c7383c99462ca028b235b2f8dadbb33f13e2d1663c8c20e3","benches/linear.rs":"ec084063923bafc6e80c2cd78deb0f7ad18ae19a7e66005e991e00dac1ff3ce4","examples/layout.rs":"38cf4d316d28e0b99925bef604b68aad05489c06ec77e6105575cd26ce994631","examples/termwidth.rs":"67d95b60feb52cfd59fe5b17c37c53e51fb7f2a8e5e483d75aec8d0044dbcbd7","src/indentation.rs":"04f8479286fd87f2d75b0f02ce8309a815a5ffd1e79a7323132e34dc0e107aef","src/lib.rs":"115bf6ec566b8241d52cff83977146f03df3460d6f94ad897f2221cb56100118","src/splitting.rs":"071ef8ce0ea6c3f33230889a3426fd645276a6de626f45223ae7b873394df662","tests/version-numbers.rs":"e0e9316073d6d410440a6ee33c2f3bdfd0faa48895f6f9d05a220a91b7afcc99"},"package":"d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/Cargo.toml
@@ -0,0 +1,56 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g. crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "textwrap"
+version = "0.11.0"
+authors = ["Martin Geisler <martin@geisler.net>"]
+exclude = [".dir-locals.el"]
+description = "Textwrap is a small library for word wrapping, indenting, and\ndedenting strings.\n\nYou can use it to format strings (such as help and error messages) for\ndisplay in commandline applications. It is designed to be efficient\nand handle Unicode characters correctly.\n"
+documentation = "https://docs.rs/textwrap/"
+readme = "README.md"
+keywords = ["text", "formatting", "wrap", "typesetting", "hyphenation"]
+categories = ["text-processing", "command-line-interface"]
+license = "MIT"
+repository = "https://github.com/mgeisler/textwrap"
+[package.metadata.docs.rs]
+all-features = true
+[dependencies.hyphenation]
+version = "0.7.1"
+features = ["embed_all"]
+optional = true
+
+[dependencies.term_size]
+version = "0.3.0"
+optional = true
+
+[dependencies.unicode-width]
+version = "0.1.3"
+[dev-dependencies.lipsum]
+version = "0.6"
+
+[dev-dependencies.rand]
+version = "0.6"
+
+[dev-dependencies.rand_xorshift]
+version = "0.1"
+
+[dev-dependencies.version-sync]
+version = "0.6"
+[badges.appveyor]
+repository = "mgeisler/textwrap"
+
+[badges.codecov]
+repository = "mgeisler/textwrap"
+
+[badges.travis-ci]
+repository = "mgeisler/textwrap"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2016 Martin Geisler
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/README.md
@@ -0,0 +1,337 @@
+# Textwrap
+
+[![](https://img.shields.io/crates/v/textwrap.svg)][crates-io]
+[![](https://docs.rs/textwrap/badge.svg)][api-docs]
+[![](https://travis-ci.org/mgeisler/textwrap.svg?branch=master)][travis-ci]
+[![](https://ci.appveyor.com/api/projects/status/github/mgeisler/textwrap?branch=master&svg=true)][appveyor]
+[![](https://codecov.io/gh/mgeisler/textwrap/branch/master/graph/badge.svg)][codecov]
+
+Textwrap is a small Rust crate for word wrapping text. You can use it
+to format strings for display in commandline applications. The crate
+name and interface is inspired by
+the [Python textwrap module][py-textwrap].
+
+## Usage
+
+Add this to your `Cargo.toml`:
+```toml
+[dependencies]
+textwrap = "0.11"
+```
+
+and this to your crate root:
+```rust
+extern crate textwrap;
+```
+
+If you would like to have automatic hyphenation, specify the
+dependency as:
+```toml
+[dependencies]
+textwrap = { version = "0.11", features = ["hyphenation"] }
+```
+
+To conveniently wrap text at the current terminal width, enable the
+`term_size` feature:
+
+```toml
+[dependencies]
+textwrap = { version = "0.11", features = ["term_size"] }
+```
+
+## Documentation
+
+**[API documentation][api-docs]**
+
+## Getting Started
+
+Word wrapping single strings is easy using the `fill` function:
+```rust
+extern crate textwrap;
+use textwrap::fill;
+
+fn main() {
+    let text = "textwrap: a small library for wrapping text.";
+    println!("{}", fill(text, 18));
+}
+```
+The output is
+```
+textwrap: a small
+library for
+wrapping text.
+```
+
+With the `hyphenation` feature, you can get automatic hyphenation
+for [about 70 languages][patterns]. Your program must load and
+configure the hyphenation patterns to use:
+```rust
+extern crate hyphenation;
+extern crate textwrap;
+
+use hyphenation::{Language, Load, Standard};
+use textwrap::Wrapper;
+
+fn main() {
+    let hyphenator = Standard::from_embedded(Language::EnglishUS).unwrap();
+    let wrapper = Wrapper::with_splitter(18, hyphenator);
+    let text = "textwrap: a small library for wrapping text.";
+    println!("{}", wrapper.fill(text))
+}
+```
+
+The output now looks like this:
+```
+textwrap: a small
+library for wrap-
+ping text.
+```
+
+The hyphenation uses high-quality TeX hyphenation patterns.
+
+## Examples
+
+The library comes with some small example programs that shows various
+features.
+
+### Layout Example
+
+The `layout` example shows how a fixed example string is wrapped at
+different widths. Run the example with:
+
+```shell
+$ cargo run --features hyphenation --example layout
+```
+
+The program will use the following string:
+
+> Memory safety without garbage collection. Concurrency without data
+> races. Zero-cost abstractions.
+
+The string is wrapped at all widths between 15 and 60 columns. With
+narrow columns the output looks like this:
+
+```
+.--- Width: 15 ---.
+| Memory safety   |
+| without garbage |
+| collection.     |
+| Concurrency     |
+| without data    |
+| races. Zero-    |
+| cost abstrac-   |
+| tions.          |
+.--- Width: 16 ----.
+| Memory safety    |
+| without garbage  |
+| collection. Con- |
+| currency without |
+| data races. Ze-  |
+| ro-cost abstrac- |
+| tions.           |
+```
+
+Later, longer lines are used and the output now looks like this:
+
+```
+.-------------------- Width: 49 --------------------.
+| Memory safety without garbage collection. Concur- |
+| rency without data races. Zero-cost abstractions. |
+.---------------------- Width: 53 ----------------------.
+| Memory safety without garbage collection. Concurrency |
+| without data races. Zero-cost abstractions.           |
+.------------------------- Width: 59 -------------------------.
+| Memory safety without garbage collection. Concurrency with- |
+| out data races. Zero-cost abstractions.                     |
+```
+
+Notice how words are split at hyphens (such as "zero-cost") but also
+how words are hyphenated using automatic/machine hyphenation.
+
+### Terminal Width Example
+
+The `termwidth` example simply shows how the width can be set
+automatically to the current terminal width. Run it with this command:
+
+```
+$ cargo run --example termwidth
+```
+
+If you run it in a narrow terminal, you'll see output like this:
+```
+Formatted in within 60 columns:
+----
+Memory safety without garbage collection. Concurrency
+without data races. Zero-cost abstractions.
+----
+```
+
+If `stdout` is not connected to the terminal, the program will use a
+default of 80 columns for the width:
+
+```
+$ cargo run --example termwidth | cat
+Formatted in within 80 columns:
+----
+Memory safety without garbage collection. Concurrency without data races. Zero-
+cost abstractions.
+----
+```
+
+## Release History
+
+This section lists the largest changes per release.
+
+### Version 0.11.0 — December 9th, 2018
+
+Due to our dependencies bumping their minimum supported version of
+Rust, the minimum version of Rust we test against is now 1.22.0.
+
+* Merged [#141][issue-141]: Fix `dedent` handling of empty lines and
+  trailing newlines. Thanks @bbqsrc!
+* Fixed [#151][issue-151]: Release of version with hyphenation 0.7.
+
+### Version 0.10.0 — April 28th, 2018
+
+Due to our dependencies bumping their minimum supported version of
+Rust, the minimum version of Rust we test against is now 1.17.0.
+
+* Fixed [#99][issue-99]: Word broken even though it would fit on line.
+* Fixed [#107][issue-107]: Automatic hyphenation is off by one.
+* Fixed [#122][issue-122]: Take newlines into account when wrapping.
+* Fixed [#129][issue-129]: Panic on string with em-dash.
+
+### Version 0.9.0 — October 5th, 2017
+
+The dependency on `term_size` is now optional, and by default this
+feature is not enabled. This is a *breaking change* for users of
+`Wrapper::with_termwidth`. Enable the `term_size` feature to restore
+the old functionality.
+
+Added a regression test for the case where `width` is set to
+`usize::MAX`, thanks @Fraser999! All public structs now implement
+`Debug`, thanks @hcpl!
+
+* Fixed [#101][issue-101]: Make `term_size` an optional dependency.
+
+### Version 0.8.0 — September 4th, 2017
+
+The `Wrapper` stuct is now generic over the type of word splitter
+being used. This means less boxing and a nicer API. The
+`Wrapper::word_splitter` method has been removed. This is a *breaking
+API change* if you used the method to change the word splitter.
+
+The `Wrapper` struct has two new methods that will wrap the input text
+lazily: `Wrapper::wrap_iter` and `Wrapper::into_wrap_iter`. Use those
+if you will be iterating over the wrapped lines one by one.
+
+* Fixed [#59][issue-59]: `wrap` could return an iterator. Thanks
+  @hcpl!
+* Fixed [#81][issue-81]: Set `html_root_url`.
+
+### Version 0.7.0 — July 20th, 2017
+
+Version 0.7.0 changes the return type of `Wrapper::wrap` from
+`Vec<String>` to `Vec<Cow<'a, str>>`. This means that the output lines
+borrow data from the input string. This is a *breaking API change* if
+you relied on the exact return type of `Wrapper::wrap`. Callers of the
+`textwrap::fill` convenience function will see no breakage.
+
+The above change and other optimizations makes version 0.7.0 roughly
+15-30% faster than version 0.6.0.
+
+The `squeeze_whitespace` option has been removed since it was
+complicating the above optimization. Let us know if this option is
+important for you so we can provide a work around.
+
+* Fixed [#58][issue-58]: Add a "fast_wrap" function.
+* Fixed [#61][issue-61]: Documentation errors.
+
+### Version 0.6.0 — May 22nd, 2017
+
+Version 0.6.0 adds builder methods to `Wrapper` for easy one-line
+initialization and configuration:
+
+```rust
+let wrapper = Wrapper::new(60).break_words(false);
+```
+
+It also add a new `NoHyphenation` word splitter that will never split
+words, not even at existing hyphens.
+
+* Fixed [#28][issue-28]: Support not squeezing whitespace.
+
+### Version 0.5.0 — May 15th, 2017
+
+Version 0.5.0 has *breaking API changes*. However, this only affects
+code using the hyphenation feature. The feature is now optional, so
+you will first need to enable the `hyphenation` feature as described
+above. Afterwards, please change your code from
+```rust
+wrapper.corpus = Some(&corpus);
+```
+to
+```rust
+wrapper.splitter = Box::new(corpus);
+```
+
+Other changes include optimizations, so version 0.5.0 is roughly
+10-15% faster than version 0.4.0.
+
+* Fixed [#19][issue-19]: Add support for finding terminal size.
+* Fixed [#25][issue-25]: Handle words longer than `self.width`.
+* Fixed [#26][issue-26]: Support custom indentation.
+* Fixed [#36][issue-36]: Support building without `hyphenation`.
+* Fixed [#39][issue-39]: Respect non-breaking spaces.
+
+### Version 0.4.0 — January 24th, 2017
+
+Documented complexities and tested these via `cargo bench`.
+
+* Fixed [#13][issue-13]: Immediatedly add word if it fits.
+* Fixed [#14][issue-14]: Avoid splitting on initial hyphens.
+
+### Version 0.3.0 — January 7th, 2017
+
+Added support for automatic hyphenation.
+
+### Version 0.2.0 — December 28th, 2016
+
+Introduced `Wrapper` struct. Added support for wrapping on hyphens.
+
+### Version 0.1.0 — December 17th, 2016
+
+First public release with support for wrapping strings on whitespace.
+
+## License
+
+Textwrap can be distributed according to the [MIT license][mit].
+Contributions will be accepted under the same license.
+
+[crates-io]: https://crates.io/crates/textwrap
+[travis-ci]: https://travis-ci.org/mgeisler/textwrap
+[appveyor]: https://ci.appveyor.com/project/mgeisler/textwrap
+[codecov]: https://codecov.io/gh/mgeisler/textwrap
+[py-textwrap]: https://docs.python.org/library/textwrap
+[patterns]: https://github.com/tapeinosyne/hyphenation/tree/master/patterns-tex
+[api-docs]: https://docs.rs/textwrap/
+[issue-13]: https://github.com/mgeisler/textwrap/issues/13
+[issue-14]: https://github.com/mgeisler/textwrap/issues/14
+[issue-19]: https://github.com/mgeisler/textwrap/issues/19
+[issue-25]: https://github.com/mgeisler/textwrap/issues/25
+[issue-26]: https://github.com/mgeisler/textwrap/issues/26
+[issue-28]: https://github.com/mgeisler/textwrap/issues/28
+[issue-36]: https://github.com/mgeisler/textwrap/issues/36
+[issue-39]: https://github.com/mgeisler/textwrap/issues/39
+[issue-58]: https://github.com/mgeisler/textwrap/issues/58
+[issue-59]: https://github.com/mgeisler/textwrap/issues/59
+[issue-61]: https://github.com/mgeisler/textwrap/issues/61
+[issue-81]: https://github.com/mgeisler/textwrap/issues/81
+[issue-99]: https://github.com/mgeisler/textwrap/issues/99
+[issue-101]: https://github.com/mgeisler/textwrap/issues/101
+[issue-107]: https://github.com/mgeisler/textwrap/issues/107
+[issue-122]: https://github.com/mgeisler/textwrap/issues/122
+[issue-129]: https://github.com/mgeisler/textwrap/issues/129
+[issue-141]: https://github.com/mgeisler/textwrap/issues/141
+[issue-151]: https://github.com/mgeisler/textwrap/issues/151
+[mit]: LICENSE
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/benches/linear.rs
@@ -0,0 +1,122 @@
+#![feature(test)]
+
+// The benchmarks here verify that the complexity grows as O(*n*)
+// where *n* is the number of characters in the text to be wrapped.
+
+#[cfg(feature = "hyphenation")]
+extern crate hyphenation;
+extern crate lipsum;
+extern crate rand;
+extern crate rand_xorshift;
+extern crate test;
+extern crate textwrap;
+
+#[cfg(feature = "hyphenation")]
+use hyphenation::{Language, Load, Standard};
+use lipsum::MarkovChain;
+use rand::SeedableRng;
+use rand_xorshift::XorShiftRng;
+use test::Bencher;
+#[cfg(feature = "hyphenation")]
+use textwrap::Wrapper;
+
+const LINE_LENGTH: usize = 60;
+
+/// Generate a lorem ipsum text with the given number of characters.
+fn lorem_ipsum(length: usize) -> String {
+    // The average word length in the lorem ipsum text is somewhere
+    // between 6 and 7. So we conservatively divide by 5 to have a
+    // long enough text that we can truncate below.
+    let rng = XorShiftRng::seed_from_u64(0);
+    let mut chain = MarkovChain::new_with_rng(rng);
+    chain.learn(lipsum::LOREM_IPSUM);
+    chain.learn(lipsum::LIBER_PRIMUS);
+
+    let mut text = chain.generate_from(length / 5, ("Lorem", "ipsum"));
+    text.truncate(length);
+    text
+}
+
+#[bench]
+fn fill_100(b: &mut Bencher) {
+    let text = &lorem_ipsum(100);
+    b.iter(|| textwrap::fill(text, LINE_LENGTH))
+}
+
+#[bench]
+fn fill_200(b: &mut Bencher) {
+    let text = &lorem_ipsum(200);
+    b.iter(|| textwrap::fill(text, LINE_LENGTH))
+}
+
+#[bench]
+fn fill_400(b: &mut Bencher) {
+    let text = &lorem_ipsum(400);
+    b.iter(|| textwrap::fill(text, LINE_LENGTH))
+}
+
+#[bench]
+fn fill_800(b: &mut Bencher) {
+    let text = &lorem_ipsum(800);
+    b.iter(|| textwrap::fill(text, LINE_LENGTH))
+}
+
+#[bench]
+fn wrap_100(b: &mut Bencher) {
+    let text = &lorem_ipsum(100);
+    b.iter(|| textwrap::wrap(text, LINE_LENGTH))
+}
+
+#[bench]
+fn wrap_200(b: &mut Bencher) {
+    let text = &lorem_ipsum(200);
+    b.iter(|| textwrap::wrap(text, LINE_LENGTH))
+}
+
+#[bench]
+fn wrap_400(b: &mut Bencher) {
+    let text = &lorem_ipsum(400);
+    b.iter(|| textwrap::wrap(text, LINE_LENGTH))
+}
+
+#[bench]
+fn wrap_800(b: &mut Bencher) {
+    let text = &lorem_ipsum(800);
+    b.iter(|| textwrap::wrap(text, LINE_LENGTH))
+}
+
+#[bench]
+#[cfg(feature = "hyphenation")]
+fn hyphenation_fill_100(b: &mut Bencher) {
+    let text = &lorem_ipsum(100);
+    let dictionary = Standard::from_embedded(Language::Latin).unwrap();
+    let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+    b.iter(|| wrapper.fill(text))
+}
+
+#[bench]
+#[cfg(feature = "hyphenation")]
+fn hyphenation_fill_200(b: &mut Bencher) {
+    let text = &lorem_ipsum(200);
+    let dictionary = Standard::from_embedded(Language::Latin).unwrap();
+    let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+    b.iter(|| wrapper.fill(text))
+}
+
+#[bench]
+#[cfg(feature = "hyphenation")]
+fn hyphenation_fill_400(b: &mut Bencher) {
+    let text = &lorem_ipsum(400);
+    let dictionary = Standard::from_embedded(Language::Latin).unwrap();
+    let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+    b.iter(|| wrapper.fill(text))
+}
+
+#[bench]
+#[cfg(feature = "hyphenation")]
+fn hyphenation_fill_800(b: &mut Bencher) {
+    let text = &lorem_ipsum(800);
+    let dictionary = Standard::from_embedded(Language::Latin).unwrap();
+    let wrapper = Wrapper::with_splitter(LINE_LENGTH, dictionary);
+    b.iter(|| wrapper.fill(text))
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/examples/layout.rs
@@ -0,0 +1,38 @@
+#[cfg(feature = "hyphenation")]
+extern crate hyphenation;
+extern crate textwrap;
+
+#[cfg(feature = "hyphenation")]
+use hyphenation::{Language, Load};
+use textwrap::Wrapper;
+
+#[cfg(not(feature = "hyphenation"))]
+fn new_wrapper<'a>() -> Wrapper<'a, textwrap::HyphenSplitter> {
+    Wrapper::new(0)
+}
+
+#[cfg(feature = "hyphenation")]
+fn new_wrapper<'a>() -> Wrapper<'a, hyphenation::Standard> {
+    let dictionary = hyphenation::Standard::from_embedded(Language::EnglishUS).unwrap();
+    Wrapper::with_splitter(0, dictionary)
+}
+
+fn main() {
+    let example = "Memory safety without garbage collection. \
+                   Concurrency without data races. \
+                   Zero-cost abstractions.";
+    let mut prev_lines = vec![];
+    let mut wrapper = new_wrapper();
+    for width in 15..60 {
+        wrapper.width = width;
+        let lines = wrapper.wrap(example);
+        if lines != prev_lines {
+            let title = format!(" Width: {} ", width);
+            println!(".{:-^1$}.", title, width + 2);
+            for line in &lines {
+                println!("| {:1$} |", line, width);
+            }
+            prev_lines = lines;
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/examples/termwidth.rs
@@ -0,0 +1,41 @@
+#[cfg(feature = "hyphenation")]
+extern crate hyphenation;
+extern crate textwrap;
+
+#[cfg(feature = "hyphenation")]
+use hyphenation::{Language, Load, Standard};
+#[cfg(feature = "term_size")]
+use textwrap::Wrapper;
+
+#[cfg(not(feature = "term_size"))]
+fn main() {
+    println!("Please enable the term_size feature to run this example.");
+}
+
+#[cfg(feature = "term_size")]
+fn main() {
+    #[cfg(not(feature = "hyphenation"))]
+    fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, textwrap::HyphenSplitter>) {
+        ("without hyphenation", Wrapper::with_termwidth())
+    }
+
+    #[cfg(feature = "hyphenation")]
+    fn new_wrapper<'a>() -> (&'static str, Wrapper<'a, Standard>) {
+        let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+        (
+            "with hyphenation",
+            Wrapper::with_splitter(textwrap::termwidth(), dictionary),
+        )
+    }
+
+    let example = "Memory safety without garbage collection. \
+                   Concurrency without data races. \
+                   Zero-cost abstractions.";
+    // Create a new Wrapper -- automatically set the width to the
+    // current terminal width.
+    let (msg, wrapper) = new_wrapper();
+    println!("Formatted {} in {} columns:", msg, wrapper.width);
+    println!("----");
+    println!("{}", wrapper.fill(example));
+    println!("----");
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/src/indentation.rs
@@ -0,0 +1,294 @@
+//! Functions related to adding and removing indentation from lines of
+//! text.
+//!
+//! The functions here can be used to uniformly indent or dedent
+//! (unindent) word wrapped lines of text.
+
+/// Add prefix to each non-empty line.
+///
+/// ```
+/// use textwrap::indent;
+///
+/// assert_eq!(indent("
+/// Foo
+/// Bar
+/// ", "  "), "
+///   Foo
+///   Bar
+/// ");
+/// ```
+///
+/// Empty lines (lines consisting only of whitespace) are not indented
+/// and the whitespace is replaced by a single newline (`\n`):
+///
+/// ```
+/// use textwrap::indent;
+///
+/// assert_eq!(indent("
+/// Foo
+///
+/// Bar
+///   \t
+/// Baz
+/// ", "->"), "
+/// ->Foo
+///
+/// ->Bar
+///
+/// ->Baz
+/// ");
+/// ```
+///
+/// Leading and trailing whitespace on non-empty lines is kept
+/// unchanged:
+///
+/// ```
+/// use textwrap::indent;
+///
+/// assert_eq!(indent(" \t  Foo   ", "->"), "-> \t  Foo   \n");
+/// ```
+pub fn indent(s: &str, prefix: &str) -> String {
+    let mut result = String::new();
+    for line in s.lines() {
+        if line.chars().any(|c| !c.is_whitespace()) {
+            result.push_str(prefix);
+            result.push_str(line);
+        }
+        result.push('\n');
+    }
+    result
+}
+
+/// Removes common leading whitespace from each line.
+///
+/// This function will look at each non-empty line and determine the
+/// maximum amount of whitespace that can be removed from all lines:
+///
+/// ```
+/// use textwrap::dedent;
+///
+/// assert_eq!(dedent("
+///     1st line
+///       2nd line
+///     3rd line
+/// "), "
+/// 1st line
+///   2nd line
+/// 3rd line
+/// ");
+/// ```
+pub fn dedent(s: &str) -> String {
+    let mut prefix = "";
+    let mut lines = s.lines();
+
+    // We first search for a non-empty line to find a prefix.
+    for line in &mut lines {
+        let mut whitespace_idx = line.len();
+        for (idx, ch) in line.char_indices() {
+            if !ch.is_whitespace() {
+                whitespace_idx = idx;
+                break;
+            }
+        }
+
+        // Check if the line had anything but whitespace
+        if whitespace_idx < line.len() {
+            prefix = &line[..whitespace_idx];
+            break;
+        }
+    }
+
+    // We then continue looking through the remaining lines to
+    // possibly shorten the prefix.
+    for line in &mut lines {
+        let mut whitespace_idx = line.len();
+        for ((idx, a), b) in line.char_indices().zip(prefix.chars()) {
+            if a != b {
+                whitespace_idx = idx;
+                break;
+            }
+        }
+
+        // Check if the line had anything but whitespace and if we
+        // have found a shorter prefix
+        if whitespace_idx < line.len() && whitespace_idx < prefix.len() {
+            prefix = &line[..whitespace_idx];
+        }
+    }
+
+    // We now go over the lines a second time to build the result.
+    let mut result = String::new();
+    for line in s.lines() {
+        if line.starts_with(&prefix) && line.chars().any(|c| !c.is_whitespace()) {
+            let (_, tail) = line.split_at(prefix.len());
+            result.push_str(tail);
+        }
+        result.push('\n');
+    }
+
+    if result.ends_with('\n') && !s.ends_with('\n') {
+        let new_len = result.len() - 1;
+        result.truncate(new_len);
+    }
+
+    result
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// Add newlines. Ensures that the final line in the vector also
+    /// has a newline.
+    fn add_nl(lines: &[&str]) -> String {
+        lines.join("\n") + "\n"
+    }
+
+    #[test]
+    fn indent_empty() {
+        assert_eq!(indent("\n", "  "), "\n");
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn indent_nonempty() {
+        let x = vec!["  foo",
+                     "bar",
+                     "  baz"];
+        let y = vec!["//  foo",
+                     "//bar",
+                     "//  baz"];
+        assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn indent_empty_line() {
+        let x = vec!["  foo",
+                     "bar",
+                     "",
+                     "  baz"];
+        let y = vec!["//  foo",
+                     "//bar",
+                     "",
+                     "//  baz"];
+        assert_eq!(indent(&add_nl(&x), "//"), add_nl(&y));
+    }
+
+    #[test]
+    fn dedent_empty() {
+        assert_eq!(dedent(""), "");
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_multi_line() {
+        let x = vec!["    foo",
+                     "  bar",
+                     "    baz"];
+        let y = vec!["  foo",
+                     "bar",
+                     "  baz"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_empty_line() {
+        let x = vec!["    foo",
+                     "  bar",
+                     "   ",
+                     "    baz"];
+        let y = vec!["  foo",
+                     "bar",
+                     "",
+                     "  baz"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_blank_line() {
+        let x = vec!["      foo",
+                     "",
+                     "        bar",
+                     "          foo",
+                     "          bar",
+                     "          baz"];
+        let y = vec!["foo",
+                     "",
+                     "  bar",
+                     "    foo",
+                     "    bar",
+                     "    baz"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_whitespace_line() {
+        let x = vec!["      foo",
+                     " ",
+                     "        bar",
+                     "          foo",
+                     "          bar",
+                     "          baz"];
+        let y = vec!["foo",
+                     "",
+                     "  bar",
+                     "    foo",
+                     "    bar",
+                     "    baz"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_mixed_whitespace() {
+        let x = vec!["\tfoo",
+                     "  bar"];
+        let y = vec!["\tfoo",
+                     "  bar"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_tabbed_whitespace() {
+        let x = vec!["\t\tfoo",
+                     "\t\t\tbar"];
+        let y = vec!["foo",
+                     "\tbar"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_mixed_tabbed_whitespace() {
+        let x = vec!["\t  \tfoo",
+                     "\t  \t\tbar"];
+        let y = vec!["foo",
+                     "\tbar"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_mixed_tabbed_whitespace2() {
+        let x = vec!["\t  \tfoo",
+                     "\t    \tbar"];
+        let y = vec!["\tfoo",
+                     "  \tbar"];
+        assert_eq!(dedent(&add_nl(&x)), add_nl(&y));
+    }
+
+    #[test]
+    #[cfg_attr(rustfmt, rustfmt_skip)]
+    fn dedent_preserve_no_terminating_newline() {
+        let x = vec!["  foo",
+                     "    bar"].join("\n");
+        let y = vec!["foo",
+                     "  bar"].join("\n");
+        assert_eq!(dedent(&x), y);
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/src/lib.rs
@@ -0,0 +1,987 @@
+//! `textwrap` provides functions for word wrapping and filling text.
+//!
+//! Wrapping text can be very useful in commandline programs where you
+//! want to format dynamic output nicely so it looks good in a
+//! terminal. A quick example:
+//!
+//! ```no_run
+//! extern crate textwrap;
+//! use textwrap::fill;
+//!
+//! fn main() {
+//!     let text = "textwrap: a small library for wrapping text.";
+//!     println!("{}", fill(text, 18));
+//! }
+//! ```
+//!
+//! This will display the following output:
+//!
+//! ```text
+//! textwrap: a small
+//! library for
+//! wrapping text.
+//! ```
+//!
+//! # Displayed Width vs Byte Size
+//!
+//! To word wrap text, one must know the width of each word so one can
+//! know when to break lines. This library measures the width of text
+//! using the [displayed width][unicode-width], not the size in bytes.
+//!
+//! This is important for non-ASCII text. ASCII characters such as `a`
+//! and `!` are simple and take up one column each. This means that
+//! the displayed width is equal to the string length in bytes.
+//! However, non-ASCII characters and symbols take up more than one
+//! byte when UTF-8 encoded: `é` is `0xc3 0xa9` (two bytes) and `⚙` is
+//! `0xe2 0x9a 0x99` (three bytes) in UTF-8, respectively.
+//!
+//! This is why we take care to use the displayed width instead of the
+//! byte count when computing line lengths. All functions in this
+//! library handle Unicode characters like this.
+//!
+//! [unicode-width]: https://docs.rs/unicode-width/
+
+#![doc(html_root_url = "https://docs.rs/textwrap/0.11.0")]
+#![deny(missing_docs)]
+#![deny(missing_debug_implementations)]
+
+#[cfg(feature = "hyphenation")]
+extern crate hyphenation;
+#[cfg(feature = "term_size")]
+extern crate term_size;
+extern crate unicode_width;
+
+use std::borrow::Cow;
+use std::str::CharIndices;
+
+use unicode_width::UnicodeWidthChar;
+use unicode_width::UnicodeWidthStr;
+
+/// A non-breaking space.
+const NBSP: char = '\u{a0}';
+
+mod indentation;
+pub use indentation::dedent;
+pub use indentation::indent;
+
+mod splitting;
+pub use splitting::{HyphenSplitter, NoHyphenation, WordSplitter};
+
+/// A Wrapper holds settings for wrapping and filling text. Use it
+/// when the convenience [`wrap_iter`], [`wrap`] and [`fill`] functions
+/// are not flexible enough.
+///
+/// [`wrap_iter`]: fn.wrap_iter.html
+/// [`wrap`]: fn.wrap.html
+/// [`fill`]: fn.fill.html
+///
+/// The algorithm used by the `WrapIter` iterator (returned from the
+/// `wrap_iter` method)  works by doing successive partial scans over
+/// words in the input string (where each single scan yields a single
+/// line) so that the overall time and memory complexity is O(*n*) where
+/// *n* is the length of the input string.
+#[derive(Clone, Debug)]
+pub struct Wrapper<'a, S: WordSplitter> {
+    /// The width in columns at which the text will be wrapped.
+    pub width: usize,
+    /// Indentation used for the first line of output.
+    pub initial_indent: &'a str,
+    /// Indentation used for subsequent lines of output.
+    pub subsequent_indent: &'a str,
+    /// Allow long words to be broken if they cannot fit on a line.
+    /// When set to `false`, some lines may be longer than
+    /// `self.width`.
+    pub break_words: bool,
+    /// The method for splitting words. If the `hyphenation` feature
+    /// is enabled, you can use a `hyphenation::Standard` dictionary
+    /// here to get language-aware hyphenation.
+    pub splitter: S,
+}
+
+impl<'a> Wrapper<'a, HyphenSplitter> {
+    /// Create a new Wrapper for wrapping at the specified width. By
+    /// default, we allow words longer than `width` to be broken. A
+    /// [`HyphenSplitter`] will be used by default for splitting
+    /// words. See the [`WordSplitter`] trait for other options.
+    ///
+    /// [`HyphenSplitter`]: struct.HyphenSplitter.html
+    /// [`WordSplitter`]: trait.WordSplitter.html
+    pub fn new(width: usize) -> Wrapper<'a, HyphenSplitter> {
+        Wrapper::with_splitter(width, HyphenSplitter)
+    }
+
+    /// Create a new Wrapper for wrapping text at the current terminal
+    /// width. If the terminal width cannot be determined (typically
+    /// because the standard input and output is not connected to a
+    /// terminal), a width of 80 characters will be used. Other
+    /// settings use the same defaults as `Wrapper::new`.
+    ///
+    /// Equivalent to:
+    ///
+    /// ```no_run
+    /// # #![allow(unused_variables)]
+    /// use textwrap::{Wrapper, termwidth};
+    ///
+    /// let wrapper = Wrapper::new(termwidth());
+    /// ```
+    #[cfg(feature = "term_size")]
+    pub fn with_termwidth() -> Wrapper<'a, HyphenSplitter> {
+        Wrapper::new(termwidth())
+    }
+}
+
+impl<'a, S: WordSplitter> Wrapper<'a, S> {
+    /// Use the given [`WordSplitter`] to create a new Wrapper for
+    /// wrapping at the specified width. By default, we allow words
+    /// longer than `width` to be broken.
+    ///
+    /// [`WordSplitter`]: trait.WordSplitter.html
+    pub fn with_splitter(width: usize, splitter: S) -> Wrapper<'a, S> {
+        Wrapper {
+            width: width,
+            initial_indent: "",
+            subsequent_indent: "",
+            break_words: true,
+            splitter: splitter,
+        }
+    }
+
+    /// Change [`self.initial_indent`]. The initial indentation is
+    /// used on the very first line of output.
+    ///
+    /// # Examples
+    ///
+    /// Classic paragraph indentation can be achieved by specifying an
+    /// initial indentation and wrapping each paragraph by itself:
+    ///
+    /// ```no_run
+    /// # #![allow(unused_variables)]
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrapper = Wrapper::new(15).initial_indent("    ");
+    /// ```
+    ///
+    /// [`self.initial_indent`]: #structfield.initial_indent
+    pub fn initial_indent(self, indent: &'a str) -> Wrapper<'a, S> {
+        Wrapper {
+            initial_indent: indent,
+            ..self
+        }
+    }
+
+    /// Change [`self.subsequent_indent`]. The subsequent indentation
+    /// is used on lines following the first line of output.
+    ///
+    /// # Examples
+    ///
+    /// Combining initial and subsequent indentation lets you format a
+    /// single paragraph as a bullet list:
+    ///
+    /// ```no_run
+    /// # #![allow(unused_variables)]
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrapper = Wrapper::new(15)
+    ///     .initial_indent("* ")
+    ///     .subsequent_indent("  ");
+    /// ```
+    ///
+    /// [`self.subsequent_indent`]: #structfield.subsequent_indent
+    pub fn subsequent_indent(self, indent: &'a str) -> Wrapper<'a, S> {
+        Wrapper {
+            subsequent_indent: indent,
+            ..self
+        }
+    }
+
+    /// Change [`self.break_words`]. This controls if words longer
+    /// than `self.width` can be broken, or if they will be left
+    /// sticking out into the right margin.
+    ///
+    /// [`self.break_words`]: #structfield.break_words
+    pub fn break_words(self, setting: bool) -> Wrapper<'a, S> {
+        Wrapper {
+            break_words: setting,
+            ..self
+        }
+    }
+
+    /// Fill a line of text at `self.width` characters. Strings are
+    /// wrapped based on their displayed width, not their size in
+    /// bytes.
+    ///
+    /// The result is a string with newlines between each line. Use
+    /// the `wrap` method if you need access to the individual lines.
+    ///
+    /// # Complexities
+    ///
+    /// This method simply joins the lines produced by `wrap_iter`. As
+    /// such, it inherits the O(*n*) time and memory complexity where
+    /// *n* is the input string length.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrapper = Wrapper::new(15);
+    /// assert_eq!(wrapper.fill("Memory safety without garbage collection."),
+    ///            "Memory safety\nwithout garbage\ncollection.");
+    /// ```
+    pub fn fill(&self, s: &str) -> String {
+        // This will avoid reallocation in simple cases (no
+        // indentation, no hyphenation).
+        let mut result = String::with_capacity(s.len());
+
+        for (i, line) in self.wrap_iter(s).enumerate() {
+            if i > 0 {
+                result.push('\n');
+            }
+            result.push_str(&line);
+        }
+
+        result
+    }
+
+    /// Wrap a line of text at `self.width` characters. Strings are
+    /// wrapped based on their displayed width, not their size in
+    /// bytes.
+    ///
+    /// # Complexities
+    ///
+    /// This method simply collects the lines produced by `wrap_iter`.
+    /// As such, it inherits the O(*n*) overall time and memory
+    /// complexity where *n* is the input string length.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrap15 = Wrapper::new(15);
+    /// assert_eq!(wrap15.wrap("Concurrency without data races."),
+    ///            vec!["Concurrency",
+    ///                 "without data",
+    ///                 "races."]);
+    ///
+    /// let wrap20 = Wrapper::new(20);
+    /// assert_eq!(wrap20.wrap("Concurrency without data races."),
+    ///            vec!["Concurrency without",
+    ///                 "data races."]);
+    /// ```
+    ///
+    /// Notice that newlines in the input are preserved. This means
+    /// that they force a line break, regardless of how long the
+    /// current line is:
+    ///
+    /// ```
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrapper = Wrapper::new(40);
+    /// assert_eq!(wrapper.wrap("First line.\nSecond line."),
+    ///            vec!["First line.", "Second line."]);
+    /// ```
+    ///
+    pub fn wrap(&self, s: &'a str) -> Vec<Cow<'a, str>> {
+        self.wrap_iter(s).collect::<Vec<_>>()
+    }
+
+    /// Lazily wrap a line of text at `self.width` characters. Strings
+    /// are wrapped based on their displayed width, not their size in
+    /// bytes.
+    ///
+    /// The [`WordSplitter`] stored in [`self.splitter`] is used
+    /// whenever when a word is too large to fit on the current line.
+    /// By changing the field, different hyphenation strategies can be
+    /// implemented.
+    ///
+    /// # Complexities
+    ///
+    /// This method returns a [`WrapIter`] iterator which borrows this
+    /// `Wrapper`. The algorithm used has a linear complexity, so
+    /// getting the next line from the iterator will take O(*w*) time,
+    /// where *w* is the wrapping width. Fully processing the iterator
+    /// will take O(*n*) time for an input string of length *n*.
+    ///
+    /// When no indentation is used, each line returned is a slice of
+    /// the input string and the memory overhead is thus constant.
+    /// Otherwise new memory is allocated for each line returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::borrow::Cow;
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrap20 = Wrapper::new(20);
+    /// let mut wrap20_iter = wrap20.wrap_iter("Zero-cost abstractions.");
+    /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
+    /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
+    /// assert_eq!(wrap20_iter.next(), None);
+    ///
+    /// let wrap25 = Wrapper::new(25);
+    /// let mut wrap25_iter = wrap25.wrap_iter("Zero-cost abstractions.");
+    /// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions.")));
+    /// assert_eq!(wrap25_iter.next(), None);
+    /// ```
+    ///
+    /// [`self.splitter`]: #structfield.splitter
+    /// [`WordSplitter`]: trait.WordSplitter.html
+    /// [`WrapIter`]: struct.WrapIter.html
+    pub fn wrap_iter<'w>(&'w self, s: &'a str) -> WrapIter<'w, 'a, S> {
+        WrapIter {
+            wrapper: self,
+            inner: WrapIterImpl::new(self, s),
+        }
+    }
+
+    /// Lazily wrap a line of text at `self.width` characters. Strings
+    /// are wrapped based on their displayed width, not their size in
+    /// bytes.
+    ///
+    /// The [`WordSplitter`] stored in [`self.splitter`] is used
+    /// whenever when a word is too large to fit on the current line.
+    /// By changing the field, different hyphenation strategies can be
+    /// implemented.
+    ///
+    /// # Complexities
+    ///
+    /// This method consumes the `Wrapper` and returns a
+    /// [`IntoWrapIter`] iterator. Fully processing the iterator has
+    /// the same O(*n*) time complexity as [`wrap_iter`], where *n* is
+    /// the length of the input string.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::borrow::Cow;
+    /// use textwrap::Wrapper;
+    ///
+    /// let wrap20 = Wrapper::new(20);
+    /// let mut wrap20_iter = wrap20.into_wrap_iter("Zero-cost abstractions.");
+    /// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
+    /// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
+    /// assert_eq!(wrap20_iter.next(), None);
+    /// ```
+    ///
+    /// [`self.splitter`]: #structfield.splitter
+    /// [`WordSplitter`]: trait.WordSplitter.html
+    /// [`IntoWrapIter`]: struct.IntoWrapIter.html
+    /// [`wrap_iter`]: #method.wrap_iter
+    pub fn into_wrap_iter(self, s: &'a str) -> IntoWrapIter<'a, S> {
+        let inner = WrapIterImpl::new(&self, s);
+
+        IntoWrapIter {
+            wrapper: self,
+            inner: inner,
+        }
+    }
+}
+
+/// An iterator over the lines of the input string which owns a
+/// `Wrapper`. An instance of `IntoWrapIter` is typically obtained
+/// through either [`wrap_iter`] or [`Wrapper::into_wrap_iter`].
+///
+/// Each call of `.next()` method yields a line wrapped in `Some` if the
+/// input hasn't been fully processed yet. Otherwise it returns `None`.
+///
+/// [`wrap_iter`]: fn.wrap_iter.html
+/// [`Wrapper::into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter
+#[derive(Debug)]
+pub struct IntoWrapIter<'a, S: WordSplitter> {
+    wrapper: Wrapper<'a, S>,
+    inner: WrapIterImpl<'a>,
+}
+
+impl<'a, S: WordSplitter> Iterator for IntoWrapIter<'a, S> {
+    type Item = Cow<'a, str>;
+
+    fn next(&mut self) -> Option<Cow<'a, str>> {
+        self.inner.next(&self.wrapper)
+    }
+}
+
+/// An iterator over the lines of the input string which borrows a
+/// `Wrapper`. An instance of `WrapIter` is typically obtained
+/// through the [`Wrapper::wrap_iter`] method.
+///
+/// Each call of `.next()` method yields a line wrapped in `Some` if the
+/// input hasn't been fully processed yet. Otherwise it returns `None`.
+///
+/// [`Wrapper::wrap_iter`]: struct.Wrapper.html#method.wrap_iter
+#[derive(Debug)]
+pub struct WrapIter<'w, 'a: 'w, S: WordSplitter + 'w> {
+    wrapper: &'w Wrapper<'a, S>,
+    inner: WrapIterImpl<'a>,
+}
+
+impl<'w, 'a: 'w, S: WordSplitter> Iterator for WrapIter<'w, 'a, S> {
+    type Item = Cow<'a, str>;
+
+    fn next(&mut self) -> Option<Cow<'a, str>> {
+        self.inner.next(self.wrapper)
+    }
+}
+
+/// Like `char::is_whitespace`, but non-breaking spaces don't count.
+#[inline]
+fn is_whitespace(ch: char) -> bool {
+    ch.is_whitespace() && ch != NBSP
+}
+
+/// Common implementation details for `WrapIter` and `IntoWrapIter`.
+#[derive(Debug)]
+struct WrapIterImpl<'a> {
+    // String to wrap.
+    source: &'a str,
+    // CharIndices iterator over self.source.
+    char_indices: CharIndices<'a>,
+    // Byte index where the current line starts.
+    start: usize,
+    // Byte index of the last place where the string can be split.
+    split: usize,
+    // Size in bytes of the character at self.source[self.split].
+    split_len: usize,
+    // Width of self.source[self.start..idx].
+    line_width: usize,
+    // Width of self.source[self.start..self.split].
+    line_width_at_split: usize,
+    // Tracking runs of whitespace characters.
+    in_whitespace: bool,
+    // Has iterator finished producing elements?
+    finished: bool,
+}
+
+impl<'a> WrapIterImpl<'a> {
+    fn new<S: WordSplitter>(wrapper: &Wrapper<'a, S>, s: &'a str) -> WrapIterImpl<'a> {
+        WrapIterImpl {
+            source: s,
+            char_indices: s.char_indices(),
+            start: 0,
+            split: 0,
+            split_len: 0,
+            line_width: wrapper.initial_indent.width(),
+            line_width_at_split: wrapper.initial_indent.width(),
+            in_whitespace: false,
+            finished: false,
+        }
+    }
+
+    fn create_result_line<S: WordSplitter>(&self, wrapper: &Wrapper<'a, S>) -> Cow<'a, str> {
+        if self.start == 0 {
+            Cow::from(wrapper.initial_indent)
+        } else {
+            Cow::from(wrapper.subsequent_indent)
+        }
+    }
+
+    fn next<S: WordSplitter>(&mut self, wrapper: &Wrapper<'a, S>) -> Option<Cow<'a, str>> {
+        if self.finished {
+            return None;
+        }
+
+        while let Some((idx, ch)) = self.char_indices.next() {
+            let char_width = ch.width().unwrap_or(0);
+            let char_len = ch.len_utf8();
+
+            if ch == '\n' {
+                self.split = idx;
+                self.split_len = char_len;
+                self.line_width_at_split = self.line_width;
+                self.in_whitespace = false;
+
+                // If this is not the final line, return the current line. Otherwise,
+                // we will return the line with its line break after exiting the loop
+                if self.split + self.split_len < self.source.len() {
+                    let mut line = self.create_result_line(wrapper);
+                    line += &self.source[self.start..self.split];
+
+                    self.start = self.split + self.split_len;
+                    self.line_width = wrapper.subsequent_indent.width();
+
+                    return Some(line);
+                }
+            } else if is_whitespace(ch) {
+                // Extend the previous split or create a new one.
+                if self.in_whitespace {
+                    self.split_len += char_len;
+                } else {
+                    self.split = idx;
+                    self.split_len = char_len;
+                }
+                self.line_width_at_split = self.line_width + char_width;
+                self.in_whitespace = true;
+            } else if self.line_width + char_width > wrapper.width {
+                // There is no room for this character on the current
+                // line. Try to split the final word.
+                self.in_whitespace = false;
+                let remaining_text = &self.source[self.split + self.split_len..];
+                let final_word = match remaining_text.find(is_whitespace) {
+                    Some(i) => &remaining_text[..i],
+                    None => remaining_text,
+                };
+
+                let mut hyphen = "";
+                let splits = wrapper.splitter.split(final_word);
+                for &(head, hyp, _) in splits.iter().rev() {
+                    if self.line_width_at_split + head.width() + hyp.width() <= wrapper.width {
+                        // We can fit head into the current line.
+                        // Advance the split point by the width of the
+                        // whitespace and the head length.
+                        self.split += self.split_len + head.len();
+                        self.split_len = 0;
+                        hyphen = hyp;
+                        break;
+                    }
+                }
+
+                if self.start >= self.split {
+                    // The word is too big to fit on a single line, so we
+                    // need to split it at the current index.
+                    if wrapper.break_words {
+                        // Break work at current index.
+                        self.split = idx;
+                        self.split_len = 0;
+                        self.line_width_at_split = self.line_width;
+                    } else {
+                        // Add smallest split.
+                        self.split = self.start + splits[0].0.len();
+                        self.split_len = 0;
+                        self.line_width_at_split = self.line_width;
+                    }
+                }
+
+                if self.start < self.split {
+                    let mut line = self.create_result_line(wrapper);
+                    line += &self.source[self.start..self.split];
+                    line += hyphen;
+
+                    self.start = self.split + self.split_len;
+                    self.line_width += wrapper.subsequent_indent.width();
+                    self.line_width -= self.line_width_at_split;
+                    self.line_width += char_width;
+
+                    return Some(line);
+                }
+            } else {
+                self.in_whitespace = false;
+            }
+            self.line_width += char_width;
+        }
+
+        self.finished = true;
+
+        // Add final line.
+        if self.start < self.source.len() {
+            let mut line = self.create_result_line(wrapper);
+            line += &self.source[self.start..];
+            return Some(line);
+        }
+
+        None
+    }
+}
+
+/// Return the current terminal width. If the terminal width cannot be
+/// determined (typically because the standard output is not connected
+/// to a terminal), a default width of 80 characters will be used.
+///
+/// # Examples
+///
+/// Create a `Wrapper` for the current terminal with a two column
+/// margin:
+///
+/// ```no_run
+/// # #![allow(unused_variables)]
+/// use textwrap::{Wrapper, NoHyphenation, termwidth};
+///
+/// let width = termwidth() - 4; // Two columns on each side.
+/// let wrapper = Wrapper::with_splitter(width, NoHyphenation)
+///     .initial_indent("  ")
+///     .subsequent_indent("  ");
+/// ```
+#[cfg(feature = "term_size")]
+pub fn termwidth() -> usize {
+    term_size::dimensions_stdout().map_or(80, |(w, _)| w)
+}
+
+/// Fill a line of text at `width` characters. Strings are wrapped
+/// based on their displayed width, not their size in bytes.
+///
+/// The result is a string with newlines between each line. Use
+/// [`wrap`] if you need access to the individual lines or
+/// [`wrap_iter`] for its iterator counterpart.
+///
+/// ```
+/// use textwrap::fill;
+///
+/// assert_eq!(fill("Memory safety without garbage collection.", 15),
+///            "Memory safety\nwithout garbage\ncollection.");
+/// ```
+///
+/// This function creates a Wrapper on the fly with default settings.
+/// If you need to set a language corpus for automatic hyphenation, or
+/// need to fill many strings, then it is suggested to create a Wrapper
+/// and call its [`fill` method].
+///
+/// [`wrap`]: fn.wrap.html
+/// [`wrap_iter`]: fn.wrap_iter.html
+/// [`fill` method]: struct.Wrapper.html#method.fill
+pub fn fill(s: &str, width: usize) -> String {
+    Wrapper::new(width).fill(s)
+}
+
+/// Wrap a line of text at `width` characters. Strings are wrapped
+/// based on their displayed width, not their size in bytes.
+///
+/// This function creates a Wrapper on the fly with default settings.
+/// If you need to set a language corpus for automatic hyphenation, or
+/// need to wrap many strings, then it is suggested to create a Wrapper
+/// and call its [`wrap` method].
+///
+/// The result is a vector of strings. Use [`wrap_iter`] if you need an
+/// iterator version.
+///
+/// # Examples
+///
+/// ```
+/// use textwrap::wrap;
+///
+/// assert_eq!(wrap("Concurrency without data races.", 15),
+///            vec!["Concurrency",
+///                 "without data",
+///                 "races."]);
+///
+/// assert_eq!(wrap("Concurrency without data races.", 20),
+///            vec!["Concurrency without",
+///                 "data races."]);
+/// ```
+///
+/// [`wrap_iter`]: fn.wrap_iter.html
+/// [`wrap` method]: struct.Wrapper.html#method.wrap
+pub fn wrap(s: &str, width: usize) -> Vec<Cow<str>> {
+    Wrapper::new(width).wrap(s)
+}
+
+/// Lazily wrap a line of text at `width` characters. Strings are
+/// wrapped based on their displayed width, not their size in bytes.
+///
+/// This function creates a Wrapper on the fly with default settings.
+/// It then calls the [`into_wrap_iter`] method. Hence, the return
+/// value is an [`IntoWrapIter`], not a [`WrapIter`] as the function
+/// name would otherwise suggest.
+///
+/// If you need to set a language corpus for automatic hyphenation, or
+/// need to wrap many strings, then it is suggested to create a Wrapper
+/// and call its [`wrap_iter`] or [`into_wrap_iter`] methods.
+///
+/// # Examples
+///
+/// ```
+/// use std::borrow::Cow;
+/// use textwrap::wrap_iter;
+///
+/// let mut wrap20_iter = wrap_iter("Zero-cost abstractions.", 20);
+/// assert_eq!(wrap20_iter.next(), Some(Cow::from("Zero-cost")));
+/// assert_eq!(wrap20_iter.next(), Some(Cow::from("abstractions.")));
+/// assert_eq!(wrap20_iter.next(), None);
+///
+/// let mut wrap25_iter = wrap_iter("Zero-cost abstractions.", 25);
+/// assert_eq!(wrap25_iter.next(), Some(Cow::from("Zero-cost abstractions.")));
+/// assert_eq!(wrap25_iter.next(), None);
+/// ```
+///
+/// [`wrap_iter`]: struct.Wrapper.html#method.wrap_iter
+/// [`into_wrap_iter`]: struct.Wrapper.html#method.into_wrap_iter
+/// [`IntoWrapIter`]: struct.IntoWrapIter.html
+/// [`WrapIter`]: struct.WrapIter.html
+pub fn wrap_iter(s: &str, width: usize) -> IntoWrapIter<HyphenSplitter> {
+    Wrapper::new(width).into_wrap_iter(s)
+}
+
+#[cfg(test)]
+mod tests {
+    #[cfg(feature = "hyphenation")]
+    extern crate hyphenation;
+
+    use super::*;
+    #[cfg(feature = "hyphenation")]
+    use hyphenation::{Language, Load, Standard};
+
+    #[test]
+    fn no_wrap() {
+        assert_eq!(wrap("foo", 10), vec!["foo"]);
+    }
+
+    #[test]
+    fn simple() {
+        assert_eq!(wrap("foo bar baz", 5), vec!["foo", "bar", "baz"]);
+    }
+
+    #[test]
+    fn multi_word_on_line() {
+        assert_eq!(wrap("foo bar baz", 10), vec!["foo bar", "baz"]);
+    }
+
+    #[test]
+    fn long_word() {
+        assert_eq!(wrap("foo", 0), vec!["f", "o", "o"]);
+    }
+
+    #[test]
+    fn long_words() {
+        assert_eq!(wrap("foo bar", 0), vec!["f", "o", "o", "b", "a", "r"]);
+    }
+
+    #[test]
+    fn max_width() {
+        assert_eq!(wrap("foo bar", usize::max_value()), vec!["foo bar"]);
+    }
+
+    #[test]
+    fn leading_whitespace() {
+        assert_eq!(wrap("  foo bar", 6), vec!["  foo", "bar"]);
+    }
+
+    #[test]
+    fn trailing_whitespace() {
+        assert_eq!(wrap("foo bar  ", 6), vec!["foo", "bar  "]);
+    }
+
+    #[test]
+    fn interior_whitespace() {
+        assert_eq!(wrap("foo:   bar baz", 10), vec!["foo:   bar", "baz"]);
+    }
+
+    #[test]
+    fn extra_whitespace_start_of_line() {
+        // Whitespace is only significant inside a line. After a line
+        // gets too long and is broken, the first word starts in
+        // column zero and is not indented. The line before might end
+        // up with trailing whitespace.
+        assert_eq!(wrap("foo               bar", 5), vec!["foo", "bar"]);
+    }
+
+    #[test]
+    fn issue_99() {
+        // We did not reset the in_whitespace flag correctly and did
+        // not handle single-character words after a line break.
+        assert_eq!(
+            wrap("aaabbbccc x yyyzzzwww", 9),
+            vec!["aaabbbccc", "x", "yyyzzzwww"]
+        );
+    }
+
+    #[test]
+    fn issue_129() {
+        // The dash is an em-dash which takes up four bytes. We used
+        // to panic since we tried to index into the character.
+        assert_eq!(wrap("x – x", 1), vec!["x", "–", "x"]);
+    }
+
+    #[test]
+    fn wide_character_handling() {
+        assert_eq!(wrap("Hello, World!", 15), vec!["Hello, World!"]);
+        assert_eq!(
+            wrap("Hello, World!", 15),
+            vec!["Hello,", "World!"]
+        );
+    }
+
+    #[test]
+    fn empty_input_not_indented() {
+        let wrapper = Wrapper::new(10).initial_indent("!!!");
+        assert_eq!(wrapper.fill(""), "");
+    }
+
+    #[test]
+    fn indent_single_line() {
+        let wrapper = Wrapper::new(10).initial_indent(">>>"); // No trailing space
+        assert_eq!(wrapper.fill("foo"), ">>>foo");
+    }
+
+    #[test]
+    fn indent_multiple_lines() {
+        let wrapper = Wrapper::new(6).initial_indent("* ").subsequent_indent("  ");
+        assert_eq!(wrapper.wrap("foo bar baz"), vec!["* foo", "  bar", "  baz"]);
+    }
+
+    #[test]
+    fn indent_break_words() {
+        let wrapper = Wrapper::new(5).initial_indent("* ").subsequent_indent("  ");
+        assert_eq!(wrapper.wrap("foobarbaz"), vec!["* foo", "  bar", "  baz"]);
+    }
+
+    #[test]
+    fn hyphens() {
+        assert_eq!(wrap("foo-bar", 5), vec!["foo-", "bar"]);
+    }
+
+    #[test]
+    fn trailing_hyphen() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(wrapper.wrap("foobar-"), vec!["foobar-"]);
+    }
+
+    #[test]
+    fn multiple_hyphens() {
+        assert_eq!(wrap("foo-bar-baz", 5), vec!["foo-", "bar-", "baz"]);
+    }
+
+    #[test]
+    fn hyphens_flag() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(
+            wrapper.wrap("The --foo-bar flag."),
+            vec!["The", "--foo-", "bar", "flag."]
+        );
+    }
+
+    #[test]
+    fn repeated_hyphens() {
+        let wrapper = Wrapper::new(4).break_words(false);
+        assert_eq!(wrapper.wrap("foo--bar"), vec!["foo--bar"]);
+    }
+
+    #[test]
+    fn hyphens_alphanumeric() {
+        assert_eq!(wrap("Na2-CH4", 5), vec!["Na2-", "CH4"]);
+    }
+
+    #[test]
+    fn hyphens_non_alphanumeric() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(wrapper.wrap("foo(-)bar"), vec!["foo(-)bar"]);
+    }
+
+    #[test]
+    fn multiple_splits() {
+        assert_eq!(wrap("foo-bar-baz", 9), vec!["foo-bar-", "baz"]);
+    }
+
+    #[test]
+    fn forced_split() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(wrapper.wrap("foobar-baz"), vec!["foobar-", "baz"]);
+    }
+
+    #[test]
+    fn no_hyphenation() {
+        let wrapper = Wrapper::with_splitter(8, NoHyphenation);
+        assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]);
+    }
+
+    #[test]
+    #[cfg(feature = "hyphenation")]
+    fn auto_hyphenation() {
+        let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+        let wrapper = Wrapper::new(10);
+        assert_eq!(
+            wrapper.wrap("Internationalization"),
+            vec!["Internatio", "nalization"]
+        );
+
+        let wrapper = Wrapper::with_splitter(10, dictionary);
+        assert_eq!(
+            wrapper.wrap("Internationalization"),
+            vec!["Interna-", "tionaliza-", "tion"]
+        );
+    }
+
+    #[test]
+    #[cfg(feature = "hyphenation")]
+    fn split_len_hyphenation() {
+        // Test that hyphenation takes the width of the wihtespace
+        // into account.
+        let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+        let wrapper = Wrapper::with_splitter(15, dictionary);
+        assert_eq!(
+            wrapper.wrap("garbage   collection"),
+            vec!["garbage   col-", "lection"]
+        );
+    }
+
+    #[test]
+    #[cfg(feature = "hyphenation")]
+    fn borrowed_lines() {
+        // Lines that end with an extra hyphen are owned, the final
+        // line is borrowed.
+        use std::borrow::Cow::{Borrowed, Owned};
+        let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+        let wrapper = Wrapper::with_splitter(10, dictionary);
+        let lines = wrapper.wrap("Internationalization");
+        if let Borrowed(s) = lines[0] {
+            assert!(false, "should not have been borrowed: {:?}", s);
+        }
+        if let Borrowed(s) = lines[1] {
+            assert!(false, "should not have been borrowed: {:?}", s);
+        }
+        if let Owned(ref s) = lines[2] {
+            assert!(false, "should not have been owned: {:?}", s);
+        }
+    }
+
+    #[test]
+    #[cfg(feature = "hyphenation")]
+    fn auto_hyphenation_with_hyphen() {
+        let dictionary = Standard::from_embedded(Language::EnglishUS).unwrap();
+        let wrapper = Wrapper::new(8).break_words(false);
+        assert_eq!(wrapper.wrap("over-caffinated"), vec!["over-", "caffinated"]);
+
+        let wrapper = Wrapper::with_splitter(8, dictionary).break_words(false);
+        assert_eq!(
+            wrapper.wrap("over-caffinated"),
+            vec!["over-", "caffi-", "nated"]
+        );
+    }
+
+    #[test]
+    fn break_words() {
+        assert_eq!(wrap("foobarbaz", 3), vec!["foo", "bar", "baz"]);
+    }
+
+    #[test]
+    fn break_words_wide_characters() {
+        assert_eq!(wrap("Hello", 5), vec!["He", "ll", "o"]);
+    }
+
+    #[test]
+    fn break_words_zero_width() {
+        assert_eq!(wrap("foobar", 0), vec!["f", "o", "o", "b", "a", "r"]);
+    }
+
+    #[test]
+    fn break_words_line_breaks() {
+        assert_eq!(fill("ab\ncdefghijkl", 5), "ab\ncdefg\nhijkl");
+        assert_eq!(fill("abcdefgh\nijkl", 5), "abcde\nfgh\nijkl");
+    }
+
+    #[test]
+    fn preserve_line_breaks() {
+        assert_eq!(fill("test\n", 11), "test\n");
+        assert_eq!(fill("test\n\na\n\n", 11), "test\n\na\n\n");
+        assert_eq!(fill("1 3 5 7\n1 3 5 7", 7), "1 3 5 7\n1 3 5 7");
+    }
+
+    #[test]
+    fn wrap_preserve_line_breaks() {
+        assert_eq!(fill("1 3 5 7\n1 3 5 7", 5), "1 3 5\n7\n1 3 5\n7");
+    }
+
+    #[test]
+    fn non_breaking_space() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(wrapper.fill("foo bar baz"), "foo bar baz");
+    }
+
+    #[test]
+    fn non_breaking_hyphen() {
+        let wrapper = Wrapper::new(5).break_words(false);
+        assert_eq!(wrapper.fill("foo‑bar‑baz"), "foo‑bar‑baz");
+    }
+
+    #[test]
+    fn fill_simple() {
+        assert_eq!(fill("foo bar baz", 10), "foo bar\nbaz");
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/src/splitting.rs
@@ -0,0 +1,139 @@
+//! Word splitting functionality.
+//!
+//! To wrap text into lines, long words sometimes need to be split
+//! across lines. The [`WordSplitter`] trait defines this
+//! functionality. [`HyphenSplitter`] is the default implementation of
+//! this treat: it will simply split words on existing hyphens.
+
+#[cfg(feature = "hyphenation")]
+use hyphenation::{Hyphenator, Standard};
+
+/// An interface for splitting words.
+///
+/// When the [`wrap_iter`] method will try to fit text into a line, it
+/// will eventually find a word that it too large the current text
+/// width. It will then call the currently configured `WordSplitter` to
+/// have it attempt to split the word into smaller parts. This trait
+/// describes that functionality via the [`split`] method.
+///
+/// If the `textwrap` crate has been compiled with the `hyphenation`
+/// feature enabled, you will find an implementation of `WordSplitter`
+/// by the `hyphenation::language::Corpus` struct. Use this struct for
+/// language-aware hyphenation. See the [`hyphenation` documentation]
+/// for details.
+///
+/// [`wrap_iter`]: ../struct.Wrapper.html#method.wrap_iter
+/// [`split`]: #tymethod.split
+/// [`hyphenation` documentation]: https://docs.rs/hyphenation/
+pub trait WordSplitter {
+    /// Return all possible splits of word. Each split is a triple
+    /// with a head, a hyphen, and a tail where `head + &hyphen +
+    /// &tail == word`. The hyphen can be empty if there is already a
+    /// hyphen in the head.
+    ///
+    /// The splits should go from smallest to longest and should
+    /// include no split at all. So the word "technology" could be
+    /// split into
+    ///
+    /// ```no_run
+    /// vec![("tech", "-", "nology"),
+    ///      ("technol", "-", "ogy"),
+    ///      ("technolo", "-", "gy"),
+    ///      ("technology", "", "")];
+    /// ```
+    fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)>;
+}
+
+/// Use this as a [`Wrapper.splitter`] to avoid any kind of
+/// hyphenation:
+///
+/// ```
+/// use textwrap::{Wrapper, NoHyphenation};
+///
+/// let wrapper = Wrapper::with_splitter(8, NoHyphenation);
+/// assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]);
+/// ```
+///
+/// [`Wrapper.splitter`]: ../struct.Wrapper.html#structfield.splitter
+#[derive(Clone, Debug)]
+pub struct NoHyphenation;
+
+/// `NoHyphenation` implements `WordSplitter` by not splitting the
+/// word at all.
+impl WordSplitter for NoHyphenation {
+    fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> {
+        vec![(word, "", "")]
+    }
+}
+
+/// Simple and default way to split words: splitting on existing
+/// hyphens only.
+///
+/// You probably don't need to use this type since it's already used
+/// by default by `Wrapper::new`.
+#[derive(Clone, Debug)]
+pub struct HyphenSplitter;
+
+/// `HyphenSplitter` is the default `WordSplitter` used by
+/// `Wrapper::new`. It will split words on any existing hyphens in the
+/// word.
+///
+/// It will only use hyphens that are surrounded by alphanumeric
+/// characters, which prevents a word like "--foo-bar" from being
+/// split on the first or second hyphen.
+impl WordSplitter for HyphenSplitter {
+    fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> {
+        let mut triples = Vec::new();
+        // Split on hyphens, smallest split first. We only use hyphens
+        // that are surrounded by alphanumeric characters. This is to
+        // avoid splitting on repeated hyphens, such as those found in
+        // --foo-bar.
+        let mut char_indices = word.char_indices();
+        // Early return if the word is empty.
+        let mut prev = match char_indices.next() {
+            None => return vec![(word, "", "")],
+            Some((_, ch)) => ch,
+        };
+
+        // Find current word, or return early if the word only has a
+        // single character.
+        let (mut idx, mut cur) = match char_indices.next() {
+            None => return vec![(word, "", "")],
+            Some((idx, cur)) => (idx, cur),
+        };
+
+        for (i, next) in char_indices {
+            if prev.is_alphanumeric() && cur == '-' && next.is_alphanumeric() {
+                let (head, tail) = word.split_at(idx + 1);
+                triples.push((head, "", tail));
+            }
+            prev = cur;
+            idx = i;
+            cur = next;
+        }
+
+        // Finally option is no split at all.
+        triples.push((word, "", ""));
+
+        triples
+    }
+}
+
+/// A hyphenation dictionary can be used to do language-specific
+/// hyphenation using patterns from the hyphenation crate.
+#[cfg(feature = "hyphenation")]
+impl WordSplitter for Standard {
+    fn split<'w>(&self, word: &'w str) -> Vec<(&'w str, &'w str, &'w str)> {
+        // Find splits based on language dictionary.
+        let mut triples = Vec::new();
+        for n in self.hyphenate(word).breaks {
+            let (head, tail) = word.split_at(n);
+            let hyphen = if head.ends_with('-') { "" } else { "-" };
+            triples.push((head, hyphen, tail));
+        }
+        // Finally option is no split at all.
+        triples.push((word, "", ""));
+
+        triples
+    }
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/textwrap-0.11.0/tests/version-numbers.rs
@@ -0,0 +1,17 @@
+#[macro_use]
+extern crate version_sync;
+
+#[test]
+fn test_readme_deps() {
+    assert_markdown_deps_updated!("README.md");
+}
+
+#[test]
+fn test_readme_changelog() {
+    assert_contains_regex!("README.md", r"^### Version {version} — .* \d\d?.., 20\d\d$");
+}
+
+#[test]
+fn test_html_root_url() {
+    assert_html_root_url_updated!("src/lib.rs");
+}
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{"Cargo.toml":"051324cbce9a044f098c6577f57e054f7122f7134f473bbee65c52ee8014e066","LICENSE-APACHE":"8173d5c29b4f956d532781d2b86e4e30f83e6b7878dce18c919451d6ba707c90","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"637a32d6be7c7f2ea9fb5d2d51c4788a44a5cb100e653f8bab71a1d33ae429b1","src/lib.rs":"660ae0d68bb09c0281c75c526c0bfb2059821dee065e14f5cb31e695b4c81c2d"},"package":"f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"}
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/Cargo.toml
@@ -0,0 +1,31 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies
+#
+# If you believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+name = "vec_map"
+version = "0.8.2"
+authors = ["Alex Crichton <alex@alexcrichton.com>", "Jorge Aparicio <japaricious@gmail.com>", "Alexis Beingessner <a.beingessner@gmail.com>", "Brian Anderson <>", "tbu- <>", "Manish Goregaokar <>", "Aaron Turon <aturon@mozilla.com>", "Adolfo Ochagavía <>", "Niko Matsakis <>", "Steven Fackler <>", "Chase Southwood <csouth3@illinois.edu>", "Eduard Burtescu <>", "Florian Wilkens <>", "Félix Raimundo <>", "Tibor Benke <>", "Markus Siemens <markus@m-siemens.de>", "Josh Branchaud <jbranchaud@gmail.com>", "Huon Wilson <dbau.pp@gmail.com>", "Corey Farwell <coref@rwell.org>", "Aaron Liblong <>", "Nick Cameron <nrc@ncameron.org>", "Patrick Walton <pcwalton@mimiga.net>", "Felix S Klock II <>", "Andrew Paseltiner <apaseltiner@gmail.com>", "Sean McArthur <sean.monstar@gmail.com>", "Vadim Petrochenkov <>"]
+exclude = ["/.travis.yml", "/deploy-docs.sh"]
+description = "A simple map based on a vector for small integer keys"
+homepage = "https://github.com/contain-rs/vec-map"
+documentation = "https://contain-rs.github.io/vec-map/vec_map"
+readme = "README.md"
+keywords = ["data-structures", "collections", "vecmap", "vec_map", "contain-rs"]
+license = "MIT/Apache-2.0"
+repository = "https://github.com/contain-rs/vec-map"
+[dependencies.serde]
+version = "1.0"
+features = ["derive"]
+optional = true
+
+[features]
+eders = ["serde"]
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/LICENSE-APACHE
@@ -0,0 +1,201 @@
+                              Apache License
+                        Version 2.0, January 2004
+                     http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+   "License" shall mean the terms and conditions for use, reproduction,
+   and distribution as defined by Sections 1 through 9 of this document.
+
+   "Licensor" shall mean the copyright owner or entity authorized by
+   the copyright owner that is granting the License.
+
+   "Legal Entity" shall mean the union of the acting entity and all
+   other entities that control, are controlled by, or are under common
+   control with that entity. For the purposes of this definition,
+   "control" means (i) the power, direct or indirect, to cause the
+   direction or management of such entity, whether by contract or
+   otherwise, or (ii) ownership of fifty percent (50%) or more of the
+   outstanding shares, or (iii) beneficial ownership of such entity.
+
+   "You" (or "Your") shall mean an individual or Legal Entity
+   exercising permissions granted by this License.
+
+   "Source" form shall mean the preferred form for making modifications,
+   including but not limited to software source code, documentation
+   source, and configuration files.
+
+   "Object" form shall mean any form resulting from mechanical
+   transformation or translation of a Source form, including but
+   not limited to compiled object code, generated documentation,
+   and conversions to other media types.
+
+   "Work" shall mean the work of authorship, whether in Source or
+   Object form, made available under the License, as indicated by a
+   copyright notice that is included in or attached to the work
+   (an example is provided in the Appendix below).
+
+   "Derivative Works" shall mean any work, whether in Source or Object
+   form, that is based on (or derived from) the Work and for which the
+   editorial revisions, annotations, elaborations, or other modifications
+   represent, as a whole, an original work of authorship. For the purposes
+   of this License, Derivative Works shall not include works that remain
+   separable from, or merely link (or bind by name) to the interfaces of,
+   the Work and Derivative Works thereof.
+
+   "Contribution" shall mean any work of authorship, including
+   the original version of the Work and any modifications or additions
+   to that Work or Derivative Works thereof, that is intentionally
+   submitted to Licensor for inclusion in the Work by the copyright owner
+   or by an individual or Legal Entity authorized to submit on behalf of
+   the copyright owner. For the purposes of this definition, "submitted"
+   means any form of electronic, verbal, or written communication sent
+   to the Licensor or its representatives, including but not limited to
+   communication on electronic mailing lists, source code control systems,
+   and issue tracking systems that are managed by, or on behalf of, the
+   Licensor for the purpose of discussing and improving the Work, but
+   excluding communication that is conspicuously marked or otherwise
+   designated in writing by the copyright owner as "Not a Contribution."
+
+   "Contributor" shall mean Licensor and any individual or Legal Entity
+   on behalf of whom a Contribution has been received by Licensor and
+   subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   copyright license to reproduce, prepare Derivative Works of,
+   publicly display, publicly perform, sublicense, and distribute the
+   Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+   this License, each Contributor hereby grants to You a perpetual,
+   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+   (except as stated in this section) patent license to make, have made,
+   use, offer to sell, sell, import, and otherwise transfer the Work,
+   where such license applies only to those patent claims licensable
+   by such Contributor that are necessarily infringed by their
+   Contribution(s) alone or by combination of their Contribution(s)
+   with the Work to which such Contribution(s) was submitted. If You
+   institute patent litigation against any entity (including a
+   cross-claim or counterclaim in a lawsuit) alleging that the Work
+   or a Contribution incorporated within the Work constitutes direct
+   or contributory patent infringement, then any patent licenses
+   granted to You under this License for that Work shall terminate
+   as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+   Work or Derivative Works thereof in any medium, with or without
+   modifications, and in Source or Object form, provided that You
+   meet the following conditions:
+
+   (a) You must give any other recipients of the Work or
+       Derivative Works a copy of this License; and
+
+   (b) You must cause any modified files to carry prominent notices
+       stating that You changed the files; and
+
+   (c) You must retain, in the Source form of any Derivative Works
+       that You distribute, all copyright, patent, trademark, and
+       attribution notices from the Source form of the Work,
+       excluding those notices that do not pertain to any part of
+       the Derivative Works; and
+
+   (d) If the Work includes a "NOTICE" text file as part of its
+       distribution, then any Derivative Works that You distribute must
+       include a readable copy of the attribution notices contained
+       within such NOTICE file, excluding those notices that do not
+       pertain to any part of the Derivative Works, in at least one
+       of the following places: within a NOTICE text file distributed
+       as part of the Derivative Works; within the Source form or
+       documentation, if provided along with the Derivative Works; or,
+       within a display generated by the Derivative Works, if and
+       wherever such third-party notices normally appear. The contents
+       of the NOTICE file are for informational purposes only and
+       do not modify the License. You may add Your own attribution
+       notices within Derivative Works that You distribute, alongside
+       or as an addendum to the NOTICE text from the Work, provided
+       that such additional attribution notices cannot be construed
+       as modifying the License.
+
+   You may add Your own copyright statement to Your modifications and
+   may provide additional or different license terms and conditions
+   for use, reproduction, or distribution of Your modifications, or
+   for any such Derivative Works as a whole, provided Your use,
+   reproduction, and distribution of the Work otherwise complies with
+   the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+   any Contribution intentionally submitted for inclusion in the Work
+   by You to the Licensor shall be under the terms and conditions of
+   this License, without any additional terms or conditions.
+   Notwithstanding the above, nothing herein shall supersede or modify
+   the terms of any separate license agreement you may have executed
+   with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+   names, trademarks, service marks, or product names of the Licensor,
+   except as required for reasonable and customary use in describing the
+   origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+   agreed to in writing, Licensor provides the Work (and each
+   Contributor provides its Contributions) on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+   implied, including, without limitation, any warranties or conditions
+   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+   PARTICULAR PURPOSE. You are solely responsible for determining the
+   appropriateness of using or redistributing the Work and assume any
+   risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+   whether in tort (including negligence), contract, or otherwise,
+   unless required by applicable law (such as deliberate and grossly
+   negligent acts) or agreed to in writing, shall any Contributor be
+   liable to You for damages, including any direct, indirect, special,
+   incidental, or consequential damages of any character arising as a
+   result of this License or out of the use or inability to use the
+   Work (including but not limited to damages for loss of goodwill,
+   work stoppage, computer failure or malfunction, or any and all
+   other commercial damages or losses), even if such Contributor
+   has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+   the Work or Derivative Works thereof, You may choose to offer,
+   and charge a fee for, acceptance of support, warranty, indemnity,
+   or other liability obligations and/or rights consistent with this
+   License. However, in accepting such obligations, You may act only
+   on Your own behalf and on Your sole responsibility, not on behalf
+   of any other Contributor, and only if You agree to indemnify,
+   defend, and hold each Contributor harmless for any liability
+   incurred by, or claims asserted against, such Contributor by reason
+   of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+   To apply the Apache License to your work, attach the following
+   boilerplate notice, with the fields enclosed by brackets "[]"
+   replaced with your own identifying information. (Don't include
+   the brackets!)  The text should be enclosed in the appropriate
+   comment syntax for the file format. We also recommend that a
+   file or class name and description of purpose be included on the
+   same "printed page" as the copyright notice for easier
+   identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2015 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/README.md
@@ -0,0 +1,15 @@
+**WARNING: THIS PROJECT IS IN MAINTENANCE MODE, DUE TO INSUFFICIENT MAINTAINER RESOURCES**
+
+It works fine, but will generally no longer be improved.
+
+We are currently only accepting changes which:
+
+* keep this compiling with the latest versions of Rust or its dependencies.
+* have minimal review requirements, such as documentation changes (so not totally new APIs).
+
+------
+
+
+A simple map based on a vector for small integer keys.
+
+Documentation is available at https://contain-rs.github.io/vec-map/vec_map.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/vec_map/src/lib.rs
@@ -0,0 +1,1623 @@
+// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![deny(missing_docs)]
+
+//! A simple map based on a vector for small integer keys. Space requirements
+//! are O(highest integer key).
+
+// optional serde support
+#[cfg(feature = "serde")]
+#[macro_use]
+extern crate serde;
+
+use self::Entry::*;
+
+use std::cmp::{Ordering, max};
+use std::fmt;
+use std::hash::{Hash, Hasher};
+use std::iter::{Enumerate, FilterMap, FromIterator};
+use std::mem::{replace, swap};
+use std::ops::{Index, IndexMut};
+use std::slice;
+use std::vec;
+
+/// A map optimized for small integer keys.
+///
+/// # Examples
+///
+/// ```
+/// use vec_map::VecMap;
+///
+/// let mut months = VecMap::new();
+/// months.insert(1, "Jan");
+/// months.insert(2, "Feb");
+/// months.insert(3, "Mar");
+///
+/// if !months.contains_key(12) {
+///     println!("The end is near!");
+/// }
+///
+/// assert_eq!(months.get(1), Some(&"Jan"));
+///
+/// if let Some(value) = months.get_mut(3) {
+///     *value = "Venus";
+/// }
+///
+/// assert_eq!(months.get(3), Some(&"Venus"));
+///
+/// // Print out all months
+/// for (key, value) in &months {
+///     println!("month {} is {}", key, value);
+/// }
+///
+/// months.clear();
+/// assert!(months.is_empty());
+/// ```
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+pub struct VecMap<V> {
+    n: usize,
+    v: Vec<Option<V>>,
+}
+
+/// A view into a single entry in a map, which may either be vacant or occupied.
+pub enum Entry<'a, V: 'a> {
+    /// A vacant Entry
+    Vacant(VacantEntry<'a, V>),
+
+    /// An occupied Entry
+    Occupied(OccupiedEntry<'a, V>),
+}
+
+/// A vacant Entry.
+pub struct VacantEntry<'a, V: 'a> {
+    map: &'a mut VecMap<V>,
+    index: usize,
+}
+
+/// An occupied Entry.
+pub struct OccupiedEntry<'a, V: 'a> {
+    map: &'a mut VecMap<V>,
+    index: usize,
+}
+
+impl<V> Default for VecMap<V> {
+    #[inline]
+    fn default() -> Self { Self::new() }
+}
+
+impl<V: Hash> Hash for VecMap<V> {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        // In order to not traverse the `VecMap` twice, count the elements
+        // during iteration.
+        let mut count: usize = 0;
+        for elt in self {
+            elt.hash(state);
+            count += 1;
+        }
+        count.hash(state);
+    }
+}
+
+impl<V> VecMap<V> {
+    /// Creates an empty `VecMap`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let mut map: VecMap<&str> = VecMap::new();
+    /// ```
+    pub fn new() -> Self { VecMap { n: 0, v: vec![] } }
+
+    /// Creates an empty `VecMap` with space for at least `capacity`
+    /// elements before resizing.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
+    /// ```
+    pub fn with_capacity(capacity: usize) -> Self {
+        VecMap { n: 0, v: Vec::with_capacity(capacity) }
+    }
+
+    /// Returns the number of elements the `VecMap` can hold without
+    /// reallocating.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let map: VecMap<String> = VecMap::with_capacity(10);
+    /// assert!(map.capacity() >= 10);
+    /// ```
+    #[inline]
+    pub fn capacity(&self) -> usize {
+        self.v.capacity()
+    }
+
+    /// Reserves capacity for the given `VecMap` to contain `len` distinct keys.
+    /// In the case of `VecMap` this means reallocations will not occur as long
+    /// as all inserted keys are less than `len`.
+    ///
+    /// The collection may reserve more space to avoid frequent reallocations.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let mut map: VecMap<&str> = VecMap::new();
+    /// map.reserve_len(10);
+    /// assert!(map.capacity() >= 10);
+    /// ```
+    pub fn reserve_len(&mut self, len: usize) {
+        let cur_len = self.v.len();
+        if len >= cur_len {
+            self.v.reserve(len - cur_len);
+        }
+    }
+
+    /// Reserves the minimum capacity for the given `VecMap` to contain `len` distinct keys.
+    /// In the case of `VecMap` this means reallocations will not occur as long as all inserted
+    /// keys are less than `len`.
+    ///
+    /// Note that the allocator may give the collection more space than it requests.
+    /// Therefore capacity cannot be relied upon to be precisely minimal.  Prefer
+    /// `reserve_len` if future insertions are expected.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let mut map: VecMap<&str> = VecMap::new();
+    /// map.reserve_len_exact(10);
+    /// assert!(map.capacity() >= 10);
+    /// ```
+    pub fn reserve_len_exact(&mut self, len: usize) {
+        let cur_len = self.v.len();
+        if len >= cur_len {
+            self.v.reserve_exact(len - cur_len);
+        }
+    }
+
+    /// Trims the `VecMap` of any excess capacity.
+    ///
+    /// The collection may reserve more space to avoid frequent reallocations.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
+    /// map.shrink_to_fit();
+    /// assert_eq!(map.capacity(), 0);
+    /// ```
+    pub fn shrink_to_fit(&mut self) {
+        // strip off trailing `None`s
+        if let Some(idx) = self.v.iter().rposition(Option::is_some) {
+            self.v.truncate(idx + 1);
+        } else {
+            self.v.clear();
+        }
+
+        self.v.shrink_to_fit()
+    }
+
+    /// Returns an iterator visiting all keys in ascending order of the keys.
+    /// The iterator's element type is `usize`.
+    pub fn keys(&self) -> Keys<V> {
+        Keys { iter: self.iter() }
+    }
+
+    /// Returns an iterator visiting all values in ascending order of the keys.
+    /// The iterator's element type is `&'r V`.
+    pub fn values(&self) -> Values<V> {
+        Values { iter: self.iter() }
+    }
+
+    /// Returns an iterator visiting all values in ascending order of the keys.
+    /// The iterator's element type is `&'r mut V`.
+    pub fn values_mut(&mut self) -> ValuesMut<V> {
+        ValuesMut { iter_mut: self.iter_mut() }
+    }
+
+    /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
+    /// The iterator's element type is `(usize, &'r V)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(3, "c");
+    /// map.insert(2, "b");
+    ///
+    /// // Print `1: a` then `2: b` then `3: c`
+    /// for (key, value) in map.iter() {
+    ///     println!("{}: {}", key, value);
+    /// }
+    /// ```
+    pub fn iter(&self) -> Iter<V> {
+        Iter {
+            front: 0,
+            back: self.v.len(),
+            n: self.n,
+            yielded: 0,
+            iter: self.v.iter()
+        }
+    }
+
+    /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
+    /// with mutable references to the values.
+    /// The iterator's element type is `(usize, &'r mut V)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(2, "b");
+    /// map.insert(3, "c");
+    ///
+    /// for (key, value) in map.iter_mut() {
+    ///     *value = "x";
+    /// }
+    ///
+    /// for (key, value) in &map {
+    ///     assert_eq!(value, &"x");
+    /// }
+    /// ```
+    pub fn iter_mut(&mut self) -> IterMut<V> {
+        IterMut {
+            front: 0,
+            back: self.v.len(),
+            n: self.n,
+            yielded: 0,
+            iter: self.v.iter_mut()
+        }
+    }
+
+    /// Moves all elements from `other` into the map while overwriting existing keys.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut a = VecMap::new();
+    /// a.insert(1, "a");
+    /// a.insert(2, "b");
+    ///
+    /// let mut b = VecMap::new();
+    /// b.insert(3, "c");
+    /// b.insert(4, "d");
+    ///
+    /// a.append(&mut b);
+    ///
+    /// assert_eq!(a.len(), 4);
+    /// assert_eq!(b.len(), 0);
+    /// assert_eq!(a[1], "a");
+    /// assert_eq!(a[2], "b");
+    /// assert_eq!(a[3], "c");
+    /// assert_eq!(a[4], "d");
+    /// ```
+    pub fn append(&mut self, other: &mut Self) {
+        self.extend(other.drain());
+    }
+
+    /// Splits the collection into two at the given key.
+    ///
+    /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
+    /// and the returned `Self` contains elements `[at, max_key)`.
+    ///
+    /// Note that the capacity of `self` does not change.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut a = VecMap::new();
+    /// a.insert(1, "a");
+    /// a.insert(2, "b");
+    /// a.insert(3, "c");
+    /// a.insert(4, "d");
+    ///
+    /// let b = a.split_off(3);
+    ///
+    /// assert_eq!(a[1], "a");
+    /// assert_eq!(a[2], "b");
+    ///
+    /// assert_eq!(b[3], "c");
+    /// assert_eq!(b[4], "d");
+    /// ```
+    pub fn split_off(&mut self, at: usize) -> Self {
+        let mut other = VecMap::new();
+
+        if at == 0 {
+            // Move all elements to other
+            // The swap will also fix .n
+            swap(self, &mut other);
+            return other
+        } else if at >= self.v.len() {
+            // No elements to copy
+            return other;
+        }
+
+        // Look up the index of the first non-None item
+        let first_index = self.v.iter().position(|el| el.is_some());
+        let start_index = match first_index {
+            Some(index) => max(at, index),
+            None => {
+                // self has no elements
+                return other;
+            }
+        };
+
+        // Fill the new VecMap with `None`s until `start_index`
+        other.v.extend((0..start_index).map(|_| None));
+
+        // Move elements beginning with `start_index` from `self` into `other`
+        let mut taken = 0;
+        other.v.extend(self.v[start_index..].iter_mut().map(|el| {
+            let el = el.take();
+            if el.is_some() {
+                taken += 1;
+            }
+            el
+        }));
+        other.n = taken;
+        self.n -= taken;
+
+        other
+    }
+
+    /// Returns an iterator visiting all key-value pairs in ascending order of
+    /// the keys, emptying (but not consuming) the original `VecMap`.
+    /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(3, "c");
+    /// map.insert(2, "b");
+    ///
+    /// let vec: Vec<(usize, &str)> = map.drain().collect();
+    ///
+    /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
+    /// ```
+    pub fn drain(&mut self) -> Drain<V> {
+        fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
+            v.map(|v| (i, v))
+        }
+        let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
+
+        self.n = 0;
+        Drain { iter: self.v.drain(..).enumerate().filter_map(filter) }
+    }
+
+    /// Returns the number of elements in the map.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut a = VecMap::new();
+    /// assert_eq!(a.len(), 0);
+    /// a.insert(1, "a");
+    /// assert_eq!(a.len(), 1);
+    /// ```
+    pub fn len(&self) -> usize {
+        self.n
+    }
+
+    /// Returns true if the map contains no elements.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut a = VecMap::new();
+    /// assert!(a.is_empty());
+    /// a.insert(1, "a");
+    /// assert!(!a.is_empty());
+    /// ```
+    pub fn is_empty(&self) -> bool {
+        self.n == 0
+    }
+
+    /// Clears the map, removing all key-value pairs.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut a = VecMap::new();
+    /// a.insert(1, "a");
+    /// a.clear();
+    /// assert!(a.is_empty());
+    /// ```
+    pub fn clear(&mut self) { self.n = 0; self.v.clear() }
+
+    /// Returns a reference to the value corresponding to the key.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// assert_eq!(map.get(1), Some(&"a"));
+    /// assert_eq!(map.get(2), None);
+    /// ```
+    pub fn get(&self, key: usize) -> Option<&V> {
+        if key < self.v.len() {
+            self.v[key].as_ref()
+        } else {
+            None
+        }
+    }
+
+    /// Returns true if the map contains a value for the specified key.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// assert_eq!(map.contains_key(1), true);
+    /// assert_eq!(map.contains_key(2), false);
+    /// ```
+    #[inline]
+    pub fn contains_key(&self, key: usize) -> bool {
+        self.get(key).is_some()
+    }
+
+    /// Returns a mutable reference to the value corresponding to the key.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// if let Some(x) = map.get_mut(1) {
+    ///     *x = "b";
+    /// }
+    /// assert_eq!(map[1], "b");
+    /// ```
+    pub fn get_mut(&mut self, key: usize) -> Option<&mut V> {
+        if key < self.v.len() {
+            self.v[key].as_mut()
+        } else {
+            None
+        }
+    }
+
+    /// Inserts a key-value pair into the map. If the key already had a value
+    /// present in the map, that value is returned. Otherwise, `None` is returned.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// assert_eq!(map.insert(37, "a"), None);
+    /// assert_eq!(map.is_empty(), false);
+    ///
+    /// map.insert(37, "b");
+    /// assert_eq!(map.insert(37, "c"), Some("b"));
+    /// assert_eq!(map[37], "c");
+    /// ```
+    pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
+        let len = self.v.len();
+        if len <= key {
+            self.v.extend((0..key - len + 1).map(|_| None));
+        }
+        let was = replace(&mut self.v[key], Some(value));
+        if was.is_none() {
+            self.n += 1;
+        }
+        was
+    }
+
+    /// Removes a key from the map, returning the value at the key if the key
+    /// was previously in the map.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// assert_eq!(map.remove(1), Some("a"));
+    /// assert_eq!(map.remove(1), None);
+    /// ```
+    pub fn remove(&mut self, key: usize) -> Option<V> {
+        if key >= self.v.len() {
+            return None;
+        }
+        let result = &mut self.v[key];
+        let was = result.take();
+        if was.is_some() {
+            self.n -= 1;
+        }
+        was
+    }
+
+    /// Gets the given key's corresponding entry in the map for in-place manipulation.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut count: VecMap<u32> = VecMap::new();
+    ///
+    /// // count the number of occurrences of numbers in the vec
+    /// for x in vec![1, 2, 1, 2, 3, 4, 1, 2, 4] {
+    ///     *count.entry(x).or_insert(0) += 1;
+    /// }
+    ///
+    /// assert_eq!(count[1], 3);
+    /// ```
+    pub fn entry(&mut self, key: usize) -> Entry<V> {
+        // FIXME(Gankro): this is basically the dumbest implementation of
+        // entry possible, because weird non-lexical borrows issues make it
+        // completely insane to do any other way. That said, Entry is a border-line
+        // useless construct on VecMap, so it's hardly a big loss.
+        if self.contains_key(key) {
+            Occupied(OccupiedEntry {
+                map: self,
+                index: key,
+            })
+        } else {
+            Vacant(VacantEntry {
+                map: self,
+                index: key,
+            })
+        }
+    }
+
+    /// Retains only the elements specified by the predicate.
+    ///
+    /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map: VecMap<usize> = (0..8).map(|x|(x, x*10)).collect();
+    /// map.retain(|k, _| k % 2 == 0);
+    /// assert_eq!(map.len(), 4);
+    /// ```
+    pub fn retain<F>(&mut self, mut f: F)
+        where F: FnMut(usize, &mut V) -> bool
+    {
+        for (i, e) in self.v.iter_mut().enumerate() {
+            let remove = match *e {
+                Some(ref mut value) => !f(i, value),
+                None => false,
+            };
+            if remove {
+                *e = None;
+                self.n -= 1;
+            }
+        }
+    }
+}
+
+impl<'a, V> Entry<'a, V> {
+    /// Ensures a value is in the entry by inserting the default if empty, and
+    /// returns a mutable reference to the value in the entry.
+    pub fn or_insert(self, default: V) -> &'a mut V {
+        match self {
+            Occupied(entry) => entry.into_mut(),
+            Vacant(entry) => entry.insert(default),
+        }
+    }
+
+    /// Ensures a value is in the entry by inserting the result of the default
+    /// function if empty, and returns a mutable reference to the value in the
+    /// entry.
+    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
+        match self {
+            Occupied(entry) => entry.into_mut(),
+            Vacant(entry) => entry.insert(default()),
+        }
+    }
+}
+
+impl<'a, V> VacantEntry<'a, V> {
+    /// Sets the value of the entry with the VacantEntry's key,
+    /// and returns a mutable reference to it.
+    pub fn insert(self, value: V) -> &'a mut V {
+        let index = self.index;
+        self.map.insert(index, value);
+        &mut self.map[index]
+    }
+}
+
+impl<'a, V> OccupiedEntry<'a, V> {
+    /// Gets a reference to the value in the entry.
+    pub fn get(&self) -> &V {
+        let index = self.index;
+        &self.map[index]
+    }
+
+    /// Gets a mutable reference to the value in the entry.
+    pub fn get_mut(&mut self) -> &mut V {
+        let index = self.index;
+        &mut self.map[index]
+    }
+
+    /// Converts the entry into a mutable reference to its value.
+    pub fn into_mut(self) -> &'a mut V {
+        let index = self.index;
+        &mut self.map[index]
+    }
+
+    /// Sets the value of the entry with the OccupiedEntry's key,
+    /// and returns the entry's old value.
+    pub fn insert(&mut self, value: V) -> V {
+        let index = self.index;
+        self.map.insert(index, value).unwrap()
+    }
+
+    /// Takes the value of the entry out of the map, and returns it.
+    pub fn remove(self) -> V {
+        let index = self.index;
+        self.map.remove(index).unwrap()
+    }
+}
+
+impl<V: Clone> Clone for VecMap<V> {
+    #[inline]
+    fn clone(&self) -> Self {
+        VecMap { n: self.n, v: self.v.clone() }
+    }
+
+    #[inline]
+    fn clone_from(&mut self, source: &Self) {
+        self.v.clone_from(&source.v);
+        self.n = source.n;
+    }
+}
+
+impl<V: PartialEq> PartialEq for VecMap<V> {
+    fn eq(&self, other: &Self) -> bool {
+        self.n == other.n && self.iter().eq(other.iter())
+    }
+}
+
+impl<V: Eq> Eq for VecMap<V> {}
+
+impl<V: PartialOrd> PartialOrd for VecMap<V> {
+    #[inline]
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        self.iter().partial_cmp(other.iter())
+    }
+}
+
+impl<V: Ord> Ord for VecMap<V> {
+    #[inline]
+    fn cmp(&self, other: &Self) -> Ordering {
+        self.iter().cmp(other.iter())
+    }
+}
+
+impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        f.debug_map().entries(self).finish()
+    }
+}
+
+impl<V> FromIterator<(usize, V)> for VecMap<V> {
+    fn from_iter<I: IntoIterator<Item = (usize, V)>>(iter: I) -> Self {
+        let mut map = Self::new();
+        map.extend(iter);
+        map
+    }
+}
+
+impl<T> IntoIterator for VecMap<T> {
+    type Item = (usize, T);
+    type IntoIter = IntoIter<T>;
+
+    /// Returns an iterator visiting all key-value pairs in ascending order of
+    /// the keys, consuming the original `VecMap`.
+    /// The iterator's element type is `(usize, &'r V)`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use vec_map::VecMap;
+    ///
+    /// let mut map = VecMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(3, "c");
+    /// map.insert(2, "b");
+    ///
+    /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
+    ///
+    /// assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
+    /// ```
+    fn into_iter(self) -> IntoIter<T> {
+        IntoIter {
+            n: self.n,
+            yielded: 0,
+            iter: self.v.into_iter().enumerate()
+        }
+    }
+}
+
+impl<'a, T> IntoIterator for &'a VecMap<T> {
+    type Item = (usize, &'a T);
+    type IntoIter = Iter<'a, T>;
+
+    fn into_iter(self) -> Iter<'a, T> {
+        self.iter()
+    }
+}
+
+impl<'a, T> IntoIterator for &'a mut VecMap<T> {
+    type Item = (usize, &'a mut T);
+    type IntoIter = IterMut<'a, T>;
+
+    fn into_iter(self) -> IterMut<'a, T> {
+        self.iter_mut()
+    }
+}
+
+impl<V> Extend<(usize, V)> for VecMap<V> {
+    fn extend<I: IntoIterator<Item = (usize, V)>>(&mut self, iter: I) {
+        for (k, v) in iter {
+            self.insert(k, v);
+        }
+    }
+}
+
+impl<'a, V: Copy> Extend<(usize, &'a V)> for VecMap<V> {
+    fn extend<I: IntoIterator<Item = (usize, &'a V)>>(&mut self, iter: I) {
+        self.extend(iter.into_iter().map(|(key, &value)| (key, value)));
+    }
+}
+
+impl<V> Index<usize> for VecMap<V> {
+    type Output = V;
+
+    #[inline]
+    fn index(&self, i: usize) -> &V {
+        self.get(i).expect("key not present")
+    }
+}
+
+impl<'a, V> Index<&'a usize> for VecMap<V> {
+    type Output = V;
+
+    #[inline]
+    fn index(&self, i: &usize) -> &V {
+        self.get(*i).expect("key not present")
+    }
+}
+
+impl<V> IndexMut<usize> for VecMap<V> {
+    #[inline]
+    fn index_mut(&mut self, i: usize) -> &mut V {
+        self.get_mut(i).expect("key not present")
+    }
+}
+
+impl<'a, V> IndexMut<&'a usize> for VecMap<V> {
+    #[inline]
+    fn index_mut(&mut self, i: &usize) -> &mut V {
+        self.get_mut(*i).expect("key not present")
+    }
+}
+
+macro_rules! iterator {
+    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
+        impl<'a, V> Iterator for $name<'a, V> {
+            type Item = $elem;
+
+            #[inline]
+            fn next(&mut self) -> Option<$elem> {
+                while self.front < self.back {
+                    if let Some(elem) = self.iter.next() {
+                        if let Some(x) = elem$(. $getter ())+ {
+                            let index = self.front;
+                            self.front += 1;
+                            self.yielded += 1;
+                            return Some((index, x));
+                        }
+                    }
+                    self.front += 1;
+                }
+                None
+            }
+
+            #[inline]
+            fn size_hint(&self) -> (usize, Option<usize>) {
+                (self.n - self.yielded, Some(self.n - self.yielded))
+            }
+        }
+    }
+}
+
+macro_rules! double_ended_iterator {
+    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
+        impl<'a, V> DoubleEndedIterator for $name<'a, V> {
+            #[inline]
+            fn next_back(&mut self) -> Option<$elem> {
+                while self.front < self.back {
+                    if let Some(elem) = self.iter.next_back() {
+                        if let Some(x) = elem$(. $getter ())+ {
+                            self.back -= 1;
+                            return Some((self.back, x));
+                        }
+                    }
+                    self.back -= 1;
+                }
+                None
+            }
+        }
+    }
+}
+
+/// An iterator over the key-value pairs of a map.
+pub struct Iter<'a, V: 'a> {
+    front: usize,
+    back: usize,
+    n: usize,
+    yielded: usize,
+    iter: slice::Iter<'a, Option<V>>
+}
+
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+impl<'a, V> Clone for Iter<'a, V> {
+    fn clone(&self) -> Iter<'a, V> {
+        Iter {
+            front: self.front,
+            back: self.back,
+            n: self.n,
+            yielded: self.yielded,
+            iter: self.iter.clone()
+        }
+    }
+}
+
+iterator! { impl Iter -> (usize, &'a V), as_ref }
+impl<'a, V> ExactSizeIterator for Iter<'a, V> {}
+double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
+
+/// An iterator over the key-value pairs of a map, with the
+/// values being mutable.
+pub struct IterMut<'a, V: 'a> {
+    front: usize,
+    back: usize,
+    n: usize,
+    yielded: usize,
+    iter: slice::IterMut<'a, Option<V>>
+}
+
+iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
+impl<'a, V> ExactSizeIterator for IterMut<'a, V> {}
+double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
+
+/// An iterator over the keys of a map.
+pub struct Keys<'a, V: 'a> {
+    iter: Iter<'a, V>,
+}
+
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+impl<'a, V> Clone for Keys<'a, V> {
+    fn clone(&self) -> Keys<'a, V> {
+        Keys {
+            iter: self.iter.clone()
+        }
+    }
+}
+
+/// An iterator over the values of a map.
+pub struct Values<'a, V: 'a> {
+    iter: Iter<'a, V>,
+}
+
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+impl<'a, V> Clone for Values<'a, V> {
+    fn clone(&self) -> Values<'a, V> {
+        Values {
+            iter: self.iter.clone()
+        }
+    }
+}
+
+/// An iterator over the values of a map.
+pub struct ValuesMut<'a, V: 'a> {
+    iter_mut: IterMut<'a, V>,
+}
+
+/// A consuming iterator over the key-value pairs of a map.
+pub struct IntoIter<V> {
+    n: usize,
+    yielded: usize,
+    iter: Enumerate<vec::IntoIter<Option<V>>>,
+}
+
+/// A draining iterator over the key-value pairs of a map.
+pub struct Drain<'a, V: 'a> {
+    iter: FilterMap<
+    Enumerate<vec::Drain<'a, Option<V>>>,
+    fn((usize, Option<V>)) -> Option<(usize, V)>>
+}
+
+impl<'a, V> Iterator for Drain<'a, V> {
+    type Item = (usize, V);
+
+    fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+}
+
+impl<'a, V> ExactSizeIterator for Drain<'a, V> {}
+
+impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
+    fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
+}
+
+impl<'a, V> Iterator for Keys<'a, V> {
+    type Item = usize;
+
+    fn next(&mut self) -> Option<usize> { self.iter.next().map(|e| e.0) }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+}
+
+impl<'a, V> ExactSizeIterator for Keys<'a, V> {}
+
+impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
+    fn next_back(&mut self) -> Option<usize> { self.iter.next_back().map(|e| e.0) }
+}
+
+impl<'a, V> Iterator for Values<'a, V> {
+    type Item = &'a V;
+
+    fn next(&mut self) -> Option<(&'a V)> { self.iter.next().map(|e| e.1) }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+}
+
+impl<'a, V> ExactSizeIterator for Values<'a, V> {}
+
+impl<'a, V> DoubleEndedIterator for Values<'a, V> {
+    fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back().map(|e| e.1) }
+}
+
+impl<'a, V> Iterator for ValuesMut<'a, V> {
+    type Item = &'a mut V;
+
+    fn next(&mut self) -> Option<(&'a mut V)> { self.iter_mut.next().map(|e| e.1) }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter_mut.size_hint() }
+}
+
+impl<'a, V> ExactSizeIterator for ValuesMut<'a, V> {}
+
+impl<'a, V> DoubleEndedIterator for ValuesMut<'a, V> {
+    fn next_back(&mut self) -> Option<&'a mut V> { self.iter_mut.next_back().map(|e| e.1) }
+}
+
+impl<V> Iterator for IntoIter<V> {
+    type Item = (usize, V);
+
+    fn next(&mut self) -> Option<(usize, V)> {
+        loop {
+            match self.iter.next() {
+                None => return None,
+                Some((i, Some(value))) => {
+                    self.yielded += 1;
+                    return Some((i, value))
+                },
+                _ => {}
+            }
+        }
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        (self.n - self.yielded, Some(self.n - self.yielded))
+    }
+}
+
+impl<V> ExactSizeIterator for IntoIter<V> {}
+
+impl<V> DoubleEndedIterator for IntoIter<V> {
+    fn next_back(&mut self) -> Option<(usize, V)> {
+        loop {
+            match self.iter.next_back() {
+                None => return None,
+                Some((i, Some(value))) => return Some((i, value)),
+                _ => {}
+            }
+        }
+    }
+}
+
+#[allow(dead_code)]
+fn assert_properties() {
+    fn vec_map_covariant<'a, T>(map: VecMap<&'static T>) -> VecMap<&'a T> { map }
+
+    fn into_iter_covariant<'a, T>(iter: IntoIter<&'static T>) -> IntoIter<&'a T> { iter }
+
+    fn iter_covariant<'i, 'a, T>(iter: Iter<'i, &'static T>) -> Iter<'i, &'a T> { iter }
+
+    fn keys_covariant<'i, 'a, T>(iter: Keys<'i, &'static T>) -> Keys<'i, &'a T> { iter }
+
+    fn values_covariant<'i, 'a, T>(iter: Values<'i, &'static T>) -> Values<'i, &'a T> { iter }
+}
+
+#[cfg(test)]
+mod test {
+    use super::VecMap;
+    use super::Entry::{Occupied, Vacant};
+    use std::hash::{Hash, Hasher};
+    use std::collections::hash_map::DefaultHasher;
+
+    #[test]
+    fn test_get_mut() {
+        let mut m = VecMap::new();
+        assert!(m.insert(1, 12).is_none());
+        assert!(m.insert(2, 8).is_none());
+        assert!(m.insert(5, 14).is_none());
+        let new = 100;
+        match m.get_mut(5) {
+            None => panic!(), Some(x) => *x = new
+        }
+        assert_eq!(m.get(5), Some(&new));
+    }
+
+    #[test]
+    fn test_len() {
+        let mut map = VecMap::new();
+        assert_eq!(map.len(), 0);
+        assert!(map.is_empty());
+        assert!(map.insert(5, 20).is_none());
+        assert_eq!(map.len(), 1);
+        assert!(!map.is_empty());
+        assert!(map.insert(11, 12).is_none());
+        assert_eq!(map.len(), 2);
+        assert!(!map.is_empty());
+        assert!(map.insert(14, 22).is_none());
+        assert_eq!(map.len(), 3);
+        assert!(!map.is_empty());
+    }
+
+    #[test]
+    fn test_clear() {
+        let mut map = VecMap::new();
+        assert!(map.insert(5, 20).is_none());
+        assert!(map.insert(11, 12).is_none());
+        assert!(map.insert(14, 22).is_none());
+        map.clear();
+        assert!(map.is_empty());
+        assert!(map.get(5).is_none());
+        assert!(map.get(11).is_none());
+        assert!(map.get(14).is_none());
+    }
+
+    #[test]
+    fn test_insert() {
+        let mut m = VecMap::new();
+        assert_eq!(m.insert(1, 2), None);
+        assert_eq!(m.insert(1, 3), Some(2));
+        assert_eq!(m.insert(1, 4), Some(3));
+    }
+
+    #[test]
+    fn test_remove() {
+        let mut m = VecMap::new();
+        m.insert(1, 2);
+        assert_eq!(m.remove(1), Some(2));
+        assert_eq!(m.remove(1), None);
+    }
+
+    #[test]
+    fn test_keys() {
+        let mut map = VecMap::new();
+        map.insert(1, 'a');
+        map.insert(2, 'b');
+        map.insert(3, 'c');
+        let keys: Vec<_> = map.keys().collect();
+        assert_eq!(keys.len(), 3);
+        assert!(keys.contains(&1));
+        assert!(keys.contains(&2));
+        assert!(keys.contains(&3));
+    }
+
+    #[test]
+    fn test_values() {
+        let mut map = VecMap::new();
+        map.insert(1, 'a');
+        map.insert(2, 'b');
+        map.insert(3, 'c');
+        let values: Vec<_> = map.values().cloned().collect();
+        assert_eq!(values.len(), 3);
+        assert!(values.contains(&'a'));
+        assert!(values.contains(&'b'));
+        assert!(values.contains(&'c'));
+    }
+
+    #[test]
+    fn test_iterator() {
+        let mut m = VecMap::new();
+
+        assert!(m.insert(0, 1).is_none());
+        assert!(m.insert(1, 2).is_none());
+        assert!(m.insert(3, 5).is_none());
+        assert!(m.insert(6, 10).is_none());
+        assert!(m.insert(10, 11).is_none());
+
+        let mut it = m.iter();
+        assert_eq!(it.size_hint(), (5, Some(5)));
+        assert_eq!(it.next().unwrap(), (0, &1));
+        assert_eq!(it.size_hint(), (4, Some(4)));
+        assert_eq!(it.next().unwrap(), (1, &2));
+        assert_eq!(it.size_hint(), (3, Some(3)));
+        assert_eq!(it.next().unwrap(), (3, &5));
+        assert_eq!(it.size_hint(), (2, Some(2)));
+        assert_eq!(it.next().unwrap(), (6, &10));
+        assert_eq!(it.size_hint(), (1, Some(1)));
+        assert_eq!(it.next().unwrap(), (10, &11));
+        assert_eq!(it.size_hint(), (0, Some(0)));
+        assert!(it.next().is_none());
+    }
+
+    #[test]
+    fn test_iterator_size_hints() {
+        let mut m = VecMap::new();
+
+        assert!(m.insert(0, 1).is_none());
+        assert!(m.insert(1, 2).is_none());
+        assert!(m.insert(3, 5).is_none());
+        assert!(m.insert(6, 10).is_none());
+        assert!(m.insert(10, 11).is_none());
+
+        assert_eq!(m.iter().size_hint(), (5, Some(5)));
+        assert_eq!(m.iter().rev().size_hint(), (5, Some(5)));
+        assert_eq!(m.iter_mut().size_hint(), (5, Some(5)));
+        assert_eq!(m.iter_mut().rev().size_hint(), (5, Some(5)));
+    }
+
+    #[test]
+    fn test_mut_iterator() {
+        let mut m = VecMap::new();
+
+        assert!(m.insert(0, 1).is_none());
+        assert!(m.insert(1, 2).is_none());
+        assert!(m.insert(3, 5).is_none());
+        assert!(m.insert(6, 10).is_none());
+        assert!(m.insert(10, 11).is_none());
+
+        for (k, v) in &mut m {
+            *v += k as isize;
+        }
+
+        let mut it = m.iter();
+        assert_eq!(it.next().unwrap(), (0, &1));
+        assert_eq!(it.next().unwrap(), (1, &3));
+        assert_eq!(it.next().unwrap(), (3, &8));
+        assert_eq!(it.next().unwrap(), (6, &16));
+        assert_eq!(it.next().unwrap(), (10, &21));
+        assert!(it.next().is_none());
+    }
+
+    #[test]
+    fn test_rev_iterator() {
+        let mut m = VecMap::new();
+
+        assert!(m.insert(0, 1).is_none());
+        assert!(m.insert(1, 2).is_none());
+        assert!(m.insert(3, 5).is_none());
+        assert!(m.insert(6, 10).is_none());
+        assert!(m.insert(10, 11).is_none());
+
+        let mut it = m.iter().rev();
+        assert_eq!(it.next().unwrap(), (10, &11));
+        assert_eq!(it.next().unwrap(), (6, &10));
+        assert_eq!(it.next().unwrap(), (3, &5));
+        assert_eq!(it.next().unwrap(), (1, &2));
+        assert_eq!(it.next().unwrap(), (0, &1));
+        assert!(it.next().is_none());
+    }
+
+    #[test]
+    fn test_mut_rev_iterator() {
+        let mut m = VecMap::new();
+
+        assert!(m.insert(0, 1).is_none());
+        assert!(m.insert(1, 2).is_none());
+        assert!(m.insert(3, 5).is_none());
+        assert!(m.insert(6, 10).is_none());
+        assert!(m.insert(10, 11).is_none());
+
+        for (k, v) in m.iter_mut().rev() {
+            *v += k as isize;
+        }
+
+        let mut it = m.iter();
+        assert_eq!(it.next().unwrap(), (0, &1));
+        assert_eq!(it.next().unwrap(), (1, &3));
+        assert_eq!(it.next().unwrap(), (3, &8));
+        assert_eq!(it.next().unwrap(), (6, &16));
+        assert_eq!(it.next().unwrap(), (10, &21));
+        assert!(it.next().is_none());
+    }
+
+    #[test]
+    fn test_move_iter() {
+        let mut m: VecMap<Box<_>> = VecMap::new();
+        m.insert(1, Box::new(2));
+        let mut called = false;
+        for (k, v) in m {
+            assert!(!called);
+            called = true;
+            assert_eq!(k, 1);
+            assert_eq!(v, Box::new(2));
+        }
+        assert!(called);
+    }
+
+    #[test]
+    fn test_drain_iterator() {
+        let mut map = VecMap::new();
+        map.insert(1, "a");
+        map.insert(3, "c");
+        map.insert(2, "b");
+
+        let vec: Vec<_> = map.drain().collect();
+
+        assert_eq!(vec, [(1, "a"), (2, "b"), (3, "c")]);
+        assert_eq!(map.len(), 0);
+    }
+
+    #[test]
+    fn test_append() {
+        let mut a = VecMap::new();
+        a.insert(1, "a");
+        a.insert(2, "b");
+        a.insert(3, "c");
+
+        let mut b = VecMap::new();
+        b.insert(3, "d");  // Overwrite element from a
+        b.insert(4, "e");
+        b.insert(5, "f");
+
+        a.append(&mut b);
+
+        assert_eq!(a.len(), 5);
+        assert_eq!(b.len(), 0);
+        // Capacity shouldn't change for possible reuse
+        assert!(b.capacity() >= 4);
+
+        assert_eq!(a[1], "a");
+        assert_eq!(a[2], "b");
+        assert_eq!(a[3], "d");
+        assert_eq!(a[4], "e");
+        assert_eq!(a[5], "f");
+    }
+
+    #[test]
+    fn test_split_off() {
+        // Split within the key range
+        let mut a = VecMap::new();
+        a.insert(1, "a");
+        a.insert(2, "b");
+        a.insert(3, "c");
+        a.insert(4, "d");
+
+        let b = a.split_off(3);
+
+        assert_eq!(a.len(), 2);
+        assert_eq!(b.len(), 2);
+
+        assert_eq!(a[1], "a");
+        assert_eq!(a[2], "b");
+
+        assert_eq!(b[3], "c");
+        assert_eq!(b[4], "d");
+
+        // Split at 0
+        a.clear();
+        a.insert(1, "a");
+        a.insert(2, "b");
+        a.insert(3, "c");
+        a.insert(4, "d");
+
+        let b = a.split_off(0);
+
+        assert_eq!(a.len(), 0);
+        assert_eq!(b.len(), 4);
+        assert_eq!(b[1], "a");
+        assert_eq!(b[2], "b");
+        assert_eq!(b[3], "c");
+        assert_eq!(b[4], "d");
+
+        // Split behind max_key
+        a.clear();
+        a.insert(1, "a");
+        a.insert(2, "b");
+        a.insert(3, "c");
+        a.insert(4, "d");
+
+        let b = a.split_off(5);
+
+        assert_eq!(a.len(), 4);
+        assert_eq!(b.len(), 0);
+        assert_eq!(a[1], "a");
+        assert_eq!(a[2], "b");
+        assert_eq!(a[3], "c");
+        assert_eq!(a[4], "d");
+    }
+
+    #[test]
+    fn test_show() {
+        let mut map = VecMap::new();
+        let empty = VecMap::<i32>::new();
+
+        map.insert(1, 2);
+        map.insert(3, 4);
+
+        let map_str = format!("{:?}", map);
+        assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
+        assert_eq!(format!("{:?}", empty), "{}");
+    }
+
+    #[test]
+    fn test_clone() {
+        let mut a = VecMap::new();
+
+        a.insert(1, 'x');
+        a.insert(4, 'y');
+        a.insert(6, 'z');
+
+        assert_eq!(a.clone().iter().collect::<Vec<_>>(), [(1, &'x'), (4, &'y'), (6, &'z')]);
+    }
+
+    #[test]
+    fn test_eq() {
+        let mut a = VecMap::new();
+        let mut b = VecMap::new();
+
+        assert!(a == b);
+        assert!(a.insert(0, 5).is_none());
+        assert!(a != b);
+        assert!(b.insert(0, 4).is_none());
+        assert!(a != b);
+        assert!(a.insert(5, 19).is_none());
+        assert!(a != b);
+        assert!(!b.insert(0, 5).is_none());
+        assert!(a != b);
+        assert!(b.insert(5, 19).is_none());
+        assert!(a == b);
+
+        a = VecMap::new();
+        b = VecMap::with_capacity(1);
+        assert!(a == b);
+    }
+
+    #[test]
+    fn test_lt() {
+        let mut a = VecMap::new();
+        let mut b = VecMap::new();
+
+        assert!(!(a < b) && !(b < a));
+        assert!(b.insert(2, 5).is_none());
+        assert!(a < b);
+        assert!(a.insert(2, 7).is_none());
+        assert!(!(a < b) && b < a);
+        assert!(b.insert(1, 0).is_none());
+        assert!(b < a);
+        assert!(a.insert(0, 6).is_none());
+        assert!(a < b);
+        assert!(a.insert(6, 2).is_none());
+        assert!(a < b && !(b < a));
+    }
+
+    #[test]
+    fn test_ord() {
+        let mut a = VecMap::new();
+        let mut b = VecMap::new();
+
+        assert!(a <= b && a >= b);
+        assert!(a.insert(1, 1).is_none());
+        assert!(a > b && a >= b);
+        assert!(b < a && b <= a);
+        assert!(b.insert(2, 2).is_none());
+        assert!(b > a && b >= a);
+        assert!(a < b && a <= b);
+    }
+
+    #[test]
+    fn test_hash() {
+        fn hash<T: Hash>(t: &T) -> u64 {
+            let mut s = DefaultHasher::new();
+            t.hash(&mut s);
+            s.finish()
+        }
+
+        let mut x = VecMap::new();
+        let mut y = VecMap::new();
+
+        assert!(hash(&x) == hash(&y));
+        x.insert(1, 'a');
+        x.insert(2, 'b');
+        x.insert(3, 'c');
+
+        y.insert(3, 'c');
+        y.insert(2, 'b');
+        y.insert(1, 'a');
+
+        assert!(hash(&x) == hash(&y));
+
+        x.insert(1000, 'd');
+        x.remove(1000);
+
+        assert!(hash(&x) == hash(&y));
+    }
+
+    #[test]
+    fn test_from_iter() {
+        let xs = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
+
+        let map: VecMap<_> = xs.iter().cloned().collect();
+
+        for &(k, v) in &xs {
+            assert_eq!(map.get(k), Some(&v));
+        }
+    }
+
+    #[test]
+    fn test_index() {
+        let mut map = VecMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        assert_eq!(map[3], 4);
+    }
+
+    #[test]
+    #[should_panic]
+    fn test_index_nonexistent() {
+        let mut map = VecMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        map[4];
+    }
+
+    #[test]
+    fn test_entry() {
+        let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
+
+        let mut map: VecMap<_> = xs.iter().cloned().collect();
+
+        // Existing key (insert)
+        match map.entry(1) {
+            Vacant(_) => unreachable!(),
+            Occupied(mut view) => {
+                assert_eq!(view.get(), &10);
+                assert_eq!(view.insert(100), 10);
+            }
+        }
+
+        assert_eq!(map.get(1).unwrap(), &100);
+        assert_eq!(map.len(), 6);
+
+        // Existing key (update)
+        match map.entry(2) {
+            Vacant(_) => unreachable!(),
+            Occupied(mut view) => {
+                let v = view.get_mut();
+                *v *= 10;
+            }
+        }
+
+        assert_eq!(map.get(2).unwrap(), &200);
+        assert_eq!(map.len(), 6);
+
+        // Existing key (take)
+        match map.entry(3) {
+            Vacant(_) => unreachable!(),
+            Occupied(view) => {
+                assert_eq!(view.remove(), 30);
+            }
+        }
+
+        assert_eq!(map.get(3), None);
+        assert_eq!(map.len(), 5);
+
+        // Inexistent key (insert)
+        match map.entry(10) {
+            Occupied(_) => unreachable!(),
+            Vacant(view) => {
+                assert_eq!(*view.insert(1000), 1000);
+            }
+        }
+
+        assert_eq!(map.get(10).unwrap(), &1000);
+        assert_eq!(map.len(), 6);
+    }
+
+    #[test]
+    fn test_extend_ref() {
+        let mut a = VecMap::new();
+        a.insert(1, "one");
+        let mut b = VecMap::new();
+        b.insert(2, "two");
+        b.insert(3, "three");
+
+        a.extend(&b);
+
+        assert_eq!(a.len(), 3);
+        assert_eq!(a[&1], "one");
+        assert_eq!(a[&2], "two");
+        assert_eq!(a[&3], "three");
+    }
+
+    #[test]
+    #[cfg(feature = "serde")]
+    fn test_serde() {
+        use serde::{Serialize, Deserialize};
+        fn impls_serde_traits<'de, S: Serialize + Deserialize<'de>>() {}
+
+        impls_serde_traits::<VecMap<u32>>();
+    }
+
+    #[test]
+    fn test_retain() {
+        let mut map = VecMap::new();
+        map.insert(1, "one");
+        map.insert(2, "two");
+        map.insert(3, "three");
+        map.retain(|k, v| match k {
+            1 => false,
+            2 => {
+                *v = "two changed";
+                true
+            },
+            3 => false,
+            _ => panic!(),
+        });
+
+        assert_eq!(map.len(), 1);
+        assert_eq!(map.get(1), None);
+        assert_eq!(map[2], "two changed");
+        assert_eq!(map.get(3), None);
+    }
+}