[
  {
    "path": ".flake8",
    "content": "[flake8]\nexclude = ./vendor/,\n          ./build/,\n          ./dist/,\n          ./webmacs.egg-info/,\n          # exclude virtual envs\n          ./venv*,\n"
  },
  {
    "path": ".gitattributes",
    "content": "**/.gitignore export-ignore\n**/.gitmodules export-ignore\n**/.travis.yml export-ignore\n\nvendor/*/test/** export-ignore\nvendor/*/vendor/depot_tools/** export-ignore\nvendor/*/.npmignore export-ignore\ngit_archive_all.py export-ignore\n"
  },
  {
    "path": ".gitignore",
    "content": "__pycache__/\nvenv/"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"vendor/hashset-cpp\"]\n\tpath = vendor/hashset-cpp\n\turl = https://github.com/bbondy/hashset-cpp\n[submodule \"vendor/bloom-filter-cpp\"]\n\tpath = vendor/bloom-filter-cpp\n\turl = https://github.com/bbondy/bloom-filter-cpp\n[submodule \"vendor/ad-block\"]\n\tpath = vendor/ad-block\n\turl = https://github.com/brave/ad-block\n"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: true\nlanguage: python\ndist: xenial\npython: 3.7\n\nmatrix:\n  include:\n    - os: linux\n      env: PYQT_VERSION=5.7.1\n    - os: linux\n      env: PYQT_VERSION=5.8.2\n    - os: linux\n      env: PYQT_VERSION=5.9.2\n    - os: linux\n      env: PYQT_VERSION=5.10.1\n    - os: linux\n      env: PYQT_VERSION=5.11.2 GENERATE_GIT_ARCHIVE=true\n  fast_finish: true\n\ncache:\n  directories:\n    - $HOME/.cache/pip\n\ninstall:\n  - pip install PyQt5==$PYQT_VERSION sphinx\n  - pip install -r test-requirements.txt\n  - sudo apt-get --yes install xvfb herbstluftwm\n\nscript:\n  - flake8\n  - pytest\n  - cd docs && READTHEDOCS=1 make html && cd ..\n\nbefore_deploy:\n  - python git_archive_all.py webmacs-${TRAVIS_TAG}.tar.gz\n\ndeploy:\n  provider: releases\n  api_key:\n    secure: MZSDuOdwUlHn55GfMy4MwkT9ZgDhd5/09gKTH2futOWtF90oIhbIO2a1ZfH8QXPB2AZtISzPFgPgMgFtdCIBkmv7ic5yD0AC+hfb6F8iWsxVaUCBQh6B7g4vUomoAEkr7+pUzjapOuJFSlaIWajSL43WcZb7Ep6gdy8M1bBnj8HsyBug5g5uV0GEFmk55Jwlg1EsXF9Jx23EstEBW1HC/wdywa3vkYZsaCzKSco+L1XU2lVtbrRBuY8SbYyvadeFPkyu315+cFNT+HkdD5yvFjRNFoaSYF4AMskv8LR7cCQ6Z7Hug1huFBNgr+LPVFxfflb+zaEETimLV5BN52pB2udv+RDJu0Xmc2hGcCb3eRrHC/w7DkxXWuldF/g8b2aCmoCUDrca1Dh+ipeXzWKo5yEFgrP4dp8l/q5ClbpH3Qc/o6IUhFvVS7YH8udO7A7bAHcZisDGuSfasQeHSDq28maU0pSH3sB0zcTvcphIzkDUjT7+9peXhn56MWUMKlBRX2JU9eoUCz1dBuxK/XCuRZ0YPHjV3xrDvEIbMBny3kdKHCTkc7rcZZs1QfZgnMmySLbM6uUXpmwxBhH5eIEqdZ5isQn/oCt+G3L99Lp7/sNr+gXJtNuocEzWcryEIeJ2Vi/hL9+Mu/I4TlgyLv6f1RS74Ndp4cPpgCCwGS2yVwY=\n  file: webmacs-${TRAVIS_TAG}.tar.gz\n  skip_cleanup: true\n  on:\n    tags: true\n    repo: parkouss/webmacs\n    branch: master\n    # limit to only one element in the matrix\n    condition: $GENERATE_GIT_ARCHIVE = true\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)\n\n## [Unreleased]\n\n### Fixed\n\n- Cookies and persistent data is now really saved on disk, and used on restart.\n- Fixed a possible security issue of the webmacs.ipc file that was readable and\n  writable by others.\n- adblock url fetching and parsing is now more verbose on error and more\n  resilient.\n- Fixed text selection within iframes.\n- Fixed minibuffer line input redo binding.\n- Fixed exiting webmacs as fast as possible by rewriting long-running tasks\n  asynchronously.\n\n\n### Added\n\n- Added passwordstore support for storing passwords (the linux 'pass' command\n  line tool)\n- Added **content-edit-select-all** in content edit mode, bound to **C-x h**.\n- Added **minibuffer-select-all** in minibuffer keymap, bound to **C-x h**.\n- Added bindings currently attached to commands when using **M-x** command.\n- Added support for an off-the-record (private) mode. It is enabled by starting\n  webmacs using **--off-the-record** flag, or using the command\n  **open-off-the-record**.\n\n### Changed\n\n- Moved codebase to PyQt6. PyQt5 is no longer supported.\n- Removed support for an internal database to store passwords.\n- Moved path to the spell checking data (to ~/.webmacs/spell_checking/)\n\n## [0.8] - 2019-09-15\n\n### Fixed\n\n- autocompletion for duckduckgo now uses duckduckgo servers\n- Fixed displaying long lines in the minibuffer popup (such as long urls in\n  history)\n- Fixed regression, unable to revive a buffer.\n- webmacs command line now handle correctly opening relative local file paths.\n- Fixed scrolling top or bottom when switching view, and losing focus sometimes.\n- Use one session file per webmacs instance.\n\n### Added\n\n- Added **where-is** command, bound to **C-h w**, to look up what keys a command\n  is bound to, if any.\n- Added **describe-key-briefly** command, bound to **C-h c**, as a less verbose\n  alternative to **describe-key**.\n- Added **print-buffer** command, bound to **C-x p** to print the current\n  buffer.\n- Improved customization of key bindings for incremental search, hinting and\n  minibuffer\n- Added key bindings **C-/** and **C-?** (resp. undo and redo) as minibuffer\n  input key bindings\n- Added a **clipboard-copy** variable to be able to copy to primary clipboard\n  (still the default), mouse selection clipboard or both.\n- Added a **--list-instances** command line flag, allowing to list current\n  running instances.\n- Passing an empty string to the **--instance** command line flag will generate\n  a new unique instance name.\n- Added a **raise-instance** command, to raise the current window of another\n  webmacs instance.\n- Added a **current-instance** command that show the name of the current\n  instance name.\n- Added **C-u C-u** prefix argument for command opening urls. Using it will open\n  the chosen url in a new window.\n- Added the variable **visited-links-display-limit**, to limit the number of\n  elements displayed in the **visited-links-history** command. Defaults to 2000.\n- Added **--profile** command line option to allow using more than one profile.\n\n## Changed\n\n- **C-h c** is now bound to **describe-key-briefly** instead of\n  **describe-command** which has in turn been moved to **C-h f**, in accordance\n  with Emacs default keybindings.\n\n## [0.7] - 2018-09-20\n\n### Fixed\n\n- Fix refreshing buffer count in the minibuffer right label when a buffer is\n  closed.\n- Fix reviving buffers that were not loaded (after restoring a session).\n- Fix hinting urls in iframes when opening in a new buffer.\n- Fixed support for Qt 5.7\n- Fixed requiring escaping of raw % signs in custom webjumps.\n- Fixed zoom-normal was bound to **0** instead of **=**.\n\n### Added\n\n- Added the **switch-buffer-current-color** variable that customize the color of\n  the current buffer row in the **switch-buffer** displayed list. The color\n  defaults to a light blue. Set to an empty string to get the old behavior (no\n  specific color).\n- **switch-buffer** now list buffers using the internal buffer order.\n- Buffers now have numbers and the current buffer number is displayed in the\n  minibuffer right label as well as in the **switch-buffer** and\n  **switch-recent-buffer** lists.\n- **M-n** and **M-p** are bound respectively to the new commands **next-buffer**\n  and **previous-buffer**, allowing to cycle through buffers.\n- **M-<**, **M->**, **C-v**, **M-v** bindings in the minibuffer lists for\n  navigation.\n- New commands and bindings added to copy stuff to clipboard.\n  **copy-current-link** bound to **c c**, **copy-current-buffer-title** bound to\n  **c t**, and copy-current-buffer-url bound to **c u** (all in the webbuffer\n  keymap)\n- Added a new method for hinting: alphabet. This allow to navigate only using\n  the home row keys, and without using Enter. Can be enabled by setting the\n  new variable **hint-method** to \"alphabet\".\n- Added a new variable **hint-alphabet-characters** to specify which characters\n  to use with the alphabet hinting.\n- Added a new variable **hint-node-style** to change the style of the hint div\n  nodes.\n- Added a **close-buffer-close-window** variable to be able to close a window\n  when a buffer is closed.\n- **C-g** in webbuffer is now bound to **buffer-escape** instead of\n  **buffer-unselect**, which does the same thing and send the Escape too (which\n  closes popup and other things).\n- Added two variables, **default-download-dir** and\n  **keep-temporary-download-dir**.\n\n### Changed\n\n- The old **switch-buffer** behavior is now offered with the\n  **switch-recent-buffer** command. The latter is now bound to **C-x b** and\n  **C-x C-b** so there is no visible change using those keybindings.\n- The **c** (copy-link) binding is now available using **c l** (think about Copy\n  Link).\n- The css style of the hints has been changed. If you prefer the old style, just\n  set the **hint-node-style** variable to {\"background\": \"red\", \"color\":\n  \"white\"}.\n- The **go-to** command (bounds to **g**) now set the current url in the\n  minibuffer input and select it.\n- The **go-to-selected-url** and **go-to-selected-url-new-buffer** commands are\n  renamed to **go-to-alternate-url** and **go-to-alternate-url-new-buffer**.\n  Also they do not anymore select the current url, but only set the cursor at\n  the end of the url.\n\n## [0.6] - 2018-08-20\n\n### Fixed\n\n- crash when opening in a new window (from right-click menu on a link), in qt\n  5.11.1.\n- crash when reviving closed buffers in some cases.\n- crash when calling switch-buffer and closing buffer (including the current\n  one) using C-k.\n\n### Added\n\n- added a basic navigation toolbar, that can be shown using the command\n  **toggle-toolbar**. Also added a new variable, **window-toolbar-on-startup**\n  that can be set to True to show the toolbar automatically.\n- added a database to keep feature permissions (geolocation, camera, ...) on a\n  per-url basis (thanks to Patrick Lafrance)\n- the allow permission for feature dialog now ask for Always/Never, and save\n  that in the database. (thanks to Patrick Lafrance)\n- it is now possible to answer Never when webmacs ask to save a password.\n  (thanks to Patrick Lafrance)\n- it is now possible to answer Always to bypass certificate errors. (thanks to\n  Patrick Lafrance)\n- when opening a download, there is now a prompt to ask to download or to open\n  the file with an external command.\n  \n### Changed\n\n- the functions **webmacs.keymaps.global_keymap()**,\n  **webmacs.keymaps.webbuffer_keymap()**,\n  **webmacs.keymaps.content_edit_keymap()** have been deprecated in favor of\n  **webmacs.keymaps.keymap()** (respectively with the argument \"global\",\n  \"webbuffer\" and \"webcontent-edit\").\n- loading page information is now displayed in the minibuffer right label, using\n  the **loading** key in the **minibuffer-right-label** variable (default value\n  of this variable has changed)\n\n## [0.5] - 2018-07-08\n\n### Fixed\n\n- focus is not lost anymore in the minibuffer input on page loading\n- adblock is fully disabled when the variable **adblock-urls-rules** is set to\n  an empty list.\n- adblock cache is rebuilt when the variable **adblock-urls-rules** has changed.\n- Fixed the **copy-link** command (**c**) when used with the argument 0.\n- Added a space after the default webjump when calling **search-default**.\n- Mouse events are now propagated to the minibuffer input and popup.\n- Fixed a bug that prevented to use multi-modifiers keybindings (e.g., C-M-a)\n- Fixed regression in **close-other-buffers** command.\n- The keyboard is not anymore lost when a new buffer is opened from javascript.\n- The **follow** command is now working in cross-origin iframes.\n- Text edition in web pages is now working in cross-origin iframes.\n- Text zoom in web pages is now working in cross-origin iframes.\n- Caret navigation is now working in cross-origin iframes.\n\n### Changed\n\n- **scroll-page-down**, **scroll-page-up**, **scroll-bottom** and\n  **scroll-top** are now implemented by sending the PageDown, PageUp and End\n  and Home key presses.\n- **search-default** now defaults to google.\n\n### Added\n\n- The minibuffer input now flashes under some circumstances to grab user's\n  attention.\n- Added **minibuffer-flash-duration**, **minibuffer-flash-color**, and\n  **minibuffer-flash-count** variables to customize the flash animation.\n\n## [0.4] - 2018-05-04\n\n### Fixed\n\n- Fixed closing buffer in some circumstances using C-k from the\n  switch-buffer command.\n- Improved position of the minibuffer popup, removing empty pixels\n  between the popup and the input.\n- Fixed using i-search when caret browsing is enabled\n- improve using multiple views, fixing a lot of bugs around that (keyboard\n  focus lost, crash using switch-buffer on an already displayed buffer, ...)\n\n### Changed\n\n- **breaking change**. The completion\\_fn argument in define\\_webjump has\n  changed, see the documentation about that.\n- improved webjump completions in multiple ways.\n- switching buffers now tries its best to keep the current scroll and cursor\n  position, so that coming back to a previous buffer feels more natural. This\n  is in part implemented by keeping one internal qt webengineview per buffer.\n- improved the visibility of the current view when there are multiple\n  views. There is now a border on each side of the view, with one pixel red and\n  one black.\n\n### Added\n\n- added a **revive-buffer** command, bound to **C-x r** in the global keymap.\n  This allow to reopen a previously closed buffer.\n- added the **revive-buffers-limit** variable, to specify how many buffers might\n  be revived. This defaults to 10.\n- added basic handling of web features to enable video, audio from javascript.\n- added two variables to customize how webmacs starts: **home-page** and\n  **home-page-in-new-window**.\n- added a command to restore previous session (windows and buffers),\n  **restore-session**.\n- Under X11, if the --instance is passed at the command line, the\n  WM_CLASS property is set to \"webmacs-{instance}\".\n- added basic support for multiple windows. New commands added: **make-window**,\n  **other-window**, **close-window**, **close-other-window**.\n- saving and restoring web views in session\n- saving and restoring window position and state in session\n- added a variable **webview-stylesheet** to customize the above view style.\n- added a command **buffer-unselect** to clear selection in the current buffer.\n- bound **buffer-unselect** to **C-g** in the webbuffer keymap.\n\n## [0.3]\n\n### Added\n\n- keymaps can now have a name and associated documentation\n- added command **describe-commands** to list all named webmacs commands\n- added command **describe-bindings** to list named commands in named keymaps\n- added command **describe-variables** to list named webmacs variables\n- added command **downloads** to open a buffer to see downloads of the session\n- added command **version** to open a version buffer.\n- added command **describe-variable** to describe a variable (bound to C-h v)\n- added command **describe-command** to describe a command (bound to C-h c)\n- added command **describe-key** to describe a keychord (bound to C-h k)\n- added python dependency *pygments* to render source code.\n- added a command line flag **--instance** to run named instances of webmacs\n\n### Fixed\n\n- If webmacs has crashed, the local socket used for ipc is now cleaned, so other\n  commands for this webmacs instance are forwarded and does not anymore create a\n  new instance.\n- do not set the webbuffer active keymap as the current local keymap if the\n  minibuffer input is currently opened.\n\n\n## [0.2]\n\nThe distinction between 0.1 and 0.2 version is not clear unfortunately - patches\nwere just going in the main git branch. To highlight some features, let's start\nthe version 0.2 from the commit cb0cea39eaab6a01ee74ca16261c2b467b4af5a3.\n\n### Added\n\n- buffers loading from last session are delayed until they are displayed\n- added caret browsing support, with a specific keymap and its set of commands.\n  The **C** binding in a web buffer enter the caret browsing mode\n- added new variable **adblock-urls-rules** to list rules url for the ad-blocker\n- added new variable **webjump-default**\n- better prompt completion\n- added information in the minibuffer\n- added new variable **minibuffer-right-label** for the format of the displayed\n  information in the minibuffer\n- support for bookmarks (see **bookmark-add** and **bookmark-open** commands,\n  bound to respectively **M** and **m** in the webbuffer keymap).\n- support for zoom and text zoom. See the **zoom-\\*** and **text-zoom-\\***\n  commands.\n- added undefine_key method on Keymaps to unbind keys\n- added command **close-other-buffers**\n- added basic notion of mode to a web buffer, normal usage being \"standard-mode\"\n  and a new mode \"no-keybindings\"\n- added new variable **auto-buffer-modes** to set up rules for settings web\n  buffer mode based on urls\n- added new command **content-edit-open-external-editor** to open a text editor\n  to edit web content, bound to **Cx e** and **C-x C-e** in the webcontent-edit\n  keymap. The external command to run is stored in the variable\n  **external-editor-command**.\n- added **content-edit-undo** and **content-edit-redo** commands, bound\n  respectively to **C-/** and **C-?** in webcontent-edit keymap.\n- added spell check support, configurable with the\n  **spell-checking-dictionaries** variable.\n\n### Fixed\n\n- fixed segfault with some graphic cards\n- retrieving ad-block rules and compiling them is now done in a thread, so\n  webmacs is not slow at startup anymore\n- added a warning when using opengl with the nouveau driver.\n- default qt shortcuts in webviews are removed, so webmacs bindings are working\n  without side-effect anymore (e.g., C-a was sometimes selecting the text)\n- changed implementation of the webcontent-edit movement text commands, so now\n  undo redo works better and it also mostly works in contenteditable fields\n\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>."
  },
  {
    "path": "README-nix.org",
    "content": "* Installation with Nix\n\nThere are two recommended ways of installing webmacs:\n\n1. Nix\n2. pip/virtualenv\n\n** Nix\n\nCurrently, the easiest way to install webmacs is via the [[https://nixos.org/nix/][Nix package\nmanager]]:\n\n#+BEGIN_SRC bash\nnix-env -i webmacs\n#+END_SRC\n\n*** Need more help with nix?\n\nNix is available for Linux, macOS and other Unix-like systems. Rest\nassured that removing Nix (along with any packages installed using\nNix) is as easy as =rm /nix -rf=.\n\nIf you do not have Nix, install it. For details see\nhttps://nixos.org/nix/manual/#chap-installation, but this step\napproximates to\n\n#+BEGIN_SRC bash\nbash <(curl https://nixos.org/nix/install)\n#+END_SRC\n\nand will require you to provide a sudo password.\n\nLook out for, and follow the instructions which will appear once\nnix is installed, and which will look something like this:\n\n#+BEGIN_SRC text\nInstallation finished!  To ensure that the necessary environment\nvariables are set, either log in again, or type\n\n  . /home/yourusername/.nix-profile/etc/profile.d/nix.sh\n\nin your shell.\n#+END_SRC\n\nIf you don't spot this, the installation will appear to have failed.\n\nNow you can use =nix-env= to install webmacs:\n\n#+BEGIN_SRC bash\nnix-env -i webmacs\n#+END_SRC\n\nFor further details, see\nhttps://nixos.org/nix/manual/#chap-quick-start.\n\n*** working on webmacs with nix\n\nThe command\n\n#+BEGIN_SRC bash\nnix-shell -p webmacs\n#+END_SRC\n\nwill drop you into a shell which makes available all the compilers and\nlibraries required to build and run webmacs, thus =nix-shell= plays\nthe role of =virtualenv= in the pip/virtualenv approach described\nbelow. Unfortunately, some of the libraries required to run the\ntests, are not yet available in this shell.\n"
  },
  {
    "path": "README.org",
    "content": "* webmacs\n\n*webmacs* is yet another browser for keyboard-based web navigation.\n\nIt mainly target emacs-like navigation, and started as a clone (in terms of\nfeatures) of [[http://conkeror.org/][conkeror]].\n\nSee the documentation manual: https://webmacs.readthedocs.io/en/latest/\n\nwebmacs is based on qt webengine and written mainly in Python (version 3).\n\n#+html: <p align=\"center\"><img src=\"webmacs-screenshot.png\" /></p>\n\n* Features\n\nShort list of features:\n\n- keyboard navigation everywhere (including basic emacs movements in editable\n  web content)\n- Integrated, fast ad-blocker\n- [[https://webmacs.readthedocs.io/en/latest/basic_usage.html#live-documentation][live documentation]]\n- [[https://webmacs.readthedocs.io/en/latest/user_configuration.html][highly customizable using Python]]\n\n\n* Installation (... and development)\n\n** Using Nix\n\n   See the [[./.README-nix.org][dedicated page]].\n\n** Using pip/virtualenv\n\nBe prepared to have a working c and c++ compiler with python development\nlibrary. Note I only have tested on linux.\n\nYou will also need the PyQt6 library, as I believe it can't be installed through\npip. It's easy to install using any package manager though.\n\nThen you have to check out the repository (do not forget the *recursive* flag):\n\n#+BEGIN_SRC bash\ngit clone --recursive https://github.com/parkouss/webmacs\n#+END_SRC\n\nTo test it, or work on it, I recommend virtualenv:\n\n#+BEGIN_SRC bash\nvirtualenv --system-site-packages -p python3 venv\n# activate the virtualenv\nsource venv/bin/activate\n# install webmacs in there\npip install -e <path_to_webmacs_sources>\n# and now to run webmacs\npython -m webmacs.main\n#+END_SRC\n\nThen you can create a system alias to run it:\n#+BEGIN_SRC bash\nsudo ln -s <path_to_venv>/bin/webmacs /usr/local/bin/webmacs\n# now you can use the webmacs command on your system, given that\n# /usr/local/bin is in your PATH.\n#+END_SRC\n\n\n* Running tests\n\nTo run the tests, you will need a few more dependencies (the virtualenv needs\nto be activated):\n\n#+BEGIN_SRC bash\n# install test dependencies\npip install -r <path_to_webmacs_sources>/test-requirements.txt\n# also install the herbstluftwm window manager, using your package manager.\n# Example on fedora:\nsudo dnf install herbstluftwm\n#+END_SRC\n\nThen you can run the tests (the virtualenv needs to be activated):\n#+BEGIN_SRC bash\npython -m pytest <path_to_webmacs_sources>/tests\n# you can run them with the windows visible:\npython -m pytest <path_to_webmacs_sources>/tests --no-xvfb\n#+END_SRC\n\n\n* Qt versions support\n\nEvery stable Qt version from (and including) 6.0 should work with webmacs.\n\n\n* Contributions\n\nContributions are much welcome! Writing this browser is exciting and I love\nthat, though I don't have many time to spend on it, having a family life and a\njob; And anyway the more we are to work on it and use the tool, the better!\n"
  },
  {
    "path": "c/adblock.c",
    "content": "// This file is part of webmacs.\n//\n// webmacs is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// webmacs is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\n#include <Python.h>\n#include \"structmember.h\"\n\n#include <iostream>\n#include <fstream>\n\n#include \"ad_block_client.h\"\n\nusing namespace std;\n\ntypedef struct {\n  PyObject_HEAD\n\n  AdBlockClient * client;\n  char * data;\n} AdBlock;\n\n\nstatic void\nAdBlock_dealloc(AdBlock* self)\n{\n  delete self->client;\n  if (self->data) delete[] self->data;\n  Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\nstatic PyObject *\nAdBlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n  AdBlock *self;\n\n  self = (AdBlock *)type->tp_alloc(type, 0);\n\n  return (PyObject *)self;\n}\n\nstatic int\nAdBlock_init(AdBlock *self, PyObject *args, PyObject *kwds)\n{\n  self->client = new AdBlockClient;\n  self->data = NULL;\n  return 0;\n}\n\nstatic PyObject *\nAdBlock_parse(AdBlock* self, PyObject *args)\n{\n  const char *data;\n\n  if (!PyArg_ParseTuple(args, \"s\", &data))\n    return NULL;\n\n  Py_BEGIN_ALLOW_THREADS\n  self->client->parse(data);\n  Py_END_ALLOW_THREADS\n\n  Py_RETURN_NONE;\n}\n\nstatic PyObject *\nAdBlock_matches(AdBlock* self, PyObject *args)\n{\n  const char *url, *domain;\n  bool result;\n\n  if (!PyArg_ParseTuple(args, \"ss\", &url, &domain))\n    return NULL;\n\n  /* I suspect that allowing threads here does create deadlocks,\n   but anyway I am not sure it would be useful to allow them. */\n  /* Py_BEGIN_ALLOW_THREADS */\n  result = self->client->matches(url, FONoFilterOption, domain);\n  /* Py_END_ALLOW_THREADS */\n\n  if (result) {\n    Py_RETURN_TRUE;\n  } else {\n    Py_RETURN_FALSE;\n  }\n}\n\nstatic PyObject *\nAdBlock_save(AdBlock* self, PyObject *args)\n{\n  const char *path;\n\n  if (!PyArg_ParseTuple(args, \"s\", &path))\n    return NULL;\n\n  int size;\n  ofstream outFile(path, ios::out | ios::binary);\n  if (!outFile) {\n    Py_RETURN_FALSE;\n  }\n\n  Py_BEGIN_ALLOW_THREADS\n  char * buffer = self->client->serialize(&size);\n  outFile.write(buffer, size);\n  outFile.close();\n  Py_END_ALLOW_THREADS\n\n  Py_RETURN_TRUE;\n}\n\nstatic PyObject *\nAdBlock_load(AdBlock* self, PyObject *args)\n{\n  const char *path;\n  bool result = false;\n\n  if (!PyArg_ParseTuple(args, \"s\", &path))\n    return NULL;\n\n  ifstream file(path, ios::binary | ios::ate);\n  if (!file) {\n    Py_RETURN_FALSE;\n  }\n\n  Py_BEGIN_ALLOW_THREADS\n  streamsize size = file.tellg();\n  file.seekg(0, ios::beg);\n\n  if (self->data) {delete[] self->data;}\n  self->data = new char[size];\n  if (file.read(self->data, size)) {\n    self->client->deserialize(self->data);\n    result = true;\n  }\n  Py_END_ALLOW_THREADS\n\n  if (result) {\n    Py_RETURN_TRUE;\n  } else {\n    Py_RETURN_FALSE;\n  }\n}\n\n\nstatic PyMethodDef AdBlock_methods[] = {\n  {\"parse\", (PyCFunction)AdBlock_parse, METH_VARARGS,\n   \"Parse adblock data string, like the content of an easylist.\"\n  },\n  {\"matches\", (PyCFunction)AdBlock_matches, METH_VARARGS,\n   \"matches an url, returns True if it should be filtered.\"\n  },\n  {\"save\", (PyCFunction)AdBlock_save, METH_VARARGS,\n   \"Save serialized data into a file.\"\n  },\n  {\"load\", (PyCFunction)AdBlock_load, METH_VARARGS,\n   \"Load serialized data from a file.\"\n  },\n  {NULL}  /* Sentinel */\n};\n\nstatic PyTypeObject AdBlockType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"adblock.AdBlock\",             /* tp_name */\n    sizeof(AdBlock),             /* tp_basicsize */\n    0,                         /* tp_itemsize */\n    (destructor)AdBlock_dealloc, /* tp_dealloc */\n    0,                         /* tp_print */\n    0,                         /* tp_getattr */\n    0,                         /* tp_setattr */\n    0,                         /* tp_reserved */\n    0,                         /* tp_repr */\n    0,                         /* tp_as_number */\n    0,                         /* tp_as_sequence */\n    0,                         /* tp_as_mapping */\n    0,                         /* tp_hash  */\n    0,                         /* tp_call */\n    0,                         /* tp_str */\n    0,                         /* tp_getattro */\n    0,                         /* tp_setattro */\n    0,                         /* tp_as_buffer */\n    Py_TPFLAGS_DEFAULT |\n        Py_TPFLAGS_BASETYPE,   /* tp_flags */\n    \"Adblock objects\",           /* tp_doc */\n    0,                         /* tp_traverse */\n    0,                         /* tp_clear */\n    0,                         /* tp_richcompare */\n    0,                         /* tp_weaklistoffset */\n    0,                         /* tp_iter */\n    0,                         /* tp_iternext */\n    AdBlock_methods,             /* tp_methods */\n    0,             /* tp_members */\n    0,                         /* tp_getset */\n    0,                         /* tp_base */\n    0,                         /* tp_dict */\n    0,                         /* tp_descr_get */\n    0,                         /* tp_descr_set */\n    0,                         /* tp_dictoffset */\n    (initproc)AdBlock_init,      /* tp_init */\n    0,                         /* tp_alloc */\n    AdBlock_new,                 /* tp_new */\n};\n\n\nstatic PyModuleDef adblockmodule = {\n  PyModuleDef_HEAD_INIT,\n  \"adblock\",\n  \"Module to speed up ad filtering.\",\n  -1,\n  NULL, NULL, NULL, NULL, NULL\n};\n\nPyMODINIT_FUNC\nPyInit__adblock(void)\n{\n  PyObject* m;\n\n  AdBlockType.tp_new = PyType_GenericNew;\n  if (PyType_Ready(&AdBlockType) < 0)\n    return NULL;\n\n  m = PyModule_Create(&adblockmodule);\n  if (m == NULL)\n    return NULL;\n\n  Py_INCREF(&AdBlockType);\n  PyModule_AddObject(m, \"AdBlock\", (PyObject *)&AdBlockType);\n  return m;\n}\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    = -W\nSPHINXBUILD   = sphinx-build\nSPHINXPROJ    = webmacs\nSOURCEDIR     = .\nBUILDDIR      = _build\n\n# Put it first so that \"make\" without argument is like \"make help\".\nhelp:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n.PHONY: help Makefile\n\n# Catch-all target: route all unknown targets to Sphinx using the new\n# \"make mode\" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).\n%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n"
  },
  {
    "path": "docs/advanced_topics.rst",
    "content": "Advanced topics\n===============\n\n.. current-keymap:: global\n\n\n.. _managing_views:\n\nManaging views\n**************\n\nIt is possible to manage multiple :term:`views` in a webmacs window:\n\n- :key:`C-x 2` split the current view in two horizontally.\n- :key:`C-x 3` split the current view in two vertically.\n- :key:`C-x o` navigate in current window views.\n- :key:`C-x 0` close the current view.\n- :key:`C-x 1` maximize the current view, closing every other view.\n\n\nManaging windows\n****************\n\nYou can also manage multiple windows:\n\n\n- :cmd:`make-window` to create a new window.\n- :cmd:`other-window` to navigate through windows.\n- :cmd:`close-window` to close the current window.\n- :cmd:`close-other-windows` to close all but the current window.\n\n\nCaret browsing\n**************\n\n.. current-keymap:: caret-browsing\n\nCaret browsing allows to navigate in a web page using a caret. It is mainly\nuseful for copying text inside a web page without using the mouse.\n\nIt is enabled by pressing :key:`C (webbuffer)`.\n\nThen you can navigate using arrow keys or standard Emacs bindings:\n\n- :key:`C-n` to go to the next line.\n- :key:`C-p` to go to the previous line.\n- :key:`C-f` to go to the next character.\n- :key:`C-b` to go to the previous character.\n- :key:`M-f` to go to the next word.\n- :key:`M-b` to go to the previous word.\n- :key:`C-e` to go to the end of the line.\n- :key:`C-a` to go to the beginning of the line.\n\nYou can select some text and copy it using:\n\n- :key:`C-Space` to toggle the mark\n- :key:`M-w` to copy the current selection to the clipboard.\n\n.. current-keymap:: webbuffer\n\n.. note::\n\n  Incremental search can be used when in caret browsing, to allow easier\n  navigation.\n\n  It is also great to start caret browsing after an incremental search, as the\n  caret will be at the beginning of the current web selection.\n\n\nBookmarks\n*********\n\nBookmarks are like a dictionary of URLs. Each bookmark must have a unique name.\nBookmarks are stored in the profile, and hence are persistent across sessions.\n\nIt is possible to manage bookmarks using:\n\n- :key:`M` to create a bookmark.\n- :key:`m` to open the bookmark list.\n\nWhen in the bookmark list, you can:\n\n- :key:`Return (bookmarks-list)` to open the bookmark URL in the current buffer\n- :key:`C-k (bookmarks-list)` to remove the highlighted bookmark.\n"
  },
  {
    "path": "docs/api.rst",
    "content": "Public api\n==========\n\n\nInitialisation\n**************\n\n.. autofunction:: webmacs.main.init\n\n\nKeymaps\n*******\n\n.. autofunction:: webmacs.keymaps.keymap\n\n.. autoclass:: webmacs.keymaps.Keymap\n   :members: define_key, undefine_key\n\n\nWebjumps\n********\n\n.. autofunction:: webmacs.commands.webjump.define_webjump\n\n.. autoclass:: webmacs.commands.webjump.WebJumpCompleter\n   :members:\n\n.. autoclass:: webmacs.commands.webjump.WebJumpRequestCompleter\n\n.. autoclass:: webmacs.commands.webjump.SyncWebJumpCompleter\n\n.. autofunction:: webmacs.commands.webjump.define_webjump_alias\n\nVariables\n*********\n\n.. autofunction:: webmacs.variables.set\n\n.. autofunction:: webmacs.variables.get\n\n.. autoexception:: webmacs.variables.VariableConditionError\n"
  },
  {
    "path": "docs/basic_usage.rst",
    "content": "Basic usage\n===========\n\nDon't panic\n***********\n\nWhen you are stuck in some interactive :term:`command` or text field, and you\nare unsure what to do, press **C-g**. This :term:`key binding` usually lets you\nout of the current action - you may have to press it more than once. **C-g** is\nthe universal *get me out of there* command.\n\n.. note::\n\n  Usually, pressing **C-g** enough times lets you focus on the current\n  :term:`web buffer`, and so activates the :keymap:`webbuffer` :term:`keymap`.\n\n\n.. current-keymap:: global\n\n\nRunning a command using its name\n********************************\n\nIt is always possible to run a :term:`command` using its name. Some commands\ndoes not have default :term:`key binding`, and requires to be called this\nway. To call a command using its name, use the :key:`M-x` keybinding, then\nselect in the list (or type) the command you want to run, followed by **Return**\n(the Enter key).\n\nFor example, :key:`M-x` toggle-toolbar <Return> will toggle the webmac's\ntoolbar.\n\n\nLive documentation\n******************\n\nwebmacs is self-documenting. You can easily access the documentation by running\nthe following commands:\n\n- :cmd:`describe-commands` to see all available commands.\n- :cmd:`describe-command` (bound to :key:`C-h f`) to choose one command, and get\n  a detailed description.\n- :cmd:`describe-variables` to see all the available :term:`variables`.\n- :cmd:`describe-variable` (bound to :key:`C-h v`) to choose one variable and\n  get a detailed description.\n- :cmd:`describe-key` (bound to :key:`C-h k`) or :cmd:`describe-key-briefly` (bound to :key:`C-h c`)\n  to discover what command a key binding would trigger.\n- :cmd:`where-is` (bound to: :key:`C-h w`) to quickly find what key(s) a command is bound to.\n- :cmd:`describe-bindings` to see the list of all keymaps, with the bindings\n  and commands they contain.\n\n\n.. note::\n\n  Self-documentation is super useful for many things. If you want, for example,\n  to define a custom binding for a command, but don't know its name, you can\n  always use :key:`C-h k` to help you.\n\n  Also, do not hesitate to use :key:`C-h v` to see the description of a\n  :term:`variable`.\n\n\n.. current-keymap:: webbuffer\n\n\nVisiting urls\n*************\n\nAn easy way to go to a new URL is to type :key:`g`. This calls the :cmd:`go-to`\ncommand, that lets you type a URL or a :term:`webjump`. Pressing **Return**\nwill then open it in the current web buffer.\n\nFor example, try typing: **g g<tab> webmacs <Return>**. This should open a new\nGoogle page with the query 'webmacs'.\n\n.. important::\n\n  Typing **C-u** before :key:`g` will open the url or webjump in a new buffer.\n\n\n.. _link_hinting:\n\nLink hinting\n************\n\nLink hinting is used to navigate through visible links of the current web\nbuffer's page, using the keyboard only.\n\nPress :key:`f`. You should see the :term:`minibuffer` right label displaying\nthat you are in the :keymap:`hint` keymap, and the links on the page\nhighlighted.\n\n.. current-keymap:: hint\n\nHinting in webmacs can be done using two methods: filter (the default) and\nalphabet. You can use the :term:`variable` :var:`hint-method` to change it.\n\nfilter\n------\n\nThere is one active hint. Typing text will narrow down the hint selection by\nfuzzy matching against the link's texts. It is also possible to directly type\nthe number of the link to activate it, and to cycle the visible hints (next,\nprevious) to change the active hint.\n\nKeybindings are as follows:\n\n- :key:`C-n` activate next visible hint\n- :key:`C-p` activate previous visible hint\n\nNote that to validate hinting, :key:`Return` has to be pressed.\n\nalphabet\n--------\n\nThis is the method used by default in vimium, for example. There is no active\nhint, and each link is associated with some characters: they must all be entered\nto validate hinting.\n\nNote that the hinting characters are usually randomly picked up from the home\nrow of the keyboard. This behavior is configured with the :term:`variable`\n:var:`hint-alphabet-characters`, defaulting to the home row characters of a\nQWERTY keyboard.\n\n\n.. current-keymap:: webbuffer\n\n\n.. _managing_buffers:\n\nManaging buffers\n****************\n\nYou can switch to a buffer using :key:`C-x b (global)`, which opens a list on\ntop of the :term:`minibuffer`. Select the buffer you want to switch to by\nfuzzy-matching text of the url or title page, or just use the arrow keys (or\nbetter, standard Emacs bindings such as **C-n**, **C-p**, **C-v**, **M-v**,\netc). Finally, validate with **Return**.\n\n.. important::\n\n  Most of the lists displayed in the :term:`minibuffer` work in this same way,\n  and have the same basic bindings.\n\nThe command is called :cmd:`switch-recent-buffer`.\n\n.. note::\n\n  The above command orders the buffers so that the most recently used is on top.\n  If you want the buffers to be ordeded by their number, you can call the\n  command :cmd:`switch-buffer`.\n\n\nYou can also navigate to the next or previous buffer by using respectively\n:key:`M-n (global)` and :key:`M-p (global)`.\n\n\nA buffer can be closed by just pressing :key:`q`. When you are running\n:cmd:`switch-buffer` or :cmd:`switch-recent-buffer`, pressing :key:`C-k\n(buffer-list)` will also kill the buffer currently highlighted in the list.\n\n\n.. important::\n\n  If you killed a buffer by accident, no worries! Just use :key:`C-x r (global)`\n  to resurrect it.\n\n\nNavigating through buffer history\n*********************************\n\n- :key:`B` goes backward in the buffer history\n- :key:`F` goes forward in the buffer history\n- :key:`b` shows the current buffer's history as a list in the\n  :term:`minibuffer`, and allows to easily navigate it.\n\n\nNavigating through global history\n*********************************\n\nType :key:`h` to display a list of every visited URL (these are saved in a\ndatabase file and are persistent in your profile). Select one to open it in the\ncurrent buffer.\n\n.. note::\n\n  Use **C-u** before :key:`h` to open the URL in a new buffer.\n\n\nScrolling in current web buffer\n*******************************\n\n- :key:`C-n` or :key:`n` scrolls the current buffer down a bit.\n- :key:`C-p` or :key:`p` scrolls the current buffer up a bit.\n- :key:`C-b` scrolls the current buffer left a bit.\n- :key:`C-f` scrolls the current buffer right a bit.\n\n- :key:`C-v` scrolls the current buffer down for one visible page.\n- :key:`M-v` scrolls the current buffer up for one visible page.\n\n- :key:`M-<` lets you go to the top of the page.\n- :key:`M->` lets you go to the bottom of the page.\n\n\nSearching in current web buffer\n*******************************\n\nType :key:`C-s` to start incremental search. Then you can type the text you are\nlooking for. Press :key:`C-s` again to go to the next match, or :key:`C-r` to go\nto the previous match.\n\n.. note::\n\n  :key:`C-r` can also be used to start incremental search.\n\n\nCopying links\n*************\n\n- :key:`c u` to copy the URL of the current buffer.\n- :key:`c l` to copy a visible link in the buffer (by :term:`hinting`).\n- :key:`c c` to copy the currently selected link.\n- :key:`c t` to copy the current buffer page title.\n\n\nDownloading\n***********\n\nA download can be started by clicking a link or button or :term:`hinting`.\n\nWhen a download is about to be started, the :term:`minibuffer` will propose to\neither **download** or **open** it.\n\n- **download** will start downloading, and save the file to your hard drive.\n- **open** will download to a temporary directory, then open the file with the given\n  command. A list of available commands is shown in the minibuffer completion\n  list. Note that when the command exits, the file will be automatically deleted\n  from your hard drive.\n\n  .. note::\n\n    open is useful for viewing PDF files for example, as you can use your\n    favorite PDF file viewer to read it.\n\nThe list of downloads can be accessed using the :cmd:`downloads` command.\n\n.. seealso::\n\n  See the :var:`default-download-dir` and :var:`keep-temporary-download-dir`\n  variables.\n\n\nZooming\n*******\n\n- :key:`+` zoom in.\n- :key:`-` zoom out.\n- :key:`=` reset the zoom to its default value.\n\n.. note::\n\n  There are variants for the zoom, using the Control modifier (:key:`C-+`,\n  :key:`C--`, and :key:`C-=`) that are used for text zoom only.\n\n\nPrinting\n********\n\n- :key:`C-x p` to print the current buffer.\n"
  },
  {
    "path": "docs/concepts.rst",
    "content": "Concepts\n========\n\nPlease make sure to understand the following basic webmacs concepts before\nfurther reading the documentation.\n\n\n.. _concept_commands:\n\nCommands, key bindings and keymaps\n**********************************\n\nThese are quite similar to the definitions found in the Emacs manual.\n\n- A :term:`command` is a named action which can be done in the browser. For\n  example, :cmd:`follow` is the command that allows to start hinting links to\n  navigate.\n\n- A :term:`key binding` is a combination of key presses used to trigger commands.\n  Key bindings are represented as in Emacs, for example **C-x C-b** means\n  \"holding the Control key while pressing x, then b on the keyboard.\"\n\n  .. note::\n\n    The control key is called a modifier. There are three keyboard modifiers:\n\n    - **C** represents the Control key.\n    - **M** represents the Alt key.\n    - **S** represents the Super key (often called the Windows key)\n\n  .. note::\n\n    .. current-keymap:: webbuffer\n\n    A key binding can also be a single key press. For example, pressing :key:`f`\n    while in the :keymap:`webbuffer` keymap will trigger the :cmd:`follow`\n    command.\n\n- A :term:`keymap` is an object holding a mapping between key bindings and\n  commands, so that a command can be triggered by pressing keyboard keys.\n  Usually, there is one global keymap, and one active local keymap activated\n  at the same time - the local keymap changes interactively depending on the\n  context.\n\n  Some important keymaps:\n\n  .. webmacs-keymaps::\n    :only: global, webbuffer, webcontent-edit, caret-browsing\n\n\nWeb buffers\n***********\n\nA :term:`web buffer` is like an Emacs buffer, but applying to a Web page.\nBuffers are like tabs in other browsers, except that they are not bound to\nany view or window.\n\nWindows, views\n**************\n\nDiffering from Emacs terminology, a window actually is what we nowadays call a\nwindow, and :term:`views` (sometimes called frames) correspond to the content\nof a window.\n"
  },
  {
    "path": "docs/conf.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# webmacs documentation build configuration file, created by\n# sphinx-quickstart on Sat Dec 23 08:47:03 2017.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\nsys.path.insert(0, os.path.join(os.path.abspath(\".\"), \"ext\"))\nsys.path.insert(0, os.path.abspath('..'))\n\n# Generating doc don't work without that flag. That could be fixed but anyway\n# on readthedocs we can't install binary package so we are stuck for now trying\n# to mock everything.\nif True or \"READTHEDOCS\" in os.environ:\n    # We can not install webmacs on readthedocs, as it requires to\n    # buid some C extensions (from dateparser, PyQt6, ...). The\n    # alternative is to mock any dependency used by webmacs.\n\n    class Mock(object):\n        def __init__(self, *a, **kw):\n            pass\n        def __getattr__(self, name):  # noqa: E301\n            return Mock()\n        def __call__(self, *a, **kw):  # noqa: E301\n            return Mock()\n        def __iter__(self):  # noqa: E301\n            return iter(())\n        def __instancecheck__(self, instance):  # noqa: E301\n            return True\n        def __subclasscheck__(self, cls):  # noqa: E301\n            return True\n        def __mro_entries__(self, a):  # noqa: E301\n            return ()\n\n    MOCK_MODULES = [\"PyQt6\", \"PyQt6.QtCore\", \"PyQt6.QtGui\",\n                    \"PyQt6.QtWidgets\", \"PyQt6.QtWebEngineWidgets\",\n                    \"PyQt6.QtWebEngineCore\", \"PyQt6.QtWebChannel\",\n                    \"PyQt6.QtNetwork\", \"PyQt6.QtPrintSupport\",\n                    \"_adblock\", \"dateparser\"]\n    sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)\n    # the version number is not important, though it must be an int.\n    sys.modules[\"PyQt6.QtCore\"].QT_VERSION \\\n        = sys.modules[\"PyQt6.QtCore\"].PYQT_VERSION = 330497\n\nimport webmacs  # noqa: E402\n\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = ['sphinx.ext.autodoc',\n              'sphinx.ext.viewcode', \"webmacs_sphinx_ext\"]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'webmacs'\ncopyright = '2017, Julien Pagès'\nauthor = 'Julien Pagès'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = webmacs.__version__\n# The full version, including alpha/beta/rc tags.\nrelease = version\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = \"en\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'alabaster'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#\nhtml_theme_options = {\n    'github_user': 'parkouss',\n    'github_repo': project,\n    \"github_button\": True,\n    'description': \"An emacs-like keyboard-driven web browser\",\n    # defaults is 940, gives a bit more so viewcode looks good.\n    'page_width': \"1050px\",\n}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n# html_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars\nhtml_sidebars = {\n    '**': [\n        'about.html',\n        'navigation.html',\n        'relations.html',  # needs 'show_related': True theme option to display\n        'searchbox.html',\n    ]\n}\n\n\n# -- Options for HTMLHelp output ------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'webmacsdoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #\n    # 'papersize': 'letterpaper',\n\n    # The font size ('10pt', '11pt' or '12pt').\n    #\n    # 'pointsize': '10pt',\n\n    # Additional stuff for the LaTeX preamble.\n    #\n    # 'preamble': '',\n\n    # Latex figure (float) alignment\n    #\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, 'webmacs.tex', 'webmacs Documentation',\n     'Julien Pagès', 'manual'),\n]\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    (master_doc, 'webmacs', 'webmacs Documentation',\n     [author], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (master_doc, 'webmacs', 'webmacs Documentation',\n     author, 'webmacs', 'One line description of project.',\n     'Miscellaneous'),\n]\n"
  },
  {
    "path": "docs/ext/webmacs_sphinx_ext.py",
    "content": "import re\n\nfrom docutils.parsers.rst import Directive\nfrom docutils.statemachine import ViewList\nfrom docutils import nodes\n\nfrom webmacs import COMMANDS\nfrom webmacs.commands import InteractiveCommand\nfrom webmacs.commands.webjump import WEBJUMPS\nfrom webmacs.application import _app_requires\nfrom webmacs.variables import VARIABLES\nfrom webmacs.mode import MODES\nfrom webmacs.keymaps import KEYMAPS\n\n\n# to include all commands, etc.\n_app_requires()\n\n\ndef as_rest_table(data):\n    numcolumns = len(data[0])\n    colsizes = [max(len(r[i]) for r in data) for i in range(numcolumns)]\n    formatter = ' '.join('{:<%d}' % c for c in colsizes)\n    rowsformatted = [formatter.format(*row) for row in data]\n    header = formatter.format(*['=' * c for c in colsizes])\n\n    yield header\n    yield rowsformatted[0]\n    yield header\n    for row in rowsformatted[1:]:\n        yield row\n    yield header\n\n\nclass SimpleAutoDirective(Directive):\n    has_content = False\n    required_arguments = 0\n    optional_arguments = 0\n    final_argument_whitespace = False\n    option_spec = {}\n\n    def run(self):\n        self._result = ViewList()\n\n        self._run()\n\n        node = nodes.paragraph()\n        node.document = self.state.document\n        self.state.nested_parse(self._result, 0, node)\n        return node.children\n\n\nclass WebmacsCommands(SimpleAutoDirective):\n    def _run(self):\n        result = self._result\n\n        def get_doc(cmd):\n            if isinstance(cmd, InteractiveCommand):\n                cmd = cmd.binding\n            return cmd.__doc__ or \"No description\"\n\n        table = [(\"Command\", \"description\")]\n        for name in sorted(COMMANDS):\n            table.append((name, get_doc(COMMANDS[name])))\n\n        for line in as_rest_table(table):\n            result.append(line, \"\")\n\n\nclass WebmacsWebjumps(SimpleAutoDirective):\n    def _run(self):\n        result = self._result\n\n        table = [(\"Name\", \"url\", \"description\")]\n        for name in sorted(WEBJUMPS):\n            webjump = WEBJUMPS[name]\n            table.append((name, webjump.url, webjump.doc))\n\n        for line in as_rest_table(table):\n            result.append(line, \"\")\n\n\nclass WebmacsVariables(SimpleAutoDirective):\n    def _run(self):\n        result = self._result\n\n        table = [(\"Name\", \"description\", \"default\")]\n        for name in sorted(VARIABLES):\n            variable = VARIABLES[name]\n            table.append((name, variable.doc, repr(variable.value)))\n\n        for line in as_rest_table(table):\n            result.append(line, \"\")\n\n\nclass WebmacsModes(SimpleAutoDirective):\n    def _run(self):\n        result = self._result\n\n        table = [(\"Name\", \"Description\")]\n        for name in sorted(MODES):\n            mode = MODES[name]\n            table.append((name, mode.description))\n\n        for line in as_rest_table(table):\n            result.append(line, \"\")\n\n\nclass WebmacsKeymaps(SimpleAutoDirective):\n    option_spec = {\n        \"only\": lambda a: (a or \"\").replace(\" \", \"\").split(\",\")\n    }\n\n    def _run(self):\n        result = self._result\n        keys = self.options.get(\"only\") or sorted(KEYMAPS)\n\n        table = [(\"Name\", \"Description\")]\n        for name in keys:\n            km = KEYMAPS[name]\n            table.append((name, km.doc or \"\"))\n\n        for line in as_rest_table(table):\n            result.append(line, \"\")\n\n\ndef webmacs_role(data):\n    \"\"\"\n    Create a simple role function handler that check for the text to be in the\n    given data, and just create a strong node for the it.\n    \"\"\"\n    def role(name, rawtext, text, lineno, inliner, options={}, content=[]):\n        if text not in data:\n            inliner.reporter.error(\"No such %s: %s\" % (name, text))\n        node = nodes.strong(text=text)\n        return [node], []\n    return role\n\n\nclass CurrentKeymapDirective(Directive):\n    has_content = False\n    required_arguments = 1\n    optional_arguments = 0\n    final_argument_whitespace = False\n    option_spec = {}\n\n    def run(self):\n        env = self.state.document.settings.env\n        keymap = self.arguments[0].strip()\n        if keymap not in KEYMAPS:\n            self.state_machine.reporter.error(\"No such keymap: %s\" % keymap)\n        env.ref_context['webmacs:keymap'] = keymap\n        return []\n\n\nKEYMAPS_BINDINGS_CACHE = {}\nRE_KEY_MAP = re.compile(r\"^(.*)\\s+\\(([\\w-]+)\\)$\")\n\n\ndef get_keymap_bindings(keymap_name):\n    if keymap_name not in KEYMAPS_BINDINGS_CACHE:\n        KEYMAPS_BINDINGS_CACHE[keymap_name] \\\n            = {k: v for k, v in KEYMAPS[keymap_name].all_bindings(raw_fn=True)}\n    return KEYMAPS_BINDINGS_CACHE[keymap_name]\n\n\ndef key_in_keymap_role(name, rawtext, text, lineno, inliner, options={},\n                       content=[]):\n    m = RE_KEY_MAP.match(text)\n    if m:\n        text = m.group(1)\n        km = m.group(2)\n    else:\n        env = inliner.document.settings.env\n        try:\n            km = env.ref_context[\"webmacs:keymap\"]\n        except KeyError:\n            inliner.reporter.error(\n                \"no current keymap. Use the current-keymap directive.\"\n            )\n    keys = get_keymap_bindings(km)\n    if text not in keys:\n        inliner.reporter.error(\"No such key: %s in keymap %s\" % (text, km))\n    node = nodes.strong(text=text)\n    return [node], []\n\n\ndef setup(app):\n    app.add_directive(\"webmacs-commands\", WebmacsCommands)\n    app.add_directive(\"webmacs-webjumps\", WebmacsWebjumps)\n    app.add_directive(\"webmacs-variables\", WebmacsVariables)\n    app.add_directive(\"webmacs-modes\", WebmacsModes)\n    app.add_directive(\"webmacs-keymaps\", WebmacsKeymaps)\n    app.add_directive(\"current-keymap\", CurrentKeymapDirective)\n\n    # use them to ensure doc is not outdated, making references to things that\n    # do not exists.\n    app.add_role(\"cmd\", webmacs_role(COMMANDS))\n    app.add_role(\"var\", webmacs_role(VARIABLES))\n    app.add_role(\"keymap\", webmacs_role(KEYMAPS))\n    app.add_role(\"key\", key_in_keymap_role)\n"
  },
  {
    "path": "docs/faq.rst",
    "content": "FAQ\n===\n\nHow do I run a new webmacs instance instead of a new buffer from the command-line?\n**********************************************************************************\n\nWhen a webmacs instance is already running, calling `webmacs <url>` from a\nshell will open the URL in a new buffer of the running instance. To run a fresh\nnew instance, use `webmacs --instance <instance-unique-name> <url>`.\n\n\nHow do I run webmacs with a specific profile from the command-line?\n**********************************************************************************\nTo have webmacs use a specific profile, use\n`webmacs --profile <profile-name> <url>`. Each profile directory will contain\ndistinct navigation data (history, cookies, ...).\n\n\nWebsite is blocked, turn off the extensions\n*******************************************\n\nThis message will appear in the browser when the URL has got filtered by the\nad-blocker.\n\nTo overcome this, you can temporarily disable the ad-blocker with *M-x toggle-ad-block*.\n\nFor a permanent change, edit the :var:`adblock-urls-rules` variable, to remove\nsome URLs in there. Note if you set this variable to an empty list, the\nadblocker will be completely disabled. See the :ref:`user_conf_variables`\nsection in the documentation.\n"
  },
  {
    "path": "docs/glossary.rst",
    "content": "Glossary\n========\n\n.. glossary::\n\n  buffer\n  web buffer\n    The content of a web page, not including its window or view.\n\n    You can learn the basics of buffer handling in :ref:`managing_buffers`.\n\n  command\n  commands\n    A command is a named action doable in the browser.\n\n    See :ref:`concept_commands` for a detailed description.\n\n    See :ref:`Commands <user_conf_commands>` for a list of commands; or better,\n    use the :cmd:`describe-commands` command to get live documentation.\n\n  hinting\n   Hinting is used to navigate through the visible links and objects of the\n   current web buffer's page, using the keyboard only.\n\n   See :ref:`link_hinting` for more information.\n\n  key binding\n  key bindings\n    A **key binding** is a combination of key presses used to trigger commands.\n\n    See :ref:`concept_commands` for a detailed description, and\n    :ref:`user_conf_binding_keys` for custom configuration of key bindings.\n\n  keymap\n  keymaps\n    A **keymap** is an object holding a mapping between key bindings and\n    commands.\n\n    See :ref:`concept_commands` for a detailed description.\n\n    See :ref:`Keymaps <user_conf_keymaps>` for a list of keymaps; or better, use\n    the :cmd:`describe-bindings` command to get live documentation.\n\n  minibuffer\n    The minibuffer is what can be seen at the bottom of a webmacs window. It\n    displays some information on the right, such as the currently active keymap\n    and the number of open buffers.\n\n  minibuffer input\n    When webmacs is waiting for some information from you, the\n    **minibuffer input** is shown: it's a text edit field in which you can type\n    some text.\n\n    Often, there also is a completion list above the minibuffer input.\n\n  variable\n  variables\n    Some behaviors of *webmacs* can be customized using variables.\n\n    See :ref:`user_conf_variables` for variables configuration.\n\n    See :ref:`All variables <user_conf_all_variables>` to see all the variables;\n    or better, use :cmd:`describe-variables` to get live documentation.\n\n  view\n  views\n    A view is a part of a window displaying a buffer. There can be multiple\n    views in one window.\n\n    See :ref:`managing_views`.\n\n  webjump\n  webjumps\n    A Webjump represents a quick way to access a URL, possibly with a variable\n    part. A webjump name becomes a part of the webmacs :cmd:`go-to` command, so\n    for example you can type ``google foo bar`` to execute a Google query with\n    \"foo bar\" terms.\n\n    See :ref:`user_conf_webjumps` to see the builtins webjumps and how to\n    configure your owns.\n"
  },
  {
    "path": "docs/index.rst",
    "content": ".. webmacs documentation master file, created by\n   sphinx-quickstart on Sat Dec 23 08:47:03 2017.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nWelcome to webmacs's documentation!\n===================================\n\n**webmacs** is yet another browser for keyboard-based web navigation.\n\nCode is hosted on a `github repository <https://github.com/parkouss/webmacs>`_.\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Contents:\n\n   concepts\n   basic_usage\n   advanced_topics\n   user_configuration\n   api\n   faq\n   glossary\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n"
  },
  {
    "path": "docs/make.bat",
    "content": "@ECHO OFF\r\n\r\npushd %~dp0\r\n\r\nREM Command file for Sphinx documentation\r\n\r\nif \"%SPHINXBUILD%\" == \"\" (\r\n\tset SPHINXBUILD=sphinx-build\r\n)\r\nset SOURCEDIR=.\r\nset BUILDDIR=_build\r\nset SPHINXPROJ=webmacs\r\n\r\nif \"%1\" == \"\" goto help\r\n\r\n%SPHINXBUILD% >NUL 2>NUL\r\nif errorlevel 9009 (\r\n\techo.\r\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\r\n\techo.installed, then set the SPHINXBUILD environment variable to point\r\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\r\n\techo.may add the Sphinx directory to PATH.\r\n\techo.\r\n\techo.If you don't have Sphinx installed, grab it from\r\n\techo.http://sphinx-doc.org/\r\n\texit /b 1\r\n)\r\n\r\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%\r\ngoto end\r\n\r\n:help\r\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%\r\n\r\n:end\r\npopd\r\n"
  },
  {
    "path": "docs/user_configuration.rst",
    "content": "User configuration\n==================\n\n**webmacs** can be configured by writing Python code. The files should live in\na ``~/.webmacs/init`` directory, starting with an ``__init__.py`` file.\n\nIf this file exists, it will be loaded early in the application.\n\nNote that you have the full power of Python in there, and as it is loaded early,\nyou can change and adapt nearly every aspect of the webmacs behavior.\n\n.. note::\n\n   Only the documented functions and objects here are considered stable (meaning\n   they will not change without change notes and explanations). Any other API\n   you can use is considered internal and might change without notification.\n\n\nThe init function\n*****************\n\nYou can write a function **init** that would be called when webmacs is about to\nstart. This function must take one parameter (usually named *opts*), that\ncontains the result of the parsed command line. For now, there is only one\nuseful parameter:\n\n- opts.url:  the url given in the command line, or None\n\nOverriding the init function does override the default init function of webmacs,\nthough it is still accessible with :func:`webmacs.main.init`. Hello world\nexample:\n\n.. code-block:: python\n\n   import webmacs.main\n\n\n   def init(opts):\n       print(\"hello wordl\")\n       if opts.url:\n           print(\"{} was given as a command line argument\".format(opts.url))\n       webmacs.main.init(opts)\n\n\nThe default webmacs.main.init function is responsible for restoring the session,\nor opening the given URL, for example.\n\n\n.. note::\n\n   It is not required to create an init function in the user configuration\n   _\\_init_\\_.py file. Only do so if you want to change the default webmacs\n   initialization. Other changes can be applied early, directly at the module\n   level, such as defining :term:`webjumps` or **binding keys**.\n\n\nUsing more than one configuration file\n**************************************\n\nIt is possible to write more than one configuration file. The\ndirectory where the ``__init__.py`` file lives is a Python package, so\nit is possible to just use relative imports.\n\nFor example:\n\n``__init__.py``\n\n.. code-block:: python\n\n   from . import webjumps\n\n\n``webjumps.py``\n\n.. code-block:: python\n\n   print(\"definition of my custom webjumps should go there.\")\n\n\n.. _user_conf_variables:\n\nVariables\n*********\n\nIt is possible to change a variable in the configuration using\n:func:`webmacs.variables.set`:\n\n.. code-block:: python\n\n   from webmacs import variables\n\n   variables.set(\"webjump-default\", \"google\")\n\n\n.. _user_conf_all_variables:\n\nHere is the list of the variables:\n\n.. webmacs-variables::\n\n\nModes\n*****\n\nModes are used to bind keymaps to a web buffer, by assigning the buffer a given\nmode. By default, all buffers use the \"standard-mode\".\n\nHere is the list of the pre-defined modes:\n\n.. webmacs-modes::\n\nAutomatically assign modes depending on the url\n-----------------------------------------------\n\nYou can use the `auto-buffer-modes` variable.\n\nExample:\n\n.. code-block:: python\n\n   from webmacs import variables\n\n   variables.set(\"auto-buffer-modes\", [\n      (\".*www.gnu.org.*\", \"no-keybindings\"),\n      (\"https://mail.google.com/.*\", \"no-keybindings\")\n  ])\n\nBinding keys\n************\n\nIn webmacs, like in Emacs, it is possible to bind a key to a command on a given\nkeymap.\n\n.. _user_conf_keymaps:\n\nKeymaps\n-------\n\nHere is the list of available keymaps. Note that you can see them live (with\ntheir associated key bindings) in webmacs by running the command\n`describe-bindings`.\n\n.. webmacs-keymaps::\n\nA keymap object in user configuration is retrieved with\n:func:`webmacs.keymaps.keymap`.\n\n\n.. _user_conf_commands:\n\nCommands\n--------\n\nHere is the list of the currently available commands:\n\n.. webmacs-commands::\n\n\n.. _user_conf_binding_keys:\n\nBinding a command to a keymap\n-----------------------------\n\nYou should use :meth:`webmacs.keymaps.Keymap.define_key`. Here is an example:\n\n.. code-block:: python\n\n   from webmacs import keymaps\n\n   global_map = keymaps.keymap(\"global\")\n   global_map.define_key(\"C-c |\", \"split-view-right\")\n   global_map.define_key(\"C-c _\", \"split-view-bottom\")\n\n   buffer_keymap = keymaps.keymap(\"webbuffer\")\n   buffer_keymap.define_key(\"x\", \"close-buffer\")\n\n\n.. note::\n\n   The global buffer should not define single letter keychords, as you\n   won't be able to type that letter in editable fields; though, this is\n   possible in the webbuffer :term:`keymap`.\n\n.. _user_conf_webjumps:\n\nWebjumps\n********\n\nHere is the implementation of the google :term:`webjump`:\n\n.. literalinclude:: ../webmacs/default_webjumps.py\n   :start-after: # ----------- doc example\n   :end-before: # ----------- end of doc example\n\n\nThe list of defined webjumps in webmacs:\n\n.. webmacs-webjumps::\n\n\nYou can implement your own webjumps, or override the existing\nones. See :func:`webmacs.commands.webjump.define_webjump` and the\nexample above.\n\nPressing the ``s`` key will call the command\n``search-default``, wich will, by default, use the Google webjump. To change\nthis default, change the value of the variable *webjump-default*.\n\nIt is also possible to define an alias to an existing webjump,\nwithout duplicating its implementation.\n\n.. code-block:: python\n\n   from webmacs.commands.webjump import define_webjump_alias\n\n   define_webjump_alias(\"g\", \"google\")\n"
  },
  {
    "path": "git_archive_all.py",
    "content": "# Script to generate a git archive with submodules\n# From https://github.com/Kentzo/git-archive-all\n\nfrom os import extsep, path, readlink\nfrom shlex import quote\nfrom subprocess import CalledProcessError, Popen, PIPE\nfrom zipfile import ZipFile, ZipInfo, ZIP_DEFLATED\nimport re\nimport sys\nimport tarfile\n\n\n__version__ = \"1.18.1\"\n\n\nclass GitArchiver(object):\n    \"\"\"\n    GitArchiver\n\n    Scan a git repository and export all tracked files, and submodules.\n    Checks for .gitattributes files in each directory and uses 'export-ignore'\n    pattern entries for ignore files in the archive.\n\n    >>> archiver = GitArchiver(main_repo_abspath='my/repo/path')\n    >>> archiver.create('output.zip')\n    \"\"\"\n    def __init__(self, prefix='', exclude=True, force_sub=False, extra=None,\n                 main_repo_abspath=None):\n        \"\"\"\n        @param prefix: Prefix used to prepend all paths in the resulting\n            archive. Extra file paths are only prefixed if they are not\n            relative. E.g. if prefix is 'foo' and extra is ['bar', '/baz'] the\n            resulting archive will look like this:\n            /\n              baz\n              foo/\n                bar\n        @type prefix: str\n\n        @param exclude: Determines whether archiver should follow rules\n        specified in .gitattributes files.\n        @type exclude: bool\n\n        @param force_sub: Determines whether submodules are initialized and\n        updated before archiving. @type force_sub: bool\n\n        @param extra: List of extra paths to include in the resulting archive.\n        @type extra: list\n\n        @param main_repo_abspath: Absolute path to the main repository (or one\n            of subdirectories). If given path is path to a subdirectory (but\n            not a submodule directory!) it will be replaced with abspath to\n            top-level directory of the repository. If None, current cwd is\n            used.\n        @type main_repo_abspath: str\n        \"\"\"\n        if extra is None:\n            extra = []\n\n        if main_repo_abspath is None:\n            main_repo_abspath = path.abspath('')\n        elif not path.isabs(main_repo_abspath):\n            raise ValueError(\"main_repo_abspath must be an absolute path\")\n\n        try:\n            main_repo_abspath = path.abspath(\n                self.run_git_shell('git rev-parse --show-toplevel',\n                                   main_repo_abspath).rstrip())\n        except CalledProcessError:\n            raise ValueError(\"{0} is not part of a git repository\"\n                             .format(main_repo_abspath))\n\n        self.prefix = prefix\n        self.exclude = exclude\n        self.extra = extra\n        self.force_sub = force_sub\n        self.main_repo_abspath = main_repo_abspath\n\n    def create(self, output_path, dry_run=False, output_format=None):\n        \"\"\"\n        Create the archive at output_file_path.\n\n        Type of the archive is determined either by extension of\n        output_file_path or by output_format. Supported formats are: gz, zip,\n        bz2, xz, tar, tgz, txz\n\n        @param output_path: Output file path.\n        @type output_path: str\n\n        @param dry_run: Determines whether create should do nothing but print\n            what it would archive.\n        @type dry_run: bool\n\n        @param output_format: Determines format of the output archive. If None,\n            format is determined from extension of output_file_path.\n        @type output_format: str\n        \"\"\"\n        if output_format is None:\n            file_name, file_ext = path.splitext(output_path)\n            output_format = file_ext[len(extsep):].lower()\n\n        if not dry_run:\n            if output_format == 'zip':\n                archive = ZipFile(path.abspath(output_path), 'w')\n\n                def add_file(file_path, arcname):\n                    if not path.islink(file_path):\n                        archive.write(file_path, arcname, ZIP_DEFLATED)\n                    else:\n                        i = ZipInfo(arcname)\n                        i.create_system = 3\n                        i.external_attr = 0xA1ED0000\n                        archive.writestr(i, readlink(file_path))\n            elif output_format in ['tar', 'bz2', 'gz', 'xz', 'tgz', 'txz']:\n                if output_format == 'tar':\n                    t_mode = 'w'\n                elif output_format == 'tgz':\n                    t_mode = 'w:gz'\n                elif output_format == 'txz':\n                    t_mode = 'w:xz'\n                else:\n                    t_mode = 'w:{0}'.format(output_format)\n\n                archive = tarfile.open(path.abspath(output_path), t_mode)\n\n                def add_file(file_path, arcname):\n                    archive.add(file_path, arcname)\n            else:\n                raise RuntimeError(\"unknown format: {0}\".format(output_format))\n\n            def archiver(file_path, arcname):\n                add_file(file_path, arcname)\n        else:\n            archive = None\n\n            def archiver(file_path, arcname):\n                print(\"{0} => {1}\".format(file_path, arcname))\n\n        self.archive_all_files(archiver)\n\n        if archive is not None:\n            archive.close()\n\n    def is_file_excluded(self, file_path):\n        \"\"\"\n        Checks whether file at a given path is excluded.\n        \"\"\"\n        out = self.run_git_shell(\n            'git check-attr -z export-ignore -- %s' % quote(file_path),\n            cwd=self.main_repo_abspath\n        ).split('\\0')\n\n        try:\n            return out[2] == 'set'\n        except IndexError:\n            return False\n\n    def archive_all_files(self, archiver):\n        \"\"\"\n        Archive all files using archiver.\n\n        @param archiver: Callable that accepts 2 arguments:\n            abspath to file on the system and relative path within archive.\n        @type archiver: Callable\n        \"\"\"\n        for file_path in self.extra:\n            archiver(path.abspath(file_path),\n                     path.join(self.prefix, file_path))\n\n        for file_path in self.walk_git_files():\n            archiver(path.join(self.main_repo_abspath, file_path),\n                     path.join(self.prefix, file_path))\n\n    def walk_git_files(self, repo_path=''):\n        \"\"\"\n        An iterator method that yields a file path relative to\n        main_repo_abspath for each file that should be included in the archive.\n        Skips those that match the exclusion patterns found in any discovered\n        .gitattributes files along the way.\n\n        Recurs into submodules as well.\n\n        @param repo_path: Path to the git submodule repository relative to\n        main_repo_abspath.\n        @type repo_path: str\n\n        @return: Iterator to traverse files under git control relative to\n        main_repo_abspath.\n        @rtype: Iterable\n        \"\"\"\n        repo_abspath = path.join(self.main_repo_abspath, repo_path)\n        repo_file_paths = self.run_git_shell(\n            'git ls-files -z --cached --full-name --no-empty-directory',\n            repo_abspath\n        ).split('\\0')[:-1]\n\n        for repo_file_path in repo_file_paths:\n            # absolute file path\n            repo_file_abspath = path.join(repo_abspath, repo_file_path)\n            # file path relative to the main repo\n            main_repo_file_path = path.join(repo_path, repo_file_path)\n\n            # Only list symlinks and files.\n            if not path.islink(repo_file_abspath) \\\n               and path.isdir(repo_file_abspath):\n                continue\n\n            if self.is_file_excluded(main_repo_file_path):\n                continue\n\n            yield main_repo_file_path\n\n        if self.force_sub:\n            self.run_git_shell('git submodule init', repo_abspath)\n            self.run_git_shell('git submodule update', repo_abspath)\n\n        try:\n            repo_gitmodules_abspath = path.join(repo_abspath, \".gitmodules\")\n\n            with open(repo_gitmodules_abspath) as f:\n                lines = f.readlines()\n\n            for l in lines:\n                m = re.match(\"^\\\\s*path\\\\s*=\\\\s*(.*)\\\\s*$\", l)\n\n                if m:\n                    repo_submodule_path = m.group(1)  # relative to repo_path\n                    # relative to main_repo_abspath\n                    gen = self.walk_git_files(\n                        path.join(repo_path, repo_submodule_path))\n\n                    for main_repo_submodule_fpath in gen:\n                        if self.is_file_excluded(main_repo_submodule_fpath):\n                            continue\n\n                        yield main_repo_submodule_fpath\n        except IOError:\n            pass\n\n    @staticmethod\n    def run_git_shell(cmd, cwd=None):\n        \"\"\"\n        Runs git shell command, reads output and decodes it into unicode\n        string.\n\n        @param cmd: Command to be executed.\n        @type cmd: str\n\n        @type cwd: str\n        @param cwd: Working directory.\n\n        @rtype: str\n        @return: Output of the command.\n\n        @raise CalledProcessError: Raises exception if return code of the\n        command is non-zero.\n        \"\"\"\n        p = Popen(cmd, shell=True, stdout=PIPE, cwd=cwd)\n        output, _ = p.communicate()\n        output = output.decode('unicode_escape')\\\n                       .encode('raw_unicode_escape').decode('utf-8')\n\n        if p.returncode:\n            if sys.version_info > (2, 6):\n                raise CalledProcessError(returncode=p.returncode, cmd=cmd,\n                                         output=output)\n            else:\n                raise CalledProcessError(returncode=p.returncode, cmd=cmd)\n\n        return output\n\n\ndef main():\n    from optparse import OptionParser\n\n    parser = OptionParser(\n        version=\"%prog {0}\".format(__version__)\n    )\n\n    parser.add_option('--prefix',\n                      type='string',\n                      dest='prefix',\n                      default=None,\n                      help=\"\"\"prepend PREFIX to each filename in the archive.\n                          OUTPUT_FILE name is used by default to avoid tarbomb.\n                          You can set it to '' in order to explicitly request\n                          tarbomb\"\"\")\n\n    parser.add_option('-v', '--verbose',\n                      action='store_true',\n                      dest='verbose',\n                      help='enable verbose mode')\n\n    parser.add_option('--no-exclude',\n                      action='store_false',\n                      dest='exclude',\n                      default=True,\n                      help=\"don't read .gitattributes files for patterns\"\n                      \" containing export-ignore attrib\")\n\n    parser.add_option('--force-submodules',\n                      action='store_true',\n                      dest='force_sub',\n                      help='force a git submodule init && git submodule update'\n                      \" at each level before iterating submodules\")\n\n    parser.add_option('--extra',\n                      action='append',\n                      dest='extra',\n                      default=[],\n                      help=\"any additional files to include in the archive\")\n\n    parser.add_option('--dry-run',\n                      action='store_true',\n                      dest='dry_run',\n                      help=\"don't actually archive anything, just show what\"\n                      \" would be done\")\n\n    options, args = parser.parse_args()\n\n    if len(args) != 1:\n        parser.error(\"You must specify exactly one output file\")\n\n    output_file_path = args[0]\n\n    if path.isdir(output_file_path):\n        parser.error(\"You cannot use directory as output\")\n\n    # avoid tarbomb\n    if options.prefix is not None:\n        options.prefix = path.join(options.prefix, '')\n    else:\n        import re\n\n        output_name = path.basename(output_file_path)\n        output_name = re.sub(\n            '(\\\\.zip|\\\\.tar|\\\\.tgz|\\\\.txz|\\\\.gz|\\\\.bz2|\\\\.xz|\\\\.tar\\\\.gz'\n            '|\\\\.tar\\\\.bz2|\\\\.tar\\\\.xz)$',\n            '',\n            output_name\n        ) or \"Archive\"\n        options.prefix = path.join(output_name, '')\n\n    try:\n        archiver = GitArchiver(options.prefix,\n                               options.exclude,\n                               options.force_sub,\n                               options.extra)\n        archiver.create(output_file_path, options.dry_run)\n    except Exception as e:\n        parser.exit(2, \"{0}\\n\".format(e))\n\n    sys.exit(0)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "pytest.ini",
    "content": "[pytest]\naddopts = tests\n\nlog_cli = true\nlog_cli_level = debug\nlog_format = %(asctime)s %(name)-10s %(levelname)s %(message)s\nlog_date_format = %Y-%m-%d %H:%M:%S"
  },
  {
    "path": "setup.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport re\nimport subprocess\n\nfrom setuptools import setup, Extension, find_packages\nfrom distutils.command.build_py import build_py as _build_py\n\n\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n\nbloom_dir = os.path.join(THIS_DIR, \"vendor\", \"bloom-filter-cpp\")\nhashset_dir = os.path.join(THIS_DIR, \"vendor\", \"hashset-cpp\")\nadblock_dir = os.path.join(THIS_DIR, \"vendor\", \"ad-block\")\n\n\nif \"CC\" not in os.environ:\n    # force g++, not sure why but else gcc is used and the code does not\n    # compile...\n    os.environ[\"CC\"] = \"g++\"\n\nadblocker = Extension(\n    '_adblock',\n    define_macros=[],\n    language=\"c++\",\n    include_dirs=[bloom_dir, hashset_dir, adblock_dir],\n    # not sure if that help for speed. Careful it strip the debug symbols\n    extra_compile_args=[\"-g0\", \"-std=c++11\"],\n    sources=[\n        os.path.join(bloom_dir, \"BloomFilter.cpp\"),\n        os.path.join(bloom_dir, \"hashFn.cpp\"),\n        os.path.join(hashset_dir, \"hash_set.cc\"),\n        os.path.join(adblock_dir, \"ad_block_client.cc\"),\n        os.path.join(adblock_dir, \"filter.cc\"),\n        os.path.join(adblock_dir, \"cosmetic_filter.cc\"),\n        os.path.join(adblock_dir, \"no_fingerprint_domain.cc\"),\n        os.path.join(adblock_dir, \"protocol.cc\"),\n        os.path.join(THIS_DIR, \"c\", \"adblock.c\"),\n    ])\n\n\ndef get_version():\n    with open(os.path.join(THIS_DIR, \"webmacs\", \"__init__.py\")) as f:\n        version = re.findall(\"__version__ = '(.+)'\", f.read())\n    return version[0]\n\n\ndef get_revision():\n    # ensure we are in a git dir\n    if not os.path.exists(os.path.join(THIS_DIR, \".git\")):\n        return None\n    p = subprocess.Popen(\n        [\"git\", \"rev-parse\", \"HEAD\"], cwd=THIS_DIR,\n        stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n    )\n    out, err = p.communicate()\n    if p.returncode == 0:\n        return out.strip().decode(\"utf-8\")\n\n\nclass build_py(_build_py):\n    \"\"\"\n    Override build to generate a revision file to install.\n    \"\"\"\n    def run(self):\n        rev = get_revision()\n        # honor the --dry-run flag\n        if not self.dry_run and rev:\n            target_dir = os.path.join(self.build_lib, 'webmacs')\n\n            # mkpath is a distutils helper to create directories\n            self.mkpath(target_dir)\n\n            with open(os.path.join(target_dir, 'revision'), 'w') as f:\n                f.write(rev)\n\n        # distutils uses old-style classes, so no super()\n        _build_py.run(self)\n\n\nsetup(\n    name='webmacs',\n    version=get_version(),\n    description='Keyboard driven web browser, emacs-like',\n    author='Julien Pagès',\n    author_email='j.parkouss@gmail.com',\n    url='https://github.com/parkouss/webmacs',\n    long_description='''\nA browser for keyboard-based web navigation.\n\nKeybindings are emacs-friendly, most of them took from the conkeror\n(http://conkeror.org/) project which is not maintained anymore.\n\nIt is based on qtwebengine, which in turns uses chromium for the web engine.\n\nSome of the features are:\n\n- integrated ad-blocker\n- emacs like navigation nearly everywhere (C-n, C-p, ...)\n- hinting to navigate with keyboard only\n- and a lot more, see the project url\n\n''',\n    packages=find_packages(),\n    install_requires=[\"dateparser\", \"jinja2\", \"pygments\"],\n    entry_points={\"console_scripts\": [\"webmacs = webmacs.main:main\"]},\n    package_data={\"webmacs\": [\n        \"scripts/*.js\",\n        \"scheme_handlers/webmacs/js/*.js\",\n        \"scheme_handlers/webmacs/templates/*.html\",\n    ]},\n    cmdclass={'build_py': build_py},\n    python_requires=\">=3.3\",\n    ext_modules=[adblocker],\n)\n"
  },
  {
    "path": "test-requirements.txt",
    "content": "-e .\npytest\npytest-qt\npytest-mock\npytest-xvfb\nflake8\n"
  },
  {
    "path": "tests/integration/conftest.py",
    "content": "import pytest\nimport os\nimport time\nimport subprocess\n\nfrom PyQt6.QtTest import QTest\nfrom PyQt6.QtCore import QEvent, QTimer\n\nfrom webmacs.application import Application, _app_requires\nfrom webmacs import (windows, buffers, WINDOWS_HANDLER, current_buffer,\n                     current_window, current_minibuffer)\nfrom webmacs import variables as wvariables\nfrom webmacs.webbuffer import create_buffer\nfrom webmacs.window import Window\nfrom webmacs.webbuffer import close_buffer\nfrom webmacs.keymaps import KeyPress\n\n\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n_app = None\n\n\ndef get_test_page(name):\n    if name.endswith(\".html\"):\n        return os.path.join(THIS_DIR, name)\n    return os.path.join(THIS_DIR, name, \"index.html\")\n\n\n@pytest.fixture(scope=\"session\")\ndef wm(xvfb):\n    if xvfb is None:\n        yield None\n    else:\n        if not any(\n                os.access(os.path.join(path, 'herbstluftwm'), os.X_OK)\n                for path in os.environ[\"PATH\"].split(os.pathsep)\n        ):\n            raise RuntimeError(\"herbstluftwm is not installed, can not run\"\n                               \" graphical tests.\")\n        env = dict(os.environ)\n        env[\"DISPLAY\"] = str(\":%s\" % xvfb.display)\n        proc = subprocess.Popen(\n            [\"herbstluftwm\"], env=env\n        )\n        time.sleep(2)  # wait for the wm to be active\n        yield proc\n        proc.kill()\n        proc.wait()\n\n\nclass VariablesWrapper(object):\n    def __init__(self):\n        self._original = {}\n\n    def set(self, name, value):\n        if name not in self._original:\n            self._original[name] = wvariables.get(name)\n        wvariables.set(name, value)\n\n    def get(self, name):\n        return wvariables.get(name)\n\n    def restore(self):\n        for name, value in self._original.items():\n            wvariables.set(name, value)\n        self._original.clear()\n\n\n@pytest.fixture()\ndef variables():\n    vars = VariablesWrapper()\n    yield vars\n    vars.restore()\n\n\n@pytest.fixture(scope='session')\ndef qapp(wm, qapp_args):\n    _app_requires()\n    global _app\n    # TODO FIXME use another path for tests\n    conf_path = os.path.join(os.path.expanduser(\"~\"), \".webmacs\")\n    _app = Application(conf_path, [\"webmacs\"])\n    return _app\n\n\nclass TestSession(object):\n    NAV_HIGHLIGHT_COLOR = 'rgb(136, 255, 0)'\n\n    def __init__(self, qtbot, qapp, prompt_exec):\n        self.qtbot = qtbot\n        self.qapp = qapp\n        self.prompt_exec = prompt_exec\n\n    def set_prompt_exec(self, fn):\n        self.prompt_exec.side_effect = fn\n\n    def waiter(self):\n        return Waiter(self)\n\n    def call_next(self, fn):\n        QTimer.singleShot(0, fn)\n\n    @property\n    def buffer(self):\n        return current_buffer()\n\n    @property\n    def window(self):\n        return current_window()\n\n    @property\n    def minibuffer(self):\n        return current_minibuffer()\n\n    @property\n    def minibuffer_input(self):\n        return self.minibuffer.input()\n\n    def wait_signal(self, *args, **kwargs):\n        return self.qtbot.wait_signal(*args, **kwargs)\n\n    def wait_until(self, func, wait=2.0, delay=0.01):\n        delay = int(delay * 1000)\n        end = time.time() + wait\n        while not func():\n            QTest.qWait(delay)\n            if time.time() > end:\n                return False\n        return True\n\n    def test_page_url(self, name):\n        return \"file://\" + get_test_page(name)\n\n    def load_page(self, name, buffer=None, wait_iframes=False):\n        buffer = buffer or self.buffer\n        with self.wait_signal(buffer.loadFinished):\n            buffer.load(self.test_page_url(name))\n\n        script = (\n            \"__webmacs_loaded = window.__webmacsHandler__ !== null;\"\n            \"if (! __webmacs_loaded) {\"\n            \"  document.addEventListener('_webmacs_external_created',\"\n            \"                             function() {\"\n            \"    __webmacs_loaded = true;\"\n            \"  });\"\n            \" }\"\n        )\n        buffer.runJavaScript(script)\n        self.check_javascript(\"__webmacs_loaded\", True)\n\n        if wait_iframes:\n            self.wait_iframes(buffer=buffer)\n\n    def check_javascript(self, script, return_value, buffer=None):\n        buffer = buffer or self.buffer\n        result = [None]\n\n        if return_value is None:\n            raise ValueError(\"return value can't be None\")\n\n        def ready():\n            if result[0] == return_value:\n                return True\n            buffer.runJavaScript(script, lambda r: result.__setitem__(0, r))\n\n        assert self.wait_until(ready), \"javascript result was %r\" % result[0]\n        return True\n\n    def wait_hints_ready(self):\n        return self.qtbot.wait_signal(\n            self.buffer.content_handler.browserObjectsInited,\n            timeout=3000,\n            raising=True\n        )\n\n    def check_nav_highlighted(self, js_elem):\n        self.check_javascript(\"%s.style.backgroundColor\" % js_elem,\n                              self.NAV_HIGHLIGHT_COLOR)\n\n    def wait_iframes(self, buffer=None):\n        buffer = buffer or self.buffer\n        script = (\n            \"var result = true;\"\n            \"for (var i = 0; i < window.frames.length; i++) { \"\n            \"  if (window.frames[i].document.readyState != 'complete') {\"\n            \"    result = false;\"\n            \"  }\"\n            \"}\"\n            \"result;\"\n        )\n        self.check_javascript(script, True, buffer=buffer)\n\n    def keyclick(self, key, **kwargs):\n        QTest.keyClick(self.qapp.focusWindow(), key, **kwargs)\n\n    def keyclicks(self, keys, **kwargs):\n        for key in keys:\n            self.keyclick(key, **kwargs)\n\n    def wkeyclicks(self, shortcut, widget=None):\n        widget = widget or self.qapp.focusWindow()\n        keys = [KeyPress.from_str(k) for k in shortcut.split()]\n        for key in keys:\n            evt = key.to_qevent(QEvent.Type.KeyPress)\n            self.keyclick(key.key, modifier=evt.modifiers())\n\n\nclass Waiter(object):\n    def __init__(self, session):\n        self.session = session\n        self.end = False\n\n    def set(self):\n        self.end = True\n\n    def wait(self, wait=5, **kwargs):\n        kwargs[\"wait\"] = wait\n        return self.session.wait_until(lambda: self.end, **kwargs)\n\n\n@pytest.yield_fixture()\ndef session(qtbot, qapp, mocker):\n    # do not close the application on last window closed\n    mocker.patch(\"webmacs.WindowsHandler._on_last_window_closing\") \\\n        .return_value = False\n\n    prompt_exec = mocker.patch(\"webmacs.minibuffer.prompt._prompt_exec\")\n    sess = TestSession(qtbot, qapp, prompt_exec)\n\n    window = Window()\n    WINDOWS_HANDLER.current_window = window\n    window.current_webview().setBuffer(create_buffer())\n\n    window.show()\n    qtbot.waitForWindowShown(window)\n\n    yield sess\n\n    for w in windows():\n        w.current_webview().setBuffer(None)\n        w.close()\n        w.deleteLater()\n\n    for buffer in buffers():\n        close_buffer(buffer)\n\n    qapp.processEvents()\n"
  },
  {
    "path": "tests/integration/iframe_follow/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>iframe testing</title>\n  </head>\n  <body>\n\n    <input id=\"input0\" type=\"text\" name=\"fname\"><br>\n    <iframe name=\"frame0\" src=\"./my_iframe.html\" frameborder=\"0\">\n    </iframe>\n    <a id=\"a_top\" href=\"https://foo/top.html\">top</a>\n\n  </body>\n</html>\n"
  },
  {
    "path": "tests/integration/iframe_follow/my_iframe.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>inside iframe</title>\n  </head>\n  <body>\n    <input id=\"input0\" type=\"text\" name=\"in-iframe\"><br>\n    <a id=\"a_inside\" href=\"https://foo/inside.html\">inside link</a>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/integration/javascript_prompt/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>inside iframe</title>\n    <script type=\"text/javascript\">\n      function fillResult(result) {\n        document.getElementById('result').textContent = result;\n      }\n\n      function getContent(clear) {\n        var res = document.getElementById('result');\n        return res.textContent;\n      }\n    </script>\n  </head>\n  <body>\n    \n    <div id=\"result\"></div>\n    <br/>\n\n    <button onclick=\"fillResult(window.confirm('hello there'))\">prompt</button>\n    <button onclick=\"window.alert('hello there')\">alert</button>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/integration/navigation/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>page index</title>\n  </head>\n  <body>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/integration/navigation/page1.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>first page</title>\n  </head>\n  <body>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/integration/test_copy_link.py",
    "content": "from webmacs.keyboardhandler import CommandContext\nfrom webmacs.application import app\nfrom webmacs.commands import COMMANDS\n\n\ndef clipboard_contains(text):\n    return app().clipboard().text() == text\n\n\ndef test_copy_current_link(session):\n    session.load_page(\"iframe_follow\", wait_iframes=True)\n\n    link = \"document.getElementById('a_top')\"\n\n    session.buffer.runJavaScript(\"%s.focus()\" % link)\n    session.check_javascript(\"document.activeElement == %s\" % link, True)\n\n    COMMANDS[\"copy-current-link\"](CommandContext())\n\n    assert session.wait_until(\n        lambda: clipboard_contains(\"https://foo/top.html\")\n    )\n\n\ndef test_copy_current_link_in_subframe(session):\n    session.load_page(\"iframe_follow\", wait_iframes=True)\n\n    link = \"window.frames[0].document.getElementById('a_inside')\"\n\n    session.buffer.runJavaScript(\"%s.focus()\" % link)\n\n    session.check_javascript(\n        \"document.activeElement.tagName\",\n        'IFRAME'\n    )\n    session.check_javascript(\n        \"window.frames[0].document.activeElement == %s\" % link,\n        True\n    )\n\n    COMMANDS[\"copy-current-link\"](CommandContext())\n\n    assert session.wait_until(\n        lambda: clipboard_contains(\"https://foo/inside.html\")\n    )\n\n\ndef test_copy_current_url(session):\n    session.load_page(\"iframe_follow\")\n    url = session.buffer.url().toString()\n\n    COMMANDS[\"copy-current-buffer-url\"](CommandContext())\n\n    assert session.wait_until(\n        lambda: clipboard_contains(url)\n    )\n\n\ndef test_copy_current_title(session):\n    session.load_page(\"iframe_follow\")\n\n    COMMANDS[\"copy-current-buffer-title\"](CommandContext())\n\n    assert session.wait_until(\n        lambda: clipboard_contains(\"iframe testing\")\n    )\n"
  },
  {
    "path": "tests/integration/test_iframe_navigation.py",
    "content": "import pytest\n\n\nINPUT0 = \"document.getElementById('input0')\"\nINPUT0_IFRAME = \"window.frames[0].document.getElementById('input0')\"\n\n\ndef test_iframe_navigation(session):\n    \"\"\"\n    Webcontent-edit keymaps are used even in sub frames.\n    \"\"\"\n    session.load_page(\"iframe_follow\", wait_iframes=True)\n\n    session.wkeyclicks(\"Tab\")\n    session.check_javascript(\"%s === document.activeElement\" % INPUT0, True)\n\n    # type some text in INPUT0 and move word backward\n\n    session.keyclicks(\"hello world\")\n    session.check_javascript(\"%s.value\" % INPUT0, \"hello world\")\n    session.check_javascript(\"%s.selectionEnd\" % INPUT0, 11)\n    session.wkeyclicks(\"M-b\")\n    session.check_javascript(\"%s.selectionEnd\" % INPUT0, 6)\n\n    session.wkeyclicks(\"Tab\")\n    session.check_javascript(\"%s === window.frames[0].document.activeElement\"\n                             % INPUT0_IFRAME, True)\n\n    # type some text in INPUT0  inside the iframe and move word backward\n    session.keyclicks(\"hello world2\")\n    session.check_javascript(\"%s.value\" % INPUT0_IFRAME, \"hello world2\")\n    session.check_javascript(\"%s.selectionEnd\" % INPUT0_IFRAME, 12)\n    session.wkeyclicks(\"M-b\")\n    session.check_javascript(\"%s.selectionEnd\" % INPUT0_IFRAME, 6)\n\n\n@pytest.mark.parametrize(\"hint_method\", [\"filter\", \"alphabet\"])\ndef test_iframe_follow(session, pytestconfig, hint_method, variables):\n    \"\"\"\n    It is possible to hint things inside sub frames.\n    \"\"\"\n    variables.set(\"hint-method\", hint_method)\n    session.load_page(\"iframe_follow\", wait_iframes=True)\n\n    end_waiter = session.waiter()\n\n    def do_check():\n        session.check_javascript(\n            \"%s === window.frames[0].document.activeElement\"\n            % INPUT0_IFRAME, True)\n        session.keyclicks(\"youhou\")\n\n        session.check_javascript(\"%s.value\" % INPUT0_IFRAME, \"youhou\")\n        end_waiter.set()\n\n    def prompt_follow(prompt, _):\n        wait_hint.wait()\n        if hint_method == \"filter\":\n            session.wkeyclicks(\"C-n\")\n            # wait until the background color is green, the above keypress has\n            # been taken in account.\n            session.check_nav_highlighted(INPUT0_IFRAME)\n\n            with session.wait_signal(prompt.closed):\n                session.wkeyclicks(\"Enter\")\n        else:\n            with session.wait_signal(prompt.closed):\n                session.keyclick(\"d\")\n\n        session.call_next(do_check)\n\n    session.set_prompt_exec(prompt_follow)\n    wait_hint = session.wait_hints_ready()\n    session.wkeyclicks(\"f\")\n    end_waiter.wait()\n"
  },
  {
    "path": "tests/integration/test_javascript_prompt.py",
    "content": "import pytest\n\n\ndef check_js_result(res):\n    def check(session):\n        session.check_javascript(\"getContent();\", res)\n    return check\n\n\ndef check_minibuffer(res):\n    def check(session):\n        assert session.wait_until(\n            lambda: session.minibuffer.label.text() == res\n        )\n    return check\n\n\n@pytest.mark.parametrize(\"selection,input,check\", [\n    # first variable is what is typed in follow command,\n    # to select the right button to click.\n    (\"pro\", \"y\", check_js_result(\"true\")),\n    (\"pro\", \"n\", check_js_result(\"false\")),\n    (\"aler\", None, check_minibuffer(\"[js-alert] hello there\")),\n])\ndef test_confirm(session, selection, input, check):\n    \"\"\"\n    test javascript confirm.\n    \"\"\"\n    session.load_page(\"javascript_prompt\")\n    end_waiter = session.waiter()\n\n    def prompt_follow(prompt, _):\n        session.keyclicks(selection)\n        session.set_prompt_exec(confirm)\n        with session.wait_signal(prompt.closed):\n            session.wkeyclicks(\"Enter\")\n        if not input:\n            session.call_next(do_check)\n\n    def confirm(prompt, _1):\n        with session.wait_signal(prompt.closed):\n            session.keyclicks(input)\n\n        session.call_next(do_check)\n\n    def do_check():\n        check(session)\n        end_waiter.set()\n\n    session.set_prompt_exec(prompt_follow)\n    session.wkeyclicks(\"f\")\n    end_waiter.wait()\n"
  },
  {
    "path": "tests/integration/test_navigation.py",
    "content": "from webmacs import BUFFERS\nfrom webmacs.webbuffer import create_buffer\n\n\ndef test_cycle_buffers(session):\n    \"\"\"\n    Webcontent-edit keymaps are used even in sub frames.\n    \"\"\"\n    session.load_page(\"navigation\")\n    session.load_page(\"navigation/page1.html\", buffer=create_buffer())\n\n    def on_index_page():\n        return session.buffer.title() == \"page index\"\n\n    def on_first_page():\n        return session.buffer.title() == \"first page\"\n\n    assert len(BUFFERS) == 2\n    assert on_index_page()\n\n    session.wkeyclicks(\"M-n\")\n    assert session.wait_until(on_first_page)\n\n    session.wkeyclicks(\"M-n\")\n    assert session.wait_until(on_index_page)\n\n    session.wkeyclicks(\"M-p\")\n    assert session.wait_until(on_first_page)\n\n    session.wkeyclicks(\"M-p\")\n    assert session.wait_until(on_index_page)\n"
  },
  {
    "path": "tests/integration/test_user_download_dir.py",
    "content": "import pytest\nimport os\n\nfrom webmacs import download_manager\n\n# should be more or less in unit test section, but uses the variables fixture.\n\n\ndef test_get_user_download_dir(variables, tmpdir):\n    # by default, no custom user download dir\n    assert download_manager.get_user_download_dir() is None\n\n    d1 = str(tmpdir.mkdir(\"d1\"))\n    d2 = str(tmpdir.mkdir(\"d2\"))\n\n    download_manager.TEMPORARY_DOWNLOAD_DIR = d2\n\n    # if default-download-_dir is set, use it\n    variables.set(\"default-download-dir\", d1)\n    assert download_manager.get_user_download_dir() == d1\n\n    # if keep-temporary-download-dir is set, it takes precendence\n    variables.set(\"keep-temporary-download-dir\", True)\n    assert download_manager.get_user_download_dir() == d2\n\n    variables.set(\"default-download-dir\", \"\")\n    assert download_manager.get_user_download_dir() == d2\n\n\n@pytest.mark.parametrize(\"fname,expected\", [\n    (\"/path/to\", (\"/path\", \"to\")),\n    (\"/path/to(1)\", (\"/path\", \"to\")),\n    (\"/path/to(3)\", (\"/path\", \"to\")),\n    (\"/path/to.txt\", (\"/path\", \"to.txt\")),\n    (\"/path/to(1).txt\", (\"/path\", \"to.txt\")),\n    (\"/path/to(3).tar.gz\", (\"/path\", \"to.tar.gz\")),\n])\ndef test_extract_suggested_filename(fname, expected):\n    assert download_manager.extract_suggested_filename(fname) == expected\n\n\n@pytest.mark.parametrize(\"files, filename, expected\", [\n    ([], \"toto\", \"toto\"),\n    ([\"toto\"], \"toto\", \"toto(1)\"),\n    ([], \"toto.txt\", \"toto.txt\"),\n    ([\"toto.txt\"], \"toto.txt\", \"toto(1).txt\"),\n    ([\"toto.tar.gz\", \"toto(1).tar.gz\"], \"toto.tar.gz\", \"toto(2).tar.gz\"),\n])\ndef test_find_unique_suggested_path(tmpdir, files, filename, expected):\n    for name in files:\n        tmpdir.join(name).ensure(file=True)\n\n    dir = str(tmpdir)\n\n    assert download_manager.find_unique_suggested_path(dir, filename) \\\n        == os.path.join(dir, expected)\n"
  },
  {
    "path": "tests/test_prompt_history.py",
    "content": "from webmacs.minibuffer.prompt import PromptHistory\n\n\ndef test_history():\n    p = PromptHistory(maxsize=10)\n    # calling next or previous on empty history is alright\n    assert p.get_next() == \"\"\n    assert p.get_previous() == \"\"\n    assert p.in_user_value()  # we are in user value\n\n    # insert some values, a bit more than what the buffer can store\n    for i in range(12):\n        p.push(str(\"test_%d\" % i))\n\n    # playing around with next/previous\n    assert p.get_previous() == \"test_11\"\n    assert p.get_previous() == \"test_10\"\n    assert p.get_next() == \"test_11\"\n    assert not p.in_user_value()\n\n    # we get back in user value when we do an equal amount of next/previous\n    # calls\n    assert p.get_next() == \"\"\n    assert p.in_user_value()\n\n    # test the custom user value\n    p.set_user_value(\"foobar\")\n\n    assert p.get_next() == \"test_2\"\n    assert not p.in_user_value()\n\n    assert p.get_previous() == \"foobar\"\n    assert p.in_user_value()\n\n    assert p.get_next() == \"test_2\"\n    assert not p.in_user_value()\n\n    # resetting put the state back to initial, including the custom user value\n    p.reset()\n    assert p.in_user_value()\n    assert p.get_next() == \"test_2\"\n    assert p.get_previous() == \"\"\n"
  },
  {
    "path": "tests/test_variables.py",
    "content": "import pytest\n\nfrom webmacs.variables import (\n    VariableConditionError, String, Int, Bool, Float, List, Tuple, Dict\n)\n\n\ndef check_type_error(type, value, regex):\n    with pytest.raises(VariableConditionError) as ei:\n        type.validate(value)\n\n    assert ei.match(regex)\n\n\ndef test_type_string():\n    s = String()\n    s.validate(\"\")\n    s.validate(\"hello\")\n    check_type_error(s, 1, r\"Must be a string\")\n\n    s = String(choices=[\"aha\", \"hoho\"])\n    s.validate(\"aha\")\n    s.validate(\"hoho\")\n    check_type_error(s, 1, r\"Must be a string\")\n    check_type_error(s, \"invalid\", r\"Must be one of \\('aha', 'hoho'\\)\")\n\n\ndef test_type_int():\n    i = Int()\n    i.validate(-5)\n    i.validate(0)\n    i.validate(5)\n    check_type_error(i, \"1\", r\"Must be an integer\")\n\n    i = Int(min=0, max=5)\n    i.validate(0)\n    i.validate(1)\n    i.validate(5)\n    check_type_error(i, \"1\", r\"Must be an integer\")\n    check_type_error(i, 6, r\"Must be lesser or equal to 5\")\n    check_type_error(i, -1, r\"Must be greater or equal to 0\")\n\n\ndef test_type_bool():\n    b = Bool()\n    b.validate(True)\n    b.validate(False)\n\n\ndef test_type_list():\n    l = List(Float(min=0.0))  # noqa: E741\n    l.validate([])\n    l.validate([1.1, 6.1])\n    check_type_error(l, 123, \"Must be a list\")\n    check_type_error(l, [2.3, \"1\"], r\"List at position 1: Must be a float\")\n    check_type_error(l, [-2.3, 3.2],\n                     r\"List at position 0: Must be greater or equal to 0.0\")\n\n\ndef test_type_dict():\n    d = Dict(String(), Tuple(Int(), Float(min=0.0, max=1.1)))\n    d.validate({})\n    d.validate({\"1\": (1, 0.5)})\n    check_type_error(d, 123, \"Must be a dict\")\n    check_type_error(d, {\"1\": (1,)},\n                     \"Value for key '1': Must be a tuple of size 2\")\n"
  },
  {
    "path": "webmacs/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport importlib\n\nfrom PyQt6.QtCore import QObject, QEvent, QTimer\n\nfrom . import hooks\n\n\n__version__ = '0.9'\n\n\n# access to every opened buffers\nBUFFERS = []\n\n# dictionary of all known commands\nCOMMANDS = {}\n\n\ndef require(module, package=__package__):\n    return importlib.import_module(module, package)\n\n\n# handler for windows, to be able to list them and determine the one currently\n# active.\nclass WindowsHandler(QObject):\n    def __init__(self, parent=None):\n        QObject.__init__(self, parent)\n        self.windows = []\n        self.current_window = None\n\n    def _on_last_window_closing(self):\n        # last window is closed, do not remove it from the list but exit the\n        # application. This is required from proper session saving.\n        from .application import app\n        app().quit()\n        return True\n\n    def register_window(self, window):\n        window.installEventFilter(self)\n        self.windows.append(window)\n\n    def eventFilter(self, window, event):\n        t = event.type()\n        if t == QEvent.Type.WindowActivate:\n            self.current_window = window\n            hooks.window_activated(window)\n        elif t == QEvent.Type.Close:\n            if window.quit_if_last_closed and len(self.windows) == 1:\n                if self._on_last_window_closing():\n                    return True\n            self.windows.remove(window)\n            window.deleteLater()\n            if window == self.current_window:\n                self.current_window = None\n            hooks.window_closed(window)\n\n        return QObject.eventFilter(self, window, event)\n\n\nWINDOWS_HANDLER = WindowsHandler()\n\n\ndef windows():\n    \"\"\"\n    Returns the window list.\n\n    Do not modify this list.\n    \"\"\"\n    return WINDOWS_HANDLER.windows\n\n\ndef current_window():\n    \"\"\"\n    Returns the currently activated window.\n    \"\"\"\n    return WINDOWS_HANDLER.current_window\n\n\ndef current_buffer():\n    \"\"\"\n    Returns the current buffer.\n    \"\"\"\n    w = current_window()\n    if w:\n        return w.current_webview().buffer()\n\n\ndef buffers():\n    \"Returns the list of buffers.\"\n    return BUFFERS\n\n\ndef recent_buffers():\n    \"\"\"\n    Returns an iterable of buffers, most recently used first.\n    \"\"\"\n    return sorted(BUFFERS, key=lambda b: b.last_use, reverse=True)\n\n\ndef current_minibuffer():\n    \"\"\"\n    Returns the current minibuffer.\n    \"\"\"\n    w = current_window()\n    if w:\n        return w.minibuffer()\n\n\ndef minibuffer_show_info(text):\n    \"\"\"\n    Display text information in the current minibuffer.\n    \"\"\"\n    minibuffer = current_minibuffer()\n    if minibuffer:\n        minibuffer.show_info(text)\n\n\ndef call_later(fn, msec=0):\n    \"\"\"\n    Call the given function after the given time interval.\n\n    If msec is 0, the function call is still delayed to the next handling of\n    events in the qt event loop.\n    \"\"\"\n    QTimer.singleShot(msec, fn)\n\n\nclass ObjRef(object):\n    \"\"\"\n    Maintain object references.\n    \"\"\"\n    __slots__ = (\"__refs\",)\n\n    def __init__(self):\n        self.__refs = {}\n\n    def ref(self, obj, data=True):\n        self.__refs[obj] = data\n\n    def unref(self, obj):\n        return self.__refs.pop(obj)\n\n\n# Sometimes we need to keep objects around with pyqt to avoid segfault;\n# This global object holder is designed to allow that.\nGLOBAL_OBJECTS = ObjRef()\n"
  },
  {
    "path": "webmacs/adblock.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport logging\nimport time\nimport json\n\nfrom datetime import datetime, timezone\nimport dateparser\n\nfrom _adblock import AdBlock\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport urllib.request\nfrom . import variables\nfrom .task import Task\n\nfrom PyQt6.QtNetwork import QNetworkRequest, QNetworkReply\nfrom PyQt6.QtCore import QUrl, QThreadPool, pyqtSignal as Signal, Qt\n\n\nDEFAULT_EASYLIST = [\n    \"https://easylist.to/easylist/easylist.txt\",\n    # easyprivacy blocks too much right now\n    # \"https://easylist.to/easylist/easyprivacy.txt\",\n    \"https://easylist.to/easylist/fanboy-annoyance.txt\"\n]\n\nadblock_urls_rules = variables.define_variable(\n    \"adblock-urls-rules\",\n    \"A list of urls to get rules for ad-blocking (using the Adblock format).\"\n    \" The default urls are taken from the easylist site https://easylist.to.\",\n    DEFAULT_EASYLIST,\n    type=variables.List(variables.String()),\n)\n\n\ndef cache_file(cache_path):\n    return os.path.join(cache_path, \"cache.dat\")\n\n\nclass AdBlockUpdateTask(Task):\n    adblock_ready = Signal(AdBlock)\n\n    def __init__(self, app, cache_path, ):\n        Task.__init__(self)\n        self.app = app\n        if not os.path.isdir(cache_path):\n            os.makedirs(cache_path)\n        self._cache_path = cache_path\n        self._cached_urls_path = os.path.join(self._cache_path, \"urls.json\")\n        self._cache_file = cache_file(cache_path)\n        self._user_urls = {\n            url: os.path.join(self._cache_path, url.rsplit(\"/\", 1)[-1])\n            for url in adblock_urls_rules.value\n        }\n\n        self.adblock_ready.connect(self._on_adblock_ready,\n                                   Qt.ConnectionType.BlockingQueuedConnection)\n\n        self._adblock = None\n        self._replies = {}\n        self._modified = False\n        self.__thread_running = False\n\n    def start(self):\n        to_download = [(url, path) for url, path in self._user_urls.items()\n                       if not os.path.isfile(path)\n                       or (os.path.getmtime(path) + 3600) < time.time()]\n        for url, path in to_download:\n            reply = self.app.network_manager.get(QNetworkRequest(QUrl(url)))\n            reply.readyRead.connect(self._dl_ready_read)\n            reply.finished.connect(self._dl_finished)\n            self._replies[reply] = {\"path\": path}\n        self._maybe_finish()\n\n    def _maybe_finish(self):\n        if self._replies:\n            return\n\n        if not self._modified:\n            try:\n                with open(self._cached_urls_path) as f:\n                    cached_urls = json.load(f)\n            except FileNotFoundError:\n                self._modified = True\n            except Exception:\n                logging.exception(\"Could not load cached urls. Removing %s.\"\n                                  % self._cached_urls_path)\n                os.unlink(self._cached_urls_path)\n                self._modified = True\n            else:\n                if cached_urls != self._user_urls or not os.path.exists(self._cache_file):\n                    self._modified = True\n\n        self.__thread_running = True\n        QThreadPool.globalInstance().start(\n            self._parse_adblock_files if self._modified else self._adblock_from_cache)\n\n    def _adblock_from_cache(self):\n        adblock = AdBlock()\n        adblock.load(self._cache_file)\n        self.adblock_ready.emit(adblock)\n\n    def _parse_adblock_files(self):\n        adblock = AdBlock()\n        for path in self._user_urls.values():\n            logging.info(\"parsing adblock file: %s\", path)\n            try:\n                with open(path) as f:\n                    adblock.parse(f.read())\n            except Exception:\n                logging.exception(f\"Unable to parse {f.name} adblock file\")\n            adblock.save(self._cache_file)\n        self.adblock_ready.emit(adblock)\n\n    def _on_adblock_ready(self, adblock):\n        self.__thread_running = False\n        with open(self._cached_urls_path, \"w\") as f:\n            json.dump(self._user_urls, f)\n        self._adblock = adblock\n        self.finished.emit()\n\n    def adblock(self):\n        return self._adblock\n\n    def _dl_ready_read(self):\n        reply = self.sender()\n        data = self._replies[reply]\n        if \"file\" not in data:\n            headers = {bytes(k).lower(): bytes(v)\n                       for k, v in reply.rawHeaderPairs()}\n            if os.path.isfile(data[\"path\"]):\n                try:\n                    last_modified = dateparser.parse(\n                        headers[b\"last-modified\"].decode(\"utf-8\"),\n                        languages=[\"en\"])\n                except Exception:\n                    logging.exception(\n                        \"Unable to parse the last-modified header for %s\",\n                        reply.url().toString())\n                else:\n                    file_time = datetime.fromtimestamp(\n                        os.path.getmtime(data[\"path\"]), timezone.utc)\n                    if last_modified < file_time:\n                        logging.info(\"no need to download adblock rule: %s\", url)\n                        # touch on the file\n                        os.utime(path, None)\n                        self._close_reply(reply)\n                        self._maybe_finish()\n                        return\n            logging.info(\"downloading adblock rule: %s\", reply.url().toString())\n            data[\"file\"] = open(data[\"path\"], \"w\")\n\n        data[\"file\"].write(bytes(reply.readAll()).decode(\"utf-8\"))\n\n    def _dl_finished(self):\n        reply = self.sender()\n        self._modified = True\n        data = self._replies.pop(reply)\n        data[\"file\"].close()\n        self._maybe_finish()\n\n    def _close_reply(self, reply):\n        del self._replies[reply]\n        reply.readyRead.disconnect(self._dl_ready_read)\n        reply.finished.disconnect(self._dl_finished)\n        reply.close()\n\n    def abort(self):\n        for reply, data in list(self._replies.items()):\n            self._close_reply(reply)\n            if \"file\" in data:\n                data[\"file\"].close()\n                os.unlink(data[\"path\"])\n        # wait for any thread to join\n        if self.__thread_running:\n            QThreadPool.globalInstance().waitForDone(1000)\n"
  },
  {
    "path": "webmacs/application.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport logging\n\nfrom PyQt6.QtCore import pyqtSlot as Slot, Qt\n\nfrom PyQt6.QtWebEngineCore import QWebEngineUrlRequestInterceptor\nfrom PyQt6.QtWidgets import QApplication\nfrom PyQt6.QtNetwork import QNetworkAccessManager\n\nfrom . import require, version\nfrom .task import TaskRunner\nfrom .adblock import AdBlockUpdateTask, adblock_urls_rules, AdBlock\nfrom .download_manager import DownloadManager\nfrom .profile import named_profile\nfrom .minibuffer.right_label import init_minibuffer_right_labels\nfrom .keyboardhandler import LOCAL_KEYMAP_SETTER\nfrom .spell_checking import SpellCheckingTask, \\\n    spell_checking_dictionaries\nfrom .scheme_handlers import register_schemes\n\n\nif version.is_linux:\n    # workaround for a nvidia issue\n    # see https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826\n    import ctypes\n    import ctypes.util\n    ctypes.CDLL(ctypes.util.find_library(\"GL\"), mode=ctypes.RTLD_GLOBAL)\n\n\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\nclass UrlInterceptor(QWebEngineUrlRequestInterceptor):\n    def __init__(self, app):\n        QWebEngineUrlRequestInterceptor.__init__(self)\n        self._adblock = AdBlock()\n        self._use_adblock = True\n\n    @Slot(object)\n    def update_adblock(self, adblock):\n        self._adblock = adblock\n\n    def toggle_use_adblock(self):\n        self._use_adblock = not self._use_adblock\n\n    def interceptRequest(self, request):\n        url = request.requestUrl()\n        url_s = url.toString()\n        if (self._use_adblock\n            and self._adblock.matches(\n                url_s,\n                request.firstPartyUrl().toString())):\n            logging.info(\"filtered: %s\", url_s)\n            request.block(True)\n\n\nclass WithoutAppEventFilter(object):\n    def __enter__(self):\n        app().removeEventFilter(LOCAL_KEYMAP_SETTER)\n\n    def __exit__(self, type, value, traceback):\n        app().installEventFilter(LOCAL_KEYMAP_SETTER)\n\n\ndef app():\n    return Application.INSTANCE\n\n\ndef _app_requires():\n    require(\".commands.follow\")\n    require(\".commands.buffer_history\")\n    require(\".commands.global\")\n    require(\".commands.isearch\")\n    require(\".commands.webbuffer\")\n    require(\".commands.caret_browsing\")\n    require(\".commands.content_edit\")\n    require(\".commands.minibuffer\")\n\n    require(\".default_webjumps\")\n\n    require(\".keymaps.global\")\n    require(\".keymaps.caret_browsing\")\n    require(\".keymaps.content_edit\")\n    require(\".keymaps.fullscreen\")\n    require(\".keymaps.minibuffer\")\n    require(\".keymaps.hints\")\n    require(\".keymaps.isearch\")\n    require(\".keymaps.webbuffer\")\n\n\nclass Application(QApplication):\n    INSTANCE = None\n\n    def __init__(self, conf_path, args, instance_name=\"default\",\n                 profile_name=\"default\", off_the_record=False):\n        QApplication.__init__(self, args)\n        self.__class__.INSTANCE = self\n        self.instance_name = instance_name\n        self.task_runner = TaskRunner()\n\n        if version.is_mac:\n            self.setAttribute(\n                Qt.ApplicationAttribute.AA_MacDontSwapCtrlAndMeta)\n\n        register_schemes()\n\n        self._conf_path = conf_path\n        if not os.path.isdir(self.profiles_path()):\n            os.makedirs(self.profiles_path())\n\n        self._interceptor = UrlInterceptor(self)\n\n        self._download_manager = DownloadManager(self)\n\n        self.profile = named_profile(profile_name,\n                                     off_the_record=off_the_record)\n\n        self.installEventFilter(LOCAL_KEYMAP_SETTER)\n\n        self.setQuitOnLastWindowClosed(False)\n\n        self.network_manager = QNetworkAccessManager(self)\n\n        self.aboutToQuit.connect(self.task_runner.stop)\n\n    def conf_path(self):\n        return self._conf_path\n\n    def profiles_path(self):\n        return os.path.join(self.conf_path(), \"profiles\")\n\n    def adblock_path(self):\n        return os.path.join(self.conf_path(), \"adblock\")\n\n    def visitedlinks(self):\n        return self.profile.visitedlinks\n\n    def bookmarks(self):\n        return self.profile.bookmarks\n\n    def features(self):\n        return self.profile.features\n\n    def url_interceptor(self):\n        return self._interceptor\n\n    def download_manager(self):\n        return self._download_manager\n\n    def ignored_certs(self):\n        return self.profile.ignored_certs\n\n    def adblock_update(self):\n        if not adblock_urls_rules.value:\n            return\n\n        task = AdBlockUpdateTask(self, self.adblock_path())\n\n        def adblock_finished():\n            adblock = task.adblock()\n            if adblock:\n                self._interceptor.update_adblock(adblock)\n\n        task.finished.connect(adblock_finished)\n        self.task_runner.run(task)\n\n    def update_spell_checking(self):\n        if not bool(spell_checking_dictionaries.value):\n            return\n\n        spell_check_path = os.path.join(self._conf_path, \"spell_checking\")\n\n        def spc_finished(*a):\n            self.profile.update_spell_checking()\n\n        task = SpellCheckingTask(self, spell_check_path)\n        task.finished.connect(spc_finished)\n        self.task_runner.run(task)\n\n    def post_init(self):\n        self.adblock_update()\n        self.update_spell_checking()\n        init_minibuffer_right_labels()\n"
  },
  {
    "path": "webmacs/bookmarks.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport sqlite3\n\n\nclass Bookmarks(object):\n    def __init__(self, dbbath):\n        self._conn = sqlite3.connect(dbbath)\n        self._conn.execute(\"\"\"\n        CREATE TABLE IF NOT EXISTS bookmarks\n        (url TEXT PRIMARY KEY, name TEXT);\n        \"\"\")\n\n    def set(self, url, name):\n        self._conn.execute(\"\"\"\n        INSERT OR REPLACE INTO bookmarks (url, name)\n        VALUES (?, ?)\n        \"\"\", (url, name))\n        self._conn.commit()\n\n    def list(self):\n        return [r for r in self._conn.execute(\n            \"select url, name from bookmarks order by name\"\n        )]\n\n    def remove(self, url):\n        self._conn.execute(\"\"\"\n        DELETE from bookmarks WHERE url = ?\n        \"\"\", (url,))\n        self._conn.commit()\n"
  },
  {
    "path": "webmacs/clipboard.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtGui import QClipboard\n\nfrom . import variables, minibuffer_show_info\n\n\n_CLIPBOARD = None\n_COPY_MODE = None\n\n\ndef _clipboard():\n    global _CLIPBOARD\n    if _CLIPBOARD is None:\n        from .application import app\n        _CLIPBOARD = app().clipboard()\n    return _CLIPBOARD\n\n\nclass Mode:\n    PRIMARY = 1 << 0\n    SELECTION = 1 << 1\n    BOTH = PRIMARY | SELECTION\n\n    _from_str = {\n        \"primary\": PRIMARY,\n        \"selection\": SELECTION,\n        \"both\": BOTH,\n    }\n\n\ndef _copy_mode_from_var(v):\n    global _COPY_MODE\n    _COPY_MODE = Mode._from_str[v.value]\n\n\nclipboard_copy = variables.define_variable(\n    \"clipboard-copy\",\n    \"Where to copy text. Allowed values are 'primary', 'selection' or 'both'\"\n    \" Defaults to primary, which is the global clipboard. selection is for\"\n    \" clipboard mouse selection, and both will copy to both clipboards.\",\n    \"primary\",\n    type=variables.String(choices=tuple(Mode._from_str.keys())),\n    callbacks=(_copy_mode_from_var,)\n)\n\n_copy_mode_from_var(clipboard_copy)\n\n\ndef set_text(text, mode=None):\n    cb = _clipboard()\n    if mode is None:\n        mode = _COPY_MODE\n\n    if mode & Mode.PRIMARY:\n        cb.setText(text)\n\n    if mode & Mode.SELECTION:\n        cb.setText(text, QClipboard.Selection)\n\n    minibuffer_show_info(\"Copied: {}\".format(text))\n"
  },
  {
    "path": "webmacs/commands/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport inspect\n\nfrom .. import COMMANDS\nfrom .. import url_opener\n\n\nclass InteractiveCommand(object):\n    \"\"\"\n    A command to interact with the system.\n\n    A prompt class can be given to get an argument using the minibuffer prompt.\n\n    :param binding: a callable to run when invoking the command.\n    :param visible: whether or not to list the command using M-x\n    \"\"\"\n    __slots__ = (\"binding\", \"visible\")\n\n    def __init__(self, binding, visible=True):\n        self.binding = binding\n        self.visible = visible\n\n    def getdoc(self):\n        return inspect.getdoc(self.binding)\n\n    def __call__(self, ctx):\n        return self.binding(ctx)\n\n\ndef define_command(name, binding=None, **args):\n    \"\"\"\n    Register an interactive command.\n    \"\"\"\n    command = InteractiveCommand(binding, **args)\n    COMMANDS[name] = command\n    if binding is None:\n        def wrapper(func):\n            command.binding = func\n            return func\n        return wrapper\n\n\nclass Opener(object):\n    CURRENT_BUFFER = 1\n    NEW_BUFFER = 2\n    NEW_WINDOW = 3\n\n    def __init__(self, prompt_ctor):\n        self.prompt_ctor = prompt_ctor\n\n    def prompt_open(self, method, ctx):\n        prompt = self.prompt_ctor(ctx)\n        if method == self.NEW_BUFFER:\n            prompt.label += \" (new buffer)\"\n        elif method == self.NEW_WINDOW:\n            prompt.label += \" (new window)\"\n        return prompt\n\n    def open(self, method, ctx, prompt, url):\n        opts = {}\n        if method == self.NEW_BUFFER:\n            opts[\"new_buffer\"] = True\n        elif method == self.NEW_WINDOW:\n            opts[\"new_window\"] = True\n        url_opener.url_open(ctx, url, **opts)\n\n    def closed(self, method, ctx, prompt):\n        pass\n\n    def run(self, method, ctx):\n        prompt = self.prompt_open(method, ctx)\n        url = ctx.minibuffer.do_prompt(prompt)\n        if url:\n            self.open(method, ctx, prompt, url)\n        self.closed(method, ctx, prompt)\n\n\ndef register_prompt_opener_commands(name, opener, doc):\n    if not isinstance(opener, Opener):\n        opener = Opener(opener)\n\n    @define_command(name + \"-new-window\")\n    def open_new_window(ctx):\n        opener.run(Opener.NEW_WINDOW, ctx)\n\n    @define_command(name + \"-new-buffer\")\n    def open_new_buffer(ctx):\n        opener.run(Opener.NEW_BUFFER, ctx)\n\n    @define_command(name)\n    def open(ctx):\n        if ctx.current_prefix_arg == (4,):\n            return open_new_buffer(ctx)\n        elif ctx.current_prefix_arg == (16,):\n            return open_new_window(ctx)\n\n        opener.run(Opener.CURRENT_BUFFER, ctx)\n\n    open.__name__ = name.replace(\"-\", \"_\")\n    open_new_buffer.__name__ = open.__name__ + \"_new_buffer\"\n    open_new_window.__name__ = open.__name__ + \"_new_window\"\n\n    open.__doc__ = doc + \".\" + \"\\n\\n You can use <C-u> as a prefix to open\" \\\n        \" in a new buffer, or <C-u C-u> to open in a new window.\"\n    open_new_buffer.__doc__ = doc + \" in a new buffer.\"\n    open_new_window.__doc__ = doc + \" in a new window.\"\n"
  },
  {
    "path": "webmacs/commands/buffer_history.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtCore import QAbstractTableModel, QModelIndex, Qt\nfrom PyQt6.QtGui import QImage\nfrom PyQt6.QtNetwork import QNetworkRequest\n\nfrom .. import current_buffer\nfrom ..minibuffer import Prompt\nfrom ..commands import define_command\nfrom ..application import app\n\n\nclass BufferHistoryTableModel(QAbstractTableModel):\n    def __init__(self, history):\n        QAbstractTableModel.__init__(self)\n        self._history = history\n        nm = app().network_manager\n        self._icons = {}\n        for h in history:\n            reply = nm.get(QNetworkRequest(h.iconUrl()))\n            reply.finished.connect(self.icon_dl_finished)\n\n    def rowCount(self, index=QModelIndex()):\n        return len(self._history)\n\n    def columnCount(self, index=QModelIndex()):\n        return 2\n\n    def data(self, index, role=Qt.ItemDataRole.DisplayRole):\n        hitem = index.internalPointer()\n        if not hitem:\n            return\n\n        col = index.column()\n        if role == Qt.ItemDataRole.DisplayRole:\n            if col == 0:\n                return hitem.url().toString()\n            else:\n                return hitem.title()\n        elif role == Qt.ItemDataRole.DecorationRole and col == 0:\n            return self._icons.get(hitem.iconUrl())  # hitem.iconUrl()\n\n    def index(self, row, col, parent=QModelIndex()):\n        try:\n            return self.createIndex(row, col, self._history[row])\n        except IndexError:\n            return QModelIndex()\n\n    def icon_dl_finished(self):\n        reply = self.sender()\n        url = reply.request().url()\n\n        img = QImage()\n        img.loadFromData(reply.readAll())\n        if not img.isNull() and img.height() != 16 and img.width != 16:\n            img = img.scaled(16, 16, Qt.AspectRatioMode.KeepAspectRatio)\n\n        reply.deleteLater()\n\n        self._icons[url] = img\n        for i, item in enumerate(self._history):\n            if item.iconUrl() == url:\n                index = self.index(i, 0)\n                self.dataChanged.emit(index, index)\n\n\nclass BufferHistoryListPrompt(Prompt):\n    label = \"buffer history:\"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    value_return_index_data = True\n\n    def enable(self, minibuffer):\n        self.page_history = current_buffer().history()\n        # keep a python reference to the items\n        self._items = self.page_history.items()\n        Prompt.enable(self, minibuffer)\n        minibuffer.input().popup().selectRow(\n            self.page_history.currentItemIndex())\n\n    def completer_model(self):\n        return BufferHistoryTableModel(self._items)\n\n\n@define_command(\"buffer-history\")\ndef buffer_history(ctx):\n    \"\"\"\n    Prompt to navigate in the local buffer history.\n    \"\"\"\n    prompt = BufferHistoryListPrompt(ctx)\n    item = ctx.minibuffer.do_prompt(prompt)\n    if item:\n        prompt.page_history.goToItem(item)\n"
  },
  {
    "path": "webmacs/commands/caret_browsing.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtWebEngineCore import QWebEngineScript\n\nfrom . import define_command\n\n\ndef call_js(ctx, script):\n    ctx.buffer.runJavaScript(script,\n                             QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n\n@define_command(\"caret-browsing-init\")\ndef init(ctx):\n    \"\"\"\n    Init caret browsing in the current buffer.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.setInitialCursor();\")\n\n\n@define_command(\"caret-browsing-shutdown\")\ndef shutdown(ctx):\n    \"\"\"\n    Shutdown caret browsing in current buffer.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.shutdown();\")\n\n\n@define_command(\"caret-browsing-down\")\ndef down(ctx):\n    \"\"\"\n    Move the caret down a line.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'line');\")\n\n\n@define_command(\"caret-browsing-up\")\ndef up(ctx):\n    \"\"\"\n    Move the caret up a line.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'line');\")\n\n\n@define_command(\"caret-browsing-backward-char\")\ndef left_char(ctx):\n    \"\"\"\n    Move the caret one character backward.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'character');\")\n\n\n@define_command(\"caret-browsing-backward-word\")\ndef left_word(ctx):\n    \"\"\"\n    Move the caret one word backward.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'word');\")\n\n\n@define_command(\"caret-browsing-forward-char\")\ndef right_char(ctx):\n    \"\"\"\n    Move the caret one character forward.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'character');\")\n\n\n@define_command(\"caret-browsing-forward-word\")\ndef right_word(ctx):\n    \"\"\"\n    Move the caret one word forward.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'word');\")\n\n\n@define_command(\"caret-browsing-toggle-mark\")\ndef toggle_mark(ctx):\n    \"\"\"\n    Set or unset (toggle) the mark where the point is.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.toggleMark();\")\n\n\n@define_command(\"caret-browsing-cut\")\ndef copy(ctx):\n    \"\"\"\n    Cut the current caret selection.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.cutSelection();\")\n\n\n@define_command(\"caret-browsing-end-of-line\")\ndef end_of_line(ctx):\n    \"\"\"\n    Move the caret to the end of the current line.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'lineboundary');\")\n\n\n@define_command(\"caret-browsing-beginning-of-line\")\ndef beginning_of_line(ctx):\n    \"\"\"\n    Move the caret to the beginning of the current line.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'lineboundary');\")\n\n\n@define_command(\"caret-browsing-end-of-document\")\ndef end_of_document(ctx):\n    \"\"\"\n    Move the caret to the end of the document.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'documentboundary');\")\n\n\n@define_command(\"caret-browsing-beginning-of-document\")\ndef beginning_of_document(ctx):\n    \"\"\"\n    Move the caret to the beginning of the document.\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'documentboundary');\")\n\n\n@define_command(\"caret-browsing-forward-paragraph\")\ndef forward_paragraph(ctx):\n    \"\"\"\n    Move the caret to the next paragraph (TODO FIXME not working yet)\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('forward', 'paragraphboundary');\")\n\n\n@define_command(\"caret-browsing-backward-paragraph\")\ndef backward_paragraph(ctx):\n    \"\"\"\n    Move the caret to the previous paragraph (TODO FIXME not working yet)\n    \"\"\"\n    call_js(ctx, \"CaretBrowsing.move('backward', 'paragraphboundary');\")\n"
  },
  {
    "path": "webmacs/commands/content_edit.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtWebEngineCore import QWebEngineScript\nfrom PyQt6.QtCore import Qt, QEvent\nfrom PyQt6.QtGui import QKeyEvent\n\nfrom ..application import app\nfrom ..webbuffer import WebBuffer\nfrom . import define_command\n\n\ndef send_raw_key(ctx, key, with_ctrl=False, auto_shift=True):\n    a = app()\n    modifiers = Qt.KeyboardModifier.NoModifier\n    if auto_shift:\n        if ctx.buffer.hasSelection() and not ctx.buffer.text_edit_mark:\n            ctx.buffer.set_text_edit_mark(True)\n        if ctx.buffer.text_edit_mark:\n            modifiers |= Qt.KeyboardModifier.ShiftModifier\n    if with_ctrl:\n        modifiers |= Qt.KeyboardModifier.ControlModifier\n\n    w = app().focusWindow()\n    a.postEvent(w, QKeyEvent(QEvent.Type.KeyPress, key, modifiers))\n    a.postEvent(w, QKeyEvent(QEvent.Type.KeyRelease, key, modifiers))\n\n\ndef run_js(ctx, cmd, cb=None):\n    if cb:\n        ctx.buffer.runJavaScript(\n            cmd, QWebEngineScript.ScriptWorldId.ApplicationWorld, cb)\n    else:\n        ctx.buffer.runJavaScript(\n            cmd, QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n\n@define_command(\"content-edit-cancel\")\ndef cancel(ctx):\n    \"\"\"\n    If a mark is active, clear that but keep the focus. If there is no\n    active mark, then just unfocus the editable js object.\n    \"\"\"\n    if ctx.buffer.hasSelection():\n        run_js(ctx, \"textedit.clear_mark();\")\n    else:\n        run_js(ctx, \"textedit.blur();\")\n    ctx.buffer.set_text_edit_mark(False)\n\n\n@define_command(\"content-edit-set-mark\")\ndef set_mark(ctx):\n    \"\"\"\n    Set or clear the mark in browser text field.\n    \"\"\"\n    if ctx.buffer.hasSelection():\n        run_js(ctx, \"textedit.clear_mark();\")\n    ctx.buffer.set_text_edit_mark(\n        not ctx.buffer.text_edit_mark\n    )\n\n\n@define_command(\"content-edit-forward-char\")\ndef forward_char(ctx):\n    \"\"\"\n    Move one character forward in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_Right)\n\n\n@define_command(\"content-edit-backward-char\")\ndef backward_char(ctx):\n    \"\"\"\n    Move one character backward in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_Left)\n\n\n@define_command(\"content-edit-forward-word\")\ndef forward_word(ctx):\n    \"\"\"\n    Move one word forward in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_Right, with_ctrl=True)\n\n\n@define_command(\"content-edit-backward-word\")\ndef backward_word(ctx):\n    \"\"\"\n    Move one word backward in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_Left, with_ctrl=True)\n\n\n@define_command(\"content-edit-beginning-of-line\")\ndef move_beginning_of_line(ctx):\n    \"\"\"\n    Move to the beginning of the line in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_Home)\n\n\n@define_command(\"content-edit-end-of-line\")\ndef move_end_of_line(ctx):\n    \"\"\"\n    Move to the end of the line in browser text field.\n    \"\"\"\n    send_raw_key(ctx, Qt.Key.Key_End)\n\n\ndef delete_selection(ctx):\n    def wrapper(_):\n        send_raw_key(ctx, Qt.Key.Key_Backspace, auto_shift=False)\n        ctx.buffer.set_text_edit_mark(False)\n    return wrapper\n\n\n@define_command(\"content-edit-delete-forward-char\")\ndef delete_char(ctx):\n    \"\"\"\n    Delete one character forward in browser text field.\n    \"\"\"\n    run_js(\n        ctx,\n        \"textedit.select_text('forward', 'character');\",\n        delete_selection(ctx),\n    )\n\n\n@define_command(\"content-edit-delete-forward-word\")\ndef delete_word(ctx):\n    \"\"\"\n    Delete one word forward in browser text field.\n    \"\"\"\n    run_js(\n        ctx,\n        \"textedit.select_text('forward', 'word');\",\n        delete_selection(ctx),\n    )\n\n\n@define_command(\"content-edit-delete-backward-word\")\ndef delete_word_backward(ctx):\n    \"\"\"\n    Delete one word backward in browser text field.\n    \"\"\"\n    run_js(\n        ctx,\n        \"textedit.select_text('backward', 'word');\",\n        delete_selection(ctx),\n    )\n\n\n@define_command(\"content-edit-copy\")\ndef copy(ctx):\n    \"\"\"\n    Copy browser text field selection to the clipboard.\n    \"\"\"\n    ctx.buffer.set_text_edit_mark(False)\n    run_js(ctx, \"textedit.copy_text(true);\")\n\n\n@define_command(\"content-edit-cut\")\ndef cut(ctx):\n    \"\"\"\n    Cut browser text field selection to the clipboard.\n    \"\"\"\n    run_js(ctx, \"textedit.copy_text();\",\n           delete_selection(ctx))\n\n\n@define_command(\"content-edit-kill\")\ndef kill(ctx):\n    \"\"\"\n    Kill from the cursor to end of line to the clipboard.\n    \"\"\"\n    run_js(ctx,\n           \"textedit.select_text('forward', 'lineboundary'); \\\n           textedit.copy_text();\",\n           delete_selection(ctx))\n\n\n@define_command(\"content-edit-upcase-forward-word\")\ndef upcase_word(ctx):\n    \"\"\"\n    Upcase the word forward in browser text field.\n    \"\"\"\n    run_js(ctx, \"textedit.upcase_word();\")\n\n\n@define_command(\"content-edit-downcase-forward-word\")\ndef downcase_word(ctx):\n    \"\"\"\n    Downcase the word forward in browser text field.\n    \"\"\"\n    run_js(ctx, \"textedit.downcase_word();\")\n\n\n@define_command(\"content-edit-capitalize-forward-word\")\ndef capitalize_word(ctx):\n    \"\"\"\n    Capitalize the word forward in browser text field.\n    \"\"\"\n    run_js(ctx, \"textedit.capitalize_word();\")\n\n\n@define_command(\"content-edit-open-external-editor\")\ndef open_external_editor(ctx):\n    \"\"\"\n    Open an external editor to change the text field content.\n    \"\"\"\n    run_js(ctx, \"textedit.external_editor_open()\")\n\n\n@define_command(\"content-edit-undo\")\ndef undo(ctx):\n    \"\"\"\n    Undo the last editing action.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Undo)\n\n\n@define_command(\"content-edit-redo\")\ndef redo(ctx):\n    \"\"\"\n    Redo the last editing action.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Redo)\n\n\n@define_command(\"content-edit-select-all\")\ndef select_all(ctx):\n    \"\"\"\n    Select all text of the current input.\n    \"\"\"\n    run_js(ctx, \"textedit.select_text()\")\n"
  },
  {
    "path": "webmacs/commands/follow.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtCore import QEvent, Qt\n\nfrom ..minibuffer import Prompt\nfrom ..keymaps import KeyPress, HINT_KEYMAP\nfrom ..commands import define_command, register_prompt_opener_commands, \\\n    Opener\nfrom .. import variables, clipboard\n\n\nHINT_METHODS = (\"filter\", \"alphabet\")\n\nhint_method = variables.define_variable(\n    \"hint-method\",\n    \"Method to hint things in web buffers.\",\n    HINT_METHODS[0],\n    type=variables.String(choices=HINT_METHODS),\n)\n\nhint_alphabet_characters = variables.define_variable(\n    \"hint-alphabet-characters\",\n    \"Which characters to use for alphabet hinting.\",\n    \"asdfghjkl\",\n    type=variables.String(),\n)\n\n\nhint_node_style = variables.define_variable(\n    \"hint-node-style\",\n    \"The style to apply to the hint div. Note that it is a dict of JavaScript\"\n    \" style property names to values. See\"\n    \" https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style.\",\n    {\n        \"whiteSpace\": \"nowrap\",\n        \"overflow\": \"hidden\",\n        \"padding\": \"1px 3px 0px 3px\",\n        \"background\": \"linear-gradient(to bottom, #fc3232 0%,#990000 100%)\",\n        \"border\": \"solid 1px #c32222\",\n        \"borderRadius\": \"3px\",\n        \"boxShadow\": \"0px 3px 7px 0px rgba(0, 0, 0, 0.3)\",\n        \"color\": \"white\",\n        \"fontWeight\": \"bold\",\n        \"fontSize\": \"13px\",\n        \"textShadow\": \"1px 1px 0 rgba(0, 0, 0, 0.6)\",\n    },\n    type=variables.Dict(variables.String(), variables.String()),\n)\n\n\ndef hint_method_options(method):\n    options = {\n        \"hint\": hint_node_style.value,\n        \"background\": \"yellow\",\n        \"background_active\": \"#88FF00\",\n        \"text_color\": \"black\",\n    }\n    if method == \"alphabet\":\n        options[\"characters\"] = hint_alphabet_characters.value\n    return options\n\n\n# took from conkeror\nSELECTOR_CLICKABLE = (\n    \"//*[@onclick or @onmouseover or @onmousedown or @onmouseup or \"\n    \"@oncommand or @role='link' or @role='button' or @role='menuitem']\"\n    \" | //input[not(@type='hidden')] | //a[@href] | //area\"\n    \" | //iframe | //textarea | //button | //select\"\n    \" | //*[@contenteditable = 'true']\"\n    \" | //xhtml:*[@onclick or @onmouseover or @onmousedown or\"\n    \" @onmouseup or @oncommand or @role='link' or @role='button' or\"\n    \" @role='menuitem'] | //xhtml:input[not(@type='hidden')]\"\n    \" | //xhtml:a[@href] | //xhtml:area | //xhtml:iframe\"\n    \" | //xhtml:textarea | //xhtml:button | //xhtml:select\"\n    \" | //xhtml:*[@contenteditable = 'true'] | //svg:a\"\n)\n\nSELECTOR_LINK = \"//a[@href] | //iframe\"\n\n\nclass HintPrompt(Prompt):\n    keymap = HINT_KEYMAP\n    hint_selector = \"\"\n\n    def enable(self, minibuffer):\n        super(HintPrompt, self).enable(minibuffer)\n        self.page = self.ctx.buffer\n        self.method = hint_method.value\n        self.method_options = hint_method_options(self.method)\n        self.page.start_select_browser_objects(\n            self.hint_selector,\n            method=self.method,\n            method_options=self.method_options\n        )\n        self.numbers = \"\"\n        minibuffer.input().textChanged.connect(self.on_text_edited)\n        self.browser_object_activated = {}\n        self.page.content_handler.browserObjectActivated.connect(\n            self.on_browser_object_activated\n        )\n        minibuffer.input().installEventFilter(self)\n\n    def on_browser_object_activated(self, bo):\n        self.browser_object_activated = bo\n        self.minibuffer.input().set_right_italic_text(bo.get(\"url\", \"\"))\n        if self.method == \"alphabet\":\n            self._on_edition_finished()\n\n    def on_text_edited(self, text):\n        self.page.filter_browser_objects(text)\n\n    def _update_label(self):\n        label = self.label\n        if self.numbers:\n            label = label + (\" #%s\" % self.numbers)\n        self.minibuffer.label.setText(label)\n\n    def eventFilter(self, obj, event):\n        numbers = (\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\")\n        if event.type() == QEvent.Type.KeyPress:\n            if self.method == \"filter\":\n                text = event.text()\n                if text in numbers:\n                    self.numbers += text\n                    self.page.select_visible_hint(self.numbers)\n                    self._update_label()\n                    return True\n                elif not event.key() in (\n                        Qt.Key.Key_Control,\n                        Qt.Key.Key_Shift,\n                        Qt.Key.Key_Alt,\n                        Qt.Key.Key_Meta,\n                        Qt.Key.Key_unknown,\n                        Qt.Key.Key_Return,\n                ):\n                    self.numbers = \"\"\n                    self._update_label()\n            elif self.method == \"alphabet\":\n                kp = KeyPress.from_qevent(event)\n                if kp is not None:\n                    char = kp.char()\n                    if not kp.has_any_modifier() \\\n                       and len(char) == 1 \\\n                       and char not in self.method_options[\"characters\"]:\n                        return True\n        return super(HintPrompt, self).eventFilter(obj, event)\n\n    def value(self):\n        return super().value() is not None\n\n\nclass CopyLinkPrompt(HintPrompt):\n    label = \"copy link:\"\n    hint_selector = SELECTOR_LINK\n\n    def eventFilter(self, obj, event):\n        res = super(CopyLinkPrompt, self).eventFilter(obj, event)\n        if self.numbers == \"0\":\n            self.minibuffer.input().set_right_italic_text(\n                self.page.url().toString()\n            )\n        return res\n\n\nclass FollowPrompt(HintPrompt):\n    label = \"follow:\"\n    hint_selector = SELECTOR_CLICKABLE\n\n\nclass FollowOpener(Opener):\n    def prompt_open(self, method, ctx):\n        prompt = super().prompt_open(method, ctx)\n        if method != self.CURRENT_BUFFER:\n            prompt.hint_selector = SELECTOR_LINK\n        return prompt\n\n    def open(self, method, ctx, prompt, url):\n        if method == self.CURRENT_BUFFER:\n            ctx.buffer.focus_active_browser_object()\n        elif \"url\" in prompt.browser_object_activated:\n            super().open(method, ctx, prompt,\n                         prompt.browser_object_activated[\"url\"])\n        ctx.buffer.stop_select_browser_objects()\n\n\nregister_prompt_opener_commands(\n    \"follow\",\n    FollowOpener(FollowPrompt),\n    \"Hint links in the buffer and follow them on selection\"\n)\n\n\n@define_command(\"copy-link\")\ndef copy_link(ctx):\n    \"\"\"\n    Hint links in the buffer to copy them.\n    \"\"\"\n    prompt = CopyLinkPrompt(ctx)\n    if not ctx.minibuffer.do_prompt(prompt):\n        return\n    url = None\n    ctx.buffer.stop_select_browser_objects()\n\n    if prompt.numbers == \"0\":\n        # special case, copy current url\n        url = str(ctx.buffer.url().toEncoded(), \"utf-8\")\n    else:\n        url = prompt.browser_object_activated.get(\"url\")\n\n    if url:\n        clipboard.set_text(url)\n\n\n@define_command(\"hint-abort\")\ndef cancel(ctx):\n    \"\"\"\n    Abort current hint session.\n    \"\"\"\n    ctx.buffer.stop_select_browser_objects()\n    ctx.minibuffer.close_prompt()\n\n\n@define_command(\"hint-next\")\ndef next_completion(ctx):\n    \"\"\"\n    Select the next hint.\n    \"\"\"\n    ctx.buffer.select_nex_browser_object()\n\n\n@define_command(\"hint-prev\")\ndef previous_completion(ctx):\n    \"\"\"\n    Select the previous hint.\n    \"\"\"\n    ctx.buffer.select_nex_browser_object(False)\n"
  },
  {
    "path": "webmacs/commands/global.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport itertools\nimport os\nimport sys\nfrom PyQt6.QtCore import QStringListModel, QModelIndex, QProcess\n\nfrom . import define_command, COMMANDS, register_prompt_opener_commands\nfrom ..minibuffer import Prompt\nfrom ..minibuffer.prompt import PromptTableModel, PromptHistory\nfrom ..application import app\nfrom ..webbuffer import create_buffer\nfrom ..keymaps import KeyPress, VISITEDLINKS_KEYMAP, BOOKMARKS_KEYMAP, \\\n    KEYMAPS, GLOBAL_KEYMAP\nfrom ..keyboardhandler import send_key_event, local_keymap, KEY_EATER, \\\n    CallHandler\nfrom .. import BUFFERS, windows, variables\nfrom ..mode import MODES\nfrom ..window import Window\nfrom ..session import session_clean, session_load\nfrom ..ipc import IpcServer\nfrom ..url_opener import url_open\n\n\nclass CommandsListPrompt(Prompt):\n    label = \"M-x: \"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    history = PromptHistory()\n\n    def __init__(self, ctx, local_keymap=None):\n        Prompt.__init__(self, ctx)\n        self.__local_keymap = local_keymap\n\n    def completer_model(self):\n        if self.__local_keymap:\n            bindings = {}\n            def add(prefix, cmd, parent):\n                bindings[cmd] = \" \".join(str(k) for k in prefix)\n            # add bindings from currently active keymaps: global and the local\n            # one, registered before opening the minibuffer.\n            GLOBAL_KEYMAP.traverse_commands(add)\n            self.__local_keymap.traverse_commands(add)\n\n            data = [(k, bindings.get(k, \"\"))\n                    for k, v in COMMANDS.items() if v.visible]\n        else:\n            data = [(k,) for k, v in COMMANDS.items() if v.visible]\n\n        model = PromptTableModel(data, self)\n        return model\n\n\n@define_command(\"quit\")\ndef quit(ctx):\n    \"\"\"\n    Quit the application.\n    \"\"\"\n    app().quit()\n\n\n@define_command(\"M-x\", visible=False)\ndef commands(ctx):\n    \"\"\"\n    Prompt for a command name to execute.\n    \"\"\"\n    prompt = CommandsListPrompt(ctx, local_keymap())\n    value = ctx.minibuffer.do_prompt(prompt)\n    try:\n        COMMANDS[value](ctx)\n    except KeyError:\n        pass\n\n\n@define_command(\"toggle-fullscreen\")\ndef toggle_fullscreen(ctx):\n    \"\"\"\n    Toggle fullscreen state of the current window.\n    \"\"\"\n    win = ctx.window\n    if not win:\n        return\n    if win.isFullScreen():\n        win.showNormal()\n    else:\n        win.showFullScreen()\n\n\n@define_command(\"toggle-maximized\")\ndef toggle_maximised(ctx):\n    \"\"\"\n    Toggle maximised state of the current window.\n    \"\"\"\n    win = ctx.window\n    if not win:\n        return\n    if win.isMaximized():\n        win.showNormal()\n    else:\n        win.showMaximized()\n\n\ndef _get_or_create_buffer(win):\n    visible_buffers = []\n    for awin in windows():\n        for view in awin.webviews():\n            visible_buffers.append(view.buffer())\n    current_buffer = win.current_webview().buffer()\n    buffers = [b for b in BUFFERS\n               if b not in visible_buffers\n               or b == current_buffer]\n\n    # if there is at least one buffer not visible, use the one just\n    # after the current one in the list\n    if len(buffers) > 1:\n        ibuffers = itertools.cycle(buffers)\n        while True:\n            buff = next(ibuffers)\n            if buff == current_buffer:\n                return next(ibuffers)\n\n    # else create a new buffer, reusing the current buffer's url\n    return create_buffer(url=current_buffer.url())\n\n\n@define_command(\"split-view-right\")\ndef split_window_right(ctx):\n    \"\"\"\n    Create a new view on the right of the current one.\n    \"\"\"\n    win = ctx.window\n    view = win.create_webview_on_right()\n    view.setBuffer(_get_or_create_buffer(win))\n    win.set_current_webview(view)\n\n\n@define_command(\"split-view-bottom\")\ndef split_window_bottom(ctx):\n    \"\"\"\n    Create a new view below the current one.\n    \"\"\"\n    win = ctx.window\n    view = win.create_webview_on_bottom()\n    view.setBuffer(_get_or_create_buffer(win))\n    win.set_current_webview(view)\n\n\n@define_command(\"make-window\")\ndef create_window(ctx):\n    \"\"\"\n    Create a new window and focus it.\n    \"\"\"\n    win = Window()\n    home_page = variables.get(\"home-page\")\n    win.current_webview().setBuffer(\n        create_buffer(home_page)\n        if home_page and variables.get(\"home-page-in-new-window\")\n        else _get_or_create_buffer(ctx.window)\n    )\n    win.show()\n    win.activateWindow()\n\n\n@define_command(\"other-window\")\ndef other_window(ctx):\n    \"\"\"\n    Switch to the next window.\n    \"\"\"\n    if len(windows()) <= 1:\n        return False\n    iterwindows = itertools.cycle(windows())\n    while True:\n        win = next(iterwindows)\n        if win == ctx.window:\n            next(iterwindows).activateWindow()\n            return True\n\n\n@define_command(\"close-window\")\ndef close_window(ctx):\n    \"\"\"\n    Close the current window, unless there is only one left.\n    \"\"\"\n    # first activate the next view\n    if other_window(ctx):\n        ctx.window.close()\n\n\n@define_command(\"close-other-windows\")\ndef close_other_windows(ctx):\n    \"\"\"\n    Close all windows except the current one.\n    \"\"\"\n    for win in windows():\n        if win != ctx.window:\n            win.close()\n\n\n@define_command(\"other-view\")\ndef other_view(ctx):\n    \"\"\"\n    Focus on the next view.\n    \"\"\"\n    win = ctx.window\n    win.other_view()\n\n\n@define_command(\"close-view\")\ndef close_view(ctx):\n    \"\"\"\n    Close the current view.\n    \"\"\"\n    window = ctx.window\n    window.close_view(window.current_webview())\n\n\n@define_command(\"maximise-view\")\ndef maximise_view(ctx):\n    \"\"\"\n    Close all the views in the current window except the current one.\n    \"\"\"\n    ctx.window.close_other_views()\n\n\n@define_command(\"toggle-ad-block\")\ndef toggle_ad_block(ctx):\n    \"\"\"\n    Toggle ad-blocking on or off.\n    \"\"\"\n    from .webbuffer import reload_buffer_no_cache\n\n    app().url_interceptor().toggle_use_adblock()\n    reload_buffer_no_cache(ctx)\n\n\n@define_command(\"toggle-toolbar\")\ndef toggle_toolbar(ctx):\n    \"\"\"\n    Toggle the main window toolbar on or off.\n    \"\"\"\n    ctx.window.toggle_toolbar()\n\n\nclass VisitedLinksModel(PromptTableModel):\n\n    def __init__(self, parent):\n        visitedlinks = app().visitedlinks()\n        PromptTableModel.__init__(self, visitedlinks.visited_urls())\n        self.visitedlinks = visitedlinks\n\n    def remove_history_entry(self, index):\n        self.beginRemoveRows(QModelIndex(), index.row(), index.row())\n        self.visitedlinks.remove(self._data.pop(index.row())[0])\n        self.endRemoveRows()\n\n\nclass VisitedLinksPrompt(Prompt):\n    label = \"Find url from visited links:\"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    keymap = VISITEDLINKS_KEYMAP\n    value_return_index_data = True\n\n    def completer_model(self):\n        return VisitedLinksModel(self)\n\n\n@define_command(\"visited-links-delete-highlighted\")\ndef visited_links_remove_entry(ctx):\n    \"\"\"\n    Deletes from the database the currently highlighted visited link.\n    \"\"\"\n    pinput = ctx.minibuffer.input()\n\n    selection = pinput.popup().selectionModel().currentIndex()\n    if not selection.isValid():\n        return\n\n    selection = selection.model().mapToSource(selection)\n    pinput.completer_model().remove_history_entry(selection)\n\n\nregister_prompt_opener_commands(\n    \"visited-links-history\",\n    VisitedLinksPrompt,\n    \"Prompt to open a link previously visited\",\n)\n\n\nclass BookmarksModel(VisitedLinksModel):\n\n    def __init__(self, parent):\n        bookmarks = app().bookmarks()\n        PromptTableModel.__init__(self, bookmarks.list())\n        # this makes the remove_history_entry method works\n        self.visitedlinks = bookmarks\n\n\n@define_command(\"bookmarks-delete-highlighted\")\ndef bookmarks_remove_entry(ctx):\n    \"\"\"\n    Deletes from the database the currently highlighted bookmark.\n    \"\"\"\n    # removing a bookmark is like removing a visited link\n    visited_links_remove_entry(ctx)\n\n\nclass BookmarksPrompt(VisitedLinksPrompt):\n    label = \"Open bookmark:\"\n    keymap = BOOKMARKS_KEYMAP\n    history = PromptHistory()\n\n    def completer_model(self):\n        return BookmarksModel(self)\n\n\nregister_prompt_opener_commands(\n    \"bookmark-open\",\n    BookmarksPrompt,\n    \"Prompt to open a bookmark\",\n)\n\n\nclass BookmarkAddPrompt(Prompt):\n    label = \"Create a bookmark for: \"\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        url = self.ctx.buffer.url().toString()\n        input = minibuffer.input()\n        input.setText(url)\n        input.setSelection(0, len(url))\n\n\nclass BookmarkNamePrompt(Prompt):\n    label = \"bookmark's name: \"\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        name = self.ctx.buffer.title()\n        input = minibuffer.input()\n        input.setText(name)\n        input.setSelection(0, len(name))\n\n\n@define_command(\"bookmark-add\")\ndef bookmark_add(ctx):\n    \"\"\"\n    Create or rename a bookmark for the current url.\n    \"\"\"\n    prompt = BookmarkAddPrompt(ctx)\n    url = ctx.minibuffer.do_prompt(prompt)\n    if not url:\n        return\n\n    otherprompt = BookmarkNamePrompt(ctx)\n    name = ctx.minibuffer.do_prompt(otherprompt)\n\n    if name:\n        app().bookmarks().set(url, name)\n        ctx.minibuffer.show_info(\"Bookmark {} created.\".format(name))\n\n\nclass ModesPrompt(Prompt):\n    label = \"switch to mode:\"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    value_return_index_data = True\n\n    def completer_model(self):\n        return PromptTableModel([\n            (name, MODES[name].description) for name in sorted(MODES)\n        ])\n\n\n@define_command(\"buffer-set-mode\")\ndef buffer_set_mode(ctx):\n    \"\"\"\n    Change the mode of the current buffer.\n    \"\"\"\n    prompt = ModesPrompt(ctx)\n    mode = ctx.minibuffer.do_prompt(prompt)\n    if mode:\n        ctx.buffer.set_mode(mode)\n\n\n@define_command(\"send-key-down\")\ndef send_down(ctx):\n    \"\"\"Send a key down event.\"\"\"\n    send_key_event(KeyPress.from_str(\"Down\"))\n\n\n@define_command(\"send-key-up\")\ndef send_up(ctx):\n    \"\"\"Send a key up event.\"\"\"\n    send_key_event(KeyPress.from_str(\"Up\"))\n\n\n@define_command(\"send-key-right\")\ndef send_right(ctx):\n    \"\"\"Send a key right event.\"\"\"\n    send_key_event(KeyPress.from_str(\"Right\"))\n\n\n@define_command(\"send-key-left\")\ndef send_left(ctx):\n    \"\"\"Send a key left event.\"\"\"\n    send_key_event(KeyPress.from_str(\"Left\"))\n\n\n@define_command(\"describe-bindings\")\ndef describe_bindings(ctx):\n    \"\"\"\n    Display current bindings in the current buffer or in a new buffer.\n    \"\"\"\n    url_open(ctx, \"webmacs://bindings\", new_buffer=ctx.current_prefix_arg == (4,))\n\n\n@define_command(\"describe-commands\")\ndef describe_commands(ctx):\n    \"\"\"\n    Display commands in the current buffer or in a new buffer.\n    \"\"\"\n    url_open(ctx, \"webmacs://commands\", new_buffer=ctx.current_prefix_arg == (4,))\n\n\n@define_command(\"describe-variables\")\ndef describe_variables(ctx):\n    \"\"\"\n    Display variables in the current buffer or in a new buffer.\n    \"\"\"\n    url_open(ctx, \"webmacs://variables\", new_buffer=ctx.current_prefix_arg == (4,))\n\n\n@define_command(\"downloads\")\ndef downloads(ctx):\n    \"\"\"\n    Display information about the current downloads.\n    \"\"\"\n    url_open(ctx, \"webmacs://downloads\", new_buffer=ctx.current_prefix_arg == (4,))\n\n\n@define_command(\"version\")\ndef version(ctx):\n    \"\"\"\n    Display version information.\n    \"\"\"\n    url_open(ctx, \"webmacs://version\", new_buffer=ctx.current_prefix_arg == (4,))\n\n\nclass VariableListPrompt(Prompt):\n    label = \"describe variable: \"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    history = PromptHistory()\n\n    def completer_model(self):\n        model = QStringListModel(self)\n        model.setStringList(sorted(variables.VARIABLES))\n        return model\n\n\n@define_command(\"describe-variable\")\ndef describe_variable(ctx):\n    \"\"\"\n    Prompt for a variable name to describe.\n    \"\"\"\n    variable = ctx.minibuffer.do_prompt(VariableListPrompt(ctx))\n    if variable in variables.VARIABLES:\n        buffer = create_buffer(\"webmacs://variable/%s\" % variable)\n        ctx.view.setBuffer(buffer)\n\n\nclass DescribeCommandsListPrompt(CommandsListPrompt):\n    label = \"describe command: \"\n    history = PromptHistory()\n\n\n@define_command(\"describe-command\")\ndef describe_command(ctx):\n    \"\"\"\n    Prompt for a command name to describe.\n    \"\"\"\n    command = ctx.minibuffer.do_prompt(DescribeCommandsListPrompt(ctx))\n    if command in COMMANDS:\n        url_open(ctx, \"webmacs://command/%s\" % command)\n\n\nclass ReportCallHandler(CallHandler):\n\n    def __init__(self, prompt):\n        CallHandler.__init__(self)\n        self.prompt = prompt\n        self.key_presses = []\n\n    def keys_as_text(self):\n        return \" - \".join(str(k) for k in self.key_presses)\n\n    def no_call(self, sender, keymap, keypress):\n        self.key_presses.append(keypress)\n        self.prompt.close()\n        self.prompt.minibuffer.show_info(\"No such key: %s\"\n                                         % self.keys_as_text())\n\n    def partial_call(self, sender, keymap, keypress):\n        self.key_presses.append(keypress)\n        self.prompt.minibuffer.input().setText(\"%s -\"\n                                               % self.keys_as_text())\n\n    def call(self, ctx, keymap, keypress, command):\n        self.key_presses.append(keypress)\n        if not isinstance(command, str):\n            command = \"{}:{}\".format(command.__module__,\n                                     command.__name__)\n        self.prompt.called_with = {\n            \"command\": command,\n            \"key\": self.keys_as_text(),\n            \"keymap\": keymap.name or \"unknown\",\n        }\n        self.prompt.finished.emit()\n        self.prompt.close()\n\n\nclass BindingPrompt(Prompt):\n    label = \"describe key: \"\n    called_with = None\n\n    def enable(self, minibuffer):\n        self.keymap = local_keymap()\n        Prompt.enable(self, minibuffer)\n        self.orig_handler = KEY_EATER.call_handler\n        KEY_EATER.set_call_handler(ReportCallHandler(self))\n\n    def close(self):\n        KEY_EATER.set_call_handler(self.orig_handler)\n        Prompt.close(self)\n\n    def value(self):\n        return self.called_with\n\n\n@define_command(\"describe-key\")\ndef describe_binding(ctx):\n    \"\"\"\n    Retrieve the command called by the given binding.\n    \"\"\"\n    called_with = ctx.minibuffer.do_prompt(BindingPrompt(ctx))\n    if called_with:\n        url = \"webmacs://key/{key}?command={command}&keymap={keymap}\".format(\n            **called_with\n        )\n        url_open(ctx, url, new_buffer=True)\n\n\n@define_command(\"describe-key-briefly\")\ndef describe_binding_briefly(ctx):\n    \"\"\"\n    Display in the minibuffer the command name called by the given binding.\n    \"\"\"\n    called_with = ctx.minibuffer.do_prompt(BindingPrompt(ctx))\n    if called_with:\n        ctx.minibuffer.show_info(\n            \"{key} runs the command {command} (keymap: {keymap})\".format(\n                **called_with\n            )\n        )\n\n\nclass WhereIsCommandsListPrompt(CommandsListPrompt):\n    label = \"Where is command: \"\n    history = PromptHistory()\n\n\n@define_command(\"where-is\")\ndef where_is(ctx):\n    \"\"\"\n    Print short notice of where a command is bound\n    \"\"\"\n    command = ctx.minibuffer.do_prompt(WhereIsCommandsListPrompt(ctx))\n    if not command:\n        return\n    bindings_str = \", \".join(\"{} (keymap: {})\".format(k, kmapname)\n                             for kmapname, kmap in KEYMAPS.items()\n                             for k, v in kmap.all_bindings() if v == command)\n    if bindings_str:\n        ctx.minibuffer.show_info(\"{} is on: {}\".format(command, bindings_str))\n    else:\n        ctx.minibuffer.show_info(\"{} is not on any key\".format(command))\n\n\n@define_command(\"restore-session\")\ndef restore_session(ctx):\n    \"\"\"\n    Restore windows and buffers from the previous sessions.\n    \"\"\"\n    session_file = app().profile.session_file\n    if not os.path.exists(session_file):\n        ctx.minibuffer.show_info(\"Error: No session file found.\")\n\n    session_clean()\n    try:\n        session_load(session_file)\n    except Exception:\n        w = Window()\n        w.current_webview().setBuffer(\"about:blank\")\n        w.show()\n\n\nclass InstancesListPrompt(Prompt):\n    label = \"webmacs instances: \"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    history = PromptHistory()\n    exclude_self_instance = True\n\n    def __init__(self, ctx):\n        super().__init__(ctx)\n        instances = IpcServer.list_all_instances(check=False)\n        if self.exclude_self_instance:\n            current = app().instance_name\n            instances = [i for i in instances if i != current]\n        self.instances = instances\n\n    def completer_model(self):\n        model = QStringListModel(self)\n        model.setStringList(self.instances)\n        return model\n\n\n@define_command(\"raise-instance\")\ndef raise_instance(ctx):\n    \"\"\"\n    Raise the current window of the selected instance.\n    \"\"\"\n    prompt = InstancesListPrompt(ctx)\n    if not prompt.instances:\n        ctx.minibuffer.show_info(\"There is only one instance running: %s\"\n                                 % app().instance_name)\n    else:\n        value = ctx.minibuffer.do_prompt(prompt)\n        if value:\n            IpcServer.instance_send(value, {})\n\n\n@define_command(\"current-instance\")\ndef current_instance(ctx):\n    \"\"\"\n    Show the current instance name.\n    \"\"\"\n    ctx.minibuffer.show_info(\"Current instance name: %s\" % app().instance_name)\n\n\n@define_command(\"is-off-the-record\")\ndef is_off_the_record(ctx):\n    \"\"\"\n    Print wether browsing is off the record.\n    \"\"\"\n    ctx.minibuffer.show_info(\n        f\"Is off the record: {app().profile.is_off_the_record()}\")\n\n@define_command(\"open-off-the-record\")\ndef open_off_the_record(ctx):\n    \"\"\"\n    Opens a new webmacs instance with off-the-record enabled.\n    \"\"\"\n    proc = QProcess()\n    proc.setProgram(sys.argv[0])\n    proc.setArguments([\"--off-the-record\", \"--instance\", \"\"])\n    proc.startDetached()\n"
  },
  {
    "path": "webmacs/commands/isearch.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom ..minibuffer import Prompt\nfrom ..keymaps import ISEARCH_KEYMAP, CARET_BROWSING_KEYMAP\nfrom ..keyboardhandler import local_keymap\nfrom ..webbuffer import WebBuffer, QWebEnginePage\nfrom ..commands import define_command\nfrom ..commands import caret_browsing as caret_browsing_commands\n\n\n@define_command(\"i-search-next\")\ndef search_next(ctx):\n    \"\"\"\n    Highlight next match in incremental search mode.\n    \"\"\"\n    if ISearchPrompt.LAST_SEARCH and not ctx.minibuffer.input().text():\n        ctx.minibuffer.input().setText(ISearchPrompt.LAST_SEARCH)\n        return\n    prompt = ctx.minibuffer.prompt()\n    prompt.set_isearch_direction(0)\n    prompt.find_text()\n\n\n@define_command(\"i-search-prev\")\ndef search_previous(ctx):\n    \"\"\"\n    Highlight previous match in incremental search mode.\n    \"\"\"\n    if ISearchPrompt.LAST_SEARCH and not ctx.minibuffer.input().text():\n        ctx.minibuffer.input().setText(ISearchPrompt.LAST_SEARCH)\n        return\n    prompt = ctx.minibuffer.prompt()\n    prompt.set_isearch_direction(WebBuffer.FindFlag.FindBackward)\n    prompt.find_text()\n\n\n@define_command(\"i-search-validate\")\ndef validate(ctx):\n    \"\"\"\n    Validate current match in incremental search mode.\n    \"\"\"\n    ISearchPrompt.LAST_SEARCH = ctx.minibuffer.input().text()\n    ctx.buffer.findText(\"\")  # to clear the highlight\n    ctx.minibuffer.close_prompt()\n\n\n@define_command(\"i-search-abort\")\ndef cancel(ctx):\n    \"\"\"\n    Abort incremental search.\n    \"\"\"\n    prompt = ctx.minibuffer.prompt()\n    scroll_pos = prompt.page_scroll_pos\n    ctx.buffer.findText(\"\")  # to clear the highlight\n    ctx.minibuffer.close_prompt()\n    prompt.set_page_scroll_pos(scroll_pos)\n\n\nclass ISearchPrompt(Prompt):\n    label = \"ISearch:\"\n    keymap = ISEARCH_KEYMAP\n\n    isearch_direction = 0  # forward\n\n    LAST_SEARCH = None\n\n    def enable(self, minibuffer):\n        self._caret_browsing = local_keymap() == CARET_BROWSING_KEYMAP\n        if self._caret_browsing:\n            caret_browsing_commands.shutdown(self.ctx)\n        Prompt.enable(self, minibuffer)\n        self._update_label()\n        self.page = self.ctx.buffer\n        self.page_scroll_pos = (0, 0)\n        self.page.async_scroll_pos(\n            lambda p: setattr(self, \"page_scroll_pos\", p))\n        minibuffer.input().textChanged.connect(self.on_text_edited)\n\n    def set_isearch_direction(self, direction):\n        self.isearch_direction = direction\n        self._update_label()\n\n    def set_page_scroll_pos(self, page_scroll_pos):\n        self.page.set_scroll_pos(*page_scroll_pos)\n\n    def find_text(self):\n        if self.isearch_direction:\n            self.page.findText(self.minibuffer.input().text(),\n                               self.isearch_direction)\n        else:\n            self.page.findText(self.minibuffer.input().text())\n\n    def on_text_edited(self, text):\n        self.find_text()\n        if not self.minibuffer.input().text():\n            self.set_page_scroll_pos(self.page_scroll_pos)\n\n    def _update_label(self):\n        direction = \"forward\" if self.isearch_direction == 0 else \"backward\"\n        self.minibuffer.label.setText(\"ISearch (%s):\" % direction)\n\n    def close(self):\n        self.minibuffer.input().textChanged.disconnect(self.on_text_edited)\n        Prompt.close(self)\n        if self._caret_browsing:\n            caret_browsing_commands.init(self.ctx)\n\n\n@define_command(\"i-search-forward\")\ndef i_search_forward(ctx):\n    \"\"\"\n    Begin an incremental search (forward).\n    \"\"\"\n    ctx.minibuffer.do_prompt(ISearchPrompt(ctx))\n\n\nclass ISearchPromptBackward(ISearchPrompt):\n    isearch_direction = QWebEnginePage.FindFlag.FindBackward\n\n\n@define_command(\"i-search-backward\")\ndef i_search_backward(ctx):\n    \"\"\"\n    Begin an incremental search (backward).\n    \"\"\"\n    ctx.minibuffer.do_prompt(ISearchPromptBackward(ctx))\n"
  },
  {
    "path": "webmacs/commands/minibuffer.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import define_command\n\nWORD_SEPS = \"#/.-_:\"\n\n\ndef move_next_word(edit, forward, mark):\n    action = edit.cursorWordForward if forward else edit.cursorWordBackward\n\n    cursor = edit.cursorPosition()\n    txt = edit.text()\n\n    while True:\n        action(mark)\n        nc = edit.cursorPosition()\n        if nc == cursor:\n            break\n        cursor = nc\n\n        if forward:\n            nc -= 1\n\n        if txt[nc] not in WORD_SEPS:\n            break\n\n\n@define_command(\"minibuffer-select-complete\")\ndef complete(ctx):\n    \"\"\"\n    Complete completion.\n    \"\"\"\n    input = ctx.minibuffer.input()\n\n    if not input.popup().isVisible():\n        input.show_completions()\n    else:\n        input.select_next_completion()\n\n\n@define_command(\"minibuffer-select-next\")\ndef next_completion(ctx):\n    \"\"\"\n    Select next completion entry.\n    \"\"\"\n    ctx.minibuffer.input().select_next_completion()\n\n\n@define_command(\"minibuffer-select-prev\")\ndef previous_completion(ctx):\n    \"\"\"\n    Select previous completion entry.\n    \"\"\"\n    ctx.minibuffer.input().select_next_completion(False)\n\n\n@define_command(\"minibuffer-select-first\")\ndef first_complqetion(ctx):\n    \"\"\"\n    Select first completion entry.\n    \"\"\"\n    ctx.minibuffer.input().select_first_completion()\n\n\n@define_command(\"minibuffer-select-last\")\ndef last_completion(ctx):\n    \"\"\"\n    Select last completion entry.\n    \"\"\"\n    ctx.minibuffer.input().select_last_completion()\n\n\n@define_command(\"minibuffer-select-next-page\")\ndef next_page_completion(ctx):\n    \"\"\"\n    Move one page down in completion entry list.\n    \"\"\"\n    ctx.minibuffer.input().select_next_page_completion()\n\n\n@define_command(\"minibuffer-select-prev-page\")\ndef previous_page_completion(ctx):\n    \"\"\"\n    Move one page up in completion entry list.\n    \"\"\"\n    ctx.minibuffer.input().select_next_page_completion(False)\n\n\ndef _prompt_history(ctx, func):\n    minibuff = ctx.minibuffer\n    history = minibuff.prompt().history\n    if history:\n        if history.in_user_value():\n            history.set_user_value(minibuff.input().text())\n        text = func(history)\n        if text is not None:\n            minibuff.input().setText(text)\n\n\n@define_command(\"minibuffer-history-next\")\ndef prompt_history_next(ctx):\n    \"\"\"\n    Insert next history value.\n    \"\"\"\n    _prompt_history(ctx, lambda h: h.get_next())\n\n\n@define_command(\"minibuffer-history-prev\")\ndef prompt_history_previous(ctx):\n    \"\"\"\n    Insert previous history value.\n    \"\"\"\n    _prompt_history(ctx, lambda h: h.get_previous())\n\n\n@define_command(\"minibuffer-validate\")\ndef edition_finished(ctx):\n    \"\"\"\n    Validate input in minibuffer.\n    \"\"\"\n    minibuffer_input = ctx.minibuffer.input()\n    minibuffer_input.complete()\n    minibuffer_input.popup().hide()\n    minibuffer_input.returnPressed.emit()\n\n\n@define_command(\"minibuffer-abort\")\ndef cancel(ctx):\n    \"\"\"\n    Abort edition of the minibuffer.\n    \"\"\"\n    minibuffer = ctx.minibuffer\n    input = minibuffer.input()\n    if input.popup().isVisible():\n        input.popup().hide()\n    minibuffer.close_prompt()\n\n\n@define_command(\"minibuffer-delete-backward-word\")\ndef clean_aindent_bsunindent(ctx):\n    \"\"\"\n    Delete the word backward.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    if edit.hasSelectedText():\n        edit.deselect()\n\n    move_next_word(edit, False, True)\n    if edit.hasSelectedText():\n        edit.del_()\n\n\n@define_command(\"minibuffer-mark\")\ndef set_mark(ctx):\n    \"\"\"\n    Set or unset the edit mark.\n    \"\"\"\n    minibuffer_input = ctx.minibuffer.input()\n    if not minibuffer_input.set_mark():\n        minibuffer_input.deselect()\n\n\n@define_command(\"minibuffer-select-all\")\ndef select_all(ctx):\n    \"\"\"\n    Select all text in the minibuffer.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.selectAll()\n\n\n@define_command(\"minibuffer-forward-char\")\ndef forward_char(ctx):\n    \"\"\"\n    Move one character forward.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.cursorForward(edit.mark(), 1)\n\n\n@define_command(\"minibuffer-backward-char\")\ndef backward_char(ctx):\n    \"\"\"\n    Move one character backward.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.cursorBackward(edit.mark(), 1)\n\n\n@define_command(\"minibuffer-forward-word\")\ndef forward_word(ctx):\n    \"\"\"\n    Move one word forward.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    move_next_word(edit, True, edit.mark())\n\n\n@define_command(\"minibuffer-backward-word\")\ndef backward_word(ctx):\n    \"\"\"\n    Move one word backward.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    move_next_word(edit, False, edit.mark())\n\n\n@define_command(\"minibuffer-copy\")\ndef copy(ctx):\n    \"\"\"\n    Copy selected text in the minibuffer.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.copy()\n    edit.deselect()\n\n\n@define_command(\"minibuffer-cut\")\ndef cut(ctx):\n    \"\"\"\n    Cut selected text in the minibuffer.\n    \"\"\"\n    ctx.minibuffer.input().cut()\n\n\n@define_command(\"minibuffer-paste\")\ndef paste(ctx):\n    \"\"\"\n    Paste text in the minibuffer.\n    \"\"\"\n    ctx.minibuffer.input().paste()\n\n\n@define_command(\"minibuffer-delete-forward-char\")\ndef delete_char(ctx):\n    \"\"\"\n    Delete forward character.\n    \"\"\"\n    ctx.minibuffer.input().del_()\n\n\n@define_command(\"minibuffer-delete-forward-word\")\ndef delete_word(ctx):\n    \"\"\"\n    Delete forward word.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    if edit.hasSelectedText():\n        edit.deselect()\n\n    move_next_word(edit, True, True)\n    if edit.hasSelectedText():\n        edit.del_()\n\n\n@define_command(\"minibuffer-beginning-of-line\")\ndef beginning_of_line(ctx):\n    \"\"\"\n    Move cursor to the beginning of the line.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.home(edit.mark())\n\n\n@define_command(\"minibuffer-end-of-line\")\ndef end_of_line(ctx):\n    \"\"\"\n    Move cursor to the end of the line.\n    \"\"\"\n    edit = ctx.minibuffer.input()\n    edit.end(edit.mark())\n\n\n@define_command(\"minibuffer-undo\")\ndef undo(ctx):\n    \"\"\"\n    Undo in the minibuffer.\n    \"\"\"\n    ctx.minibuffer.input().undo()\n\n\n@define_command(\"minibuffer-redo\")\ndef redo(ctx):\n    \"\"\"\n    Redo in the minibuffer.\n    \"\"\"\n    ctx.minibuffer.input().redo()\n"
  },
  {
    "path": "webmacs/commands/webbuffer.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport itertools\n\nfrom PyQt6.QtCore import QAbstractTableModel, QModelIndex, Qt\nfrom PyQt6.QtGui import QColor\nfrom PyQt6.QtPrintSupport import QPrinter, QPrintDialog\nfrom PyQt6.QtWebEngineCore import QWebEngineScript\n\nfrom ..application import app\nfrom ..commands import define_command\nfrom ..minibuffer import Prompt\nfrom ..webbuffer import WebBuffer, close_buffer, create_buffer\nfrom ..killed_buffers import KilledBuffer\nfrom ..keyboardhandler import send_key_event\nfrom .. import BUFFERS, version, current_buffer, recent_buffers\nfrom .. import variables, clipboard, GLOBAL_OBJECTS\nfrom ..keymaps import KeyPress, BUFFERLIST_KEYMAP\nfrom ..password_manager import PasswordManagerNotReady\n\n\nswitch_buffer_current_color = variables.define_variable(\n    \"switch-buffer-current-color\",\n    \"The color to use for the current buffer in the switch-buffer list.\"\n    \" Set to an empty string if you don't want a special color.\",\n    \"#c0d5f7\",\n    type=variables.String(),\n)\n\n\nclass BufferTableModel(QAbstractTableModel):\n\n    def __init__(self, buffers):\n        QAbstractTableModel.__init__(self)\n        self._buffers = list(buffers)\n\n    def rowCount(self, index=QModelIndex()):\n        return len(self._buffers)\n\n    def columnCount(self, index=QModelIndex()):\n        return 2\n\n    def data(self, index, role=Qt.ItemDataRole.DisplayRole):\n        buff = index.internalPointer()\n        if not buff:\n            return\n\n        col = index.column()\n        if role == Qt.ItemDataRole.DisplayRole:\n            if col == 0:\n                return buff.url().toString()\n            else:\n                return \"[{}] {}\".format(BUFFERS.index(buff) + 1, buff.title())\n        elif role == Qt.ItemDataRole.DecorationRole and col == 0:\n            return buff.icon()\n        elif role == Qt.ItemDataRole.BackgroundRole:\n            if buff == current_buffer():\n                if switch_buffer_current_color.value:\n                    return QColor(switch_buffer_current_color.value)\n\n    def index(self, row, col, parent=QModelIndex()):\n        try:\n            return self.createIndex(row, col, self._buffers[row])\n        except IndexError:\n            return QModelIndex()\n\n    def close_buffer_at(self, index):\n        try:\n            if not close_buffer(self._buffers[index.row()]):\n                return\n        except ValueError:\n            return\n\n        self.beginRemoveRows(QModelIndex(), index.row(), index.row())\n        self._buffers.pop(index.row())\n        self.endRemoveRows()\n\n\n@define_command(\"buffer-list-delete-highlighted\")\ndef close_buffer_in_prompt_selection(ctx):\n    \"\"\"\n    Close currently highlighted buffer.\n    \"\"\"\n    pinput = ctx.minibuffer.input()\n\n    selection = pinput.popup().selectionModel().currentIndex()\n    if not selection.isValid():\n        return\n\n    selection = selection.model().mapToSource(selection)\n    pinput.completer_model().close_buffer_at(selection)\n\n\nclass BufferListPrompt(Prompt):\n    label = \"select buffer:\"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    keymap = BUFFERLIST_KEYMAP\n    value_return_index_data = True\n\n    def completer_model(self):\n        return BufferTableModel(self.ordered_buffers())\n\n    def ordered_buffers(self):\n        \"\"\"\n        How to display buffers.\n        \"\"\"\n        return BUFFERS\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        # select the next buffer\n        buffers = self.ordered_buffers()\n        index = buffers.index(current_buffer()) + 1\n        if index >= len(buffers):\n            index = 0\n        minibuffer.input().popup().selectRow(index)\n\n\nclass RecentBufferListPrompt(BufferListPrompt):\n\n    def ordered_buffers(self):\n        return recent_buffers()\n\n\nclass BufferSwitchListPrompt(BufferListPrompt):\n    label = \"switch to buffer:\"\n\n\nclass RecentBufferSwitchListPrompt(RecentBufferListPrompt):\n    label = \"switch to buffer:\"\n\n\nclass BufferKillListPrompt(BufferListPrompt):\n    label = \"kill all buffers except:\"\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        # auto-select the currently visible buffer\n        buffers = self.ordered_buffers()\n        minibuffer.input().popup().selectRow(buffers.index(current_buffer()))\n\n\ndef show_buffer(buffer, view):\n    \"\"\"\n    Display the given buffer in the given view.\n    \"\"\"\n    if view.buffer() == buffer:\n        # switch to the same buffer, nothing to do\n        return\n    if buffer.view():\n        # swap buffers if the buffer is already displayed\n        otherbuffer = view.buffer()\n        view.setBuffer(None)\n        otherview = buffer.view()\n        otherview.setBuffer(otherbuffer)\n    view.setBuffer(buffer)\n\n\n@define_command(\"switch-buffer\")\ndef switch_buffer(ctx):\n    \"\"\"\n    Prompt to select a buffer to display in the current view.\n    \"\"\"\n    buffer = ctx.minibuffer.do_prompt(BufferSwitchListPrompt(ctx))\n    if buffer:\n        show_buffer(buffer, ctx.view)\n\n\n@define_command(\"switch-recent-buffer\")\ndef switch_recent_buffer(ctx):\n    \"\"\"\n    Prompt to select a buffer to display in the current view.\n    \"\"\"\n    buffer = ctx.minibuffer.do_prompt(RecentBufferSwitchListPrompt(ctx))\n    if buffer:\n        show_buffer(buffer, ctx.view)\n\n\ndef _next_buffer(ctx, reverse=False):\n    if len(BUFFERS) <= 1:\n        return\n\n    buffers = itertools.cycle(reversed(BUFFERS) if reverse else BUFFERS)\n    next_b = next(buffers)\n    while next_b != ctx.buffer:\n        next_b = next(buffers)\n\n    show_buffer(next(buffers), ctx.view)\n\n\n@define_command(\"next-buffer\")\ndef next_buffer(ctx):\n    \"\"\"\n    Cycle to the next buffer in the current view.\n    \"\"\"\n    _next_buffer(ctx)\n\n\n@define_command(\"previous-buffer\")\ndef previous_buffer(ctx):\n    \"\"\"\n    Cycle to the previous buffer in the current view.\n    \"\"\"\n    _next_buffer(ctx, reverse=True)\n\n\nclass OpenDevToolsPrompt(BufferListPrompt):\n    label = \"open dev tools for buffer:\"\n    keymap = None\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        # auto-select the currently visible buffer\n        minibuffer.input().popup().selectRow(0)\n\n\n@define_command(\"open-dev-tools\")\ndef open_dev_tools(ctx):\n    \"\"\"\n    Opens a dev tool page for a buffer.\n    \"\"\"\n    buffer = ctx.minibuffer.do_prompt(OpenDevToolsPrompt(ctx))\n    if buffer:\n        dev_tools = create_buffer()\n        buffer.setDevToolsPage(dev_tools)\n\n\n@define_command(\"go-forward\")\ndef go_forward(ctx):\n    \"\"\"\n    Navigate forward in history for the current buffer.\n    \"\"\"\n    if not ctx.buffer.history().canGoForward():\n        ctx.minibuffer.show_info(\"Can't go forward in history.\")\n    else:\n        ctx.buffer.runJavaScript(\"history.go(1)\",\n                                 QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n\n@define_command(\"go-backward\")\ndef go_backward(ctx):\n    \"\"\"\n    Navigate backward in history for the current buffer.\n    \"\"\"\n    if not ctx.buffer.history().canGoBack():\n        ctx.minibuffer.show_info(\"Can't go back in history.\")\n    else:\n        ctx.buffer.runJavaScript(\"history.go(-1)\",\n                                 QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n\n@define_command(\"scroll-down\")\ndef scroll_down(ctx):\n    \"\"\"\n    Scroll the current buffer down a bit.\n    \"\"\"\n    ctx.buffer.scroll_by(y=20)\n\n\n@define_command(\"scroll-up\")\ndef scroll_up(ctx):\n    \"\"\"\n    Scroll the current buffer up a bit.\n    \"\"\"\n    ctx.buffer.scroll_by(y=-20)\n\n\n@define_command(\"scroll-page-down\")\ndef scroll_page_down(ctx):\n    \"\"\"\n    Scroll the current buffer one page down.\n    \"\"\"\n    send_key_event(KeyPress.from_str(\"PageDown\"))\n\n\n@define_command(\"scroll-page-up\")\ndef scroll_page_up(ctx):\n    \"\"\"\n    Scroll the current buffer one page up.\n    \"\"\"\n    send_key_event(KeyPress.from_str(\"PageUp\"))\n\n\n@define_command(\"scroll-top\")\ndef scroll_top(ctx):\n    \"\"\"\n    Scroll the current buffer to the top.\n    \"\"\"\n    send_key_event(KeyPress.from_str(\"Home\"))\n\n\n@define_command(\"scroll-bottom\")\ndef scroll_bottom(ctx):\n    \"\"\"\n    Scroll the current buffer to the bottom.\n    \"\"\"\n    send_key_event(KeyPress.from_str(\"End\"))\n\n\n@define_command(\"webcontent-copy\")\ndef webcontent_copy(ctx):\n    \"\"\"\n    Copy the selection in the current buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Copy)\n\n\n@define_command(\"webcontent-cut\")\ndef webcontent_cut(ctx):\n    \"\"\"\n    Cut the selection in the current buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Cut)\n\n\n@define_command(\"webcontent-paste\")\ndef webcontent_paste(ctx):\n    \"\"\"\n    Paste the selection in the current buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Paste)\n\n\n@define_command(\"reload-buffer\")\ndef reload_buffer(ctx):\n    \"\"\"\n    Reload the current buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Reload)\n\n\n@define_command(\"reload-buffer-no-cache\")\ndef reload_buffer_no_cache(ctx):\n    \"\"\"\n    Reload the current buffer bypassing any cache.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.ReloadAndBypassCache)\n\n\n@define_command(\"close-buffer\")\ndef buffer_close(ctx):\n    \"\"\"\n    Close the current buffer.\n    \"\"\"\n    close_buffer(ctx.buffer)\n\n\n@define_command(\"close-other-buffers\")\ndef close_other_buffers(ctx):\n    \"\"\"\n    Close all but one buffer.\n    \"\"\"\n    # Select a buffer\n    buffer = ctx.minibuffer.do_prompt(BufferKillListPrompt(ctx))\n    if buffer:\n        # Get all other buffers and kill them\n        for wb in [b for b in BUFFERS if b != buffer]:\n            close_buffer(wb)\n\n\n@define_command(\"select-buffer-content\")\ndef buffer_select_content(ctx):\n    \"\"\"\n    Select all content in the buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.SelectAll)\n\n\n@define_command(\"zoom-in\")\ndef zoom_in(ctx):\n    \"\"\"\n    Zoom-in in the buffer.\n    \"\"\"\n    ctx.buffer.zoom_in()\n\n\n@define_command(\"zoom-out\")\ndef zoom_out(ctx):\n    \"\"\"\n    Zoom-out in the buffer.\n    \"\"\"\n    ctx.buffer.zoom_out()\n\n\n@define_command(\"zoom-normal\")\ndef zoom_normal(ctx):\n    \"\"\"\n    Zoom-normal in the buffer.\n    \"\"\"\n    ctx.buffer.zoom_normal()\n\n\ndef _show_info_text_zoom(ctx):\n    def _wrapper(ratio):\n        ctx.minibuffer.show_info(\"Text zoom level: %02d%%\"\n                                 % (ratio * 100))\n    return _wrapper\n\n\n@define_command(\"text-zoom-in\")\ndef text_zoom_in(ctx):\n    \"\"\"\n    Zom in (text only) in the buffer.\n    \"\"\"\n    ctx.buffer.runJavaScript(\"textzoom.changeFont(0.1);\",\n                             QWebEngineScript.ScriptWorldId.ApplicationWorld,\n                             _show_info_text_zoom(ctx))\n\n\n@define_command(\"text-zoom-out\")\ndef text_zoom_out(ctx):\n    \"\"\"\n    Zom out (text only) in the buffer.\n    \"\"\"\n    ctx.buffer.runJavaScript(\"textzoom.changeFont(-0.1);\",\n                             QWebEngineScript.ScriptWorldId.ApplicationWorld,\n                             _show_info_text_zoom(ctx))\n\n\n@define_command(\"text-zoom-reset\")\ndef text_zoom_reset(ctx):\n    \"\"\"\n    Reset the zoom (text only) in the buffer.\n    \"\"\"\n    ctx.buffer.runJavaScript(\"textzoom.resetChangeFont();\",\n                             QWebEngineScript.ScriptWorldId.ApplicationWorld,\n                             _show_info_text_zoom(ctx))\n\n\n@define_command(\"buffer-unselect\")\ndef buffer_unselect(ctx):\n    \"\"\"\n    Unselect selection in the current web buffer.\n    \"\"\"\n    ctx.buffer.triggerAction(WebBuffer.WebAction.Unselect)\n\n\n@define_command(\"buffer-escape\")\ndef buffer_escape(ctx):\n    \"\"\"\n    Clear selection or menus in the current buffer.\n\n    The implementation clears the selection in the buffer if there is any, else\n    it sends the Escape key which usually closes whatever takes the focus.\n    \"\"\"\n    if ctx.buffer.hasSelection():\n        buffer_unselect(ctx)\n    else:\n        send_key_event(KeyPress.from_str(\"Esc\"))\n\n\nclass KilledBufferTableModel(QAbstractTableModel):\n\n    def __init__(self):\n        QAbstractTableModel.__init__(self)\n        self._buffers = list(KilledBuffer.all)\n\n    def rowCount(self, index=QModelIndex()):\n        return len(self._buffers)\n\n    def columnCount(self, index=QModelIndex()):\n        return 2\n\n    def data(self, index, role=Qt.ItemDataRole.DisplayRole):\n        killed_buff = index.internalPointer()\n        if not killed_buff:\n            return\n\n        col = index.column()\n        if role == Qt.ItemDataRole.DisplayRole:\n            if col == 0:\n                return killed_buff.url.toString()\n            else:\n                return killed_buff.title\n        elif role == Qt.ItemDataRole.DecorationRole and col == 0:\n            return killed_buff.icon\n\n    def index(self, row, col, parent=QModelIndex()):\n        try:\n            return self.createIndex(row, col, self._buffers[row])\n        except IndexError:\n            return QModelIndex()\n\n\nclass KilledBufferListPrompt(Prompt):\n    label = \"buffer to revive:\"\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    value_return_index_data = True\n\n    def completer_model(self):\n        return KilledBufferTableModel()\n\n    def enable(self, minibuffer):\n        Prompt.enable(self, minibuffer)\n        if KilledBuffer.all:\n            minibuffer.input().popup().selectRow(0)\n\n\n@define_command(\"revive-buffer\")\ndef revive_buffer(ctx):\n    \"\"\"\n    Revive a previously killed buffer in the current view.\n    \"\"\"\n    killed_buffer = ctx.minibuffer.do_prompt(KilledBufferListPrompt(ctx))\n    if killed_buffer:\n        buff = killed_buffer.revive()\n        ctx.window.current_webview().setBuffer(buff)\n\n\n@define_command(\"copy-current-link\")\ndef copy_current_link(ctx):\n    \"\"\"\n    Copy the current link to the clipboard.\n    \"\"\"\n\n    # note the implementation does not rely on the CopyLinkToClipboard action\n    # as it does not work fully (e.g, in case a link is set current using an\n    # incremental search).\n    buffer = ctx.buffer\n    minibuff = ctx.minibuffer\n\n    def copy_to_clipboard(url):\n        buffer.content_handler.foundCurrentLinkUrl \\\n                              .disconnect(copy_to_clipboard)\n        if url:\n            clipboard.set_text(url)\n        else:\n            minibuff.show_info(\"No current link url to copy.\")\n\n    buffer.content_handler.foundCurrentLinkUrl.connect(copy_to_clipboard)\n    buffer.runJavaScript(\"currentLinkUrl();\",\n                         QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n\n@define_command(\"copy-current-buffer-url\")\ndef copy_buffer_url(ctx):\n    \"\"\"\n    Copy the URL of the current buffer to the clipboard.\n    \"\"\"\n    url = str(ctx.buffer.url().toEncoded(), \"utf-8\")\n    clipboard.set_text(url)\n\n\n@define_command(\"copy-current-buffer-title\")\ndef copy_buffer_title(ctx):\n    \"\"\"\n    Copy the title of the current buffer to the clipboard.\n    \"\"\"\n    clipboard.set_text(ctx.buffer.title())\n\n\n@define_command(\"print-buffer\")\ndef print_buffer(ctx):\n    \"\"\"\n    Opens a dialog to select the printer and prints the current buffer.\n    \"\"\"\n    from ..application import WithoutAppEventFilter\n\n    def notif(ok):\n        GLOBAL_OBJECTS.unref(printer)\n        ctx.minibuffer.show_info(\"print successful\" if ok\n                                 else \"failed to print\")\n\n    printer = QPrinter()\n    dlg = QPrintDialog(printer)\n    with WithoutAppEventFilter():\n        ok = dlg.exec() == dlg.Accepted\n    if ok:\n        # printer must be kept around to avoid a crash.\n        # it must be released in the notif callback\n        GLOBAL_OBJECTS.ref(printer)\n        ctx.minibuffer.show_info(\"printing...\")\n        ctx.buffer.print(printer, notif)\n\n\n@define_command(\"password-manager-fill-buffer\")\ndef password_manager_fill_buffer(ctx):\n    \"\"\"\n    Fill the current buffer inputs using password manager data.\n    \"\"\"\n    password_mgr = app().profile.password_manager\n    url = ctx.buffer.url().toString()\n    try:\n        cred = password_mgr.credential_for_url(url)\n    except PasswordManagerNotReady as exc:\n        ctx.minibuffer.show_info(str(exc))\n        return\n    if cred:\n        password_mgr.complete_buffer(ctx.buffer, cred)\n"
  },
  {
    "path": "webmacs/commands/webjump.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport re\nimport logging\nfrom collections import namedtuple\n\nfrom PyQt6.QtCore import QUrl, pyqtSlot as Slot, \\\n    pyqtSignal as Signal, QStringListModel, QObject, QEvent, Qt\nfrom PyQt6.QtNetwork import QNetworkRequest\n\nfrom ..commands import define_command\nfrom ..minibuffer.prompt import Prompt, PromptTableModel, PromptHistory\nfrom .. keymaps import WEBJUMP_KEYMAP\nfrom ..commands import register_prompt_opener_commands\nfrom .. import current_buffer\nfrom ..application import app\nfrom .. import variables\nfrom .. import version\n\n\nWebJump = namedtuple(\n    \"WebJump\", (\"name\", \"url\", \"doc\", \"allow_args\", \"complete_fn\", \"protocol\"))\nWEBJUMPS = {}\n\n\nwebjump_default = variables.define_variable(\n    \"webjump-default\",\n    \"The default webjump\",\n    \"\",\n    type=variables.String(choices=WEBJUMPS),\n)\n\n\ndef define_webjump(name, url, doc=\"\", complete_fn=None, protocol=False):\n    \"\"\"\n    Define a webjump.\n\n    A webjump is a quick way to access a URL, optionally with a\n    variable section (for example a URL for a Google search). A\n    function may be given to provide auto-completion.\n\n    :param name: the name of the webjump.\n    :param url: the url of the webjump. If the url contains \"%s\", it is\n        assumed that it has a variable part.\n    :param doc: associated documentation for the webjump.\n    :param complete_fn: a function that should create a suitable\n        :class:`WebJumpCompleter` to provide auto-completion, or None if there\n        is no completion support for this webjump.\n    :param protocol: True if the webjump should be treated as the protocol\n                     part of a URI (eg: file://)\n\n    \"\"\"\n    allow_args = \"%s\" in url\n    WEBJUMPS[name.strip()] = WebJump(\n        name.strip(), url,\n        doc,\n        allow_args,\n        complete_fn or empty_completer,\n        protocol\n    )\n\n\ndef define_webjump_alias(alias_name, webjump_name):\n    \"\"\"\n    Define an alias for an existing webjump.\n\n    The alias can then be used as a shortcut.\n    :param alias_name: the name of the alias to be created.\n    :param webjump_name: the name of the existing webjump.\n\n    \"\"\"\n    w = WEBJUMPS[webjump_name]\n\n    define_webjump(alias_name.strip(), url=w.url,\n                   doc=w.doc, complete_fn=w.complete_fn, protocol=w.protocol)\n\n\ndef define_protocol(name, doc=\"\", complete_fn=None):\n    define_webjump(name, name + \"://%s\", doc, complete_fn, True)\n\n\ndef set_default(name):\n    \"\"\"\n    Set the default webjump.\n\n    Deprecated: use the *webjump-default* variable instead.\n\n    :param name: the name of the webjump.\n    \"\"\"\n    webjump_default.set_value(name)\n\n\nclass WebJumpCompleter(object if version.building_doc else QObject):\n\n    \"\"\"\n    Provides auto-completion in webjumps.\n\n    An instance is created automatically when required, and lives while the\n    webjump is active. When a key is entered in the minibuffer input, the\n    method :meth:`complete` is called with the current text, asking for\n    completion.\n\n    The signal `completed` must then be emitted with the list of possible\n    completions.\n\n    Note that there is no underlying thread in the completion framework.\n    \"\"\"\n    completed = Signal(list)\n\n    def complete(self, text):\n        \"\"\"Must be implemented by subclasses.\"\"\"\n        raise NotImplementedError\n\n    def abort(self):\n        \"\"\"\n        Called when the completion request should be aborted.\n\n        Subclasses should implement this if possible.\n        \"\"\"\n        pass\n\n\nclass SyncWebJumpCompleter(WebJumpCompleter):\n\n    \"\"\"\n    A simple completer that provides completion given a function.\n\n    This completer will block the UI: use it with care.\n\n    :param complete_fn: a function that takes the current string, and must\n        return the possible completions as a list of strings.\n    \"\"\"\n\n    def __init__(self, complete_fn):\n        WebJumpCompleter.__init__(self)\n        self.complete_fn = complete_fn\n\n    def complete(self, text):\n        self.completed.emit(self.complete_fn(text))\n\n\ndef empty_completer():\n    return SyncWebJumpCompleter(lambda _: [])\n\n\nclass WebJumpRequestCompleter(WebJumpCompleter):\n\n    \"\"\"\n    A completer that executes a Web request to provide completion.\n\n    This completer will not block the UI.\n\n    :param url_fn: a function that takes the text to complete, and returns a\n        URL that will provide completion. The returned value can be none\n        if no URL is suitable for the given text.\n    :param extract_completions_fn: a function that takes the bytes of the\n        request reply, and must convert them to the completions\n        (a string list).\n    \"\"\"\n\n    def __init__(self, url_fn, extract_completions_fn):\n        WebJumpCompleter.__init__(self)\n        self.url_fn = url_fn\n        self.extract_completions_fn = extract_completions_fn\n        self.reply = None\n\n    def complete(self, text):\n        url = self.url_fn(text)\n        if not url:\n            self.completed.emit([])\n            return\n        elif not isinstance(url, QUrl):\n            url = QUrl(url)\n        req = QNetworkRequest(QUrl(url))\n        self.reply = app().network_manager.get(req)\n        self.reply.finished.connect(self._on_reply_finished)\n\n    def abort(self):\n        if self.reply:\n            self.reply.abort()\n\n    def _on_reply_finished(self):\n        if self.reply.error() == self.reply.NetworkError.NoError:\n            try:\n                completions = self.extract_completions_fn(self.reply.readAll())\n            except Exception:\n                logging.exception(\n                    \"Error when trying to extract completions from %s\"\n                    % self.reply.url().toString()\n                )\n                completions = []\n            self.completed.emit(completions)\n\n        self.reply.deleteLater()\n        self.reply = None\n\n\n@define_command(\"webjump-complete\")\ndef wb_complete(ctx):\n    \"\"\"\n    Complete webjump name in the minibuffer.\n    \"\"\"\n    input = ctx.minibuffer.input()\n    if not input.popup().isVisible():\n        input.show_completions()\n    else:\n        input.complete()\n        ctx.minibuffer.prompt()._text_edited(input.text())\n\n\nclass WebJumpPrompt(Prompt):\n    label = \"url/webjump:\"\n    complete_options = {\n        \"match\": Prompt.SimpleMatch\n    }\n    history = PromptHistory()\n    keymap = WEBJUMP_KEYMAP\n    default_input = \"alternate\"\n\n    def completer_model(self):\n        data = []\n        for name, w in WEBJUMPS.items():\n            data.append((name, w.doc))\n\n        for url, name in self.bookmarks:\n            data.append((name, url))\n\n        return PromptTableModel(data)\n\n    def enable(self, minibuffer):\n        self.bookmarks = app().bookmarks().list()\n        Prompt.enable(self, minibuffer)\n        minibuffer.input().textEdited.connect(self._text_edited)\n        minibuffer.input().installEventFilter(self)\n        self._wc_model = QStringListModel()\n        self._wb_model = minibuffer.input().completer_model()\n        self._active_webjump = None\n        self._completer = None\n        self._popup_sel_model = None\n        input = minibuffer.input()\n        if self.default_input in (\"current_url\", \"alternate\"):\n            url = current_buffer().url().toString()\n            input.setText(url)\n            input.setSelection(0, len(url))\n            if self.default_input == \"alternate\":\n                input.deselect()\n        elif self.default_input == \"default_webjump\":\n            wj = WEBJUMPS.get(webjump_default.value)\n            if wj:\n                input.setText(\n                    wj.name + (\"://\" if wj.protocol else \" \")\n                )\n\n    def eventFilter(self, obj, event):\n        # call _text_edited on backspace release, as this is not reported by\n        # the textEdited slot.\n        if event.type() == QEvent.Type.KeyRelease:\n            if event.key() == Qt.Key.Key_Backspace:\n                self._text_edited(self.minibuffer.input().text())\n        return Prompt.eventFilter(self, obj, event)\n\n    def _set_active_webjump(self, wj):\n        if self._active_webjump == wj:\n            return\n\n        if self._active_webjump:\n            if self._completer:\n                self._completer.completed.disconnect(self._got_completions)\n                self._completer.abort()\n                self._completer.deleteLater()\n                self._completer = None\n\n        m_input = self.minibuffer.input()\n        if wj:\n            self._completer = wj.complete_fn()\n            self._completer.completed.connect(self._got_completions)\n            # set matching strategy\n            m_input.set_match(None)\n            model = self._wc_model\n        else:\n            m_input.set_match(Prompt.SimpleMatch)\n            model = self._wb_model\n\n        self._active_webjump = wj\n        if m_input.completer_model() != model:\n            m_input.popup().hide()\n            m_input.set_completer_model(model)\n            if self._popup_sel_model:\n                self._popup_sel_model.selectionChanged.disconnect(\n                    self._popup_selection_changed\n                )\n                self._popup_sel_model = None\n            if wj:\n                m_input.popup().selectionModel()\\\n                               .selectionChanged.connect(\n                                   self._popup_selection_changed\n                )\n\n    def _popup_selection_changed(self, _sel, _desel):\n        # try to abort any completion if the user select something in\n        # the popup\n        if self._completer:\n            self._completer.abort()\n\n    def _text_edited(self, text):\n        # search for a matching webjump\n        first_word = text.split(\" \")[0].split(\"://\")[0]\n        if first_word in [w for w in WEBJUMPS if len(w) < len(text)]:\n            self._set_active_webjump(WEBJUMPS[first_word])\n            self.start_completion(self._active_webjump)\n        else:\n            # didn't find a webjump, go back to matching\n            # webjump/bookmark/history\n            self._set_active_webjump(None)\n\n    def start_completion(self, webjump):\n        text = self.minibuffer.input().text()\n        prefix = webjump.name + (\"://\" if webjump.protocol else \" \")\n        self._completer.abort()\n        self._completer.complete(text[len(prefix):])\n\n    @Slot(list)\n    def _got_completions(self, data):\n        if self._active_webjump:\n            self._wc_model.setStringList(data)\n            text = self.minibuffer.input().text()\n            prefix = self._active_webjump.name + \\\n                (\"://\" if self._active_webjump.protocol else \" \")\n            self.minibuffer.input().show_completions(text[len(prefix):])\n\n    def close(self):\n        Prompt.close(self)\n        self.minibuffer.input().removeEventFilter(self)\n        # not sure if those are required;\n        self._wb_model.deleteLater()\n        self._wc_model.deleteLater()\n\n    def _on_completion_activated(self, index):\n        super()._on_completion_activated(index)\n\n        chosen_text = self.minibuffer.input().text()\n        # if there is already an active webjump,\n        if self._active_webjump:\n            # add the selected completion after it\n            if self._active_webjump.protocol:\n                self.minibuffer.input().setText(\n                    self._active_webjump.name + \"://\" + chosen_text)\n            else:\n                self.minibuffer.input().setText(\n                    self._active_webjump.name + \" \" + chosen_text)\n\n        # if we just chose a webjump\n        # and not WEBJUMPS[chosen_text].protocol:\n        elif chosen_text in WEBJUMPS:\n            # add a space after the selection\n            self.minibuffer.input().setText(\n                chosen_text + (\" \" if not WEBJUMPS[chosen_text].protocol\n                               else \"://\"))\n\n    def value(self):\n        value = super().value()\n        if value is None:\n            return\n\n        # split webjumps and protocols between command and argument\n        if re.match(r\"^\\S+://.*\", value):\n            args = value.split(\"://\", 1)\n        else:\n            args = value.split(\" \", 1)\n        command = args[0]\n\n        # Look for webjumps\n        webjump = None\n        if command in WEBJUMPS:\n            webjump = WEBJUMPS[command]\n        else:\n            # Look for a incomplete webjump, accepting a candidate\n            # if there is a single option\n            candidates = [wj for wj in WEBJUMPS if wj.startswith(command)]\n            if len(candidates) == 1:\n                webjump = WEBJUMPS[candidates[0]]\n\n        if webjump:\n            if not webjump.allow_args:\n                # send the url as is\n                return webjump.url\n            elif len(args) < 2:\n                # send the url without a search string\n                return webjump.url.replace(\"%s\", \"\")\n\n            else:\n                # format the url as entered\n                if webjump.protocol:\n                    return value\n                else:\n                    return webjump.url.replace(\n                        \"%s\",\n                        str(QUrl.toPercentEncoding(args[1]), \"utf-8\")\n                    )\n\n        # Look for a bookmark\n        bookmarks = {name: url\n                     for url, name in self.bookmarks}\n        if value in bookmarks:\n            return bookmarks[value]\n\n        # Look for a incomplete bookmarks, accepting a candidate\n        # if there is a single option\n        candidates = [bm for bm in bookmarks if bm.startswith(command)]\n        if len(candidates) == 1:\n            return bookmarks[candidates[0]]\n\n        # No webjump, no bookmark, look for a url\n        if \"://\" not in value:\n            url = QUrl.fromUserInput(value)\n            if url.isValid():\n                # default scheme is https for us\n                if url.scheme() == \"http\":\n                    url.setScheme(\"https\")\n                return url\n        return value\n\n\ndef wj_prompt(default_input):\n    def prompt_ctor(ctx):\n        p = WebJumpPrompt(ctx)\n        p.default_input = default_input\n        return p\n    return prompt_ctor\n\n\nregister_prompt_opener_commands(\n    \"go-to\",\n    wj_prompt(\"current_url\"),\n    \"Prompt to open a URL or a webjump\",\n)\n\nregister_prompt_opener_commands(\n    \"go-to-alternate-url\",\n    wj_prompt(\"alternate\"),\n    \"Prompt to open an alternative URL from the current one\",\n)\n\nregister_prompt_opener_commands(\n    \"search-default\",\n    wj_prompt(\"default_webjump\"),\n    \"Prompt to open a URL with the default webjump\",\n)\n"
  },
  {
    "path": "webmacs/content_handler.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport json\n\nfrom PyQt6.QtCore import QObject, pyqtSlot as Slot, pyqtSignal as Signal\nfrom PyQt6.QtWebEngineCore import QWebEngineScript\n\nfrom .keyboardhandler import LOCAL_KEYMAP_SETTER\nfrom .external_editor import open_external_editor\nfrom . import clipboard\n\n\nclass WebContentHandler(QObject):\n    \"\"\"\n    Interface to communicate with the javascript side in the web pages.\n    \"\"\"\n    browserObjectActivated = Signal(dict)\n    foundCurrentLinkUrl = Signal(str)\n    # for testing, when the hints are ready\n    browserObjectsInited = Signal()\n\n    def __init__(self, buff):\n        QObject.__init__(self)\n        self.buffer = buff\n\n    @Slot(bool)\n    def onTextFocus(self, enabled):\n        LOCAL_KEYMAP_SETTER.web_content_edit_focus_changed(self.buffer,\n                                                           enabled)\n\n    @Slot(str)\n    def currentLinkUrl(self, url):\n        self.foundCurrentLinkUrl.emit(url)\n\n    @Slot(bool)\n    def onCaretBrowsing(self, enabled):\n        LOCAL_KEYMAP_SETTER.caret_browsing_changed(self.buffer, enabled)\n\n    @Slot(str)\n    def _browserObjectActivated(self, obj):\n        # It is hard to pass dict objects from javascript, so a string is used\n        # and decoded here.\n        obj = json.loads(obj)\n        if obj is not None:\n            self.browserObjectActivated.emit(obj)\n        else:\n            self.browserObjectsInited.emit()\n\n    @Slot(str)\n    def copyToClipboard(self, text):\n        clipboard.set_text(text)\n\n    @Slot(str, str)\n    def openExternalEditor(self, request_id, content):\n        new_content = open_external_editor(content.encode(\"utf-8\"))\n        if new_content is None:\n            new_content = 'false'\n        else:\n            new_content = repr(new_content)\n        self.buffer.runJavaScript(\n            \"textedit.external_editor_finish({}, {});\".format(\n                repr(request_id),\n                new_content\n            ),\n            QWebEngineScript.ScriptWorldId.ApplicationWorld\n        )\n"
  },
  {
    "path": "webmacs/default_webjumps.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport json\n\nfrom PyQt6.QtCore import QUrl\n\nfrom .commands.webjump import define_webjump, define_protocol, \\\n    webjump_default, WebJumpRequestCompleter, SyncWebJumpCompleter\nfrom .minibuffer.prompt import FSModel\nfrom .scheme_handlers.webmacs import PAGES as webmacs_pages\n\n\n# ----------- doc example\n\ndef complete_google():\n    def url_fn(text):\n        if not text:\n            return None\n        return (\n            \"https://www.google.com/complete/search?client=firefox&q=\"\n            + str(QUrl.toPercentEncoding(text), \"utf-8\"))\n\n    return WebJumpRequestCompleter(\n        url_fn,\n        lambda response: json.loads(str(response, \"utf-8\"))[1]\n    )\n\n\ndefine_webjump(\"google\",\n               \"https://www.google.com/search?q=%s&ie=utf-8&oe=utf-8\",\n               \"Google Search\",\n               complete_fn=complete_google)\n\n# ----------- end of doc example\n\n\ndef complete_fs():\n    model = FSModel()\n\n    def _complete(text):\n        model.text_changed(text)\n        dircontent = [model.data(model.index(i, 0))\n                      for i in range(model.rowCount())]\n        return [c for c in dircontent if c.startswith(text)]\n\n    return SyncWebJumpCompleter(_complete)\n\n\ndefine_protocol(\"file\",\n                \"Local uris\",\n                complete_fn=complete_fs)\n\n\ndef complete_pages():\n    return SyncWebJumpCompleter(\n        lambda text: [p for p in webmacs_pages if text in p]\n    )\n\n\ndefine_protocol(\"webmacs\",\n                \"webmacs internal pages\",\n                complete_fn=complete_pages)\n\n\ndef complete_protocol(protocol):\n\n    def complete():\n        completer = complete_google()\n        extract_fn = completer.extract_completions_fn\n        url_fn = completer.url_fn\n\n        completer.extract_completions_fn \\\n            = lambda data: [r[len(protocol):]\n                            for r in extract_fn(data)\n                            if r.startswith(protocol)]\n\n        completer.url_fn \\\n            = lambda text: url_fn(protocol + text)\n        return completer\n    return complete\n\n\ndefine_protocol(\"http\",\n                \"web sites\",\n                complete_fn=complete_protocol(\"http://\"))\n\ndefine_protocol(\"https\",\n                \"secure web sites\",\n                complete_fn=complete_protocol(\"https://\"))\n\n\ndef complete_duckduckgo():\n    def url_fn(text):\n        if not text:\n            return None\n        # took from https://github.com/jarun/ddgr/blob/master/ddgr\n        return (\n            'https://duckduckgo.com/ac/?q=%s&kl=wt-wt' %\n            str(QUrl.toPercentEncoding(text), \"utf-8\")\n        )\n\n    return WebJumpRequestCompleter(\n        url_fn,\n        lambda response: [e[\"phrase\"]\n                          for e in json.loads(str(response, \"utf-8\"))]\n    )\n\n\ndefine_webjump(\"duckduckgo\",\n               \"https://www.duckduckgo.com/?q=%s\",\n               \"Duckduckgo Search\",\n               complete_fn=complete_duckduckgo)\n\nwebjump_default.set_value(\"google\")\n"
  },
  {
    "path": "webmacs/download_manager/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport re\nimport json\nimport shlex\nimport logging\nimport itertools\nimport tempfile\n\nfrom PyQt6.QtCore import QObject, pyqtSlot as Slot, pyqtSignal as Signal, \\\n    QProcess\n\nfrom PyQt6.QtWebEngineCore import QWebEngineDownloadRequest\n\nfrom .prompts import (DlChooseActionPrompt, DlOpenActionPrompt, DlPrompt,\n                      OverwriteFilePrompt)\nfrom .. import current_minibuffer, hooks, variables\n\n\ndefault_download_dir = variables.define_variable(\n    \"default-download-dir\",\n    \"Change the default download dir.\",\n    \"\",\n    type=variables.String(),\n)\n\nTEMPORARY_DOWNLOAD_DIR = None\nkeep_temporary_download_dir = variables.define_variable(\n    \"keep-temporary-download-dir\",\n    \"If set to True, the download dir proposed will be the last used one.\",\n    False,\n    type=variables.Bool(),\n)\n\n\ndef dl_path(dl):\n    return os.path.join(dl.downloadDirectory(), dl.suggestedFileName())\n\n\ndef get_user_download_dir():\n    \"\"\"\n    Returns the directory the user wants to put its download in.\n\n    Return None if there is no specific directory.\n    \"\"\"\n    if keep_temporary_download_dir.value and TEMPORARY_DOWNLOAD_DIR:\n        return TEMPORARY_DOWNLOAD_DIR\n    return default_download_dir.value or None\n\n\n\ndef find_unique_suggested_path(dirname, filename):\n    \"\"\"\n    Do the same logic as chromium does to create a unique path suggestion.\n    \"\"\"\n    fnames = set(os.listdir(dirname))\n\n    if filename not in fnames:\n        return os.path.join(dirname, filename)\n\n    parts = filename.split(\".\", 1)\n    if len(parts) == 1:\n        name, ext = parts[0], \"\"\n    else:\n        name, ext = parts[0], \".\" + parts[1]\n\n    counter = itertools.count(1)\n    while True:\n        newfname = \"{}({}){}\".format(name, next(counter), ext)\n        if newfname not in fnames:\n            return os.path.join(dirname, newfname)\n\n\nSTATE_STR = {\n    QWebEngineDownloadRequest.DownloadState.DownloadRequested: \"Requested\",\n    QWebEngineDownloadRequest.DownloadState.DownloadInProgress: \"In progress\",\n    QWebEngineDownloadRequest.DownloadState.DownloadCompleted: \"Completed\",\n    QWebEngineDownloadRequest.DownloadState.DownloadCancelled: \"Cancelled\",\n    QWebEngineDownloadRequest.DownloadState.DownloadInterrupted: \"Interrupted\",\n}\n\n\ndef state_str(state):\n    return STATE_STR.get(state, \"Unknown state\")\n\n\ndef download_to_json(dlitem):\n    try:\n        progress = (round(dlitem.receivedBytes() / float(dlitem.totalBytes())\n                          * 100, 2))\n    except ZeroDivisionError:\n        progress = -1\n    return json.dumps({\n        \"path\": dl_path(dlitem),\n        \"state\": state_str(dlitem.state()),\n        \"id\": dlitem.id(),\n        \"isFinished\": dlitem.isFinished(),\n        \"progress\": progress,\n    })\n\n\nclass DownloadManager(QObject):\n    download_started = Signal(object)\n\n    def __init__(self, parent=None):\n        QObject.__init__(self, parent)\n        self.downloads = []\n        self._buffers = []  # list of web buffers currently showing downloads\n        self._running_procs = {}\n\n        def on_buffer_load_finished(buff):\n            url = buff.url()\n            if url.scheme() == \"webmacs\" and url.authority() == \"downloads\":\n                self.attach_buffer(buff)\n            else:\n                self.detach_buffer(buff)\n\n        hooks.webbuffer_load_finished.add(on_buffer_load_finished)\n        hooks.webbuffer_closed.add(self.detach_buffer)\n\n    def attach_buffer(self, buffer):\n        self._buffers.append(buffer)\n        for dl in self.downloads:\n            buffer.runJavaScript(\"add_download(%s);\" % download_to_json(dl))\n\n    def detach_buffer(self, buffer):\n        try:\n            self._buffers.remove(buffer)\n        except ValueError:\n            pass\n\n    def _start_download(self, dlitem):\n        dlitem.accept()\n        self.downloads.append(dlitem)\n        dlitem.destroyed.connect(lambda: self.downloads.remove(dlitem))\n        self.download_started.emit(dlitem)\n        dl = download_to_json(dlitem)\n        for buffer in self._buffers:\n            buffer.runJavaScript(\"add_download(%s);\" % dl)\n        dlitem.receivedBytesChanged.connect(self._download_state_changed)\n        dlitem.totalBytesChanged.connect(self._download_state_changed)\n        dlitem.stateChanged.connect(self._download_state_changed)\n        dlitem.isFinishedChanged.connect(self._download_state_changed)\n        dlitem.isFinishedChanged.connect(dlitem.deleteLater)\n\n    @Slot()\n    def _download_state_changed(self):\n        dlitem = self.sender()\n        dl = download_to_json(dlitem)\n        for buffer in self._buffers:\n            buffer.runJavaScript(\"update_download(%s);\" % dl)\n\n    @Slot(\"QWebEngineDownloadRequest*\")\n    def download_requested(self, dl):\n        minibuff = current_minibuffer()\n\n        prompt = DlChooseActionPrompt(os.path.join(dl.downloadDirectory(),\n                                                   dl.suggestedFileName()),\n                                      dl.mimeType())\n        action = minibuff.do_prompt(prompt)\n\n        if action == \"open\":\n            prompt = DlOpenActionPrompt()\n            executable = minibuff.do_prompt(prompt)\n            if executable is None:\n                return\n\n            dl.setDownloadDirectory(tempfile.gettempdir())\n            \n            logging.info(f\"Downloading {dl_path(dl)}...\")\n\n            def finished():\n                if dl.state() == \\\n                   QWebEngineDownloadRequest.DownloadState.DownloadCompleted:\n                    logging.info(\n                        f\"Opening external file {dl_path(dl)} with {executable}\")\n                    self._run_program(executable, dl_path(dl))\n\n            dl.isFinishedChanged.connect(finished)\n            self._start_download(dl)\n\n        elif action == \"download\":\n            dl_dir = get_user_download_dir() or dl.downloadDirectory()\n            name = dl.suggestedFileName()\n            path = os.path.join(dl_dir, name)\n            if os.path.exists(path):\n                try:\n                    path = find_unique_suggested_path(dl_dir, name)\n                except OSError as exc:\n                    logging.warning(\n                        \"Can't use user_dir %s: %s\", user_dir, str(exc)\n                    )\n\n            prompt = DlPrompt(path, dl.mimeType())\n            path = minibuff.do_prompt(prompt)\n            if path is None:\n                return\n\n            if os.path.isdir(path):\n                path = find_unique_suggested_path(path, name)\n\n            if os.path.isfile(path):\n                if not minibuff.do_prompt(OverwriteFilePrompt(path)):\n                    return\n\n            dl.setDownloadDirectory(os.path.dirname(path))\n            dl.setDownloadFileName(os.path.basename(path))\n            if keep_temporary_download_dir.value:\n                global TEMPORARY_DOWNLOAD_DIR\n                TEMPORARY_DOWNLOAD_DIR = os.path.dirname(path)\n\n            logging.info(\"Downloading %s...\", path)\n\n            def finished():\n                state = state_str(dl.state())\n                logging.info(\"Finished download [%s] of %s\", state, dl_path(dl))\n                minibuff.show_info(\"[{}] download: {}\".format(state,\n                                                              dl_path(dl)))\n            dl.isFinishedChanged.connect(finished)\n            self._start_download(dl)\n\n    def _run_program(self, executable, path):\n        shell_arg = \"{} {}\".format(executable, shlex.quote(path))\n        args = [\"-c\", shell_arg]\n        shell = get_shell()\n        proc = QProcess()\n        self._running_procs[proc] = path\n\n        logging.debug(\"Executing command: %s %s\", shell, \" \".join(args))\n\n        proc.finished.connect(self._program_finished)\n        proc.start(shell, args, QProcess.OpenModeFlag.ReadOnly)\n\n    @Slot(int, QProcess.ExitStatus)\n    def _program_finished(self, code, status):\n        proc = self.sender()\n        path = self._running_procs.pop(proc)\n        logging.debug(\"Removing downloaded file %s\", path)\n        try:\n            os.unlink(path)\n        except Exception:\n            pass\n\n\ndef get_shell():\n    return os.environ.get(\"SHELL\", \"/bin/sh\")\n"
  },
  {
    "path": "webmacs/download_manager/prompts.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\n\nfrom ..minibuffer.prompt import Prompt, FSModel, PromptTableModel, YesNoPrompt\n\n\ndef OverwriteFilePrompt(path):\n    return YesNoPrompt(\"File {} already exists. Overwrite it?\".format(path))\n\n\nclass DlChooseActionPrompt(Prompt):\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    value_return_index_data = True\n\n    def __init__(self, path, mimetype):\n        Prompt.__init__(self, None)\n        self.__actions = [\n            (\"download\", \"download file on disk\"),\n            (\"open\", \"open file with external command\"),\n        ]\n        name = os.path.basename(path)\n        if len(name) > 33:\n            name = name[:30] + \"...\"\n        self.label = \"File {} [{}]: \".format(name, mimetype)\n\n    def completer_model(self):\n        return PromptTableModel(self.__actions)\n\n    def enable(self, minibuffer):\n        super().enable(minibuffer)\n        minibuffer.input().popup().selectRow(0)\n\n\nclass DlOpenActionPrompt(Prompt):\n    complete_options = {\n        \"match\": Prompt.FuzzyMatch,\n        \"complete-empty\": True,\n    }\n    label = \"Open file with:\"\n    value_return_index_data = True\n\n    def __init__(self):\n        Prompt.__init__(self, None)\n\n    def completer_model(self):\n        return PromptTableModel([[e] for e in list_executables()])\n\n\nclass DlPrompt(Prompt):\n    complete_options = {\n        \"autocomplete\": True\n    }\n\n    def __init__(self, path, mimetype):\n        Prompt.__init__(self, None)\n        self.label = \"Download file [{}]:\".format(mimetype)\n        self._dlpath = path\n\n    def completer_model(self):\n        # todo, not working\n        model = FSModel(self)\n        return model\n\n    def enable(self, minibuffer):\n        super().enable(minibuffer)\n        minibuffer.input().setText(self._dlpath)\n\n\ndef list_executables():\n    try:\n        paths = os.environ[\"PATH\"].split(os.pathsep)\n    except KeyError:\n        return []\n\n    executables = []\n    for path in paths:\n        try:\n            for file_ in os.listdir(path):\n                if os.access(os.path.join(path, file_), os.X_OK):\n                    executables.append(file_)\n        except Exception:\n            pass\n\n    return executables\n"
  },
  {
    "path": "webmacs/egrid.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtWidgets import QLayout\nfrom PyQt6.QtCore import QRect, QSize\n\nfrom . import call_later, BUFFERS\nfrom .webview import WebView\n\n\nclass LayoutEntry(object):\n\n    def __init__(self, parent=None, item=None):\n        self.parent = parent\n        self.item = item\n        self.split = None\n        self.children = []\n\n    def do_split(self, item, direction):\n        assert self.item\n        if self.parent and self.parent.split == direction:\n            index = self.parent.children.index(self)\n            self.parent.children.insert(\n                index+1,\n                LayoutEntry(parent=self.parent, item=item))\n        else:\n            self.split = direction\n            self.children.append(LayoutEntry(parent=self, item=self.item))\n            self.children.append(LayoutEntry(parent=self, item=item))\n            self.item = None\n\n    def pop(self):\n        assert self.parent\n        parent = self.parent\n        parent.children.remove(self)\n        # if there is only one sibling left, replace the parent by\n        # this sibling.\n        if len(parent.children) == 1:\n            other = parent.children[0]\n            parent.item = other.item\n            parent.split = other.split\n            parent.children = other.children\n\n    def set_geometry(self, rect):\n        if self.item:\n            self.item.setGeometry(rect)\n\n        elif self.split == ViewGridLayout.VERTICAL:\n            x = rect.x()\n            width = round(rect.width() / len(self.children))\n            for child in self.children:\n                cr = QRect(x, rect.y(), width, int(rect.height()))\n                child.set_geometry(cr)\n                x += width\n\n        elif self.split == ViewGridLayout.HORIZONTAL:\n            y = rect.y()\n            height = round(rect.height() / len(self.children))\n            for child in self.children:\n                cr = QRect(rect.x(), y, rect.width(), height)\n                child.set_geometry(cr)\n                y += height\n\n    def __iter__(self):\n        entries = [self]\n        while entries:\n            entry = entries.pop(0)\n            yield entry\n            entries.extend(entry.children)\n\n    def entry_for_item(self, item):\n        for entry in self:\n            if entry.item == item:\n                return entry\n        return None\n\n\nclass ViewGridLayout(QLayout):\n    VERTICAL = 1\n    HORIZONTAL = 2\n\n    def __init__(self, window=None):\n        QLayout.__init__(self)\n        self._window = window\n        main_view = WebView(window)\n        # keep an ordered list of the widgets\n        self._views = []\n        self._current_view = main_view\n        # to avoid asking reordering many times\n        self.__view_sort_asked = False\n        self._item_added = None\n        self._root = LayoutEntry()\n        self.add_view(main_view, self._root)\n\n    def current_view(self):\n        return self._current_view\n\n    def set_current_view(self, widget):\n        assert widget in self._views\n        self._current_view = widget\n\n    def views(self):\n        return self._views\n\n    def __sort_views_by_position(self):\n        def top_top_bottom(w):\n            return w.geometry().center().y()\n\n        def left_to_right(w):\n            return w.geometry().center().x()\n\n        self._views = sorted(self._views, key=top_top_bottom)\n        self._views = sorted(self._views, key=left_to_right)\n        self.__view_sort_asked = False\n\n    def _sort_views_by_position(self):\n        # compress requests for reordering widgets\n        if self.__view_sort_asked:\n            return\n        self.__view_sort_asked = True\n        call_later(self.__sort_views_by_position)\n\n    def add_view(self, widget, parent_entry, direction=None):\n        self.addWidget(widget)\n        self._views.append(widget)\n        self._sort_views_by_position()\n        item = self._item_added\n        self._item_added = None\n        if direction is not None:\n            parent_entry.do_split(item, direction)\n        else:\n            parent_entry.item = item\n\n    def entries(self):\n        return [e for e in self._root if e.item]\n\n    def addItem(self, item):\n        self._item_added = item\n\n    def count(self):\n        return len(self.entries())\n\n    def itemAt(self, index):\n        try:\n            return self.entries()[index].item\n        except IndexError:\n            return None\n\n    def takeAt(self, index):\n        entry = self.entries()[index]\n        if entry.item:\n            self._views.remove(entry.item.widget())\n            self._sort_views_by_position()\n        return entry.pop()\n\n    def sizeHint(self):\n        size = QSize(0, 0)\n        for entry in self.entries():\n            size = size.expandedTo(entry.item.sizeHint())\n\n        return size + self.count() * QSize(self.spacing(), self.spacing())\n\n    def setGeometry(self, rect):\n        self._root.set_geometry(rect)\n\n    def split_view(self, direction, reference=None):\n        widget = WebView(self._window)\n        refindex = self.indexOf(reference or self._current_view)\n        refitem = self.itemAt(refindex)\n        for entry in self._root:\n            if entry.item == refitem:\n                self.add_view(widget, entry, direction)\n                self.invalidate()\n                break\n        return widget\n\n    def dump_state(self):\n        def item_dump_state(entry):\n            if entry.item is None:\n                return {\n                    \"split\": (\"horizontal\"\n                              if entry.split == self.HORIZONTAL\n                              else \"vertical\"),\n                    \"views\": [item_dump_state(c) for c in entry.children]\n                }\n            else:\n                view = entry.item.widget()\n                buffer_index = BUFFERS.index(view.buffer())\n                if view == self._current_view:\n                    return {\"buffer\": buffer_index, \"current\": True}\n                else:\n                    return {\"buffer\": buffer_index}\n\n        return item_dump_state(self._root)\n\n    def restore_state(self, grid_data):\n        main_view = self._current_view\n\n        def restore(data, view):\n            split = data.get(\"split\")\n\n            if split is None:\n                # attach the buffer to the view.\n                view.setBuffer(BUFFERS[data[\"buffer\"]], update_last_use=False)\n                if data.get(\"current\"):\n                    self._current_view = view\n\n            else:\n                # we have splits to do.\n                split = (self.HORIZONTAL if split == \"horizontal\"\n                         else self.VERTICAL)\n\n                # first split everything, to create the views\n                rest = [(data[\"views\"][0], view)]\n                for wdata in data[\"views\"][1:]:\n                    view = self.split_view(split, view)\n                    rest.append((wdata, view))\n\n                # and now let's recurse to set nested buffers\n                for wdata, view in rest:\n                    restore(wdata, view)\n\n        restore(grid_data, main_view)\n\n        # and update the focus of the views\n        for w in self._views:\n            w.show_focused(w == self._current_view)\n\n        # required to have the right keyboard focus\n        main_view.main_window.set_current_webview(main_view)\n"
  },
  {
    "path": "webmacs/external_editor.py",
    "content": "import os\nimport tempfile\nimport subprocess\nfrom . import variables\nimport shlex\n\n\neditor_cmd = variables.define_variable(\n    \"external-editor-command\",\n    \"command to open an external editor. You must use the {file}\"\n    \" placeholder in the command, as it will be used to open the\"\n    \" temporary file.\",\n    \"emacsclient -c -a '' {file}\",\n    type=variables.String(),\n)\n\n\ndef open_external_editor(content):\n    with tempfile.NamedTemporaryFile(delete=False) as tf:\n        tf.write(content)\n\n    cmd = editor_cmd.value.format(file=shlex.quote(tf.name))\n\n    if subprocess.call(cmd, shell=True) != 0:\n        return\n\n    with open(tf.name) as f:\n        return f.read()\n\n    os.unlink(tf.name)\n"
  },
  {
    "path": "webmacs/features.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport sqlite3\nimport logging\nfrom PyQt6.QtWebEngineCore import QWebEnginePage\n\n\nclass Features(object):\n    def __init__(self, db_path):\n        self._conn = sqlite3.connect(db_path)\n        self._conn.execute(\"\"\"\n        CREATE TABLE IF NOT EXISTS features\n        (url TEXT,\n        feature NUMBER,\n        permission NUMBER,\n        PRIMARY KEY(url, feature));\n        \"\"\")\n\n    def set_permission(self, url, feature, permission):\n        logging.info(f\"[{url}]: Saving {feature} to {permission}\")\n        self._conn.execute(\"\"\"\n        INSERT OR REPLACE INTO features (url, feature, permission)\n        VALUES (?, ?, ?)\n        \"\"\", (url, feature.value, permission.value))\n        self._conn.commit()\n\n    def get_permission(self, url, feature):\n        permission_value = self._conn.execute(\n            \"SELECT permission FROM features WHERE url = ? AND feature = ?\",\n            (url, feature.value)).fetchone()\n\n        permission = QWebEnginePage.PermissionPolicy.PermissionUnknown\n        if permission_value:\n            for p in QWebEnginePage.PermissionPolicy:\n                if p.value == permission_value[0]:\n                    permission = p\n                    logging.info(f\"[{url}]: Found permission {permission} for {feature}\")\n                    break\n        else:\n            logging.info(f\"[{url}] No permission found for {feature}\")\n        return permission\n"
  },
  {
    "path": "webmacs/filter_webengine_output.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport re\nimport sys\nimport logging\nimport traceback\n\nfrom PyQt6.QtNetwork import QLocalSocket\n\nfrom . import version\n\n\nclass NoFilter(object):\n    def __init__(self, *a, **kw):\n        pass\n\n    def enable(self):\n        pass\n\n\nclass OutputFilter(object):\n    \"\"\"\n    Filter what is send on stderr file descriptor, on unix systems only.\n    \"\"\"\n    def __init__(self, regexes):\n        # duplicate stderr on a new file descriptor that we assign to\n        # sys.stderr (so from python there is no difference when writing to the\n        # standard error) and redirect stderr to a pipe that we will read,\n        # filter and log manually.\n        sys.stderr.flush()\n        r, w = os.pipe()\n\n        newerr = os.dup(sys.stderr.fileno())\n        os.dup2(w, sys.stderr.fileno())\n\n        os.close(w)\n        sys.stderr = os.fdopen(newerr, \"w\")\n\n        def _excepthook(e, v, tb):\n            # use our custom stderr\n            traceback.print_exception(e, v, tb, None, sys.stderr)\n            sys.exit(1)\n\n        sys.excepthook = _excepthook\n\n        self._notifier = QLocalSocket()\n        self._fd = r\n        self._regexes = regexes\n\n    def enable(self):\n        self._notifier.setSocketDescriptor(self._fd)\n        self._notifier.readyRead.connect(self._redirect)\n\n    def _redirect(self):\n        while self._notifier.canReadLine():\n            line = self._notifier.readLine().data().rstrip().decode(\"utf-8\")\n            logging.log(self._regexes.get_level_for_line(line), line)\n\n\nclass FilterRegexes(object):\n    def __init__(self):\n        self._data = []\n\n    def get_level_for_line(self, line):\n        for regex, level in self._data:\n            if regex.match(line):\n                return level\n        return logging.CRITICAL\n\n    def filter(self, regexstr, level=logging.DEBUG):\n        self._data.append((re.compile(regexstr), level))\n\n\ndef make_filter():\n    # when there is a qtwebengine crash, the OutputFilter will prevent the\n    # stack trace from being printed. Need to find a way to have those stack\n    # traces somewhere before filtering.\n    return NoFilter()\n\n    regexes = FilterRegexes()\n\n    regexes.filter(r\"^libpng warning: iCCP: known incorrect sRGB profile$\")\n    regexes.filter(r\".*gles2_cmd_decoder_autogen.h.*\")\n\n    if version.qt_version >= (5, 12):\n        regexes.filter(\n            r\"QNetworkReplyHttpImplPrivate::_q_startOperation was called more\"\n            r\" than once.*\"\n        )\n    else:\n        # see https://bugreports.qt.io/browse/QTBUG-68547\n        regexes.filter(r\".*stack_trace_posix\\.cc.* Failed to open file: .*\")\n        regexes.filter(r\"^  Error: No such file or directory$\")\n\n        regexes.filter(r\".*nss_ocsp.cc.*No URLRequestContext for NSS HTTP\"\n                       r\" handler..*\")\n\n    cls = OutputFilter if version.is_posix else NoFilter\n    return cls(regexes)\n"
  },
  {
    "path": "webmacs/hooks.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\n\nclass Hook(list):\n    def call(self, *arg, **kwargs):\n        for callback in self:\n            callback(*arg, **kwargs)\n\n    __call__ = call\n\n    add = list.append\n\n    def remove_if_exists(self, cb):\n        try:\n            self.remove(cb)\n        except ValueError:\n            pass\n\n\nwebbuffer_created = Hook()\n\nwebbuffer_closed = Hook()\n\nwebbuffer_load_finished = Hook()\n\nwebbuffer_current_changed = Hook()\n\nlocal_mode_changed = Hook()\n\nwindow_activated = Hook()\n\nwindow_closed = Hook()\n"
  },
  {
    "path": "webmacs/ignore_certificates.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport sqlite3\n\n\nclass IgnoredCertificates(object):\n    def __init__(self, dbbath):\n        self._conn = sqlite3.connect(dbbath)\n        self._conn.execute(\"\"\"\n        CREATE TABLE IF NOT EXISTS ignorecerts\n        (url TEXT PRIMARY KEY);\n        \"\"\")\n\n    def is_ignored(self, url):\n        return self._conn.execute(\"\"\"\n        SELECT url from ignorecerts WHERE url = ?\n        \"\"\", (url,)).fetchone() is not None\n\n    def ignore(self, url):\n        self._conn.execute(\"\"\"\n        INSERT OR REPLACE INTO ignorecerts (url)\n        VALUES (?)\n        \"\"\", (url,))\n        self._conn.commit()\n\n    def remove(self, url):\n        self._conn.execute(\"\"\"\n        DELETE from ignorecerts WHERE url = ?\n        \"\"\", (url,))\n"
  },
  {
    "path": "webmacs/ipc.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport json\nimport struct\nimport logging\nfrom PyQt6.QtCore import QObject, pyqtSlot as Slot, pyqtSignal as Signal, Qt, \\\n    QDir\nfrom PyQt6.QtNetwork import QLocalServer, QLocalSocket\nfrom . import version\n\n\nHEADER_FMT = \"!I\"\nHEADER_SIZE = struct.calcsize(HEADER_FMT)\n\n\nclass IPcReader(QObject):\n    message_received = Signal(object)\n\n    def __init__(self, sock):\n        QObject.__init__(self)\n        self.sock = sock\n        self._msg_size = None\n        self._data = b\"\"\n\n    @Slot()\n    def on_ready_read(self):\n        if self._msg_size is None:\n            if self.sock.bytesAvailable() < HEADER_SIZE:\n                # not enough data yet\n                return\n            self._msg_size = struct.unpack(HEADER_FMT,\n                                           self.sock.read(HEADER_SIZE))[0]\n        remaining = self._msg_size - len(self._data)\n        if remaining <= 0:\n            return\n        self._data += self.sock.read(min(remaining,\n                                         self.sock.bytesAvailable()))\n        if len(self._data) == self._msg_size:\n            msg = json.loads(self._data.decode(\"utf-8\"))\n            self.message_received.emit(msg)\n            return msg\n\n    @Slot(object)\n    def send_data(self, data):\n        data = json.dumps(data).encode(\"utf-8\")\n        len_data = len(data)\n        self.sock.write(struct.pack(HEADER_FMT, len_data))\n        self.sock.write(data)\n\n    def get_data(self):\n        while self.sock.waitForReadyRead():\n            r = self.on_ready_read()\n            if r is not None:\n                return r\n\n    def clear(self):\n        self.sock.deleteLater()\n        self.sock = None\n\n\nclass IpcServer(QObject):\n    @classmethod\n    def get_sock_name(cls, instance):\n        run_path = f\"/run/user/{os.getuid()}\"\n        prefix = run_path if os.access(run_path, os.W_OK) else \"\"\n\n        if instance == \"default\":\n            return os.path.join(prefix, \"webmacs.ipc\")\n        return os.path.join(prefix, f\"webmacs.{instance}.ipc\")\n\n    @classmethod\n    def list_all_instances(cls, check=True):\n        if version.is_windows:\n            logging.error(\n                \"list all instances is not supported on windows\"\n            )\n            return []\n        # from qt sources, named pipes are created in QDir.tempPath()\n        instances = [\n            n[8:-4] or \"default\"\n            for n in os.listdir(QDir.tempPath())\n            if n.startswith(\"webmacs.\") and n.endswith(\".ipc\")\n        ]\n        if check:\n            new_instances = []\n            for instance in instances:\n                local = cls.check_server_connection(instance)\n                if local is not None:\n                    local.clear()\n                    new_instances.append(instance)\n            instances = new_instances\n        return instances\n\n    @classmethod\n    def instance_send(cls, instance, data, cb=None):\n        \"\"\"\n        Send some data to a webmacs instance asynchronously.\n        \"\"\"\n        conn = cls.check_server_connection(instance)\n        if conn is None:\n            return\n\n        def callback(result):\n            conn.clear()\n            if cb is not None:\n                cb(result)\n\n        conn.message_received.connect(callback)\n        conn.send_data(data)\n\n    @classmethod\n    def check_server_connection(cls, instance=None):\n        sock = QLocalSocket()\n        sock.connectToServer(cls.get_sock_name(instance))\n        if sock.waitForConnected(1000):\n            return IPcReader(sock)\n        return None\n\n    def __init__(self, instance=None):\n        QObject.__init__(self)\n        sock_name = self.get_sock_name(instance)\n        QLocalServer.removeServer(sock_name)\n        self._server = QLocalServer()\n        self._server.setSocketOptions(\n            QLocalServer.SocketOption.UserAccessOption)\n        self._server.newConnection.connect(self._on_new_connection)\n        if not self._server.listen(sock_name):\n            logging.error(\"Can not start ipc: %s\"\n                          % self._server.errorString())\n        self._readers = {}\n\n    def cleanup(self):\n        try:\n            os.unlink(self._server.fullServerName())\n        except OSError:\n            pass\n\n    @Slot()\n    def _on_new_connection(self):\n        conn = self._server.nextPendingConnection()\n        reader = IPcReader(conn)\n        reader.message_received.connect(self.handle_data)\n        conn.readyRead.connect(reader.on_ready_read)\n        conn.disconnected.connect(self.reader_disconnected)\n        self._readers[conn] = reader\n\n    @Slot(object)\n    def handle_data(self, data):\n        reader = self.sender()\n        try:\n            res = ipc_dispatch(data)\n        except Exception as exc:\n            res = str(exc)\n\n        if res in (True, None):\n            reader.send_data({\"result\": True})\n        else:\n            reader.send_data({\"result\": False, \"message\": res})\n\n    def reader_disconnected(self):\n        conn = self.sender()\n        reader = self._readers.pop(conn)\n        reader.clear()\n        reader.deleteLater()\n\n\ndef ipc_dispatch(data):\n    from . import current_window\n    from .webbuffer import create_buffer\n    win = current_window()\n    url = data.get(\"url\")\n    if url:\n        view = win.current_webview()\n        view.setBuffer(create_buffer(url))\n\n    # this is quite hard to raise a window. The following works fine\n    # for me with gnome 3.\n    flags = win.windowFlags()\n    win.setWindowFlags(flags | Qt.WindowType.Popup)\n    win.raise_()\n    win.activateWindow()\n    win.setWindowFlags(flags)\n    win.show()\n"
  },
  {
    "path": "webmacs/keyboardhandler.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport logging\n\nfrom PyQt6.QtCore import QObject, QEvent\nfrom PyQt6.QtGui import QWindow\n\nfrom .keymaps import KeyPress, GLOBAL_KEYMAP, CHAR2KEY\nfrom . import hooks\nfrom . import COMMANDS, minibuffer_show_info, current_minibuffer, \\\n    current_window\nfrom .mode import Mode\n\n\nclass CommandContext(object):\n    def __init__(self):\n        self.window = current_window()\n        self.view = self.window.current_webview() if self.window else None\n        self.buffer = self.view.buffer() if self.view else None\n        self.current_prefix_arg = KEY_EATER._prefix_arg\n        self.prompt = None\n\n    @property\n    def minibuffer(self):\n        win = self.window\n        if win:\n            return win.minibuffer()\n\n\nclass LocalKeymapSetter(QObject):\n    def __init__(self):\n        QObject.__init__(self)\n        self.enabled_minibuffer = False\n\n    def eventFilter(self, obj, evt):\n        # event filter on the global app is required to avoid click on webviews\n        t = evt.type()\n\n        if t == QEvent.Type.KeyPress and isinstance(obj, QWindow):\n            return KEY_EATER.event_filter(obj, evt)\n        elif t == QEvent.Type.ShortcutOverride:\n            # disable automatic shortcuts in browser, like C-a\n            return True\n        elif self.enabled_minibuffer and t in (\n                QEvent.Type.MouseButtonPress,\n                QEvent.Type.MouseButtonDblClick,\n                QEvent.Type.MouseButtonRelease,\n                QEvent.Type.MouseMove):\n            minibuff = current_minibuffer()\n            if minibuff:\n                # allow clicks in minibuffer inputs and popup only\n                # note: QWidget.underMouse does not works here.\n                input = minibuff.input()\n                if input.rect().contains(\n                        input.mapFromGlobal(evt.globalPosition().toPoint())):\n                    return False\n                else:\n                    popup = input.popup()\n                    if popup.isVisible() and popup.rect().contains(\n                            popup.mapFromGlobal(\n                                evt.globalPosition().toPoint())):\n                        return False\n                # else flash the minibuffer on click.\n                if evt.type() in (QEvent.Type.MouseButtonPress,\n                                  QEvent.Type.MouseButtonDblClick) \\\n                                  and minibuff.prompt():  # noqa: 125\n                    minibuff.prompt().flash()\n            return True\n        return False\n\n    def minibuffer_input_focus_changed(self, mbi, enabled):\n        self.enabled_minibuffer = enabled\n        if enabled:\n            set_local_keymap(mbi.keymap())\n        else:\n            if not mbi.isVisible():\n                # when the minibuffer input is hidden, enable its view's\n                # buffer\n                buff = mbi.parent().parent().current_webview().buffer()\n                set_local_keymap(buff.active_keymap())\n\n    def view_focus_changed(self, view, enabled):\n        if enabled and not self.enabled_minibuffer:\n            # fixes issue were a raw qwebenginepage comes here. To\n            # reproduce, have two opened buffers, then C-x 2, C-x 3.\n            if hasattr(view.buffer(), \"active_keymap\"):\n                set_local_keymap(view.buffer().active_keymap())\n                if view.main_window.current_webview() == view:\n                    hooks.webbuffer_current_changed(view.buffer())\n\n    def web_content_edit_focus_changed(self, buff, enabled):\n        if enabled:\n            buff.set_keymap_mode(Mode.KEYMAP_CONTENT_EDIT)\n            if not self.enabled_minibuffer:\n                set_local_keymap(buff.active_keymap())\n        else:\n            buff.set_keymap_mode(Mode.KEYMAP_NORMAL)\n            if not self.enabled_minibuffer:\n                set_local_keymap(buff.active_keymap())\n\n    def caret_browsing_changed(self, buff, enabled):\n        if enabled:\n            buff.set_keymap_mode(Mode.KEYMAP_CARET_BROWSING)\n            if not self.enabled_minibuffer:\n                set_local_keymap(buff.active_keymap())\n        else:\n            buff.set_keymap_mode(Mode.KEYMAP_NORMAL)\n            if not self.enabled_minibuffer:\n                set_local_keymap(buff.active_keymap())\n\n    def buffer_mode_changed(self, buffer, old_mode):\n        # check that the previous keymap was the one corresponding to the mode\n        old_km = old_mode.keymap_for_mode(buffer.keymap_mode)\n        if old_km == local_keymap():\n            set_local_keymap(buffer.active_keymap())\n\n    def buffer_opened_in_view(self, buffer):\n        if not self.enabled_minibuffer:\n            set_local_keymap(buffer.active_keymap())\n\n\nLOCAL_KEYMAP_SETTER = LocalKeymapSetter()\n\n\nclass KeyEater(object):\n    \"\"\"\n    Handle Qt keypresses events.\n    \"\"\"\n    def __init__(self):\n        self.set_call_handler(CallHandler())\n        self._keypresses = []\n        self._local_key_map = None\n        self._use_global_keymap = True\n        self.universal_key = KeyPress.from_str(\"C-u\")\n        self._prefix_arg = None\n        self._prefix_arg_keys = []\n        self._allowed_universal_keys = {}\n        for i in \"1234567890\":\n            self._allowed_universal_keys[CHAR2KEY[i]] \\\n                = lambda: self._num_update_prefix_arg(i)\n\n    def set_call_handler(self, call_handler):\n        self.call_handler = call_handler\n\n    def set_local_key_map(self, keymap):\n        if keymap != self._local_key_map:\n            self._local_key_map = keymap\n            hooks.local_mode_changed(keymap)\n            logging.debug(\"local keymap activated: %s\", keymap)\n\n    def local_key_map(self):\n        return self._local_key_map\n\n    def set_global_keymap_enabled(self, enable):\n        self._use_global_keymap = enable\n\n    def event_filter(self, obj, event):\n        key = KeyPress.from_qevent(event)\n        if key is None:\n            return False\n        if self._handle_keypress(obj, key):\n            return True\n        return False\n\n    def active_keymaps(self):\n        if self._local_key_map:\n            yield self._local_key_map\n        if self._use_global_keymap:\n            yield GLOBAL_KEYMAP\n\n    def _add_keypress(self, keypress):\n        self._keypresses.append(keypress)\n        logging.debug(\"keychord: %s\" % self._keypresses)\n\n    def _num_update_prefix_arg(self, numstr):\n        if not isinstance(self._prefix_arg, int):\n            self._prefix_arg = int(numstr)\n        else:\n            self._prefix_arg = int(str(self._prefix_arg) + numstr)\n\n    def _show_info_kbd(self, extra=\"\"):\n        all_presses = self._prefix_arg_keys + self._keypresses\n        minibuffer_show_info(\n            \" \".join((str(k) for k in all_presses)) + extra\n        )\n\n    def _handle_keypress(self, sender, keypress):\n        if keypress == self.universal_key and not self._keypresses:\n            if isinstance(self._prefix_arg, tuple):\n                self._prefix_arg = (self._prefix_arg[0] * 4,)\n            else:\n                self._prefix_arg = (4,)\n            self._prefix_arg_keys.append(keypress)\n            self._show_info_kbd()\n            return True\n        if self._prefix_arg is not None:\n            try:\n                func = self._allowed_universal_keys[keypress.key]\n            except KeyError:\n                pass\n            else:\n                if not keypress.has_any_modifier():\n                    func()\n                    self._prefix_arg_keys.append(keypress)\n                    self._show_info_kbd()\n                    return True\n\n        result = None\n        self._add_keypress(keypress)\n\n        for keymap in self.active_keymaps():\n            result = keymap.lookup(self._keypresses)\n            if result:\n                break\n\n        if not result:\n            if len(self._keypresses) > 1:\n                self._show_info_kbd(\" is undefined.\")\n            else:\n                minibuffer_show_info(\"\")\n            self._keypresses = []\n            self.call_handler.no_call(sender, keymap, keypress)\n            self._prefix_arg = None\n            self._prefix_arg_keys = []\n            return False\n\n        if result.complete:\n            self._show_info_kbd()\n            self._keypresses = []\n            ctx = CommandContext()\n            self._prefix_arg = None\n            self._prefix_arg_keys = []\n            try:\n                self.call_handler.call(ctx, keymap, keypress,\n                                       result.command)\n            except Exception:\n                logging.exception(\"Error calling command:\")\n        else:\n            self._show_info_kbd(\" -\")\n            self.call_handler.partial_call(sender, keymap, keypress)\n\n        return result is not None\n\n\nclass CallHandler(object):\n    def __init__(self):\n        self._commands = COMMANDS\n\n    def call(self, ctx, keymap, keypress, command):\n        if isinstance(command, str):\n            try:\n                command = self._commands[command]\n            except KeyError:\n                raise KeyError(\"No such command: %s\" % command)\n\n        command(ctx)\n\n    def no_call(self, sender, keymap, keypress):\n        pass\n\n    def partial_call(self, sender, keymap, keypress):\n        pass\n\n\nKEY_EATER = KeyEater()\n\n\ndef send_key_event(keypress):\n    from .application import app as _app\n    app = _app()\n    w = app.focusWindow()\n    app.postEvent(w, keypress.to_qevent(QEvent.Type.KeyPress))\n    app.postEvent(w, keypress.to_qevent(QEvent.Type.KeyRelease))\n\n\ndef local_keymap():\n    return KEY_EATER.local_key_map()\n\n\ndef set_local_keymap(keymap):\n    KEY_EATER.set_local_key_map(keymap)\n\n\ndef set_global_keymap_enabled(enable):\n    KEY_EATER.set_global_keymap_enabled(enable)\n"
  },
  {
    "path": "webmacs/keymaps/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport warnings\n\nfrom collections import namedtuple\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtGui import QKeyEvent\n\nfrom .. import COMMANDS\n\n\nKEY2CHAR = {}\nCHAR2KEY = {}\nKEYMAPS = {}\n\n\ndef _set_key(key, char, *chars):\n    KEY2CHAR[key] = char\n    CHAR2KEY[char] = key\n    for ch in chars:\n        CHAR2KEY[ch] = key\n\n\n# see http://doc.qt.io/qt-5/qt.html#Key-enum,\n# https://www.blunix.org/using-german-umlauts-on-us-layout-keyboards/\n\n_set_key(Qt.Key.Key_Escape, \"Esc\")\n_set_key(Qt.Key.Key_Tab, \"Tab\")\n_set_key(Qt.Key.Key_Backtab, \"Backtab\")\n_set_key(Qt.Key.Key_Backspace, \"Backspace\")\n_set_key(Qt.Key.Key_Return, \"Return\")\n_set_key(Qt.Key.Key_Enter, \"Enter\")\n_set_key(Qt.Key.Key_Insert, \"Insert\")\n_set_key(Qt.Key.Key_Delete, \"Delete\")\n_set_key(Qt.Key.Key_Pause, \"Pause\")  # pause/break key, not media pause\n_set_key(Qt.Key.Key_Print, \"Print\")\n_set_key(Qt.Key.Key_SysReq, \"SysReq\")\n_set_key(Qt.Key.Key_Clear, \"Clear\")\n_set_key(Qt.Key.Key_Home, \"Home\")\n_set_key(Qt.Key.Key_End, \"End\")\n_set_key(Qt.Key.Key_Left, \"Left\")\n_set_key(Qt.Key.Key_Up, \"Up\")\n_set_key(Qt.Key.Key_Right, \"Right\")\n_set_key(Qt.Key.Key_Down, \"Down\")\n_set_key(Qt.Key.Key_PageUp, \"PageUp\")\n_set_key(Qt.Key.Key_PageDown, \"PageDown\")\n\n_set_key(Qt.Key.Key_F1, \"F1\")\n_set_key(Qt.Key.Key_F2, \"F2\")\n_set_key(Qt.Key.Key_F3, \"F3\")\n_set_key(Qt.Key.Key_F4, \"F4\")\n_set_key(Qt.Key.Key_F5, \"F5\")\n_set_key(Qt.Key.Key_F6, \"F6\")\n_set_key(Qt.Key.Key_F7, \"F7\")\n_set_key(Qt.Key.Key_F8, \"F8\")\n_set_key(Qt.Key.Key_F9, \"F9\")\n_set_key(Qt.Key.Key_F10, \"F10\")\n_set_key(Qt.Key.Key_F11, \"F11\")\n_set_key(Qt.Key.Key_F12, \"F12\")\n\n\n_set_key(Qt.Key.Key_Space, \"Space\")\n_set_key(Qt.Key.Key_Exclam, \"!\")\n_set_key(Qt.Key.Key_QuoteDbl, '\"')\n_set_key(Qt.Key.Key_Dollar, '$')\n_set_key(Qt.Key.Key_Percent, \"%\")\n_set_key(Qt.Key.Key_Ampersand, \"&\")\n_set_key(Qt.Key.Key_Apostrophe, \"'\")\n_set_key(Qt.Key.Key_ParenLeft, \"(\")\n_set_key(Qt.Key.Key_ParenRight, \")\")\n_set_key(Qt.Key.Key_Asterisk, \"*\")\n_set_key(Qt.Key.Key_Plus, \"+\")\n_set_key(Qt.Key.Key_Comma, \",\")\n_set_key(Qt.Key.Key_Minus, \"-\")\n_set_key(Qt.Key.Key_Period, \".\")\n_set_key(Qt.Key.Key_Slash, \"/\")\n\n_set_key(Qt.Key.Key_0, \"0\")\n_set_key(Qt.Key.Key_1, \"1\")\n_set_key(Qt.Key.Key_2, \"2\")\n_set_key(Qt.Key.Key_3, \"3\")\n_set_key(Qt.Key.Key_4, \"4\")\n_set_key(Qt.Key.Key_5, \"5\")\n_set_key(Qt.Key.Key_6, \"6\")\n_set_key(Qt.Key.Key_7, \"7\")\n_set_key(Qt.Key.Key_8, \"8\")\n_set_key(Qt.Key.Key_9, \"9\")\n\n_set_key(Qt.Key.Key_Colon, \":\")\n_set_key(Qt.Key.Key_Semicolon, \";\")\n_set_key(Qt.Key.Key_Less, \"<\")\n_set_key(Qt.Key.Key_Equal, \"=\")\n_set_key(Qt.Key.Key_Greater, \">\")\n_set_key(Qt.Key.Key_Question, \"?\")\n_set_key(Qt.Key.Key_At, \"@\")\n\n_set_key(Qt.Key.Key_A, \"a\", \"A\")\n_set_key(Qt.Key.Key_B, \"b\", \"B\")\n_set_key(Qt.Key.Key_C, \"c\", \"C\")\n_set_key(Qt.Key.Key_D, \"d\", \"D\")\n_set_key(Qt.Key.Key_E, \"e\", \"E\")\n_set_key(Qt.Key.Key_F, \"f\", \"F\")\n_set_key(Qt.Key.Key_G, \"g\", \"G\")\n_set_key(Qt.Key.Key_H, \"h\", \"H\")\n_set_key(Qt.Key.Key_I, \"i\", \"I\")\n_set_key(Qt.Key.Key_J, \"j\", \"J\")\n_set_key(Qt.Key.Key_K, \"k\", \"K\")\n_set_key(Qt.Key.Key_L, \"l\", \"L\")\n_set_key(Qt.Key.Key_M, \"m\", \"M\")\n_set_key(Qt.Key.Key_N, \"n\", \"N\")\n_set_key(Qt.Key.Key_O, \"o\", \"O\")\n_set_key(Qt.Key.Key_P, \"p\", \"P\")\n_set_key(Qt.Key.Key_Q, \"q\", \"Q\")\n_set_key(Qt.Key.Key_R, \"r\", \"R\")\n_set_key(Qt.Key.Key_S, \"s\", \"S\")\n_set_key(Qt.Key.Key_T, \"t\", \"T\")\n_set_key(Qt.Key.Key_U, \"u\", \"U\")\n_set_key(Qt.Key.Key_V, \"v\", \"V\")\n_set_key(Qt.Key.Key_W, \"w\", \"W\")\n_set_key(Qt.Key.Key_X, \"x\", \"X\")\n_set_key(Qt.Key.Key_Y, \"y\", \"Y\")\n_set_key(Qt.Key.Key_Z, \"z\", \"Z\")\n\n_set_key(Qt.Key.Key_BracketLeft, \"[\")\n_set_key(Qt.Key.Key_Backslash, \"\\\\\")\n_set_key(Qt.Key.Key_BracketRight, \"]\")\n_set_key(Qt.Key.Key_AsciiCircum, \"^\")\n_set_key(Qt.Key.Key_Underscore, \"_\")\n_set_key(Qt.Key.Key_Underscore, \"_\")\n# _set_key(Qt.Key.Key_QuoteLeft, \"\")\n_set_key(Qt.Key.Key_BraceLeft, \"{\")\n_set_key(Qt.Key.Key_Bar, \"|\")\n_set_key(Qt.Key.Key_BraceRight, \"}\")\n_set_key(Qt.Key.Key_AsciiTilde, \"~\")\n_set_key(Qt.Key.Key_nobreakspace, \" \")\n_set_key(Qt.Key.Key_nobreakspace, \" \")\n_set_key(Qt.Key.Key_exclamdown, \"¡\")\n_set_key(Qt.Key.Key_cent, \"¢\")\n_set_key(Qt.Key.Key_sterling, \"£\")\n_set_key(Qt.Key.Key_currency, \"¤\")\n_set_key(Qt.Key.Key_yen, \"¥\")\n_set_key(Qt.Key.Key_brokenbar, \"¦\")\n_set_key(Qt.Key.Key_section, \"§\")\n_set_key(Qt.Key.Key_diaeresis, \"¨\")\n_set_key(Qt.Key.Key_copyright, \"©\")\n_set_key(Qt.Key.Key_ordfeminine, \"ª\")\n_set_key(Qt.Key.Key_guillemotleft, \"«\")\n_set_key(Qt.Key.Key_notsign, \"¬\")\n# _set_key(Qt.Key.Key_hyphen, \"\")\n_set_key(Qt.Key.Key_registered, \"®\")\n_set_key(Qt.Key.Key_macron, \"¯\")\n_set_key(Qt.Key.Key_degree, \"°\")\n_set_key(Qt.Key.Key_plusminus, \"±\")\n_set_key(Qt.Key.Key_twosuperior, \"²\")\n_set_key(Qt.Key.Key_threesuperior, \"³\")\n_set_key(Qt.Key.Key_acute, \"´\")\n_set_key(Qt.Key.Key_mu, \"µ\")\n_set_key(Qt.Key.Key_paragraph, \"¶\")\n_set_key(Qt.Key.Key_periodcentered, \"·\")\n_set_key(Qt.Key.Key_cedilla, \"¸\")\n_set_key(Qt.Key.Key_onesuperior, \"¹\")\n_set_key(Qt.Key.Key_masculine, \"º\")\n_set_key(Qt.Key.Key_guillemotright, \"»\")\n_set_key(Qt.Key.Key_onequarter, \"¼\")\n_set_key(Qt.Key.Key_onehalf, \"½\")\n_set_key(Qt.Key.Key_threequarters, \"¾\")\n_set_key(Qt.Key.Key_questiondown, \"¿\")\n_set_key(Qt.Key.Key_Agrave, \"à\", \"À\")\n_set_key(Qt.Key.Key_Aacute, \"á\", \"Á\")\n_set_key(Qt.Key.Key_Acircumflex, \"â\", \"Â\")\n_set_key(Qt.Key.Key_Atilde, \"ã\", \"Ã\")\n_set_key(Qt.Key.Key_Adiaeresis, \"ä\", \"Ä\")\n_set_key(Qt.Key.Key_Aring, \"å\", \"Å\")\n_set_key(Qt.Key.Key_AE, \"æ\", \"Æ\")\n_set_key(Qt.Key.Key_Ccedilla, \"ç\", \"Ç\")\n_set_key(Qt.Key.Key_Egrave, \"è\", \"È\")\n_set_key(Qt.Key.Key_Eacute, \"é\", \"É\")\n_set_key(Qt.Key.Key_Ecircumflex, \"ê\", \"Ê\")\n_set_key(Qt.Key.Key_Ediaeresis, \"Ë\", \"ë\")\n_set_key(Qt.Key.Key_Igrave, \"ì\", \"Ì\")\n_set_key(Qt.Key.Key_Iacute, \"í\", \"Í\")\n_set_key(Qt.Key.Key_Icircumflex, \"î\", \"Î\")\n_set_key(Qt.Key.Key_Idiaeresis, \"ï\", \"Ï\")\n_set_key(Qt.Key.Key_ETH, \"Ð\")\n_set_key(Qt.Key.Key_Ntilde, \"ñ\", \"Ñ\")\n_set_key(Qt.Key.Key_Ograve, \"ò\", \"Ò\")\n_set_key(Qt.Key.Key_Oacute, \"ó\", \"Ó\")\n_set_key(Qt.Key.Key_Ocircumflex, \"ô\", \"Ô\")\n_set_key(Qt.Key.Key_Odiaeresis, \"ö\", \"Ö\")\n_set_key(Qt.Key.Key_multiply, \"×\")\n_set_key(Qt.Key.Key_Ooblique, \"Ø\", \"ø\")\n_set_key(Qt.Key.Key_Ugrave, \"ù\", \"Ù\")\n_set_key(Qt.Key.Key_Uacute, \"ú\", \"Ú\")\n_set_key(Qt.Key.Key_Ucircumflex, \"û\", \"Û\")\n_set_key(Qt.Key.Key_Udiaeresis, \"ü\", \"Ü\")\n_set_key(Qt.Key.Key_Yacute, \"ý\", \"Ý\")\n_set_key(Qt.Key.Key_THORN, \"þ\", \"Þ\")\n\n\ndef is_one_letter_upcase(char):\n    return len(char) == 1 and char.isalpha() and char.isupper()\n\n\n_KeyPress = namedtuple(\"_KeyPress\", (\"key\", \"control_modifier\", \"alt_modifier\",\n                                     \"super_modifier\", \"is_upper_case\"))\n\n\nclass KeyPress(_KeyPress):\n    @classmethod\n    def from_qevent(cls, event):\n        text = event.text()\n\n        # Try to get the key value depending on the text. Despite what the qt\n        # doc says, it seems more reliable to get the good value this way. For\n        # example, to match C-? on my french keyboard (using the bépo layout)\n        # this is required (Ctrl-Shift-'), else event.key() is equal to the key\n        # DOWN.\n        key = CHAR2KEY.get(text)\n        if key is None:\n            key = event.key()\n            if key not in KEY2CHAR:\n                return None\n\n        modifiers = event.modifiers()\n\n        return cls(\n            key,\n            bool(modifiers & Qt.KeyboardModifier.ControlModifier),\n            bool(modifiers & Qt.KeyboardModifier.AltModifier),\n            bool(modifiers & Qt.KeyboardModifier.MetaModifier),\n            is_one_letter_upcase(text)\n        )\n\n    @classmethod\n    def from_str(cls, string):\n        ctrl, alt, super = False, False, False\n        left, _, text = string.rpartition(\"-\")\n        if text == \"\":\n            text = \"-\"\n        parts = left.split(\"-\")\n        for p in parts:\n            if p == \"\":\n                break\n            elif p == \"C\":\n                ctrl = True\n            elif p == \"M\":\n                alt = True\n            elif p == \"S\":\n                super = True\n            else:\n                raise Exception(\n                    \"Unknown key modifier: %s in key definition %s\"\n                    % (p, string)\n                )\n\n        try:\n            key = CHAR2KEY[text]\n        except KeyError:\n            raise Exception(\"Unknown key %s\" % text)\n\n        return cls(\n            key,\n            ctrl,\n            alt,\n            super,\n            is_one_letter_upcase(text)\n        )\n\n    def to_qevent(self, type):\n        modifiers = Qt.KeyboardModifier.NoModifier\n        key = self.key\n        if self.control_modifier:\n            modifiers |= Qt.KeyboardModifier.ControlModifier\n        if self.alt_modifier:\n            modifiers |= Qt.KeyboardModifier.AltModifier\n        if self.super_modifier:\n            modifiers |= Qt.KeyboardModifier.MetaModifier\n\n        if self.is_upper_case:\n            return QKeyEvent(type, key, modifiers, KEY2CHAR[key].upper())\n        else:\n            return QKeyEvent(type, key, modifiers)\n\n    def has_any_modifier(self):\n        return (self.control_modifier or self.alt_modifier\n                or self.super_modifier)\n\n    def char(self):\n        char = KEY2CHAR[self.key]\n        if self.is_upper_case:\n            return char.upper()\n        return char\n\n    def __str__(self):\n        keyrepr = []\n\n        if self.control_modifier:\n            keyrepr.append(\"C\")\n        if self.alt_modifier:\n            keyrepr.append(\"M\")\n        if self.super_modifier:\n            keyrepr.append(\"S\")\n\n        keyrepr.append(self.char())\n\n        return \"-\".join(keyrepr)\n\n    def __repr__(self):\n        return \"<%s (%s)>\" % (self.__class__.__name__, str(self))\n\n\nKeymapLookupResult = namedtuple(\"KeymapLookupResult\",\n                                (\"complete\", \"command\", \"keymap\"))\n\n\nclass InternalKeymap(object):\n    __slots__ = (\"bindings\", \"parent\")\n\n    def __init__(self, parent=None):\n        self.bindings = {}\n        self.parent = parent\n\n    def _traverse_commands(self, prefix, acc_fn, parent=None):\n        for keypress, cmd in self.bindings.items():\n            new_prefix = prefix + [keypress]\n            if isinstance(cmd, InternalKeymap):\n                cmd._traverse_commands(new_prefix, acc_fn, parent)\n            else:\n                acc_fn(new_prefix, cmd, parent)\n        if self.parent:\n            for keypress, cmd in self.parent.bindings.items():\n                if keypress not in self.bindings:\n                    new_prefix = prefix + [keypress]\n                    if isinstance(cmd, InternalKeymap):\n                        cmd._traverse_commands(new_prefix, acc_fn, self.parent)\n                    else:\n                        acc_fn(new_prefix, cmd, self.parent)\n\n    def traverse_commands(self, acc_fn):\n        self._traverse_commands([], acc_fn)\n\n    def all_bindings(self, raw_fn=False, with_parent=True):\n        \"\"\"\n        Returns the list of bindings as (keychord, command-name) tuples.\n        \"\"\"\n        acc = []\n\n        def add(prefix, cmd, parent):\n            if not with_parent and parent is not None:\n                return\n            if isinstance(cmd, str):\n                acc.append((\" \".join(str(k) for k in prefix), cmd))\n            elif raw_fn:\n                acc.append((\" \".join(str(k) for k in prefix), cmd.__name__))\n        self.traverse_commands(add)\n        return acc\n\n    def _define_key(self, key, binding):\n        keys = [KeyPress.from_str(k) for k in key.split()]\n        assert keys, \"key should not be empty\"\n        assert callable(binding) or isinstance(binding, str), \\\n            \"binding should be callable or a command name\"\n\n        kmap = self\n        for keypress in keys[:-1]:\n            if keypress in kmap.bindings:\n                othermap = kmap.bindings[keypress]\n                if not isinstance(othermap, InternalKeymap):\n                    othermap = InternalKeymap()\n            else:\n                othermap = InternalKeymap()\n            kmap.bindings[keypress] = othermap\n            kmap = othermap\n\n        kmap.bindings[keys[-1]] = binding\n\n    def define_key(self, key, binding=None):\n        \"\"\"\n        Define a binding (callable or command name) for a key chord.\n\n        :param key: a string representing the key chord, such as \"C-c x\".\n        :param binding: A command name (a string), a callable, or None.\n                        If None, it must be used as a function decorator.\n        \"\"\"\n        if binding is None:\n            def wrapper(func):\n                self._define_key(key, func)\n                return func\n            return wrapper\n        else:\n            if isinstance(binding, str):\n                if binding not in COMMANDS:\n                    raise KeyError(\"No such command: %s\" % binding)\n            self._define_key(key, binding)\n\n    def undefine_key(self, key):\n        \"\"\"\n        Undefine the binding under a key chord.\n\n        :param key: a string representing the key chord, such as \"C-c x\".\n        \"\"\"\n        keys = [KeyPress.from_str(k) for k in key.split()]\n        if not keys:\n            return None\n        res = self.lookup(keys)\n        if res is not None and res.complete:\n            del res.keymap.bindings[keys[-1]]\n            return res.keymap\n        return None\n\n    def _look_up(self, keypress):\n        keymap = self\n        while keymap:\n            try:\n                return keymap.bindings[keypress]\n            except KeyError:\n                keymap = keymap.parent\n\n    def lookup(self, keypresses):\n        partial_match = False\n        keymap = self\n        for keypress in keypresses:\n            while keymap:\n                entry = keymap.bindings.get(keypress)\n                if entry is not None:\n                    if isinstance(entry, InternalKeymap):\n                        keymap = entry\n                        partial_match = True\n                        break\n                    else:\n                        return KeymapLookupResult(True, entry, keymap)\n                keymap = keymap.parent\n\n        if keymap is None:\n            return None\n        elif partial_match:\n            return KeymapLookupResult(False, None, keymap)\n        else:\n            return None\n\n\nclass Keymap(InternalKeymap):\n    __slots__ = InternalKeymap.__slots__ + (\"name\", \"doc\")\n\n    def __init__(self, name, parent=None, doc=None):\n        InternalKeymap.__init__(self, parent=parent)\n        self.name = name\n        self.doc = doc\n        if self.name in KEYMAPS:\n            raise ValueError(\"A keymap named %s already exists.\"\n                             % self.name)\n        KEYMAPS[self.name] = self\n\n    def __str__(self):\n        return self.name\n\n    @property\n    def brief_doc(self):\n        if self.doc:\n            return self.doc.split(\"\\n\", 1)[0]\n\n\nEMPTY_KEYMAP = Keymap(\"empty\")\n\nGLOBAL_KEYMAP = Keymap(\"global\", doc=\"\"\"\\\nThe global keymap is always active.\n\nIt act as a fallback to other keymaps, which are considered local. Only one\nlocal keymap can be active at a time. A binding is first searched in the\ncurrently active local keymap, and if not found the global keymap is used.\n\nOnly bindings with modifiers should be bound to it, else it will be impossible\nto edit text inside the browser.\"\"\")\n\nBUFFER_KEYMAP = Keymap(\"webbuffer\", doc=\"\"\"\\\nLocal keymap activated when a web buffer is focused.\\\n\nA web buffer is focused when there is no text editing, no caret browsing, or\nwhen the minibuffer input is not shown... It is enabled when no other local\nkeymap is enabled.\"\"\")\n\nCONTENT_EDIT_KEYMAP = Keymap(\"webcontent-edit\", doc=\"\"\"\\\nLocal keymap activated when a webcontent field (input, textarea, ...) is \\\nfocused.\"\"\")\n\nCARET_BROWSING_KEYMAP = Keymap(\"caret-browsing\", doc=\"\"\"\\\nLocal keymap activated when you are navigating the webbuffer with a caret.\\\n\"\"\")\n\nFULLSCREEN_KEYMAP = Keymap(\"video-fullscreen\", doc=\"\"\"\\\nLocal Keymap activated when a video is played full screen.\n\"\"\")\n\nMINIBUFFER_KEYMAP = Keymap(\"minibuffer\", doc=\"\"\"\\\nLocal keymap activated when input is in the minibuffer line edit.\n\"\"\")\n\nVISITEDLINKS_KEYMAP = Keymap(\"visited-links-list\",\n                             parent=MINIBUFFER_KEYMAP,\n                             doc=\"\"\"\\\nLocal keymap activated while looking into visited links.\n\"\"\")\n\nBOOKMARKS_KEYMAP = Keymap(\"bookmarks-list\", parent=MINIBUFFER_KEYMAP, doc=\"\"\"\\\nLocal keymap activated while looking into bookmarks.\n\"\"\")\n\nBUFFERLIST_KEYMAP = Keymap(\"buffer-list\", parent=MINIBUFFER_KEYMAP, doc=\"\"\"\\\nLocal keymap activated while looking into buffers.\n\"\"\")\n\nWEBJUMP_KEYMAP = Keymap(\"webjump\", parent=MINIBUFFER_KEYMAP, doc=\"\"\"\\\nLocal keymap activated while using webjumps.\n\"\"\")\n\nHINT_KEYMAP = Keymap(\"hint\", parent=MINIBUFFER_KEYMAP, doc=\"\"\"\\\nLocal keymap used when hinting.\n\"\"\")\n\nISEARCH_KEYMAP = Keymap(\"i-search\", parent=MINIBUFFER_KEYMAP, doc=\"\"\"\\\nLocal keymap used in incremental search.\n\"\"\")\n\n\ndef global_keymap():\n    \"\"\"\n    Returns the global :class:`Keymap`.\n\n    It is almost always active, and act as a fallback if there is\n    an active keymap.\n    \"\"\"\n    warnings.warn(\n        \"global_keymap() is deprecated, use keymap('global') instead\",\n        DeprecationWarning\n    )\n    return GLOBAL_KEYMAP\n\n\ndef webbuffer_keymap():\n    \"\"\"\n    Returns the :class:`Keymap` associated to web buffers.\n\n    This keymap is active when there is no focus for an editable\n    element in web contents.\n    \"\"\"\n    warnings.warn(\n        \"webbuffer_keymap() is deprecated, use keymap('webbuffer') instead\",\n        DeprecationWarning\n    )\n    return BUFFER_KEYMAP\n\n\ndef content_edit_keymap():\n    \"\"\"\n    Returns the :class:`Keymap` associated to content editing.\n\n    Local keymap activated when a webcontent field (input, textarea,\n    ...) is focused\n    \"\"\"\n    warnings.warn(\n        \"content_edit_keymap() is deprecated, use keymap('webcontent-edit')\"\n        \" instead\",\n        DeprecationWarning\n    )\n    return CONTENT_EDIT_KEYMAP\n\n\ndef keymap(name):\n    \"\"\"Get a keymap given its name.\"\"\"\n    return KEYMAPS[name]\n"
  },
  {
    "path": "webmacs/keymaps/caret_browsing.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import CARET_BROWSING_KEYMAP as KEYMAP\n\n\nKEYMAP.define_key(\"C-n\", \"caret-browsing-down\")\nKEYMAP.define_key(\"n\", \"caret-browsing-down\")\nKEYMAP.define_key(\"Down\", \"caret-browsing-down\")\nKEYMAP.define_key(\"C-p\", \"caret-browsing-up\")\nKEYMAP.define_key(\"p\", \"caret-browsing-up\")\nKEYMAP.define_key(\"Up\", \"caret-browsing-up\")\nKEYMAP.define_key(\"C-g\", \"caret-browsing-shutdown\")\nKEYMAP.define_key(\"Esc\", \"caret-browsing-shutdown\")\nKEYMAP.define_key(\"C-f\", \"caret-browsing-forward-char\")\nKEYMAP.define_key(\"f\", \"caret-browsing-forward-char\")\nKEYMAP.define_key(\"Right\", \"caret-browsing-forward-char\")\nKEYMAP.define_key(\"C-b\", \"caret-browsing-backward-char\")\nKEYMAP.define_key(\"b\", \"caret-browsing-backward-char\")\nKEYMAP.define_key(\"Left\", \"caret-browsing-backward-char\")\nKEYMAP.define_key(\"M-f\", \"caret-browsing-forward-word\")\nKEYMAP.define_key(\"C-Right\", \"caret-browsing-forward-word\")\nKEYMAP.define_key(\"M-b\", \"caret-browsing-backward-word\")\nKEYMAP.define_key(\"C-Left\", \"caret-browsing-backward-word\")\nKEYMAP.define_key(\"C-Space\", \"caret-browsing-toggle-mark\")\nKEYMAP.define_key(\"M-w\", \"caret-browsing-cut\")\nKEYMAP.define_key(\"C-a\", \"caret-browsing-beginning-of-line\")\nKEYMAP.define_key(\"C-e\", \"caret-browsing-end-of-line\")\nKEYMAP.define_key(\"M-<\", \"caret-browsing-beginning-of-document\")\nKEYMAP.define_key(\"M->\", \"caret-browsing-end-of-document\")\nKEYMAP.define_key(\"M-{\", \"caret-browsing-backward-paragraph\")\nKEYMAP.define_key(\"M-}\", \"caret-browsing-forward-paragraph\")\nKEYMAP.define_key(\"C-s\", \"i-search-forward\")\nKEYMAP.define_key(\"C-r\", \"i-search-backward\")\n"
  },
  {
    "path": "webmacs/keymaps/content_edit.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import CONTENT_EDIT_KEYMAP as KEYMAP\n\n\nKEYMAP.define_key(\"C-g\", \"content-edit-cancel\")\nKEYMAP.define_key(\"C-n\", \"send-key-down\")\nKEYMAP.define_key(\"C-p\", \"send-key-up\")\nKEYMAP.define_key(\"C-Space\", \"content-edit-set-mark\")\nKEYMAP.define_key(\"C-f\", \"content-edit-forward-char\")\nKEYMAP.define_key(\"C-b\", \"content-edit-backward-char\")\nKEYMAP.define_key(\"M-f\", \"content-edit-forward-word\")\nKEYMAP.define_key(\"M-b\", \"content-edit-backward-word\")\nKEYMAP.define_key(\"C-a\", \"content-edit-beginning-of-line\")\nKEYMAP.define_key(\"C-e\", \"content-edit-end-of-line\")\nKEYMAP.define_key(\"C-d\", \"content-edit-delete-forward-char\")\nKEYMAP.define_key(\"M-d\", \"content-edit-delete-forward-word\")\nKEYMAP.define_key(\"M-Backspace\", \"content-edit-delete-backward-word\")\nKEYMAP.define_key(\"M-w\", \"content-edit-copy\")\nKEYMAP.define_key(\"C-w\", \"content-edit-cut\")\nKEYMAP.define_key(\"C-y\", \"webcontent-paste\")\nKEYMAP.define_key(\"C-k\", \"content-edit-kill\")\nKEYMAP.define_key(\"M-u\", \"content-edit-upcase-forward-word\")\nKEYMAP.define_key(\"M-l\", \"content-edit-downcase-forward-word\")\nKEYMAP.define_key(\"M-c\", \"content-edit-capitalize-forward-word\")\nKEYMAP.define_key(\"C-x e\", \"content-edit-open-external-editor\")\nKEYMAP.define_key(\"C-x C-e\", \"content-edit-open-external-editor\")\nKEYMAP.define_key(\"C-/\", \"content-edit-undo\")\nKEYMAP.define_key(\"C-?\", \"content-edit-redo\")\nKEYMAP.define_key(\"C-x h\", \"content-edit-select-all\")\n"
  },
  {
    "path": "webmacs/keymaps/fullscreen.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import FULLSCREEN_KEYMAP\nfrom .. import current_window\n\nfrom PyQt6.QtWebEngineCore import QWebEnginePage\n\n\n@FULLSCREEN_KEYMAP.define_key(\"q\")\n@FULLSCREEN_KEYMAP.define_key(\"C-g\")\n@FULLSCREEN_KEYMAP.define_key(\"Esc\")\ndef exit_full_screen(ctx):\n    fw = current_window().fullscreen_window\n    if fw:\n        fw.internal_view.triggerPageAction(\n            QWebEnginePage.WebAction.ExitFullScreen)\n"
  },
  {
    "path": "webmacs/keymaps/global.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom ..keymaps import GLOBAL_KEYMAP\n\nKEYMAP = GLOBAL_KEYMAP\n\n\nKEYMAP.define_key(\"C-x C-c\", \"quit\")\nKEYMAP.define_key(\"M-x\", \"M-x\")\nKEYMAP.define_key(\"C-x C-f\", \"go-to-new-buffer\")\nKEYMAP.define_key(\"C-x b\", \"switch-recent-buffer\")\nKEYMAP.define_key(\"C-x C-b\", \"switch-recent-buffer\")\nKEYMAP.define_key(\"C-x o\", \"other-view\")\nKEYMAP.define_key(\"C-x 3\", \"split-view-right\")\nKEYMAP.define_key(\"C-x 2\", \"split-view-bottom\")\nKEYMAP.define_key(\"C-x 0\", \"close-view\")\nKEYMAP.define_key(\"C-x 1\", \"maximise-view\")\nKEYMAP.define_key(\"C-x k\", \"close-buffer\")\nKEYMAP.define_key(\"C-x r\", \"revive-buffer\")\nKEYMAP.define_key(\"C-h v\", \"describe-variable\")\nKEYMAP.define_key(\"C-h f\", \"describe-command\")\nKEYMAP.define_key(\"C-h c\", \"describe-key-briefly\")\nKEYMAP.define_key(\"C-h k\", \"describe-key\")\nKEYMAP.define_key(\"C-h w\", \"where-is\")\nKEYMAP.define_key(\"M-n\", \"next-buffer\")\nKEYMAP.define_key(\"M-p\", \"previous-buffer\")\n"
  },
  {
    "path": "webmacs/keymaps/hints.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import HINT_KEYMAP as KEYMAP\n\nKEYMAP.define_key(\"C-g\", \"hint-abort\")\nKEYMAP.define_key(\"Esc\", \"hint-abort\")\n\nKEYMAP.define_key(\"C-n\", \"hint-next\")\nKEYMAP.define_key(\"Down\", \"hint-next\")\n\nKEYMAP.define_key(\"C-p\", \"hint-prev\")\nKEYMAP.define_key(\"Up\", \"hint-prev\")\n"
  },
  {
    "path": "webmacs/keymaps/isearch.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import ISEARCH_KEYMAP as KEYMAP\n\n\nKEYMAP.define_key(\"C-n\", \"i-search-next\")\nKEYMAP.define_key(\"C-s\", \"i-search-next\")\n\nKEYMAP.define_key(\"C-p\", \"i-search-prev\")\nKEYMAP.define_key(\"C-r\", \"i-search-prev\")\n\nKEYMAP.define_key(\"Return\", \"i-search-validate\")\n\nKEYMAP.define_key(\"C-g\", \"i-search-abort\")\nKEYMAP.define_key(\"Esc\", \"i-search-abort\")\n"
  },
  {
    "path": "webmacs/keymaps/minibuffer.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import MINIBUFFER_KEYMAP as KEYMAP, VISITEDLINKS_KEYMAP, \\\n    BOOKMARKS_KEYMAP, BUFFERLIST_KEYMAP, WEBJUMP_KEYMAP\n\n\nKEYMAP.define_key(\"Tab\", \"minibuffer-select-complete\")\nKEYMAP.define_key(\"C-n\", \"minibuffer-select-next\")\nKEYMAP.define_key(\"Down\", \"minibuffer-select-next\")\nKEYMAP.define_key(\"C-p\", \"minibuffer-select-prev\")\nKEYMAP.define_key(\"Up\", \"minibuffer-select-prev\")\nKEYMAP.define_key(\"M-<\", \"minibuffer-select-first\")\nKEYMAP.define_key(\"M->\", \"minibuffer-select-last\")\nKEYMAP.define_key(\"C-v\", \"minibuffer-select-next-page\")\nKEYMAP.define_key(\"M-v\", \"minibuffer-select-prev-page\")\nKEYMAP.define_key(\"M-n\", \"minibuffer-history-next\")\nKEYMAP.define_key(\"M-p\", \"minibuffer-history-prev\")\nKEYMAP.define_key(\"Return\", \"minibuffer-validate\")\nKEYMAP.define_key(\"C-g\", \"minibuffer-abort\")\nKEYMAP.define_key(\"Esc\", \"minibuffer-abort\")\nKEYMAP.define_key(\"M-Backspace\", \"minibuffer-delete-backward-word\")\nKEYMAP.define_key(\"C-Space\", \"minibuffer-mark\")\nKEYMAP.define_key(\"C-x h\", \"minibuffer-select-all\")\nKEYMAP.define_key(\"C-f\", \"minibuffer-forward-char\")\nKEYMAP.define_key(\"Right\", \"minibuffer-forward-char\")\nKEYMAP.define_key(\"C-b\", \"minibuffer-backward-char\")\nKEYMAP.define_key(\"Left\", \"minibuffer-backward-char\")\nKEYMAP.define_key(\"M-f\", \"minibuffer-forward-word\")\nKEYMAP.define_key(\"M-Right\", \"minibuffer-forward-word\")\nKEYMAP.define_key(\"M-b\", \"minibuffer-backward-word\")\nKEYMAP.define_key(\"M-Left\", \"minibuffer-backward-word\")\nKEYMAP.define_key(\"M-w\", \"minibuffer-copy\")\nKEYMAP.define_key(\"C-w\", \"minibuffer-cut\")\nKEYMAP.define_key(\"C-y\", \"minibuffer-paste\")\nKEYMAP.define_key(\"C-d\", \"minibuffer-delete-forward-char\")\nKEYMAP.define_key(\"M-d\", \"minibuffer-delete-forward-word\")\nKEYMAP.define_key(\"C-a\", \"minibuffer-beginning-of-line\")\nKEYMAP.define_key(\"C-e\", \"minibuffer-end-of-line\")\nKEYMAP.define_key(\"C-/\", \"minibuffer-undo\")\nKEYMAP.define_key(\"C-?\", \"minibuffer-redo\")\n\n\nVISITEDLINKS_KEYMAP.define_key(\"C-k\", \"visited-links-delete-highlighted\")\n\nBOOKMARKS_KEYMAP.define_key(\"C-k\", \"bookmarks-delete-highlighted\")\n\nBUFFERLIST_KEYMAP.define_key(\"C-k\", \"buffer-list-delete-highlighted\")\n\nWEBJUMP_KEYMAP.define_key(\"Tab\", \"webjump-complete\")\n"
  },
  {
    "path": "webmacs/keymaps/webbuffer.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import BUFFER_KEYMAP as KEYMAP\n\n\nKEYMAP.define_key(\"g\", \"go-to\")\nKEYMAP.define_key(\"s\", \"search-default\")\nKEYMAP.define_key(\"G\", \"go-to-alternate-url\")\nKEYMAP.define_key(\"b\", \"buffer-history\")\nKEYMAP.define_key(\"F\", \"go-forward\")\nKEYMAP.define_key(\"B\", \"go-backward\")\nKEYMAP.define_key(\"C-s\", \"i-search-forward\")\nKEYMAP.define_key(\"C-r\", \"i-search-backward\")\nKEYMAP.define_key(\"C-v\", \"scroll-page-down\")\nKEYMAP.define_key(\"M-v\", \"scroll-page-up\")\nKEYMAP.define_key(\"M->\", \"scroll-bottom\")\nKEYMAP.define_key(\"M-<\", \"scroll-top\")\nKEYMAP.define_key(\"f\", \"follow\")\nKEYMAP.define_key(\"c l\", \"copy-link\")\nKEYMAP.define_key(\"c c\", \"copy-current-link\")\nKEYMAP.define_key(\"c t\", \"copy-current-buffer-title\")\nKEYMAP.define_key(\"c u\", \"copy-current-buffer-url\")\nKEYMAP.define_key(\"M-w\", \"webcontent-copy\")\nKEYMAP.define_key(\"r\", \"reload-buffer\")\nKEYMAP.define_key(\"R\", \"reload-buffer-no-cache\")\nKEYMAP.define_key(\"h\", \"visited-links-history\")\nKEYMAP.define_key(\"q\", \"close-buffer\")\nKEYMAP.define_key(\"C-x h\", \"select-buffer-content\")\nKEYMAP.define_key(\"C\", \"caret-browsing-init\")\nKEYMAP.define_key(\"m\", \"bookmark-open\")\nKEYMAP.define_key(\"M\", \"bookmark-add\")\nKEYMAP.define_key(\"C-+\", \"text-zoom-in\")\nKEYMAP.define_key(\"C--\", \"text-zoom-out\")\nKEYMAP.define_key(\"C-=\", \"text-zoom-reset\")\nKEYMAP.define_key(\"+\", \"zoom-in\")\nKEYMAP.define_key(\"-\", \"zoom-out\")\nKEYMAP.define_key(\"=\", \"zoom-normal\")\nKEYMAP.define_key(\"C-n\", \"send-key-down\")\nKEYMAP.define_key(\"n\", \"send-key-down\")\nKEYMAP.define_key(\"C-p\", \"send-key-up\")\nKEYMAP.define_key(\"p\", \"send-key-up\")\nKEYMAP.define_key(\"P\", \"password-manager-fill-buffer\")\nKEYMAP.define_key(\"C-f\", \"send-key-right\")\nKEYMAP.define_key(\"C-b\", \"send-key-left\")\nKEYMAP.define_key(\"C-g\", \"buffer-escape\")\nKEYMAP.define_key(\"C-x p\", \"print-buffer\")\n"
  },
  {
    "path": "webmacs/killed_buffers.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport collections\nfrom PyQt6.QtCore import QDataStream, QByteArray, QIODevice\nfrom .webbuffer import create_buffer\nfrom . import variables, hooks\n\n\nmax_size = variables.define_variable(\n    \"revive-buffers-limit\",\n    \"The maximum number of killed buffers that can be revived.\"\n    \" If set to a -1, there is no limit. Default to 10.\",\n    10,\n    type=variables.Int(min=-1),\n    callbacks=(\n        lambda v: KilledBuffer.update_max_size(v.value)\n    ),\n)\n\n\nclass KilledBuffer(object):\n    all = collections.deque(maxlen=max_size.value)\n\n    @classmethod\n    def update_max_size(cls, nb):\n        new_all = collections.deque(maxlen=nb if nb >= 0 else None)\n        for item in reversed(cls.all):\n            new_all.appendleft(item)\n        cls.all = new_all\n\n    def __init__(self, url, title, icon, history_data, delayed):\n        self.url = url\n        self.title = title\n        self.icon = icon\n        self.history_data = history_data\n        self.delayed = delayed\n        self.all.appendleft(self)\n\n    @classmethod\n    def from_buffer(cls, buff):\n        data = QByteArray()\n        stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly)\n        stream << buff.history()\n\n        return cls(\n            buff.url(),\n            buff.title(),\n            buff.icon(),\n            data,\n            buff.delayed_loading_url()\n        )\n\n    def revive(self):\n        buff = create_buffer()\n        stream = QDataStream(self.history_data,\n                             QIODevice.OpenModeFlag.ReadOnly)\n        stream >> buff.history()\n        self.all.remove(self)\n\n        if self.delayed:\n            buff.load(self.delayed.url)\n        return buff\n\n\nhooks.webbuffer_closed.add(KilledBuffer.from_buffer)\n"
  },
  {
    "path": "webmacs/main.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport argparse\nimport signal\nimport socket\nimport logging\nimport sys\nimport atexit\nimport os\nimport warnings\n\nfrom PyQt6.QtNetwork import QAbstractSocket\n\nfrom .ipc import IpcServer\nfrom . import variables, filter_webengine_output\n\n\nlog_to_disk = variables.define_variable(\n    \"log-to-disk-max-files\",\n    \"Maximum number of log files to keep. Log files are stored in\"\n    \" ~/.webmacs/logs. Setting this to 0 will deactivate file logging\"\n    \" completely.\",\n    0,\n    type=variables.Int(min=0),\n)\n\n\ndef signal_wakeup(app):\n    \"\"\"\n    Allow to be notified in Python for signals when in long-running calls from\n    the C or c++ side, like QApplication.exec().\n\n    See https://stackoverflow.com/a/37229299.\n    \"\"\"\n    sock = QAbstractSocket(QAbstractSocket.SocketType.UdpSocket, app)\n    # Create a socket pair\n    sock.wsock, sock.rsock = socket.socketpair(type=socket.SOCK_DGRAM)\n    # Let Qt listen on the one end\n    sock.setSocketDescriptor(sock.rsock.fileno())\n    # And let Python write on the other end\n    sock.wsock.setblocking(False)\n    signal.set_wakeup_fd(sock.wsock.fileno())\n    # add a dummy callback just to be on the python side as soon as possible.\n    sock.readyRead.connect(lambda: None)\n\n\ndef setup_logging(level, webcontent_level):\n    root = logging.getLogger()\n    webcontent = logging.getLogger(\"webcontent\")\n    for logger, format, lvl in (\n            (root,\n             \"%(levelname)s: %(message)s\",\n             level),\n            (webcontent,\n             \"%(levelname)s %(name)s: [%(url)s] %(message)s\",\n             webcontent_level)):\n        logger.setLevel(logging.DEBUG)\n        handler = logging.StreamHandler()\n        fmt = logging.Formatter(format)\n        handler.setFormatter(fmt)\n        handler.setLevel(lvl)\n        logger.addHandler(handler)\n\n    webcontent.propagate = False\n\n    warnings.filterwarnings('always', r\"^.*$\", DeprecationWarning,\n                            r\"^webmacs.*$\")\n\n\ndef setup_logging_on_disk(log_dir, backup_count=5):\n    from logging.handlers import RotatingFileHandler\n\n    root = logging.getLogger()\n    webcontent = logging.getLogger(\"webcontent\")\n\n    class Formatter(logging.Formatter):\n\n        def formatMessage(self, record):\n            fmt = (\"%(levelname)s %(name)s: [%(url)s] %(message)s\"\n                   if record.name == \"webcontent\"\n                   else \"%(levelname)s: %(message)s\")\n            return fmt % record.__dict__\n\n    if not os.path.isdir(log_dir):\n        os.makedirs(log_dir)\n\n    handler = RotatingFileHandler(os.path.join(log_dir, \"log\"),\n                                  backupCount=backup_count,\n                                  delay=True)\n    handler.setFormatter(Formatter())\n    handler.doRollover()\n    handler.setLevel(logging.DEBUG)\n\n    for logger in (root, webcontent):\n        logger.addHandler(handler)\n\n\ndef parse_args(argv=None):\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"-l\", \"--log-level\",\n                        help=\"Set the log level, defaults to %(default)s.\",\n                        default=\"warning\",\n                        choices=(\"debug\", \"info\", \"warning\",\n                                 \"error\", \"critical\"))\n\n    # There is no such JavaScript error level, critical - still since there\n    # are some logs that are printed anyway and that it is easier to implement.\n    # Let's keep the critical level.\n    parser.add_argument(\"-w\", \"--webcontent-log-level\",\n                        help=\"Set the log level for the web contents,\"\n                        \" defaults to %(default)s.\",\n                        default=\"critical\",\n                        choices=(\"info\", \"warning\", \"error\", \"critical\"))\n\n    parser.add_argument(\"-i\", \"--instance\", default=\"default\",\n                        help=\"Create or reuse a named webmacs instance.\"\n                        \" If the given instance name is the empty string, an\"\n                        \" automatically generated name will be used.\")\n\n    parser.add_argument(\"-p\", \"--profile\", default=\"default\",\n                        help=\"Use the named profile directory.\"\n                        \" Each profile will contain distinct navigation data\"\n                        \" (history, cookies, ...).\")\n\n    parser.add_argument(\"--list-instances\", action=\"store_true\",\n                        help=\"List running instances and exit.\")\n\n    parser.add_argument(\"--off-the-record\", action=\"store_true\",\n                        help=\"Private browsing mode.\")\n\n    parser.add_argument(\"url\", nargs=\"?\",\n                        help=\"url to open\")\n\n    opts = parser.parse_args(argv)\n\n    # handle local file path\n    if opts.url and os.path.exists(opts.url) \\\n       and not os.path.isabs(opts.url):\n        opts.url = os.path.realpath(opts.url)\n\n    return opts\n\n\ndef init(opts):\n    \"\"\"\n    Default initialization of webmacs.\n\n    If a URL is given on the command line, this method opens it. Else, it tries\n    to load the buffers that were opened the last time webmacs has\n    exited. If none of that works, the default is to open a buffer\n    with an url to the duckduck go search engine.\n\n    Also open the view maximized.\n\n    :param opts: the result of the parsed command line.\n    \"\"\"\n    from .application import app\n    from .session import session_load, session_save\n    from .window import Window\n    from .webbuffer import create_buffer\n\n    a = app()\n    a.aboutToQuit.connect(lambda: session_save(a.profile.session_file))\n\n    def create_window(url):\n        w = Window()\n        buff = create_buffer(url)\n        w.current_webview().setBuffer(buff)\n        w.showMaximized()\n\n    if opts.url:\n        create_window(opts.url)\n        return\n\n    home_page = variables.get(\"home-page\")\n    session_file = a.profile.session_file\n    if home_page:\n        create_window(home_page)\n        return\n    if session_file and os.path.exists(session_file):\n        try:\n            session_load(session_file)\n            return\n        except Exception:\n            logging.exception(\"Unable to load session from '%s'\", session_file)\n\n    create_window(\"about:blank\")\n\n\ndef _handle_user_init_error(conf_path, msg):\n    import traceback\n\n    stack_size = 0\n    tbs = traceback.extract_tb(sys.exc_info()[2])\n    for i, t in enumerate(tbs):\n        if t[0].startswith(conf_path):\n            stack_size = -len(tbs[i:])\n            break\n    logging.critical((\"%s\\n\\n\" % msg)\n                     + traceback.format_exc(stack_size))\n    sys.exit(1)\n\n\nif sys.version_info >= (3, 5):\n    import importlib.machinery\n    import importlib.util\n\n    def load_user_module(conf_path):\n        spec = importlib.machinery.PathFinder.find_spec(\"init\", [conf_path])\n        if spec is None:\n            return None\n        user_init = importlib.util.module_from_spec(spec)\n        sys.modules[\"init\"] = user_init\n        spec.loader.exec_module(user_init)\n        return user_init\nelse:\n    import imp\n\n    def load_user_module(conf_path):\n        try:\n            spec = imp.find_module(\"init\", [conf_path])\n        except ImportError:\n            return None\n        return imp.load_module(\"_webmacs_userconfig\", *spec)\n\n\ndef main():\n    opts = parse_args()\n\n    if opts.list_instances:\n        for instance in IpcServer.list_all_instances():\n            print(instance)\n        sys.exit(0)\n    elif not opts.instance:\n        # pick a random instance name.\n        uniq = [int(n) for n in IpcServer.list_all_instances(check=False)\n                if n.isdigit()]\n        opts.instance = str(max(uniq) + 1) if uniq else \"1\"\n\n    conf_path = os.path.join(os.path.expanduser(\"~\"), \".webmacs\")\n    if not os.path.isdir(conf_path):\n        os.makedirs(conf_path)\n\n    out_filter = filter_webengine_output.make_filter()\n\n    setup_logging(getattr(logging, opts.log_level.upper()),\n                  getattr(logging, opts.webcontent_log_level.upper()))\n\n    conn = IpcServer.check_server_connection(opts.instance)\n\n    if conn:\n        conn.send_data(opts.__dict__)\n        data = conn.get_data()\n        conn.sock.close()\n        msg = data.get(\"message\")\n        if msg:\n            print(msg)\n        return\n\n    # Delay loading after command line parsing and ipc checking.\n    # Loading qwebengine stuff takes a couple of seconds...\n    from .application import Application, _app_requires\n\n    _app_requires()\n\n    # load a user init module if any\n    try:\n        user_init = load_user_module(conf_path)\n    except Exception:\n        _handle_user_init_error(\n            conf_path,\n            \"Error reading the user configuration.\"\n        )\n\n    os.environ[\"QTWEBENGINE_DICTIONARIES_PATH\"] = os.path.join(conf_path,\n                                                               \"spell_checking\")\n    app = Application(conf_path, [\n        # The first argument passed to the QApplication args defines\n        # the x11 property WM_CLASS.\n        \"webmacs\" if opts.instance == \"default\"\n        else \"webmacs-%s\" % opts.instance\n    ], instance_name=opts.instance, profile_name=opts.profile,\n                      off_the_record=opts.off_the_record)\n    server = IpcServer(opts.instance)\n    atexit.register(server.cleanup)\n\n    out_filter.enable()\n\n    # execute the user init function if there is one\n    if user_init is None or not hasattr(user_init, \"init\"):\n        init(opts)\n    else:\n        try:\n            user_init.init(opts)\n        except Exception:\n            _handle_user_init_error(\n                conf_path,\n                \"Error executing user init function in %s.\"\n                % user_init.__file__\n            )\n\n    if log_to_disk.value > 0 and not opts.off_the_record:\n        setup_logging_on_disk(os.path.join(conf_path, \"logs\"),\n                              backup_count=log_to_disk.value)\n    app.post_init()\n    signal_wakeup(app)\n    signal.signal(signal.SIGINT, lambda s, h: app.quit())\n    sys.exit(app.exec())\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "webmacs/minibuffer/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtWidgets import QWidget, QLineEdit, QHBoxLayout, QLabel, \\\n    QTableView, QHeaderView, QApplication, QSizePolicy, QFrame\nfrom PyQt6.QtGui import QPainter\nfrom PyQt6.QtCore import pyqtSignal as Signal, \\\n    QEvent, QSortFilterProxyModel, QRegularExpression, Qt, QModelIndex, \\\n    pyqtProperty\n\nfrom ..keymaps import MINIBUFFER_KEYMAP as KEYMAP\nfrom .prompt import Prompt\nfrom .. import variables\nfrom .. import windows\nfrom ..keyboardhandler import LOCAL_KEYMAP_SETTER\n\n\nclass Popup(QTableView):\n    def __init__(self, window, buffer_input):\n        QTableView.__init__(self, window)\n        # do not diplay more than one line in a cell, and elide text on middle\n        # (best for urls)\n        self.setWordWrap(False)\n        self.setTextElideMode(Qt.TextElideMode.ElideMiddle)\n\n        self.setVisible(False)\n        self.setFrameStyle(QFrame.Shape.Box)\n        self._window = window\n        self._buffer_input = buffer_input\n        window.installEventFilter(self)\n        self.setFocusPolicy(Qt.FocusPolicy.NoFocus)\n        self.horizontalHeader().hide()\n        self.verticalHeader().hide()\n        self.verticalHeader().setSectionResizeMode(\n            QHeaderView.ResizeMode.Fixed)\n        self.verticalHeader().setDefaultSectionSize(24)\n        self.setHorizontalScrollBarPolicy(\n            Qt.ScrollBarPolicy.ScrollBarAlwaysOff)\n        self.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)\n        self.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)\n        self.setSelectionMode(QTableView.SelectionMode.SingleSelection)\n        self.setShowGrid(False)\n        self._max_visible_items = 10\n\n    def _resize(self, size):\n        # size is calculated given the window and the minibuffer input\n        # geometries\n        h = (24) * min(self._max_visible_items, self.model().rowCount()) + (\n            2 * self.lineWidth())\n        w = size.width()\n        y = size.height() - h - self._buffer_input.height()\n\n        self.setGeometry(0, y, w, h)\n\n        # Split the columns width, nicer when we have at least two of them.\n        cols = self.model().columnCount()\n        if cols > 0:\n            col_width = round(w / cols)\n            for i in range(cols):\n                self.setColumnWidth(i, col_width)\n\n    def popup(self):\n        self._resize(self._window.size())\n\n        if not self.isVisible():\n            self.show()\n\n    def eventFilter(self, obj, event):\n        # resize the popup when the window is resized\n        if obj == self._window and event.type() == QEvent.Type.Resize:\n            self._resize(event.size())\n        return False\n\n\nclass MinibufferInput(QLineEdit):\n    completion_activated = Signal(QModelIndex)\n\n    FuzzyMatch = Prompt.FuzzyMatch\n    SimpleMatch = Prompt.SimpleMatch\n\n    def __init__(self, parent, window):\n        QLineEdit.__init__(self, parent)\n        self._completer_model = None\n        self._popup = Popup(window, self)\n        self.textEdited.connect(self._show_completions)\n        self._popup.installEventFilter(self)\n        self.installEventFilter(self)\n        self._eat_focusout = False\n        self._proxy_model = QSortFilterProxyModel(self)\n        self._proxy_model.setFilterKeyColumn(-1)\n        self._popup.setModel(self._proxy_model)\n        self._popup.activated.connect(self._on_completion_activated)\n        self._popup.selectionModel().currentRowChanged.connect(\n            self._on_row_changed)\n        self._right_italic_text = \"\"\n        self._mark = False\n        self.configure_completer({})\n\n    def configure_completer(self, opts):\n        self._popup._max_visible_items = opts.get(\"max-visible-items\", 10)\n        self._match = opts.get(\"match\", self.SimpleMatch)\n        self._autocomplete_single = opts.get(\"autocomplete-single\", True)\n        self._autocomplete = opts.get(\"autocomplete\", False)\n        if self._autocomplete:\n            self._autocomplete_single = False\n        self._complete_empty = opts.get(\"complete-empty\", False)\n\n    def keymap(self):\n        prompt = self.parent()._prompt\n        if prompt and prompt.keymap:\n            return prompt.keymap\n        return KEYMAP\n\n    def eventFilter(self, obj, event):\n        etype = event.type()\n        if etype == QEvent.Type.FocusOut and obj == self \\\n           and self._eat_focusout and self._popup.isVisible():\n            # keep the focus on the line edit\n            return True\n        elif etype == QEvent.Type.MouseButtonPress:\n            # if we've clicked in the widget (or its descendant), let it handle\n            # the click\n            pos = obj.mapToGlobal(event.pos())\n            target = QApplication.widgetAt(pos)\n            if target and (self.isAncestorOf(target) or target == self):\n                if not self._popup.underMouse():\n                    self._popup.hide()\n                target.event(event)\n                return True\n\n            if not self._popup.underMouse():\n                self._popup.hide()\n                return True\n        elif etype in (QEvent.Type.KeyPress, QEvent.Type.KeyRelease):\n            # send event to the line edit\n            self._eat_focusout = True\n            self.event(event)\n            self._eat_focusout = False\n            return True\n\n        return QLineEdit.eventFilter(self, obj, event)\n\n    def event(self, evt):\n        t = evt.type()\n        if t == QEvent.Type.Show:\n            LOCAL_KEYMAP_SETTER.minibuffer_input_focus_changed(self, True)\n        elif t == QEvent.Type.Hide:\n            LOCAL_KEYMAP_SETTER.minibuffer_input_focus_changed(self, False)\n        return QLineEdit.event(self, evt)\n\n    def set_completer_model(self, completer_model):\n        self._proxy_model.setSourceModel(completer_model)\n\n    def completer_model(self):\n        return self._proxy_model.sourceModel()\n\n    def set_match(self, type):\n        self._match = type\n        if self._popup.isVisible():\n            self._show_completions(self.text())\n\n    def _on_row_changed(self, current, old):\n        if self._autocomplete:\n            self.complete(hide_popup=False)\n\n    def _show_completions(self, txt, force=False):\n        force = force or self._complete_empty\n        if self._match is not None:\n            if self._match == self.SimpleMatch:\n                pattern = \"^\" + QRegularExpression.escape(txt)\n            elif self._match == self.FuzzyMatch:\n                pattern = \".*\".join(QRegularExpression.escape(t)\n                                    for t in txt.split())\n            self._proxy_model.setFilterRegularExpression(QRegularExpression(\n                pattern,\n                QRegularExpression.PatternOption.CaseInsensitiveOption\n            ))\n        else:\n            self._proxy_model.setFilterRegularExpression(None)\n\n        if self._proxy_model.rowCount() == 0:\n            self._popup.hide()\n        elif not txt and not force:\n            self._popup.hide()\n        else:\n            self._popup.popup()\n\n    def show_completions(self, filter_text=None):\n        self._show_completions(\n            filter_text if filter_text is not None else self.text(), True)\n\n    def _on_completion_activated(self, index, hide_popup=True):\n        if hide_popup:\n            self._popup.hide()\n        model = index.model()\n        if index.column() != 0:\n            index = model.index(index.row(), 0)\n\n        self.setText(model.data(index))\n        self.completion_activated.emit(model.mapToSource(index))\n\n    def popup(self):\n        return self._popup\n\n    def complete(self, hide_popup=True):\n        if not self._popup.isVisible():\n            return\n\n        index = self._popup.selectionModel().currentIndex()\n        if index.isValid():\n            self._on_completion_activated(index, hide_popup=hide_popup)\n        elif self._autocomplete_single and self._proxy_model.rowCount() == 1:\n            self._on_completion_activated(self._proxy_model.index(0, 0),\n                                          hide_popup=hide_popup)\n\n    def select_next_completion(self, forward=True, steps=1):\n        model = self._proxy_model\n        entries = model.rowCount()\n        if entries == 0:\n            return\n\n        selection = self._popup.selectionModel().currentIndex()\n        if not selection.isValid():\n            row = 0 if forward else (entries - 1)\n        else:\n            row = selection.row()\n            if forward:\n                row = row + steps\n                if row >= entries:\n                    row = 0\n            else:\n                row = row - steps\n                if row < 0:\n                    row = (entries - 1)\n\n        self._popup.selectRow(row)\n\n    def select_first_completion(self):\n        self._popup.selectRow(0)\n\n    def select_last_completion(self):\n        entries = self._proxy_model.rowCount()\n        self._popup.selectRow(entries - 1)\n\n    def select_next_page_completion(self, forward=True):\n        self.select_next_completion(forward=forward,\n                                    steps=self._popup._max_visible_items - 1)\n\n    def mark(self):\n        return self._mark\n\n    def set_mark(self, value=None):\n        if value is None:\n            value = not self._mark\n        self._mark = value\n        return self._mark\n\n    def reinit(self):\n        self.setText(\"\")\n        self.setEchoMode(self.EchoMode.Normal)\n        self.setValidator(None)\n        self._right_italic_text = \"\"\n\n    def set_right_italic_text(self, text):\n        self._right_italic_text = text\n        self.update()\n\n    def paintEvent(self, event):\n        QLineEdit.paintEvent(self, event)\n        if not self._right_italic_text:\n            return\n        painter = QPainter(self)\n        font = painter.font()\n        font.setItalic(True)\n        painter.setFont(font)\n        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)\n        painter.drawText(self.rect().adjusted(0, 0, -10, 0),\n                         Qt.AlignmentFlag.AlignRight,\n                         self._right_italic_text)\n\n    @pyqtProperty(\"QColor\")\n    def background_color(self):\n        return self.palette().color(self.backgroundRole())\n\n    @background_color.setter\n    def background_color(self, color):\n        palette = self.palette()\n        palette.setColor(self.backgroundRole(), color)\n        self.setPalette(palette)\n\n\ndef _update_minibuffer_height(var):\n    for window in windows():\n        window.minibuffer().set_height(var.value)\n\n\nMINIBUFFER_HEIGHT = variables.define_variable(\n    \"minibuffer-height\",\n    \"The height in pixel of the minibuffer.\",\n    25,\n    type=variables.Int(min=1),\n    callbacks=(_update_minibuffer_height,)\n)\n\n\nclass Minibuffer(QWidget):\n    def __init__(self, window):\n        QWidget.__init__(self, window)\n        layout = QHBoxLayout(self)\n        layout.setContentsMargins(0, 0, 0, 0)\n        self.setLayout(layout)\n\n        self.label = QLabel(self)\n        self.rlabel = QLabel(self)\n        self.__default_label_policy = self.label.sizePolicy()\n        # when input line edit is hidden, this size policy allow to not resize\n        # the parent widget if the text in the label is too long.\n        self.label.setSizePolicy(QSizePolicy.Policy.Ignored,\n                                 QSizePolicy.Policy.Fixed)\n        layout.addWidget(self.label)\n\n        self._input = MinibufferInput(self, window)\n        layout.addWidget(self._input)\n\n        self.rlabel.setAlignment(\n            Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)\n        layout.addWidget(self.rlabel)\n\n        self.set_height(MINIBUFFER_HEIGHT.value)\n\n        self._input.installEventFilter(self)\n        self._input.hide()\n        self._prompt = None\n\n    def set_height(self, height):\n        self.label.setMinimumHeight(height)\n\n    def eventFilter(self, obj, event):\n        if obj == self._input:\n            if event.type() == QEvent.Type.Hide:\n                self.label.setSizePolicy(QSizePolicy.Policy.Ignored,\n                                         QSizePolicy.Policy.Fixed)\n            elif event.type() == QEvent.Type.Show:\n                self.label.setSizePolicy(self.__default_label_policy)\n                obj.setMaximumHeight(self.label.height())\n        return False\n\n    def show_info(self, text):\n        if self._input.isHidden():\n            self.label.setText(text)\n\n    def input(self):\n        return self._input\n\n    def prompt(self):\n        return self._prompt\n\n    def do_prompt(self, prompt, **kwargs):\n        self.close_prompt()\n        self._prompt = prompt\n        if prompt:\n            prompt.closed.connect(self._prompt_closed)\n            prompt.closed.connect(prompt.deleteLater)\n            return prompt.exec(self, **kwargs)\n\n    def close_prompt(self):\n        if self._prompt:\n            self._prompt.close()\n            self._prompt = None\n\n    def _prompt_closed(self):\n        self._prompt = None\n"
  },
  {
    "path": "webmacs/minibuffer/prompt.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport itertools\nimport collections\n\nfrom PyQt6.QtCore import QObject, QAbstractTableModel, QModelIndex, Qt, \\\n    pyqtSlot as Slot, pyqtSignal as Signal, QEventLoop, QPropertyAnimation, \\\n    QEvent, QRegularExpression\n\nfrom PyQt6.QtGui import QColor, QRegularExpressionValidator\n\nfrom ..keyboardhandler import set_global_keymap_enabled\nfrom ..keymaps import Keymap\nfrom .. import variables\n\n\nFLASH_DURATION = variables.define_variable(\n    \"minibuffer-flash-duration\",\n    \"Total duration in seconds of the minibuffer flash animation.\",\n    0.3,\n    type=variables.Float(min=0.0),\n)\nFLASH_COLOR = variables.define_variable(\n    \"minibuffer-flash-color\",\n    \"Color for the minibuffer flash animation. Should be given as\"\n    \" an hexadecimal string.\",\n    \"#ff0000\",\n    type=variables.String(),\n)\nFLASH_COUNT = variables.define_variable(\n    \"minibuffer-flash-count\",\n    \"How many flashes should be displayed during the minibuffer\"\n    \" flash animation.\",\n    2,\n    type=variables.Int(min=0),\n)\n\n\nclass FSModel(QAbstractTableModel):\n    \"\"\"\n    A custom filesystemmodel that does work with the custom completer;\n\n    May not be as efficient as the qt version, but works without much pain.\n    \"\"\"\n\n    def __init__(self, parent=None):\n        QAbstractTableModel.__init__(self, parent)\n        self._root_dir = \"\"\n        self._files = []\n\n    def rowCount(self, index=QModelIndex()):\n        return len(self._files)\n\n    def columnCount(self, index=QModelIndex()):\n        return 1\n\n    def data(self, index, role=Qt.ItemDataRole.DisplayRole):\n        if role != Qt.ItemDataRole.DisplayRole:\n            return None\n\n        try:\n            return os.path.join(self._root_dir, self._files[index.row()])\n        except IndexError:\n            return None\n\n    @Slot(str)\n    def text_changed(self, text):\n        if text.endswith(\"/\"):\n            root_dir = text\n        else:\n            root_dir = os.path.dirname(text)\n\n        if root_dir != self._root_dir:\n            try:\n                files = os.listdir(root_dir)\n            except OSError:\n                return\n            self.beginResetModel()\n            self._files = files\n            self._root_dir = root_dir\n            self.endResetModel()\n\n\nclass PromptTableModel(QAbstractTableModel):\n    def __init__(self, data, parent=None):\n        QAbstractTableModel.__init__(self, parent)\n        self._data = data\n\n    def rowCount(self, index=QModelIndex()):\n        return len(self._data)\n\n    def columnCount(self, index=QModelIndex()):\n        if self._data:\n            return len(self._data[0])\n        return 0\n\n    def data(self, index, role=Qt.ItemDataRole.DisplayRole):\n        if role != Qt.ItemDataRole.DisplayRole:\n            return None\n\n        return index.internalPointer()\n\n    def index(self, row, col, parent=QModelIndex()):\n        try:\n            return self.createIndex(row, col, self._data[row][col])\n        except IndexError:\n            return QModelIndex()\n\n\ndef _prompt_exec(prompt, loop):\n    # mocked in tests to not block.\n    loop.exec()\n\n\nclass Prompt(QObject):\n    label = \"\"\n    complete_options = {}\n    keymap = None\n    history = None\n    value_return_index_data = False\n\n    SimpleMatch = 0\n    FuzzyMatch = 1\n\n    finished = Signal()\n    closed = Signal()\n\n    def __init__(self, ctx):\n        QObject.__init__(self)\n        self.ctx = ctx\n        self.__finished = False\n\n    def completer_model(self):\n        return None\n\n    def enable(self, minibuffer):\n        self.__flash = None\n        self.__index = QModelIndex()\n        self.minibuffer = minibuffer\n        minibuffer.label.setText(self.label)\n        buffer_input = minibuffer.input()\n        buffer_input.reinit()\n        buffer_input.show()\n        buffer_input.setFocus()\n        # keeping valid references of qobjects is really hard sometimes\n        # without this completer reference on self, visited_links_history\n        # will (quite) randomly generate segfault...\n        self.__completer_model = completer_model = self.completer_model()\n        if hasattr(completer_model, \"text_changed\"):\n            buffer_input.textEdited.connect(completer_model.text_changed)\n        buffer_input.set_completer_model(completer_model)\n        buffer_input.returnPressed.connect(self._on_edition_finished)\n        buffer_input.completion_activated.connect(\n            self._on_completion_activated)\n        buffer_input.configure_completer(self.complete_options)\n        if self.complete_options.get(\"complete-empty\"):\n            buffer_input.show_completions()\n\n    def close(self):\n        minibuffer = self.minibuffer\n        minibuffer.label.setText(\"\")\n        buffer_input = minibuffer.input()\n        buffer_input.returnPressed.disconnect(self._on_edition_finished)\n        buffer_input.completion_activated.disconnect(\n            self._on_completion_activated)\n\n        view = minibuffer.parent().current_webview()\n        # calling setFocus() on the view is required, else the view is scrolled\n        # to the top automatically. But we don't even get a focus in event;\n        view.internal_view().setFocus()\n        # and to not lose the keyboard focus\n        view.show_focused(True)\n\n        buffer_input.hide()\n        buffer_input.set_mark(False)\n        c_model = buffer_input.completer_model()\n        buffer_input.set_completer_model(None)\n        if c_model:\n            c_model.deleteLater()\n        if self.history:\n            self.history.reset()\n        if self.__flash:\n            self.__flash.stop()\n            self.__flash.deleteLater()\n        self.closed.emit()\n\n    def flash(self):\n        if self.__flash is None:\n            self.__flash = self._create_flash_animation()\n            if self.__flash:\n                self.__flash.start()\n        elif self.__flash.state() == self.__flash.State.Stopped:\n            self.__flash.start()\n\n    def _create_flash_animation(self):\n        if FLASH_COUNT.value <= 0 or \\\n           FLASH_DURATION.value <= 0:\n            return None\n        minibuff_input = self.minibuffer.input()\n        anim = QPropertyAnimation(minibuff_input,\n                                  b\"background_color\")\n        base = minibuff_input.property(b\"background_color\")\n        flash_color = QColor(FLASH_COLOR.value)\n        anim.setDuration(int(FLASH_DURATION.value * 1000))\n\n        step = 1./(FLASH_COUNT.value * 2)\n        pos = step\n        colors = itertools.cycle((flash_color, base))\n\n        anim.setStartValue(base)\n        while pos < 1:\n            anim.setKeyValueAt(pos, next(colors))\n            pos += step\n        anim.setEndValue(base)\n        return anim\n\n    def _on_completion_activated(self, index):\n        self.__index = index\n\n    def value(self):\n        if not self.__finished:\n            return None\n        if self.value_return_index_data:\n            index = self.index()\n            if index:\n                return index.internalPointer()\n        else:\n            return self.minibuffer.input().text()\n\n    def index(self):\n        return self.__index\n\n    @Slot()\n    def _on_edition_finished(self):\n        history = self.history\n        if history:\n            history.push(self.minibuffer.input().text())\n        self.close()\n        self.__finished = True\n        self.finished.emit()\n\n    def exec(self, minibuffer, flash=False, sync=True):\n        self.enable(minibuffer)\n        if flash:\n            self.flash()\n        if sync:\n            loop = QEventLoop()\n            self.closed.connect(loop.quit)\n            _prompt_exec(self, loop)\n            return self.value()\n\n\nclass PromptHistory(object):\n    \"\"\"\n    In memory history for prompts.\n    \"\"\"\n\n    def __init__(self, maxsize=50):\n        self._history = collections.deque((), maxlen=maxsize)\n        self.reset()\n\n    def reset(self):\n        self._in_user_value = True\n        self._user_value = \"\"\n        self._cursor = 0\n\n    def push(self, text):\n        # avoid following duplicates\n        if self._history and self._history[0] == text:\n            return\n        self._history.append(text)\n\n    def in_user_value(self):\n        \"\"\"\n        indicate if we are in the state where the user see its custom value\n        \"\"\"\n        return self._in_user_value\n\n    def set_user_value(self, text):\n        self._user_value = text\n\n    def __get(self, delta):\n        # delta must be 1 or -1\n        size = len(self._history)\n        if size == 0:\n            return self._user_value\n\n        if self._in_user_value:\n            self._in_user_value = False\n            self._cursor = 0 if delta > 0 else size - 1\n        else:\n            cursor = self._cursor + delta\n            if cursor >= size or cursor < 0:\n                self._in_user_value = True\n                return self._user_value\n            self._cursor = cursor\n\n        return self._history[self._cursor]\n\n    def get_next(self):\n        return self.__get(1)\n\n    def get_previous(self):\n        return self.__get(-1)\n\n\nclass YesNoPrompt(Prompt):\n    NO = 0\n    YES = 1\n    ALWAYS = 2\n    NEVER = 3\n\n    keymap = Keymap(\"yes-no\")  # an empty keymap\n\n    def __init__(self, label, parent=None, always=False, never=False):\n        Prompt.__init__(self, parent)\n        self.never = never\n        self.always = always\n        self.label = label + self.build_label()\n        self.valid_keys = self.build_valid_keys()\n        self._value = 0\n\n    def build_label(self):\n        optional = \"\"\n        if self.always:\n            optional += \"/Always\"\n        if self.never:\n            optional += \"/Never\"\n        return \"[yes/no{}]\".format(optional)\n\n    def build_valid_keys(self):\n        optional = \"\"\n        if self.always:\n            optional += \"A\"\n        if self.never:\n            optional += \"N\"\n        return \"yYn{}\".format(optional)\n\n    def enable(self, minibuffer):\n        set_global_keymap_enabled(False)  # disable any global keychord\n\n        Prompt.enable(self, minibuffer)\n        buffer_input = minibuffer.input()\n\n        validator = QRegularExpressionValidator(QRegularExpression(\n            \"[\" + self.valid_keys + \"]\"), buffer_input)\n        buffer_input.setValidator(validator)\n        minibuffer.input().installEventFilter(self)\n        buffer_input.textEdited.connect(self._on_text_edited)\n\n    def _on_text_edited(self, text):\n        if text in (\"y\", \"Y\"):\n            self._value = self.YES\n        elif text == \"N\":\n            self._value = self.NEVER\n        elif text == \"A\":\n            self._value = self.ALWAYS\n        else:\n            self._value = self.NO\n\n        self.close()\n        set_global_keymap_enabled(True)\n\n    def value(self):\n        return self._value\n\n    def eventFilter(self, obj, evt):\n        if evt.type() in (QEvent.Type.KeyPress, QEvent.Type.KeyRelease,\n                          QEvent.Type.ShortcutOverride):\n            if evt.text() in self.valid_keys:\n                return False\n            evt.accept()\n            self.flash()\n            return True\n        return False\n\n    def close(self):\n        self.minibuffer.input().removeEventFilter(self)\n        set_global_keymap_enabled(True)\n        Prompt.close(self)\n\n\nclass AskPasswordPrompt(Prompt):\n    def __init__(self, buffer):\n        Prompt.__init__(self, None)\n        self.buffer = buffer\n        self.username, self.password = \"\", \"\"\n        self.label = \"username: \"\n        set_global_keymap_enabled(False)\n\n    def _on_edition_finished(self):\n        input = self.minibuffer.input()\n        if not self.username:\n            self.username = input.text()\n            input.clear()\n            input.setEchoMode(input.EchoMode.Password)\n            self.minibuffer.label.setText(\"password: \")\n        else:\n            self.password = input.text()\n            Prompt._on_edition_finished(self)\n            set_global_keymap_enabled(True)\n"
  },
  {
    "path": "webmacs/minibuffer/right_label.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom .. import hooks, variables, keyboardhandler\nfrom .. import windows, BUFFERS, call_later\n\n\nMINIBUFFER_RIGHTLABEL = variables.define_variable(\n    \"minibuffer-right-label\",\n    \"Format for displaying some information in right label of minibuffer.\",\n    \"{loading}{mode}: {local_keymap} [{buffer_current}/{buffer_count}]\",\n    type=variables.String(),\n)\n\n\nREQUEST_WINDOW_UPDATE = {}\n\n\ndef update_minibuffer_right_label(window):\n    # only really update the minibuffer once in a qt loop cycle.\n    if window in REQUEST_WINDOW_UPDATE:\n        return\n\n    call_later(lambda: _update_minibuffer_right_label(window))\n    REQUEST_WINDOW_UPDATE[window] = True\n\n\ndef _update_minibuffer_right_label(window):\n    from ..application import app\n    try:\n        # KeyError if the window was closed, in such case no update is\n        # required.\n        del REQUEST_WINDOW_UPDATE[window]\n    except KeyError:\n        return\n\n    buff = window.current_webview().buffer()\n\n    try:\n        loading_p = BUFF_PROGRESS[buff]\n    except KeyError:\n        loading = \"\"\n    else:\n        loading = \" loading: %d%% \" % loading_p\n\n    label = window.minibuffer().rlabel\n    if not label.text():\n        # first time we update the label\n        if app().profile.is_off_the_record():\n            label.setStyleSheet(\"QLabel { background: orangered }\")\n    label.setText(\n        MINIBUFFER_RIGHTLABEL.value.format(\n            buffer_current=BUFFERS.index(buff) + 1,\n            buffer_count=len(BUFFERS),\n            local_keymap=keyboardhandler.local_keymap(),\n            mode=getattr(buff, \"mode\", \"unknown\"),\n            loading=loading,\n        )\n    )\n\n\ndef update_minibuffer_right_labels():\n    for window in windows():\n        update_minibuffer_right_label(window)\n\n\nBUFF_PROGRESS = {}\n\n\ndef update_label_for_buffer(buff):\n    update_minibuffer_right_labels()\n\n\ndef init_minibuffer_right_labels():\n\n    def register_buffer_load_progress(buff):\n        # first update all labels because the buffer count changed\n        update_minibuffer_right_labels()\n\n        def load_changed(p):\n            if p is None:\n                del BUFF_PROGRESS[buff]\n            else:\n                BUFF_PROGRESS[buff] = p\n\n            view = buff.view()\n            if view and view.main_window.current_webview() == view:\n                update_minibuffer_right_label(view.main_window)\n\n        # then connect this buffer to keep track of its load percent\n        buff.loadStarted.connect(lambda: load_changed(0))\n        buff.loadProgress.connect(load_changed)\n        buff.loadFinished.connect(lambda: load_changed(None))\n\n    for buff in BUFFERS:\n        register_buffer_load_progress(buff)\n\n    hooks.webbuffer_created.add(register_buffer_load_progress)\n    hooks.webbuffer_current_changed.add(update_label_for_buffer)\n\n    def on_buffer_closed(buff):\n        # first update all labels because the buffer count changed\n        update_minibuffer_right_labels()\n        BUFF_PROGRESS.pop(buff, None)\n\n    hooks.local_mode_changed.add(\n        lambda a: update_minibuffer_right_labels()\n    )\n    hooks.webbuffer_closed.add(on_buffer_closed)\n\n    # following hook should not be useful, but this ensure we don't keep\n    # window references\n    hooks.window_closed.add(\n        lambda w: REQUEST_WINDOW_UPDATE.pop(w, None)\n    )\n\n    update_minibuffer_right_labels()\n"
  },
  {
    "path": "webmacs/mode.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport re\n\nfrom .keymaps import BUFFER_KEYMAP, CONTENT_EDIT_KEYMAP, \\\n    CARET_BROWSING_KEYMAP, EMPTY_KEYMAP, FULLSCREEN_KEYMAP\n\nfrom . import variables\n\n\nMODES = {}\n\n\nclass Mode(object):\n    KEYMAP_NORMAL = 1\n    KEYMAP_CONTENT_EDIT = 2\n    KEYMAP_CARET_BROWSING = 3\n    KEYMAP_FULLSCREEN = 4\n\n    def __init__(self, name, description):\n        self.name = name\n        self.description = description\n        self._mode_to_km = {\n            self.KEYMAP_NORMAL: self.keymap,\n            self.KEYMAP_CONTENT_EDIT: self.content_edit_keymap,\n            self.KEYMAP_CARET_BROWSING: self.caret_browsing_keymap,\n            self.KEYMAP_FULLSCREEN: self.fullscreen_keymap,\n        }\n\n    def keymap(self):\n        return BUFFER_KEYMAP\n\n    def content_edit_keymap(self):\n        return CONTENT_EDIT_KEYMAP\n\n    def caret_browsing_keymap(self):\n        return CARET_BROWSING_KEYMAP\n\n    def keymap_for_mode(self, mode):\n        return self._mode_to_km[mode]()\n\n    def fullscreen_keymap(self):\n        return FULLSCREEN_KEYMAP\n\n    def __str__(self):\n        return self.name\n\n\ndef get_mode(name):\n    return MODES[name]\n\n\ndef define_mode(mode):\n    assert mode.name not in MODES\n    MODES[mode.name] = mode\n\n\ndefine_mode(Mode(\"standard-mode\", \"standard navigation mode\"))\n\n\nclass EmptyMode(Mode):\n\n    def keymap(self):\n        return EMPTY_KEYMAP\n\n    content_edit_keymap = keymap\n    caret_browsing_keymap = keymap\n    fullscreen_keymap = keymap\n\n\ndefine_mode(EmptyMode(\"no-keybindings\", \"no-keybindings navigation mode\"))\n\n\nAUTO_MODES = []\n\n\ndef get_auto_modename_for_url(url, default=\"standard-mode\"):\n    for reg, mode in AUTO_MODES:\n        if reg.match(url):\n            return mode\n\n    return default\n\n\ndef _set_auto_buffer_modes(modes):\n    global AUTO_MODES\n    AUTO_MODES = [((\n        re.compile(reg) if isinstance(reg, str) else reg),\n        mode\n    ) for reg, mode in modes.value]\n\n\nauto_buffer_modes = variables.define_variable(\n    \"auto-buffer-modes\",\n    \"List of tuple of regexes and mode name to automatically associate\"\n    \" web pages to some mode. If nothing matches the url, standard-mode is\"\n    \" used.\",\n    (),\n    type=variables.List(\n        variables.Tuple(variables.String(), variables.String(choices=MODES))\n    ),\n    callbacks=(\n        _set_auto_buffer_modes,\n    ),\n)\n"
  },
  {
    "path": "webmacs/password_manager/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\n\nfrom .. import require, variables\n\nimport json\n\nfrom PyQt6.QtCore import QObject\nfrom PyQt6.QtWebEngineCore import QWebEngineScript\nfrom collections import namedtuple\n\n\npassword_managers = {\n    \"none\": lambda: BasePaswordManager(),\n    \"passwordstore\":\n        lambda: require(\"webmacs.password_manager.password_store\").Pass()\n}\n\n\npassword_manager = variables.define_variable(\n    \"password-manager\",\n    \"\"\"Which password manager to use.\n\n- none: no password manager\n- passwordstore: the standard unix password manager.\n    \"\"\",\n    \"none\",\n    type=variables.String(choices=password_managers.keys()),\n)\n\n\ndef make_password_manager():\n    return password_managers[password_manager.value]()\n\n\nCredentials = namedtuple(\n    \"Credentials\",\n    (\"username\", \"password\", \"fields\")\n)\n\n\nclass PasswordManagerNotReady(Exception):\n    pass\n\n\nclass BasePaswordManager(QObject):\n    def __init__(self, parent=None):\n        QObject.__init__(self, parent)\n\n    def credential_for_url(self, url):\n        \"Get credentials for the given url.\"\n        raise PasswordManagerNotReady(\"No password manager set.\")\n\n    def complete_buffer(self, buffer, credential):\n        \"\"\"Fill buffer with the given credentials\"\"\"\n        dct = json.dumps(credential._asdict())\n        buffer.runJavaScript(\n            f\"password_manager.complete_form_data({dct})\",\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n"
  },
  {
    "path": "webmacs/password_manager/password_store.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\n\nfrom . import BasePaswordManager, Credentials, PasswordManagerNotReady\nfrom ..task import Task\nfrom .. import variables\n\nfrom PyQt6.QtCore import QProcess\n\nimport os\nimport logging\nimport glob\n\n\npass_store_path = variables.define_variable(\n    \"password-manager-pass-store-path\",\n    \"The path to store the pass passwords. Defaults to ~/.password-store.\",\n    os.path.expanduser(\"~/.password-store\"),\n    type=variables.String()\n)\n\n\nclass PassCredentials:\n    \"\"\"\n    Object to store the credentials read from the passwordstore utility.\n    \"\"\"\n    def __init__(self):\n        self.__cred_by_name = {}\n        self.__cred_by_url = {}\n        self.__search_needs_compil = True\n        self.__search_url_list = None\n\n    def add_credential(self, name, url, credential):\n        self.__cred_by_name[name] = credential\n        if url:\n            self.__cred_by_url[url] = credential\n        self.__search_needs_compil = True\n\n    def compile(self):\n        if self.__search_needs_compil:\n            def by_len_name(tup):\n                return len(tup[0])\n            shortened_names = [(k.rsplit(\"/\", 1)[-1], v)\n                               for k, v in self.__cred_by_name.items()]\n            # order by reverse len of url to find best suitable match first\n            self.__search_url_list = \\\n                sorted(self.__cred_by_url.items(),\n                       key=by_len_name, reverse=True) + \\\n                sorted(shortened_names, key=by_len_name,\n                       reverse=True)\n            self.__search_needs_compil = False\n\n    def for_url(self, url):\n        \"\"\"\n        Try to find the appropriate Credential for the given url, or None.\n        \"\"\"\n        self.compile()\n        for url_part, credential in self.__search_url_list:\n            if url.find(url_part) >= 0:\n                return credential\n\n    def names(self):\n        \"\"\"\n        Return the list of known passwordstore names (file names, without .gpg\n        extension)\n        \"\"\"\n        return list(self.__cred_by_name.keys())\n\n    def for_name(self, name):\n        \"\"\"\n        Return the Credential associated to the given name.\n        \"\"\"\n        return self.__cred_by_name[name]\n\n\nclass ReadCredentialsTask(Task):\n    def __init__(self):\n        Task.__init__(self)\n        self.__names = None\n        # one proc at a time, otherwise authentication might fail;;\n        self.__proc = None\n        self.__output = b\"\"\n        self.__credentials = PassCredentials()\n\n    def start(self):\n        self.__names = [os.path.splitext(fname)[0] for fname in\n                        glob.glob(\"**/*.gpg\", recursive=True,\n                                  root_dir=pass_store_path.value)]\n\n        self.__process_next()\n\n    def __process_next(self):\n        self.__output = b\"\"\n        if not self.__names:\n            self.finished.emit()\n            return\n\n        self.__name = name = self.__names.pop(0)\n        self.__proc = QProcess()\n        self.__proc.finished.connect(self.__process_finished)\n        self.__proc.readyReadStandardOutput.connect(self.__process_read)\n        logging.info(f\"Running external command: pass show {name}\")\n        self.__proc.start(\"pass\", [\"show\", name])\n\n    def __process_finished(self, code, status):\n        if status == QProcess.ExitStatus.CrashExit:\n            self.set_error_message(\"The pass process crashed.\")\n            self.finished.emit()\n        elif code != 0:\n            self.set_error_message(f\"The pass process exited with {code}.\")\n            self.finished.emit()\n        else:\n            lines = self.__output.decode(\"utf-8\").splitlines()\n            passwd = lines[0].rstrip()\n            fields = {}\n            for line in lines[1:]:\n                try:\n                    k, v = line.split(\":\", 1)\n                except ValueError:\n                    pass\n                else:\n                    fields[k.rstrip()] = v.strip()\n                username = fields.pop(\"login\", None)\n                self.__credentials.add_credential(self.__name, fields.pop(\"url\", None),\n                                                  Credentials(username, passwd, fields))\n            self.__process_next()\n\n    def __process_read(self):\n        self.__output += bytes(self.__proc.readAllStandardOutput())\n\n    def credentials(self):\n        return self.__credentials\n\n    def abort(self):\n        if self.__proc:\n            self.__proc.finished.disconnect(self.__process_finished)\n            self.__proc.kill()\n            self.__proc.waitForFinished(300)\n\n\nclass Pass(BasePaswordManager):\n    \"\"\"\n    This is the public object that the rest of the application can use.\n\n    By using reload(), it reads the passwordstore credentials (this takes time,\n    a few seconds!) and then keep the data in memory.\n    \"\"\"\n    def __init__(self):\n        BasePaswordManager.__init__(self)\n        self.__creds = None\n        self.__reloading = False\n        self.reload()\n\n    def __on_reloaded(self):\n        self.__reloading = False\n        task = self.sender()\n        if not task.error():\n            self.__creds = task.credentials()\n\n    def reload(self):\n        from ..application import app as _app\n        if not self.__reloading:\n            self.__reloading = True\n\n            app = _app()\n            task = ReadCredentialsTask()\n            task.finished.connect(self.__on_reloaded)\n            app.task_runner.run(task)\n\n    def credential_for_url(self, url):\n        if self.__reloading:\n            raise PasswordManagerNotReady(\n                \"passwordstore not ready - still reading configuration.\")\n        return self.__creds.for_url(url)\n"
  },
  {
    "path": "webmacs/profile.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\n\nfrom PyQt6.QtWebEngineCore import QWebEngineProfile, QWebEngineScript, \\\n    QWebEngineSettings\nfrom PyQt6.QtCore import QFile, QTextStream\n\nfrom .scheme_handlers import all_schemes\nfrom .visited_links import VisitedLinks\nfrom .ignore_certificates import IgnoredCertificates\nfrom .bookmarks import Bookmarks\nfrom .features import Features\nfrom . import variables, version, require\nfrom .password_manager import make_password_manager\nfrom .variables import define_variable, Bool\n\n\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\nenable_javascript = define_variable(\n    \"enable-javascript\",\n    \"Enable the running of javascript programs. Default to True.\",\n    True,\n    type=Bool(),\n)\n\nenable_pdfviewer = define_variable(\n    \"enable-pdfviewer\",\n    \"Specifies that PDF documents will be opened in the internal PDF viewer.\"\n    \" Default to False\",\n    False,\n    type=Bool(),\n)\n\n\ndef make_dir(*parts):\n    path = os.path.join(*parts)\n    os.makedirs(path, exist_ok=True)\n    return path\n\n\nclass Profile(object):\n    def __init__(self, name, off_the_record=False):\n        self.name = name\n        if off_the_record:\n            self.q_profile = QWebEngineProfile()\n        else:\n            self.q_profile = QWebEngineProfile(name)\n        self._scheme_handlers = {}  # keep a python reference\n\n        app = require(\".application\").app()\n\n        self.q_profile.setUrlRequestInterceptor(app.url_interceptor())\n\n        for handler in all_schemes():\n            h = handler(app)\n            self._scheme_handlers[handler.scheme] = h\n            self.q_profile.installUrlSchemeHandler(handler.scheme, h)\n\n        self.path = None\n        self.session_file = None\n\n        visited_links, ignored_certs, bookmarks, features = \\\n            \":memory:\", \":memory:\", \":memory:\", \":memory:\"\n\n        if not off_the_record:\n            self.path = path = make_dir(app.profiles_path(), self.name)\n            persistent_path = make_dir(path, \"persistent\")\n            cache_path = make_dir(path, \"cache\")\n\n            self.q_profile.setPersistentStoragePath(persistent_path)\n            self.q_profile.setPersistentCookiesPolicy(\n                QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies)\n            self.q_profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.DiskHttpCache)\n            self.q_profile.setCachePath(cache_path)\n\n            if app.instance_name == \"default\":\n                session_fname = \"session.json\"\n            else:\n                session_fname = \"session-{}.json\".format(app.instance_name)\n            self.session_file = os.path.join(path, session_fname)\n\n            visited_links = os.path.join(path, \"visitedlinks.db\")\n            ignored_certs = os.path.join(path, \"ignoredcerts.db\")\n            bookmarks = os.path.join(path, \"bookmarks.db\")\n            features = os.path.join(path, \"features.db\")\n\n        self.visitedlinks = VisitedLinks(visited_links)\n        self.ignored_certs = IgnoredCertificates(ignored_certs)\n        self.bookmarks = Bookmarks(bookmarks)\n        self.features = Features(features)\n\n        self.q_profile.downloadRequested.connect(\n            app.download_manager().download_requested\n        )\n        self.password_manager = make_password_manager()\n\n        self.update_spell_checking()\n\n        def inject_js(filepath,\n                      ipoint=QWebEngineScript.InjectionPoint.DocumentCreation,\n                      iid=QWebEngineScript.ScriptWorldId.ApplicationWorld,\n                      sub_frames=False,\n                      script_transform=None):\n            f = QFile(filepath)\n            assert f.open(\n                QFile.OpenModeFlag.ReadOnly | QFile.OpenModeFlag.Text)\n            src = QTextStream(f).readAll()\n            if script_transform:\n                src = script_transform(src)\n\n            script = QWebEngineScript()\n            script.setInjectionPoint(ipoint)\n            script.setSourceCode(src)\n            script.setWorldId(iid)\n            script.setRunsOnSubFrames(sub_frames)\n            self.q_profile.scripts().insert(script)\n\n        inject_js(\":/qtwebchannel/qwebchannel.js\")\n\n        contentjs = [\"WEBMACS_SECURE_ID = {};\".format(str(id(self)))]\n        with open(os.path.join(THIS_DIR, \"scripts\", \"setup.js\")) as f:\n            contentjs.append(f.read())\n        with open(os.path.join(THIS_DIR, \"scripts\", \"textedit.js\")) as f:\n            contentjs.append(f.read())\n        with open(os.path.join(THIS_DIR, \"scripts\", \"hint.js\")) as f:\n            contentjs.append(f.read())\n        with open(os.path.join(THIS_DIR, \"scripts\", \"textzoom.js\")) as f:\n            contentjs.append(f.read())\n        with open(os.path.join(THIS_DIR, \"scripts\", \"caret_browsing.js\")) as f:\n            contentjs.append(f.read())\n\n        script = QWebEngineScript()\n        script.setInjectionPoint(\n            QWebEngineScript.InjectionPoint.DocumentCreation)\n        script.setSourceCode(\"\\n\".join(contentjs))\n        script.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld)\n        script.setRunsOnSubFrames(True)\n        self.q_profile.scripts().insert(script)\n\n        inject_js(os.path.join(THIS_DIR, \"scripts\", \"password_manager.js\"))\n\n        settings = self.q_profile.settings()\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain, False,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.PluginsEnabled, True,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, True,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows, True,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.FocusOnNavigationEnabled, False,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.JavascriptEnabled,\n            enable_javascript.value,\n        )\n        settings.setAttribute(\n            QWebEngineSettings.WebAttribute.PdfViewerEnabled,\n            enable_pdfviewer.value\n        )\n\n    def update_spell_checking(self):\n        dicts = variables.get(\"spell-checking-dictionaries\")\n        self.q_profile.setSpellCheckEnabled(bool(dicts))\n        self.q_profile.setSpellCheckLanguages(dicts)\n\n    def is_off_the_record(self):\n        return self.q_profile.isOffTheRecord()\n\n\nnamed_profile = Profile\n"
  },
  {
    "path": "webmacs/scheme_handlers/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom .webmacs import WebmacsSchemeHandler\nfrom PyQt6.QtWebEngineCore import QWebEngineUrlScheme\n\n\ndef all_schemes():\n    return (WebmacsSchemeHandler,)\n\n\ndef register_schemes():\n    for scheme in all_schemes():\n        qscheme = QWebEngineUrlScheme(scheme.scheme)\n        QWebEngineUrlScheme.registerScheme(qscheme)\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/__init__.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport sys\nimport re\nimport importlib\nimport inspect\nfrom itertools import groupby\nfrom PyQt6.QtCore import QBuffer, QFile, QUrlQuery\nfrom PyQt6.QtWebEngineCore import QWebEngineUrlSchemeHandler\nfrom jinja2 import Environment, PackageLoader\nfrom ... import version, COMMANDS\nfrom ...variables import VARIABLES\nfrom ...keymaps import KEYMAPS\n\n\nPAGES = []\n_REQUESTS_HANDLER = []\nTHIS_DIR = os.path.dirname(os.path.realpath(__file__))\n\n\ndef register_page(match_url=None, visible=True):\n    def wrapper(meth):\n        if visible:\n            PAGES.append(meth.__name__)\n        if match_url is None:\n            match = re.compile(r\"^(%s)$\" % re.escape(meth.__name__))\n        elif isinstance(match_url, str):\n            match = re.compile(match_url)\n        else:\n            match = match_url\n\n        _REQUESTS_HANDLER.append((match, meth))\n\n        return meth\n    return wrapper\n\n\nclass WebmacsSchemeHandler(QWebEngineUrlSchemeHandler):\n    scheme = b\"webmacs\"\n\n    def __init__(self, parent=None):\n        QWebEngineUrlSchemeHandler.__init__(self, parent)\n        self.env = Environment(\n            autoescape=True,\n            loader=PackageLoader(__name__),\n        )\n\n    def reply_template(self, job, tpl_name, data):\n        template = self.env.get_template(tpl_name + \".html\")\n        buffer = QBuffer(self)\n        buffer.setData(template.render(**data).encode(\"utf-8\"))\n        job.reply(b\"text/html\", buffer)\n\n    def requestStarted(self, job):\n        url = job.requestUrl()\n        url_s = url.toString()[10:]  # strip webmacs://\n\n        for re_match, meth in _REQUESTS_HANDLER:\n            res = re_match.match(url_s)\n            if res:\n                meth(self, job, url, *res.groups())\n                return\n\n    @register_page(match_url=r\"^/js/(.+\\.js)$\", visible=False)\n    def to_js(self, job, _, path):\n        js_path = os.path.join(THIS_DIR, \"js\", path)\n        if os.path.isfile(js_path):\n            f = QFile(js_path, self)\n            job.reply(b\"application/javascript\", f)\n\n    @register_page()\n    def version(self, job, _, name):\n        rev = version.webmacs_revision() or \"\"\n        if rev:\n            rev = \" (%s)\" % rev\n        self.reply_template(job, name, {\n            \"versions\": (\n                (\"Webmacs version\", version.WEBMACS_VERSION_STR + rev),\n                (\"Operating system\", sys.platform),\n                (\"Python version\", sys.version),\n                (\"Qt version\", version.QT_VERSION_STR),\n                (\"PyQt version\", version.PYQT_VERSION_STR),\n                (\"Chromium version\", version.chromium_version()),\n            )\n        })\n\n    @register_page()\n    def downloads(self, job, _, name):\n        self.reply_template(job, name, {})\n\n    @register_page()\n    def commands(self, job, _, name):\n        self.reply_template(job, name, {\"commands\": COMMANDS})\n\n    @register_page(match_url=r\"^command/(\\S+)$\", visible=False)\n    def command(self, job, _, command):\n        used_in_keymaps = []\n\n        for name, km in KEYMAPS.items():\n            def add(prefix, cmd, parent):\n                if cmd == command:\n                    used_in_keymaps.append((\n                        \" \".join(str(k) for k in prefix),\n                        name,\n                    ))\n\n            km.traverse_commands(add)\n\n        cmd = COMMANDS[command]\n\n        src_url = get_src_url(cmd.binding)\n\n        self.reply_template(job, \"command\", {\n            \"command_name\": command,\n            \"command\": cmd,\n            \"command_src_url\": src_url,\n            \"used_in_keymaps\": used_in_keymaps,\n        })\n\n    @register_page()\n    def variables(self, job, _, name):\n        self.reply_template(job, name, {\"variables\": VARIABLES})\n\n    @register_page(match_url=r\"^variable/(\\S+)$\", visible=False)\n    def variable(self, job, _, name):\n        self.reply_template(job, \"variable\", {\"variable\": VARIABLES[name]})\n\n    @register_page(match_url=r\"^keymap/(\\S+)$\", visible=False)\n    def keymap(self, job, _, keymap):\n        km = KEYMAPS[keymap]\n        acc = []\n\n        def add(prefix, cmd, parent):\n            if isinstance(cmd, str):\n                acc.append((\" \".join(str(k) for k in prefix), cmd, parent))\n\n        km.traverse_commands(add)\n\n        def by_parent(v):\n            return v[2].name if v[2] else \"\"\n\n        acc = sorted(acc, key=lambda v: v[0])\n        acc = sorted(acc, key=by_parent)\n\n        self.reply_template(job, \"keymap\", {\n            \"name\": keymap,\n            \"keymap\": km,\n            \"bindings\": groupby(acc, by_parent),\n        })\n\n    @register_page()\n    def bindings(self, job, _, name):\n        self.reply_template(job, name, {\"keymaps\": KEYMAPS})\n\n    @register_page(match_url=r\"^pydoc/.+$\", visible=False)\n    def pydoc(self, job, url):\n        from pygments.formatters import HtmlFormatter\n        from pygments.lexers.python import Python3Lexer\n        from pygments import highlight\n\n        modname = url.path().lstrip(\"/\")\n        query = QUrlQuery(url)\n        extras = {}\n        if query.hasQueryItem(\"hl_lines\"):\n            start, end = query.queryItemValue(\"hl_lines\").split(\"-\")\n            extras[\"hl_lines\"] = list(range(int(start), int(end) + 1))\n\n        mod = importlib.import_module(modname)\n        filepath = inspect.getsourcefile(mod)\n\n        formatter = HtmlFormatter(\n            title=\"Module %s\" % modname,\n            full=True,\n            lineanchors=\"line\",\n            **extras\n        )\n\n        with open(filepath) as f:\n            code = highlight(f.read(), Python3Lexer(), formatter)\n\n        buffer = QBuffer(self)\n        buffer.setData(code.encode(\"utf-8\"))\n        job.reply(b\"text/html\", buffer)\n\n    @register_page(match_url=r\"^key/.+$\", visible=False)\n    def key(self, job, url):\n        key = url.path().lstrip(\"/\")\n        query = QUrlQuery(url)\n        command = query.queryItemValue(\"command\")\n        keymap = query.queryItemValue(\"keymap\")\n\n        if \":\" in command:\n            modname, fname = command.split(\":\", 1)\n            fn = getattr(importlib.import_module(modname), fname)\n            command_name = fn.__name__\n            named_command = False\n        else:\n            command_name = command\n            cmd = COMMANDS[command]\n            fn = cmd.binding\n            named_command = True\n            modname = fn.__module__\n        command_doc = fn.__doc__\n        src_url = get_src_url(fn)\n\n        def _get_all_keys(km):\n            acc = []\n\n            cmd = command_name if named_command else fn\n\n            def add(prefix, cmd_, parent_):\n                if cmd == cmd_:\n                    acc.append(\" \".join(str(k) for k in prefix))\n            km.traverse_commands(add)\n            return acc\n\n        try:\n            all_keys = _get_all_keys(KEYMAPS[keymap])\n        except KeyError:\n            all_keys = (key,)\n\n        self.reply_template(job, \"key\", {\n            \"command_name\": command_name,\n            \"keymap\": keymap,\n            \"key\": key,\n            \"command_doc\": command_doc,\n            \"named_command\": named_command,\n            \"command_src_url\": src_url,\n            \"modname\": modname,\n            \"all_keys\": all_keys,\n        })\n\n\ndef get_src_url(obj):\n    lines, loc = inspect.getsourcelines(obj)\n    return \"webmacs://pydoc/{}?hl_lines={}-{}#line-{}\".format(\n        obj.__module__,\n        loc,\n        loc + len(lines),\n        loc\n    )\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/js/vue.js",
    "content": "/*!\n * Vue.js v2.4.4\n * (c) 2014-2017 Evan You\n * Released under the MIT License.\n */\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.Vue = factory());\n}(this, (function () { 'use strict';\n\n/*  */\n\n// these helpers produces better vm code in JS engines due to their\n// explicitness and function inlining\nfunction isUndef (v) {\n  return v === undefined || v === null\n}\n\nfunction isDef (v) {\n  return v !== undefined && v !== null\n}\n\nfunction isTrue (v) {\n  return v === true\n}\n\nfunction isFalse (v) {\n  return v === false\n}\n\n/**\n * Check if value is primitive\n */\nfunction isPrimitive (value) {\n  return (\n    typeof value === 'string' ||\n    typeof value === 'number' ||\n    typeof value === 'boolean'\n  )\n}\n\n/**\n * Quick object check - this is primarily used to tell\n * Objects from primitive values when we know the value\n * is a JSON-compliant type.\n */\nfunction isObject (obj) {\n  return obj !== null && typeof obj === 'object'\n}\n\nvar _toString = Object.prototype.toString;\n\n/**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\nfunction isPlainObject (obj) {\n  return _toString.call(obj) === '[object Object]'\n}\n\nfunction isRegExp (v) {\n  return _toString.call(v) === '[object RegExp]'\n}\n\n/**\n * Check if val is a valid array index.\n */\nfunction isValidArrayIndex (val) {\n  var n = parseFloat(val);\n  return n >= 0 && Math.floor(n) === n && isFinite(val)\n}\n\n/**\n * Convert a value to a string that is actually rendered.\n */\nfunction toString (val) {\n  return val == null\n    ? ''\n    : typeof val === 'object'\n      ? JSON.stringify(val, null, 2)\n      : String(val)\n}\n\n/**\n * Convert a input value to a number for persistence.\n * If the conversion fails, return original string.\n */\nfunction toNumber (val) {\n  var n = parseFloat(val);\n  return isNaN(n) ? val : n\n}\n\n/**\n * Make a map and return a function for checking if a key\n * is in that map.\n */\nfunction makeMap (\n  str,\n  expectsLowerCase\n) {\n  var map = Object.create(null);\n  var list = str.split(',');\n  for (var i = 0; i < list.length; i++) {\n    map[list[i]] = true;\n  }\n  return expectsLowerCase\n    ? function (val) { return map[val.toLowerCase()]; }\n    : function (val) { return map[val]; }\n}\n\n/**\n * Check if a tag is a built-in tag.\n */\nvar isBuiltInTag = makeMap('slot,component', true);\n\n/**\n * Check if a attribute is a reserved attribute.\n */\nvar isReservedAttribute = makeMap('key,ref,slot,is');\n\n/**\n * Remove an item from an array\n */\nfunction remove (arr, item) {\n  if (arr.length) {\n    var index = arr.indexOf(item);\n    if (index > -1) {\n      return arr.splice(index, 1)\n    }\n  }\n}\n\n/**\n * Check whether the object has the property.\n */\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwn (obj, key) {\n  return hasOwnProperty.call(obj, key)\n}\n\n/**\n * Create a cached version of a pure function.\n */\nfunction cached (fn) {\n  var cache = Object.create(null);\n  return (function cachedFn (str) {\n    var hit = cache[str];\n    return hit || (cache[str] = fn(str))\n  })\n}\n\n/**\n * Camelize a hyphen-delimited string.\n */\nvar camelizeRE = /-(\\w)/g;\nvar camelize = cached(function (str) {\n  return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })\n});\n\n/**\n * Capitalize a string.\n */\nvar capitalize = cached(function (str) {\n  return str.charAt(0).toUpperCase() + str.slice(1)\n});\n\n/**\n * Hyphenate a camelCase string.\n */\nvar hyphenateRE = /\\B([A-Z])/g;\nvar hyphenate = cached(function (str) {\n  return str.replace(hyphenateRE, '-$1').toLowerCase()\n});\n\n/**\n * Simple bind, faster than native\n */\nfunction bind (fn, ctx) {\n  function boundFn (a) {\n    var l = arguments.length;\n    return l\n      ? l > 1\n        ? fn.apply(ctx, arguments)\n        : fn.call(ctx, a)\n      : fn.call(ctx)\n  }\n  // record original fn length\n  boundFn._length = fn.length;\n  return boundFn\n}\n\n/**\n * Convert an Array-like object to a real Array.\n */\nfunction toArray (list, start) {\n  start = start || 0;\n  var i = list.length - start;\n  var ret = new Array(i);\n  while (i--) {\n    ret[i] = list[i + start];\n  }\n  return ret\n}\n\n/**\n * Mix properties into target object.\n */\nfunction extend (to, _from) {\n  for (var key in _from) {\n    to[key] = _from[key];\n  }\n  return to\n}\n\n/**\n * Merge an Array of Objects into a single Object.\n */\nfunction toObject (arr) {\n  var res = {};\n  for (var i = 0; i < arr.length; i++) {\n    if (arr[i]) {\n      extend(res, arr[i]);\n    }\n  }\n  return res\n}\n\n/**\n * Perform no operation.\n * Stubbing args to make Flow happy without leaving useless transpiled code\n * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/)\n */\nfunction noop (a, b, c) {}\n\n/**\n * Always return false.\n */\nvar no = function (a, b, c) { return false; };\n\n/**\n * Return same value\n */\nvar identity = function (_) { return _; };\n\n/**\n * Generate a static keys string from compiler modules.\n */\nfunction genStaticKeys (modules) {\n  return modules.reduce(function (keys, m) {\n    return keys.concat(m.staticKeys || [])\n  }, []).join(',')\n}\n\n/**\n * Check if two values are loosely equal - that is,\n * if they are plain objects, do they have the same shape?\n */\nfunction looseEqual (a, b) {\n  if (a === b) { return true }\n  var isObjectA = isObject(a);\n  var isObjectB = isObject(b);\n  if (isObjectA && isObjectB) {\n    try {\n      var isArrayA = Array.isArray(a);\n      var isArrayB = Array.isArray(b);\n      if (isArrayA && isArrayB) {\n        return a.length === b.length && a.every(function (e, i) {\n          return looseEqual(e, b[i])\n        })\n      } else if (!isArrayA && !isArrayB) {\n        var keysA = Object.keys(a);\n        var keysB = Object.keys(b);\n        return keysA.length === keysB.length && keysA.every(function (key) {\n          return looseEqual(a[key], b[key])\n        })\n      } else {\n        /* istanbul ignore next */\n        return false\n      }\n    } catch (e) {\n      /* istanbul ignore next */\n      return false\n    }\n  } else if (!isObjectA && !isObjectB) {\n    return String(a) === String(b)\n  } else {\n    return false\n  }\n}\n\nfunction looseIndexOf (arr, val) {\n  for (var i = 0; i < arr.length; i++) {\n    if (looseEqual(arr[i], val)) { return i }\n  }\n  return -1\n}\n\n/**\n * Ensure a function is called only once.\n */\nfunction once (fn) {\n  var called = false;\n  return function () {\n    if (!called) {\n      called = true;\n      fn.apply(this, arguments);\n    }\n  }\n}\n\nvar SSR_ATTR = 'data-server-rendered';\n\nvar ASSET_TYPES = [\n  'component',\n  'directive',\n  'filter'\n];\n\nvar LIFECYCLE_HOOKS = [\n  'beforeCreate',\n  'created',\n  'beforeMount',\n  'mounted',\n  'beforeUpdate',\n  'updated',\n  'beforeDestroy',\n  'destroyed',\n  'activated',\n  'deactivated'\n];\n\n/*  */\n\nvar config = ({\n  /**\n   * Option merge strategies (used in core/util/options)\n   */\n  optionMergeStrategies: Object.create(null),\n\n  /**\n   * Whether to suppress warnings.\n   */\n  silent: false,\n\n  /**\n   * Show production mode tip message on boot?\n   */\n  productionTip: \"development\" !== 'production',\n\n  /**\n   * Whether to enable devtools\n   */\n  devtools: \"development\" !== 'production',\n\n  /**\n   * Whether to record perf\n   */\n  performance: false,\n\n  /**\n   * Error handler for watcher errors\n   */\n  errorHandler: null,\n\n  /**\n   * Warn handler for watcher warns\n   */\n  warnHandler: null,\n\n  /**\n   * Ignore certain custom elements\n   */\n  ignoredElements: [],\n\n  /**\n   * Custom user key aliases for v-on\n   */\n  keyCodes: Object.create(null),\n\n  /**\n   * Check if a tag is reserved so that it cannot be registered as a\n   * component. This is platform-dependent and may be overwritten.\n   */\n  isReservedTag: no,\n\n  /**\n   * Check if an attribute is reserved so that it cannot be used as a component\n   * prop. This is platform-dependent and may be overwritten.\n   */\n  isReservedAttr: no,\n\n  /**\n   * Check if a tag is an unknown element.\n   * Platform-dependent.\n   */\n  isUnknownElement: no,\n\n  /**\n   * Get the namespace of an element\n   */\n  getTagNamespace: noop,\n\n  /**\n   * Parse the real tag name for the specific platform.\n   */\n  parsePlatformTagName: identity,\n\n  /**\n   * Check if an attribute must be bound using property, e.g. value\n   * Platform-dependent.\n   */\n  mustUseProp: no,\n\n  /**\n   * Exposed for legacy reasons\n   */\n  _lifecycleHooks: LIFECYCLE_HOOKS\n});\n\n/*  */\n\nvar emptyObject = Object.freeze({});\n\n/**\n * Check if a string starts with $ or _\n */\nfunction isReserved (str) {\n  var c = (str + '').charCodeAt(0);\n  return c === 0x24 || c === 0x5F\n}\n\n/**\n * Define a property.\n */\nfunction def (obj, key, val, enumerable) {\n  Object.defineProperty(obj, key, {\n    value: val,\n    enumerable: !!enumerable,\n    writable: true,\n    configurable: true\n  });\n}\n\n/**\n * Parse simple path.\n */\nvar bailRE = /[^\\w.$]/;\nfunction parsePath (path) {\n  if (bailRE.test(path)) {\n    return\n  }\n  var segments = path.split('.');\n  return function (obj) {\n    for (var i = 0; i < segments.length; i++) {\n      if (!obj) { return }\n      obj = obj[segments[i]];\n    }\n    return obj\n  }\n}\n\n/*  */\n\nvar warn = noop;\nvar tip = noop;\nvar formatComponentName = (null); // work around flow check\n\n{\n  var hasConsole = typeof console !== 'undefined';\n  var classifyRE = /(?:^|[-_])(\\w)/g;\n  var classify = function (str) { return str\n    .replace(classifyRE, function (c) { return c.toUpperCase(); })\n    .replace(/[-_]/g, ''); };\n\n  warn = function (msg, vm) {\n    var trace = vm ? generateComponentTrace(vm) : '';\n\n    if (config.warnHandler) {\n      config.warnHandler.call(null, msg, vm, trace);\n    } else if (hasConsole && (!config.silent)) {\n      console.error((\"[Vue warn]: \" + msg + trace));\n    }\n  };\n\n  tip = function (msg, vm) {\n    if (hasConsole && (!config.silent)) {\n      console.warn(\"[Vue tip]: \" + msg + (\n        vm ? generateComponentTrace(vm) : ''\n      ));\n    }\n  };\n\n  formatComponentName = function (vm, includeFile) {\n    if (vm.$root === vm) {\n      return '<Root>'\n    }\n    var name = typeof vm === 'string'\n      ? vm\n      : typeof vm === 'function' && vm.options\n        ? vm.options.name\n        : vm._isVue\n          ? vm.$options.name || vm.$options._componentTag\n          : vm.name;\n\n    var file = vm._isVue && vm.$options.__file;\n    if (!name && file) {\n      var match = file.match(/([^/\\\\]+)\\.vue$/);\n      name = match && match[1];\n    }\n\n    return (\n      (name ? (\"<\" + (classify(name)) + \">\") : \"<Anonymous>\") +\n      (file && includeFile !== false ? (\" at \" + file) : '')\n    )\n  };\n\n  var repeat = function (str, n) {\n    var res = '';\n    while (n) {\n      if (n % 2 === 1) { res += str; }\n      if (n > 1) { str += str; }\n      n >>= 1;\n    }\n    return res\n  };\n\n  var generateComponentTrace = function (vm) {\n    if (vm._isVue && vm.$parent) {\n      var tree = [];\n      var currentRecursiveSequence = 0;\n      while (vm) {\n        if (tree.length > 0) {\n          var last = tree[tree.length - 1];\n          if (last.constructor === vm.constructor) {\n            currentRecursiveSequence++;\n            vm = vm.$parent;\n            continue\n          } else if (currentRecursiveSequence > 0) {\n            tree[tree.length - 1] = [last, currentRecursiveSequence];\n            currentRecursiveSequence = 0;\n          }\n        }\n        tree.push(vm);\n        vm = vm.$parent;\n      }\n      return '\\n\\nfound in\\n\\n' + tree\n        .map(function (vm, i) { return (\"\" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)\n            ? ((formatComponentName(vm[0])) + \"... (\" + (vm[1]) + \" recursive calls)\")\n            : formatComponentName(vm))); })\n        .join('\\n')\n    } else {\n      return (\"\\n\\n(found in \" + (formatComponentName(vm)) + \")\")\n    }\n  };\n}\n\n/*  */\n\nfunction handleError (err, vm, info) {\n  if (config.errorHandler) {\n    config.errorHandler.call(null, err, vm, info);\n  } else {\n    {\n      warn((\"Error in \" + info + \": \\\"\" + (err.toString()) + \"\\\"\"), vm);\n    }\n    /* istanbul ignore else */\n    if (inBrowser && typeof console !== 'undefined') {\n      console.error(err);\n    } else {\n      throw err\n    }\n  }\n}\n\n/*  */\n/* globals MutationObserver */\n\n// can we use __proto__?\nvar hasProto = '__proto__' in {};\n\n// Browser environment sniffing\nvar inBrowser = typeof window !== 'undefined';\nvar UA = inBrowser && window.navigator.userAgent.toLowerCase();\nvar isIE = UA && /msie|trident/.test(UA);\nvar isIE9 = UA && UA.indexOf('msie 9.0') > 0;\nvar isEdge = UA && UA.indexOf('edge/') > 0;\nvar isAndroid = UA && UA.indexOf('android') > 0;\nvar isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\nvar isChrome = UA && /chrome\\/\\d+/.test(UA) && !isEdge;\n\n// Firefox has a \"watch\" function on Object.prototype...\nvar nativeWatch = ({}).watch;\n\nvar supportsPassive = false;\nif (inBrowser) {\n  try {\n    var opts = {};\n    Object.defineProperty(opts, 'passive', ({\n      get: function get () {\n        /* istanbul ignore next */\n        supportsPassive = true;\n      }\n    })); // https://github.com/facebook/flow/issues/285\n    window.addEventListener('test-passive', null, opts);\n  } catch (e) {}\n}\n\n// this needs to be lazy-evaled because vue may be required before\n// vue-server-renderer can set VUE_ENV\nvar _isServer;\nvar isServerRendering = function () {\n  if (_isServer === undefined) {\n    /* istanbul ignore if */\n    if (!inBrowser && typeof global !== 'undefined') {\n      // detect presence of vue-server-renderer and avoid\n      // Webpack shimming the process\n      _isServer = global['process'].env.VUE_ENV === 'server';\n    } else {\n      _isServer = false;\n    }\n  }\n  return _isServer\n};\n\n// detect devtools\nvar devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;\n\n/* istanbul ignore next */\nfunction isNative (Ctor) {\n  return typeof Ctor === 'function' && /native code/.test(Ctor.toString())\n}\n\nvar hasSymbol =\n  typeof Symbol !== 'undefined' && isNative(Symbol) &&\n  typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);\n\n/**\n * Defer a task to execute it asynchronously.\n */\nvar nextTick = (function () {\n  var callbacks = [];\n  var pending = false;\n  var timerFunc;\n\n  function nextTickHandler () {\n    pending = false;\n    var copies = callbacks.slice(0);\n    callbacks.length = 0;\n    for (var i = 0; i < copies.length; i++) {\n      copies[i]();\n    }\n  }\n\n  // the nextTick behavior leverages the microtask queue, which can be accessed\n  // via either native Promise.then or MutationObserver.\n  // MutationObserver has wider support, however it is seriously bugged in\n  // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It\n  // completely stops working after triggering a few times... so, if native\n  // Promise is available, we will use it:\n  /* istanbul ignore if */\n  if (typeof Promise !== 'undefined' && isNative(Promise)) {\n    var p = Promise.resolve();\n    var logError = function (err) { console.error(err); };\n    timerFunc = function () {\n      p.then(nextTickHandler).catch(logError);\n      // in problematic UIWebViews, Promise.then doesn't completely break, but\n      // it can get stuck in a weird state where callbacks are pushed into the\n      // microtask queue but the queue isn't being flushed, until the browser\n      // needs to do some other work, e.g. handle a timer. Therefore we can\n      // \"force\" the microtask queue to be flushed by adding an empty timer.\n      if (isIOS) { setTimeout(noop); }\n    };\n  } else if (!isIE && typeof MutationObserver !== 'undefined' && (\n    isNative(MutationObserver) ||\n    // PhantomJS and iOS 7.x\n    MutationObserver.toString() === '[object MutationObserverConstructor]'\n  )) {\n    // use MutationObserver where native Promise is not available,\n    // e.g. PhantomJS, iOS7, Android 4.4\n    var counter = 1;\n    var observer = new MutationObserver(nextTickHandler);\n    var textNode = document.createTextNode(String(counter));\n    observer.observe(textNode, {\n      characterData: true\n    });\n    timerFunc = function () {\n      counter = (counter + 1) % 2;\n      textNode.data = String(counter);\n    };\n  } else {\n    // fallback to setTimeout\n    /* istanbul ignore next */\n    timerFunc = function () {\n      setTimeout(nextTickHandler, 0);\n    };\n  }\n\n  return function queueNextTick (cb, ctx) {\n    var _resolve;\n    callbacks.push(function () {\n      if (cb) {\n        try {\n          cb.call(ctx);\n        } catch (e) {\n          handleError(e, ctx, 'nextTick');\n        }\n      } else if (_resolve) {\n        _resolve(ctx);\n      }\n    });\n    if (!pending) {\n      pending = true;\n      timerFunc();\n    }\n    if (!cb && typeof Promise !== 'undefined') {\n      return new Promise(function (resolve, reject) {\n        _resolve = resolve;\n      })\n    }\n  }\n})();\n\nvar _Set;\n/* istanbul ignore if */\nif (typeof Set !== 'undefined' && isNative(Set)) {\n  // use native Set when available.\n  _Set = Set;\n} else {\n  // a non-standard Set polyfill that only works with primitive keys.\n  _Set = (function () {\n    function Set () {\n      this.set = Object.create(null);\n    }\n    Set.prototype.has = function has (key) {\n      return this.set[key] === true\n    };\n    Set.prototype.add = function add (key) {\n      this.set[key] = true;\n    };\n    Set.prototype.clear = function clear () {\n      this.set = Object.create(null);\n    };\n\n    return Set;\n  }());\n}\n\n/*  */\n\n\nvar uid = 0;\n\n/**\n * A dep is an observable that can have multiple\n * directives subscribing to it.\n */\nvar Dep = function Dep () {\n  this.id = uid++;\n  this.subs = [];\n};\n\nDep.prototype.addSub = function addSub (sub) {\n  this.subs.push(sub);\n};\n\nDep.prototype.removeSub = function removeSub (sub) {\n  remove(this.subs, sub);\n};\n\nDep.prototype.depend = function depend () {\n  if (Dep.target) {\n    Dep.target.addDep(this);\n  }\n};\n\nDep.prototype.notify = function notify () {\n  // stabilize the subscriber list first\n  var subs = this.subs.slice();\n  for (var i = 0, l = subs.length; i < l; i++) {\n    subs[i].update();\n  }\n};\n\n// the current target watcher being evaluated.\n// this is globally unique because there could be only one\n// watcher being evaluated at any time.\nDep.target = null;\nvar targetStack = [];\n\nfunction pushTarget (_target) {\n  if (Dep.target) { targetStack.push(Dep.target); }\n  Dep.target = _target;\n}\n\nfunction popTarget () {\n  Dep.target = targetStack.pop();\n}\n\n/*\n * not type checking this file because flow doesn't play well with\n * dynamically accessing methods on Array prototype\n */\n\nvar arrayProto = Array.prototype;\nvar arrayMethods = Object.create(arrayProto);[\n  'push',\n  'pop',\n  'shift',\n  'unshift',\n  'splice',\n  'sort',\n  'reverse'\n]\n.forEach(function (method) {\n  // cache original method\n  var original = arrayProto[method];\n  def(arrayMethods, method, function mutator () {\n    var args = [], len = arguments.length;\n    while ( len-- ) args[ len ] = arguments[ len ];\n\n    var result = original.apply(this, args);\n    var ob = this.__ob__;\n    var inserted;\n    switch (method) {\n      case 'push':\n      case 'unshift':\n        inserted = args;\n        break\n      case 'splice':\n        inserted = args.slice(2);\n        break\n    }\n    if (inserted) { ob.observeArray(inserted); }\n    // notify change\n    ob.dep.notify();\n    return result\n  });\n});\n\n/*  */\n\nvar arrayKeys = Object.getOwnPropertyNames(arrayMethods);\n\n/**\n * By default, when a reactive property is set, the new value is\n * also converted to become reactive. However when passing down props,\n * we don't want to force conversion because the value may be a nested value\n * under a frozen data structure. Converting it would defeat the optimization.\n */\nvar observerState = {\n  shouldConvert: true\n};\n\n/**\n * Observer class that are attached to each observed\n * object. Once attached, the observer converts target\n * object's property keys into getter/setters that\n * collect dependencies and dispatches updates.\n */\nvar Observer = function Observer (value) {\n  this.value = value;\n  this.dep = new Dep();\n  this.vmCount = 0;\n  def(value, '__ob__', this);\n  if (Array.isArray(value)) {\n    var augment = hasProto\n      ? protoAugment\n      : copyAugment;\n    augment(value, arrayMethods, arrayKeys);\n    this.observeArray(value);\n  } else {\n    this.walk(value);\n  }\n};\n\n/**\n * Walk through each property and convert them into\n * getter/setters. This method should only be called when\n * value type is Object.\n */\nObserver.prototype.walk = function walk (obj) {\n  var keys = Object.keys(obj);\n  for (var i = 0; i < keys.length; i++) {\n    defineReactive$$1(obj, keys[i], obj[keys[i]]);\n  }\n};\n\n/**\n * Observe a list of Array items.\n */\nObserver.prototype.observeArray = function observeArray (items) {\n  for (var i = 0, l = items.length; i < l; i++) {\n    observe(items[i]);\n  }\n};\n\n// helpers\n\n/**\n * Augment an target Object or Array by intercepting\n * the prototype chain using __proto__\n */\nfunction protoAugment (target, src, keys) {\n  /* eslint-disable no-proto */\n  target.__proto__ = src;\n  /* eslint-enable no-proto */\n}\n\n/**\n * Augment an target Object or Array by defining\n * hidden properties.\n */\n/* istanbul ignore next */\nfunction copyAugment (target, src, keys) {\n  for (var i = 0, l = keys.length; i < l; i++) {\n    var key = keys[i];\n    def(target, key, src[key]);\n  }\n}\n\n/**\n * Attempt to create an observer instance for a value,\n * returns the new observer if successfully observed,\n * or the existing observer if the value already has one.\n */\nfunction observe (value, asRootData) {\n  if (!isObject(value)) {\n    return\n  }\n  var ob;\n  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\n    ob = value.__ob__;\n  } else if (\n    observerState.shouldConvert &&\n    !isServerRendering() &&\n    (Array.isArray(value) || isPlainObject(value)) &&\n    Object.isExtensible(value) &&\n    !value._isVue\n  ) {\n    ob = new Observer(value);\n  }\n  if (asRootData && ob) {\n    ob.vmCount++;\n  }\n  return ob\n}\n\n/**\n * Define a reactive property on an Object.\n */\nfunction defineReactive$$1 (\n  obj,\n  key,\n  val,\n  customSetter,\n  shallow\n) {\n  var dep = new Dep();\n\n  var property = Object.getOwnPropertyDescriptor(obj, key);\n  if (property && property.configurable === false) {\n    return\n  }\n\n  // cater for pre-defined getter/setters\n  var getter = property && property.get;\n  var setter = property && property.set;\n\n  var childOb = !shallow && observe(val);\n  Object.defineProperty(obj, key, {\n    enumerable: true,\n    configurable: true,\n    get: function reactiveGetter () {\n      var value = getter ? getter.call(obj) : val;\n      if (Dep.target) {\n        dep.depend();\n        if (childOb) {\n          childOb.dep.depend();\n          if (Array.isArray(value)) {\n            dependArray(value);\n          }\n        }\n      }\n      return value\n    },\n    set: function reactiveSetter (newVal) {\n      var value = getter ? getter.call(obj) : val;\n      /* eslint-disable no-self-compare */\n      if (newVal === value || (newVal !== newVal && value !== value)) {\n        return\n      }\n      /* eslint-enable no-self-compare */\n      if (\"development\" !== 'production' && customSetter) {\n        customSetter();\n      }\n      if (setter) {\n        setter.call(obj, newVal);\n      } else {\n        val = newVal;\n      }\n      childOb = !shallow && observe(newVal);\n      dep.notify();\n    }\n  });\n}\n\n/**\n * Set a property on an object. Adds the new property and\n * triggers change notification if the property doesn't\n * already exist.\n */\nfunction set (target, key, val) {\n  if (Array.isArray(target) && isValidArrayIndex(key)) {\n    target.length = Math.max(target.length, key);\n    target.splice(key, 1, val);\n    return val\n  }\n  if (hasOwn(target, key)) {\n    target[key] = val;\n    return val\n  }\n  var ob = (target).__ob__;\n  if (target._isVue || (ob && ob.vmCount)) {\n    \"development\" !== 'production' && warn(\n      'Avoid adding reactive properties to a Vue instance or its root $data ' +\n      'at runtime - declare it upfront in the data option.'\n    );\n    return val\n  }\n  if (!ob) {\n    target[key] = val;\n    return val\n  }\n  defineReactive$$1(ob.value, key, val);\n  ob.dep.notify();\n  return val\n}\n\n/**\n * Delete a property and trigger change if necessary.\n */\nfunction del (target, key) {\n  if (Array.isArray(target) && isValidArrayIndex(key)) {\n    target.splice(key, 1);\n    return\n  }\n  var ob = (target).__ob__;\n  if (target._isVue || (ob && ob.vmCount)) {\n    \"development\" !== 'production' && warn(\n      'Avoid deleting properties on a Vue instance or its root $data ' +\n      '- just set it to null.'\n    );\n    return\n  }\n  if (!hasOwn(target, key)) {\n    return\n  }\n  delete target[key];\n  if (!ob) {\n    return\n  }\n  ob.dep.notify();\n}\n\n/**\n * Collect dependencies on array elements when the array is touched, since\n * we cannot intercept array element access like property getters.\n */\nfunction dependArray (value) {\n  for (var e = (void 0), i = 0, l = value.length; i < l; i++) {\n    e = value[i];\n    e && e.__ob__ && e.__ob__.dep.depend();\n    if (Array.isArray(e)) {\n      dependArray(e);\n    }\n  }\n}\n\n/*  */\n\n/**\n * Option overwriting strategies are functions that handle\n * how to merge a parent option value and a child option\n * value into the final value.\n */\nvar strats = config.optionMergeStrategies;\n\n/**\n * Options with restrictions\n */\n{\n  strats.el = strats.propsData = function (parent, child, vm, key) {\n    if (!vm) {\n      warn(\n        \"option \\\"\" + key + \"\\\" can only be used during instance \" +\n        'creation with the `new` keyword.'\n      );\n    }\n    return defaultStrat(parent, child)\n  };\n}\n\n/**\n * Helper that recursively merges two data objects together.\n */\nfunction mergeData (to, from) {\n  if (!from) { return to }\n  var key, toVal, fromVal;\n  var keys = Object.keys(from);\n  for (var i = 0; i < keys.length; i++) {\n    key = keys[i];\n    toVal = to[key];\n    fromVal = from[key];\n    if (!hasOwn(to, key)) {\n      set(to, key, fromVal);\n    } else if (isPlainObject(toVal) && isPlainObject(fromVal)) {\n      mergeData(toVal, fromVal);\n    }\n  }\n  return to\n}\n\n/**\n * Data\n */\nfunction mergeDataOrFn (\n  parentVal,\n  childVal,\n  vm\n) {\n  if (!vm) {\n    // in a Vue.extend merge, both should be functions\n    if (!childVal) {\n      return parentVal\n    }\n    if (!parentVal) {\n      return childVal\n    }\n    // when parentVal & childVal are both present,\n    // we need to return a function that returns the\n    // merged result of both functions... no need to\n    // check if parentVal is a function here because\n    // it has to be a function to pass previous merges.\n    return function mergedDataFn () {\n      return mergeData(\n        typeof childVal === 'function' ? childVal.call(this) : childVal,\n        typeof parentVal === 'function' ? parentVal.call(this) : parentVal\n      )\n    }\n  } else if (parentVal || childVal) {\n    return function mergedInstanceDataFn () {\n      // instance merge\n      var instanceData = typeof childVal === 'function'\n        ? childVal.call(vm)\n        : childVal;\n      var defaultData = typeof parentVal === 'function'\n        ? parentVal.call(vm)\n        : parentVal;\n      if (instanceData) {\n        return mergeData(instanceData, defaultData)\n      } else {\n        return defaultData\n      }\n    }\n  }\n}\n\nstrats.data = function (\n  parentVal,\n  childVal,\n  vm\n) {\n  if (!vm) {\n    if (childVal && typeof childVal !== 'function') {\n      \"development\" !== 'production' && warn(\n        'The \"data\" option should be a function ' +\n        'that returns a per-instance value in component ' +\n        'definitions.',\n        vm\n      );\n\n      return parentVal\n    }\n    return mergeDataOrFn.call(this, parentVal, childVal)\n  }\n\n  return mergeDataOrFn(parentVal, childVal, vm)\n};\n\n/**\n * Hooks and props are merged as arrays.\n */\nfunction mergeHook (\n  parentVal,\n  childVal\n) {\n  return childVal\n    ? parentVal\n      ? parentVal.concat(childVal)\n      : Array.isArray(childVal)\n        ? childVal\n        : [childVal]\n    : parentVal\n}\n\nLIFECYCLE_HOOKS.forEach(function (hook) {\n  strats[hook] = mergeHook;\n});\n\n/**\n * Assets\n *\n * When a vm is present (instance creation), we need to do\n * a three-way merge between constructor options, instance\n * options and parent options.\n */\nfunction mergeAssets (parentVal, childVal) {\n  var res = Object.create(parentVal || null);\n  return childVal\n    ? extend(res, childVal)\n    : res\n}\n\nASSET_TYPES.forEach(function (type) {\n  strats[type + 's'] = mergeAssets;\n});\n\n/**\n * Watchers.\n *\n * Watchers hashes should not overwrite one\n * another, so we merge them as arrays.\n */\nstrats.watch = function (parentVal, childVal) {\n  // work around Firefox's Object.prototype.watch...\n  if (parentVal === nativeWatch) { parentVal = undefined; }\n  if (childVal === nativeWatch) { childVal = undefined; }\n  /* istanbul ignore if */\n  if (!childVal) { return Object.create(parentVal || null) }\n  if (!parentVal) { return childVal }\n  var ret = {};\n  extend(ret, parentVal);\n  for (var key in childVal) {\n    var parent = ret[key];\n    var child = childVal[key];\n    if (parent && !Array.isArray(parent)) {\n      parent = [parent];\n    }\n    ret[key] = parent\n      ? parent.concat(child)\n      : Array.isArray(child) ? child : [child];\n  }\n  return ret\n};\n\n/**\n * Other object hashes.\n */\nstrats.props =\nstrats.methods =\nstrats.inject =\nstrats.computed = function (parentVal, childVal) {\n  if (!parentVal) { return childVal }\n  var ret = Object.create(null);\n  extend(ret, parentVal);\n  if (childVal) { extend(ret, childVal); }\n  return ret\n};\nstrats.provide = mergeDataOrFn;\n\n/**\n * Default strategy.\n */\nvar defaultStrat = function (parentVal, childVal) {\n  return childVal === undefined\n    ? parentVal\n    : childVal\n};\n\n/**\n * Validate component names\n */\nfunction checkComponents (options) {\n  for (var key in options.components) {\n    var lower = key.toLowerCase();\n    if (isBuiltInTag(lower) || config.isReservedTag(lower)) {\n      warn(\n        'Do not use built-in or reserved HTML elements as component ' +\n        'id: ' + key\n      );\n    }\n  }\n}\n\n/**\n * Ensure all props option syntax are normalized into the\n * Object-based format.\n */\nfunction normalizeProps (options) {\n  var props = options.props;\n  if (!props) { return }\n  var res = {};\n  var i, val, name;\n  if (Array.isArray(props)) {\n    i = props.length;\n    while (i--) {\n      val = props[i];\n      if (typeof val === 'string') {\n        name = camelize(val);\n        res[name] = { type: null };\n      } else {\n        warn('props must be strings when using array syntax.');\n      }\n    }\n  } else if (isPlainObject(props)) {\n    for (var key in props) {\n      val = props[key];\n      name = camelize(key);\n      res[name] = isPlainObject(val)\n        ? val\n        : { type: val };\n    }\n  }\n  options.props = res;\n}\n\n/**\n * Normalize all injections into Object-based format\n */\nfunction normalizeInject (options) {\n  var inject = options.inject;\n  if (Array.isArray(inject)) {\n    var normalized = options.inject = {};\n    for (var i = 0; i < inject.length; i++) {\n      normalized[inject[i]] = inject[i];\n    }\n  }\n}\n\n/**\n * Normalize raw function directives into object format.\n */\nfunction normalizeDirectives (options) {\n  var dirs = options.directives;\n  if (dirs) {\n    for (var key in dirs) {\n      var def = dirs[key];\n      if (typeof def === 'function') {\n        dirs[key] = { bind: def, update: def };\n      }\n    }\n  }\n}\n\n/**\n * Merge two option objects into a new one.\n * Core utility used in both instantiation and inheritance.\n */\nfunction mergeOptions (\n  parent,\n  child,\n  vm\n) {\n  {\n    checkComponents(child);\n  }\n\n  if (typeof child === 'function') {\n    child = child.options;\n  }\n\n  normalizeProps(child);\n  normalizeInject(child);\n  normalizeDirectives(child);\n  var extendsFrom = child.extends;\n  if (extendsFrom) {\n    parent = mergeOptions(parent, extendsFrom, vm);\n  }\n  if (child.mixins) {\n    for (var i = 0, l = child.mixins.length; i < l; i++) {\n      parent = mergeOptions(parent, child.mixins[i], vm);\n    }\n  }\n  var options = {};\n  var key;\n  for (key in parent) {\n    mergeField(key);\n  }\n  for (key in child) {\n    if (!hasOwn(parent, key)) {\n      mergeField(key);\n    }\n  }\n  function mergeField (key) {\n    var strat = strats[key] || defaultStrat;\n    options[key] = strat(parent[key], child[key], vm, key);\n  }\n  return options\n}\n\n/**\n * Resolve an asset.\n * This function is used because child instances need access\n * to assets defined in its ancestor chain.\n */\nfunction resolveAsset (\n  options,\n  type,\n  id,\n  warnMissing\n) {\n  /* istanbul ignore if */\n  if (typeof id !== 'string') {\n    return\n  }\n  var assets = options[type];\n  // check local registration variations first\n  if (hasOwn(assets, id)) { return assets[id] }\n  var camelizedId = camelize(id);\n  if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }\n  var PascalCaseId = capitalize(camelizedId);\n  if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }\n  // fallback to prototype chain\n  var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];\n  if (\"development\" !== 'production' && warnMissing && !res) {\n    warn(\n      'Failed to resolve ' + type.slice(0, -1) + ': ' + id,\n      options\n    );\n  }\n  return res\n}\n\n/*  */\n\nfunction validateProp (\n  key,\n  propOptions,\n  propsData,\n  vm\n) {\n  var prop = propOptions[key];\n  var absent = !hasOwn(propsData, key);\n  var value = propsData[key];\n  // handle boolean props\n  if (isType(Boolean, prop.type)) {\n    if (absent && !hasOwn(prop, 'default')) {\n      value = false;\n    } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {\n      value = true;\n    }\n  }\n  // check default value\n  if (value === undefined) {\n    value = getPropDefaultValue(vm, prop, key);\n    // since the default value is a fresh copy,\n    // make sure to observe it.\n    var prevShouldConvert = observerState.shouldConvert;\n    observerState.shouldConvert = true;\n    observe(value);\n    observerState.shouldConvert = prevShouldConvert;\n  }\n  {\n    assertProp(prop, key, value, vm, absent);\n  }\n  return value\n}\n\n/**\n * Get the default value of a prop.\n */\nfunction getPropDefaultValue (vm, prop, key) {\n  // no default, return undefined\n  if (!hasOwn(prop, 'default')) {\n    return undefined\n  }\n  var def = prop.default;\n  // warn against non-factory defaults for Object & Array\n  if (\"development\" !== 'production' && isObject(def)) {\n    warn(\n      'Invalid default value for prop \"' + key + '\": ' +\n      'Props with type Object/Array must use a factory function ' +\n      'to return the default value.',\n      vm\n    );\n  }\n  // the raw prop value was also undefined from previous render,\n  // return previous default value to avoid unnecessary watcher trigger\n  if (vm && vm.$options.propsData &&\n    vm.$options.propsData[key] === undefined &&\n    vm._props[key] !== undefined\n  ) {\n    return vm._props[key]\n  }\n  // call factory function for non-Function types\n  // a value is Function if its prototype is function even across different execution context\n  return typeof def === 'function' && getType(prop.type) !== 'Function'\n    ? def.call(vm)\n    : def\n}\n\n/**\n * Assert whether a prop is valid.\n */\nfunction assertProp (\n  prop,\n  name,\n  value,\n  vm,\n  absent\n) {\n  if (prop.required && absent) {\n    warn(\n      'Missing required prop: \"' + name + '\"',\n      vm\n    );\n    return\n  }\n  if (value == null && !prop.required) {\n    return\n  }\n  var type = prop.type;\n  var valid = !type || type === true;\n  var expectedTypes = [];\n  if (type) {\n    if (!Array.isArray(type)) {\n      type = [type];\n    }\n    for (var i = 0; i < type.length && !valid; i++) {\n      var assertedType = assertType(value, type[i]);\n      expectedTypes.push(assertedType.expectedType || '');\n      valid = assertedType.valid;\n    }\n  }\n  if (!valid) {\n    warn(\n      'Invalid prop: type check failed for prop \"' + name + '\".' +\n      ' Expected ' + expectedTypes.map(capitalize).join(', ') +\n      ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',\n      vm\n    );\n    return\n  }\n  var validator = prop.validator;\n  if (validator) {\n    if (!validator(value)) {\n      warn(\n        'Invalid prop: custom validator check failed for prop \"' + name + '\".',\n        vm\n      );\n    }\n  }\n}\n\nvar simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;\n\nfunction assertType (value, type) {\n  var valid;\n  var expectedType = getType(type);\n  if (simpleCheckRE.test(expectedType)) {\n    var t = typeof value;\n    valid = t === expectedType.toLowerCase();\n    // for primitive wrapper objects\n    if (!valid && t === 'object') {\n      valid = value instanceof type;\n    }\n  } else if (expectedType === 'Object') {\n    valid = isPlainObject(value);\n  } else if (expectedType === 'Array') {\n    valid = Array.isArray(value);\n  } else {\n    valid = value instanceof type;\n  }\n  return {\n    valid: valid,\n    expectedType: expectedType\n  }\n}\n\n/**\n * Use function string name to check built-in types,\n * because a simple equality check will fail when running\n * across different vms / iframes.\n */\nfunction getType (fn) {\n  var match = fn && fn.toString().match(/^\\s*function (\\w+)/);\n  return match ? match[1] : ''\n}\n\nfunction isType (type, fn) {\n  if (!Array.isArray(fn)) {\n    return getType(fn) === getType(type)\n  }\n  for (var i = 0, len = fn.length; i < len; i++) {\n    if (getType(fn[i]) === getType(type)) {\n      return true\n    }\n  }\n  /* istanbul ignore next */\n  return false\n}\n\n/*  */\n\nvar mark;\nvar measure;\n\n{\n  var perf = inBrowser && window.performance;\n  /* istanbul ignore if */\n  if (\n    perf &&\n    perf.mark &&\n    perf.measure &&\n    perf.clearMarks &&\n    perf.clearMeasures\n  ) {\n    mark = function (tag) { return perf.mark(tag); };\n    measure = function (name, startTag, endTag) {\n      perf.measure(name, startTag, endTag);\n      perf.clearMarks(startTag);\n      perf.clearMarks(endTag);\n      perf.clearMeasures(name);\n    };\n  }\n}\n\n/* not type checking this file because flow doesn't play well with Proxy */\n\nvar initProxy;\n\n{\n  var allowedGlobals = makeMap(\n    'Infinity,undefined,NaN,isFinite,isNaN,' +\n    'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n    'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +\n    'require' // for Webpack/Browserify\n  );\n\n  var warnNonPresent = function (target, key) {\n    warn(\n      \"Property or method \\\"\" + key + \"\\\" is not defined on the instance but \" +\n      \"referenced during render. Make sure to declare reactive data \" +\n      \"properties in the data option.\",\n      target\n    );\n  };\n\n  var hasProxy =\n    typeof Proxy !== 'undefined' &&\n    Proxy.toString().match(/native code/);\n\n  if (hasProxy) {\n    var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');\n    config.keyCodes = new Proxy(config.keyCodes, {\n      set: function set (target, key, value) {\n        if (isBuiltInModifier(key)) {\n          warn((\"Avoid overwriting built-in modifier in config.keyCodes: .\" + key));\n          return false\n        } else {\n          target[key] = value;\n          return true\n        }\n      }\n    });\n  }\n\n  var hasHandler = {\n    has: function has (target, key) {\n      var has = key in target;\n      var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';\n      if (!has && !isAllowed) {\n        warnNonPresent(target, key);\n      }\n      return has || !isAllowed\n    }\n  };\n\n  var getHandler = {\n    get: function get (target, key) {\n      if (typeof key === 'string' && !(key in target)) {\n        warnNonPresent(target, key);\n      }\n      return target[key]\n    }\n  };\n\n  initProxy = function initProxy (vm) {\n    if (hasProxy) {\n      // determine which proxy handler to use\n      var options = vm.$options;\n      var handlers = options.render && options.render._withStripped\n        ? getHandler\n        : hasHandler;\n      vm._renderProxy = new Proxy(vm, handlers);\n    } else {\n      vm._renderProxy = vm;\n    }\n  };\n}\n\n/*  */\n\nvar VNode = function VNode (\n  tag,\n  data,\n  children,\n  text,\n  elm,\n  context,\n  componentOptions,\n  asyncFactory\n) {\n  this.tag = tag;\n  this.data = data;\n  this.children = children;\n  this.text = text;\n  this.elm = elm;\n  this.ns = undefined;\n  this.context = context;\n  this.functionalContext = undefined;\n  this.key = data && data.key;\n  this.componentOptions = componentOptions;\n  this.componentInstance = undefined;\n  this.parent = undefined;\n  this.raw = false;\n  this.isStatic = false;\n  this.isRootInsert = true;\n  this.isComment = false;\n  this.isCloned = false;\n  this.isOnce = false;\n  this.asyncFactory = asyncFactory;\n  this.asyncMeta = undefined;\n  this.isAsyncPlaceholder = false;\n};\n\nvar prototypeAccessors = { child: {} };\n\n// DEPRECATED: alias for componentInstance for backwards compat.\n/* istanbul ignore next */\nprototypeAccessors.child.get = function () {\n  return this.componentInstance\n};\n\nObject.defineProperties( VNode.prototype, prototypeAccessors );\n\nvar createEmptyVNode = function (text) {\n  if ( text === void 0 ) text = '';\n\n  var node = new VNode();\n  node.text = text;\n  node.isComment = true;\n  return node\n};\n\nfunction createTextVNode (val) {\n  return new VNode(undefined, undefined, undefined, String(val))\n}\n\n// optimized shallow clone\n// used for static nodes and slot nodes because they may be reused across\n// multiple renders, cloning them avoids errors when DOM manipulations rely\n// on their elm reference.\nfunction cloneVNode (vnode, deep) {\n  var cloned = new VNode(\n    vnode.tag,\n    vnode.data,\n    vnode.children,\n    vnode.text,\n    vnode.elm,\n    vnode.context,\n    vnode.componentOptions,\n    vnode.asyncFactory\n  );\n  cloned.ns = vnode.ns;\n  cloned.isStatic = vnode.isStatic;\n  cloned.key = vnode.key;\n  cloned.isComment = vnode.isComment;\n  cloned.isCloned = true;\n  if (deep && vnode.children) {\n    cloned.children = cloneVNodes(vnode.children);\n  }\n  return cloned\n}\n\nfunction cloneVNodes (vnodes, deep) {\n  var len = vnodes.length;\n  var res = new Array(len);\n  for (var i = 0; i < len; i++) {\n    res[i] = cloneVNode(vnodes[i], deep);\n  }\n  return res\n}\n\n/*  */\n\nvar normalizeEvent = cached(function (name) {\n  var passive = name.charAt(0) === '&';\n  name = passive ? name.slice(1) : name;\n  var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first\n  name = once$$1 ? name.slice(1) : name;\n  var capture = name.charAt(0) === '!';\n  name = capture ? name.slice(1) : name;\n  var plain = !(passive || once$$1 || capture);\n  return {\n    name: name,\n    plain: plain,\n    once: once$$1,\n    capture: capture,\n    passive: passive\n  }\n});\n\nfunction createFnInvoker (fns) {\n  function invoker () {\n    var arguments$1 = arguments;\n\n    var fns = invoker.fns;\n    if (Array.isArray(fns)) {\n      var cloned = fns.slice();\n      for (var i = 0; i < cloned.length; i++) {\n        cloned[i].apply(null, arguments$1);\n      }\n    } else {\n      // return handler return value for single handlers\n      return fns.apply(null, arguments)\n    }\n  }\n  invoker.fns = fns;\n  return invoker\n}\n\n// #6552\nfunction prioritizePlainEvents (a, b) {\n  return a.plain ? -1 : b.plain ? 1 : 0\n}\n\nfunction updateListeners (\n  on,\n  oldOn,\n  add,\n  remove$$1,\n  vm\n) {\n  var name, cur, old, event;\n  var toAdd = [];\n  var hasModifier = false;\n  for (name in on) {\n    cur = on[name];\n    old = oldOn[name];\n    event = normalizeEvent(name);\n    if (!event.plain) { hasModifier = true; }\n    if (isUndef(cur)) {\n      \"development\" !== 'production' && warn(\n        \"Invalid handler for event \\\"\" + (event.name) + \"\\\": got \" + String(cur),\n        vm\n      );\n    } else if (isUndef(old)) {\n      if (isUndef(cur.fns)) {\n        cur = on[name] = createFnInvoker(cur);\n      }\n      event.handler = cur;\n      toAdd.push(event);\n    } else if (cur !== old) {\n      old.fns = cur;\n      on[name] = old;\n    }\n  }\n  if (toAdd.length) {\n    if (hasModifier) { toAdd.sort(prioritizePlainEvents); }\n    for (var i = 0; i < toAdd.length; i++) {\n      var event$1 = toAdd[i];\n      add(event$1.name, event$1.handler, event$1.once, event$1.capture, event$1.passive);\n    }\n  }\n  for (name in oldOn) {\n    if (isUndef(on[name])) {\n      event = normalizeEvent(name);\n      remove$$1(event.name, oldOn[name], event.capture);\n    }\n  }\n}\n\n/*  */\n\nfunction mergeVNodeHook (def, hookKey, hook) {\n  var invoker;\n  var oldHook = def[hookKey];\n\n  function wrappedHook () {\n    hook.apply(this, arguments);\n    // important: remove merged hook to ensure it's called only once\n    // and prevent memory leak\n    remove(invoker.fns, wrappedHook);\n  }\n\n  if (isUndef(oldHook)) {\n    // no existing hook\n    invoker = createFnInvoker([wrappedHook]);\n  } else {\n    /* istanbul ignore if */\n    if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {\n      // already a merged invoker\n      invoker = oldHook;\n      invoker.fns.push(wrappedHook);\n    } else {\n      // existing plain hook\n      invoker = createFnInvoker([oldHook, wrappedHook]);\n    }\n  }\n\n  invoker.merged = true;\n  def[hookKey] = invoker;\n}\n\n/*  */\n\nfunction extractPropsFromVNodeData (\n  data,\n  Ctor,\n  tag\n) {\n  // we are only extracting raw values here.\n  // validation and default values are handled in the child\n  // component itself.\n  var propOptions = Ctor.options.props;\n  if (isUndef(propOptions)) {\n    return\n  }\n  var res = {};\n  var attrs = data.attrs;\n  var props = data.props;\n  if (isDef(attrs) || isDef(props)) {\n    for (var key in propOptions) {\n      var altKey = hyphenate(key);\n      {\n        var keyInLowerCase = key.toLowerCase();\n        if (\n          key !== keyInLowerCase &&\n          attrs && hasOwn(attrs, keyInLowerCase)\n        ) {\n          tip(\n            \"Prop \\\"\" + keyInLowerCase + \"\\\" is passed to component \" +\n            (formatComponentName(tag || Ctor)) + \", but the declared prop name is\" +\n            \" \\\"\" + key + \"\\\". \" +\n            \"Note that HTML attributes are case-insensitive and camelCased \" +\n            \"props need to use their kebab-case equivalents when using in-DOM \" +\n            \"templates. You should probably use \\\"\" + altKey + \"\\\" instead of \\\"\" + key + \"\\\".\"\n          );\n        }\n      }\n      checkProp(res, props, key, altKey, true) ||\n      checkProp(res, attrs, key, altKey, false);\n    }\n  }\n  return res\n}\n\nfunction checkProp (\n  res,\n  hash,\n  key,\n  altKey,\n  preserve\n) {\n  if (isDef(hash)) {\n    if (hasOwn(hash, key)) {\n      res[key] = hash[key];\n      if (!preserve) {\n        delete hash[key];\n      }\n      return true\n    } else if (hasOwn(hash, altKey)) {\n      res[key] = hash[altKey];\n      if (!preserve) {\n        delete hash[altKey];\n      }\n      return true\n    }\n  }\n  return false\n}\n\n/*  */\n\n// The template compiler attempts to minimize the need for normalization by\n// statically analyzing the template at compile time.\n//\n// For plain HTML markup, normalization can be completely skipped because the\n// generated render function is guaranteed to return Array<VNode>. There are\n// two cases where extra normalization is needed:\n\n// 1. When the children contains components - because a functional component\n// may return an Array instead of a single root. In this case, just a simple\n// normalization is needed - if any child is an Array, we flatten the whole\n// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep\n// because functional components already normalize their own children.\nfunction simpleNormalizeChildren (children) {\n  for (var i = 0; i < children.length; i++) {\n    if (Array.isArray(children[i])) {\n      return Array.prototype.concat.apply([], children)\n    }\n  }\n  return children\n}\n\n// 2. When the children contains constructs that always generated nested Arrays,\n// e.g. <template>, <slot>, v-for, or when the children is provided by user\n// with hand-written render functions / JSX. In such cases a full normalization\n// is needed to cater to all possible types of children values.\nfunction normalizeChildren (children) {\n  return isPrimitive(children)\n    ? [createTextVNode(children)]\n    : Array.isArray(children)\n      ? normalizeArrayChildren(children)\n      : undefined\n}\n\nfunction isTextNode (node) {\n  return isDef(node) && isDef(node.text) && isFalse(node.isComment)\n}\n\nfunction normalizeArrayChildren (children, nestedIndex) {\n  var res = [];\n  var i, c, last;\n  for (i = 0; i < children.length; i++) {\n    c = children[i];\n    if (isUndef(c) || typeof c === 'boolean') { continue }\n    last = res[res.length - 1];\n    //  nested\n    if (Array.isArray(c)) {\n      res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + \"_\" + i)));\n    } else if (isPrimitive(c)) {\n      if (isTextNode(last)) {\n        // merge adjacent text nodes\n        // this is necessary for SSR hydration because text nodes are\n        // essentially merged when rendered to HTML strings\n        (last).text += String(c);\n      } else if (c !== '') {\n        // convert primitive to vnode\n        res.push(createTextVNode(c));\n      }\n    } else {\n      if (isTextNode(c) && isTextNode(last)) {\n        // merge adjacent text nodes\n        res[res.length - 1] = createTextVNode(last.text + c.text);\n      } else {\n        // default key for nested array children (likely generated by v-for)\n        if (isTrue(children._isVList) &&\n          isDef(c.tag) &&\n          isUndef(c.key) &&\n          isDef(nestedIndex)) {\n          c.key = \"__vlist\" + nestedIndex + \"_\" + i + \"__\";\n        }\n        res.push(c);\n      }\n    }\n  }\n  return res\n}\n\n/*  */\n\nfunction ensureCtor (comp, base) {\n  if (comp.__esModule && comp.default) {\n    comp = comp.default;\n  }\n  return isObject(comp)\n    ? base.extend(comp)\n    : comp\n}\n\nfunction createAsyncPlaceholder (\n  factory,\n  data,\n  context,\n  children,\n  tag\n) {\n  var node = createEmptyVNode();\n  node.asyncFactory = factory;\n  node.asyncMeta = { data: data, context: context, children: children, tag: tag };\n  return node\n}\n\nfunction resolveAsyncComponent (\n  factory,\n  baseCtor,\n  context\n) {\n  if (isTrue(factory.error) && isDef(factory.errorComp)) {\n    return factory.errorComp\n  }\n\n  if (isDef(factory.resolved)) {\n    return factory.resolved\n  }\n\n  if (isTrue(factory.loading) && isDef(factory.loadingComp)) {\n    return factory.loadingComp\n  }\n\n  if (isDef(factory.contexts)) {\n    // already pending\n    factory.contexts.push(context);\n  } else {\n    var contexts = factory.contexts = [context];\n    var sync = true;\n\n    var forceRender = function () {\n      for (var i = 0, l = contexts.length; i < l; i++) {\n        contexts[i].$forceUpdate();\n      }\n    };\n\n    var resolve = once(function (res) {\n      // cache resolved\n      factory.resolved = ensureCtor(res, baseCtor);\n      // invoke callbacks only if this is not a synchronous resolve\n      // (async resolves are shimmed as synchronous during SSR)\n      if (!sync) {\n        forceRender();\n      }\n    });\n\n    var reject = once(function (reason) {\n      \"development\" !== 'production' && warn(\n        \"Failed to resolve async component: \" + (String(factory)) +\n        (reason ? (\"\\nReason: \" + reason) : '')\n      );\n      if (isDef(factory.errorComp)) {\n        factory.error = true;\n        forceRender();\n      }\n    });\n\n    var res = factory(resolve, reject);\n\n    if (isObject(res)) {\n      if (typeof res.then === 'function') {\n        // () => Promise\n        if (isUndef(factory.resolved)) {\n          res.then(resolve, reject);\n        }\n      } else if (isDef(res.component) && typeof res.component.then === 'function') {\n        res.component.then(resolve, reject);\n\n        if (isDef(res.error)) {\n          factory.errorComp = ensureCtor(res.error, baseCtor);\n        }\n\n        if (isDef(res.loading)) {\n          factory.loadingComp = ensureCtor(res.loading, baseCtor);\n          if (res.delay === 0) {\n            factory.loading = true;\n          } else {\n            setTimeout(function () {\n              if (isUndef(factory.resolved) && isUndef(factory.error)) {\n                factory.loading = true;\n                forceRender();\n              }\n            }, res.delay || 200);\n          }\n        }\n\n        if (isDef(res.timeout)) {\n          setTimeout(function () {\n            if (isUndef(factory.resolved)) {\n              reject(\n                \"timeout (\" + (res.timeout) + \"ms)\"\n              );\n            }\n          }, res.timeout);\n        }\n      }\n    }\n\n    sync = false;\n    // return in case resolved synchronously\n    return factory.loading\n      ? factory.loadingComp\n      : factory.resolved\n  }\n}\n\n/*  */\n\nfunction isAsyncPlaceholder (node) {\n  return node.isComment && node.asyncFactory\n}\n\n/*  */\n\nfunction getFirstComponentChild (children) {\n  if (Array.isArray(children)) {\n    for (var i = 0; i < children.length; i++) {\n      var c = children[i];\n      if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {\n        return c\n      }\n    }\n  }\n}\n\n/*  */\n\n/*  */\n\nfunction initEvents (vm) {\n  vm._events = Object.create(null);\n  vm._hasHookEvent = false;\n  // init parent attached events\n  var listeners = vm.$options._parentListeners;\n  if (listeners) {\n    updateComponentListeners(vm, listeners);\n  }\n}\n\nvar target;\n\nfunction add (event, fn, once$$1) {\n  if (once$$1) {\n    target.$once(event, fn);\n  } else {\n    target.$on(event, fn);\n  }\n}\n\nfunction remove$1 (event, fn) {\n  target.$off(event, fn);\n}\n\nfunction updateComponentListeners (\n  vm,\n  listeners,\n  oldListeners\n) {\n  target = vm;\n  updateListeners(listeners, oldListeners || {}, add, remove$1, vm);\n}\n\nfunction eventsMixin (Vue) {\n  var hookRE = /^hook:/;\n  Vue.prototype.$on = function (event, fn) {\n    var this$1 = this;\n\n    var vm = this;\n    if (Array.isArray(event)) {\n      for (var i = 0, l = event.length; i < l; i++) {\n        this$1.$on(event[i], fn);\n      }\n    } else {\n      (vm._events[event] || (vm._events[event] = [])).push(fn);\n      // optimize hook:event cost by using a boolean flag marked at registration\n      // instead of a hash lookup\n      if (hookRE.test(event)) {\n        vm._hasHookEvent = true;\n      }\n    }\n    return vm\n  };\n\n  Vue.prototype.$once = function (event, fn) {\n    var vm = this;\n    function on () {\n      vm.$off(event, on);\n      fn.apply(vm, arguments);\n    }\n    on.fn = fn;\n    vm.$on(event, on);\n    return vm\n  };\n\n  Vue.prototype.$off = function (event, fn) {\n    var this$1 = this;\n\n    var vm = this;\n    // all\n    if (!arguments.length) {\n      vm._events = Object.create(null);\n      return vm\n    }\n    // array of events\n    if (Array.isArray(event)) {\n      for (var i = 0, l = event.length; i < l; i++) {\n        this$1.$off(event[i], fn);\n      }\n      return vm\n    }\n    // specific event\n    var cbs = vm._events[event];\n    if (!cbs) {\n      return vm\n    }\n    if (arguments.length === 1) {\n      vm._events[event] = null;\n      return vm\n    }\n    if (fn) {\n      // specific handler\n      var cb;\n      var i$1 = cbs.length;\n      while (i$1--) {\n        cb = cbs[i$1];\n        if (cb === fn || cb.fn === fn) {\n          cbs.splice(i$1, 1);\n          break\n        }\n      }\n    }\n    return vm\n  };\n\n  Vue.prototype.$emit = function (event) {\n    var vm = this;\n    {\n      var lowerCaseEvent = event.toLowerCase();\n      if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {\n        tip(\n          \"Event \\\"\" + lowerCaseEvent + \"\\\" is emitted in component \" +\n          (formatComponentName(vm)) + \" but the handler is registered for \\\"\" + event + \"\\\". \" +\n          \"Note that HTML attributes are case-insensitive and you cannot use \" +\n          \"v-on to listen to camelCase events when using in-DOM templates. \" +\n          \"You should probably use \\\"\" + (hyphenate(event)) + \"\\\" instead of \\\"\" + event + \"\\\".\"\n        );\n      }\n    }\n    var cbs = vm._events[event];\n    if (cbs) {\n      cbs = cbs.length > 1 ? toArray(cbs) : cbs;\n      var args = toArray(arguments, 1);\n      for (var i = 0, l = cbs.length; i < l; i++) {\n        try {\n          cbs[i].apply(vm, args);\n        } catch (e) {\n          handleError(e, vm, (\"event handler for \\\"\" + event + \"\\\"\"));\n        }\n      }\n    }\n    return vm\n  };\n}\n\n/*  */\n\n/**\n * Runtime helper for resolving raw children VNodes into a slot object.\n */\nfunction resolveSlots (\n  children,\n  context\n) {\n  var slots = {};\n  if (!children) {\n    return slots\n  }\n  var defaultSlot = [];\n  for (var i = 0, l = children.length; i < l; i++) {\n    var child = children[i];\n    var data = child.data;\n    // remove slot attribute if the node is resolved as a Vue slot node\n    if (data && data.attrs && data.attrs.slot) {\n      delete data.attrs.slot;\n    }\n    // named slots should only be respected if the vnode was rendered in the\n    // same context.\n    if ((child.context === context || child.functionalContext === context) &&\n      data && data.slot != null\n    ) {\n      var name = child.data.slot;\n      var slot = (slots[name] || (slots[name] = []));\n      if (child.tag === 'template') {\n        slot.push.apply(slot, child.children);\n      } else {\n        slot.push(child);\n      }\n    } else {\n      defaultSlot.push(child);\n    }\n  }\n  // ignore whitespace\n  if (!defaultSlot.every(isWhitespace)) {\n    slots.default = defaultSlot;\n  }\n  return slots\n}\n\nfunction isWhitespace (node) {\n  return node.isComment || node.text === ' '\n}\n\nfunction resolveScopedSlots (\n  fns, // see flow/vnode\n  res\n) {\n  res = res || {};\n  for (var i = 0; i < fns.length; i++) {\n    if (Array.isArray(fns[i])) {\n      resolveScopedSlots(fns[i], res);\n    } else {\n      res[fns[i].key] = fns[i].fn;\n    }\n  }\n  return res\n}\n\n/*  */\n\nvar activeInstance = null;\nvar isUpdatingChildComponent = false;\n\nfunction initLifecycle (vm) {\n  var options = vm.$options;\n\n  // locate first non-abstract parent\n  var parent = options.parent;\n  if (parent && !options.abstract) {\n    while (parent.$options.abstract && parent.$parent) {\n      parent = parent.$parent;\n    }\n    parent.$children.push(vm);\n  }\n\n  vm.$parent = parent;\n  vm.$root = parent ? parent.$root : vm;\n\n  vm.$children = [];\n  vm.$refs = {};\n\n  vm._watcher = null;\n  vm._inactive = null;\n  vm._directInactive = false;\n  vm._isMounted = false;\n  vm._isDestroyed = false;\n  vm._isBeingDestroyed = false;\n}\n\nfunction lifecycleMixin (Vue) {\n  Vue.prototype._update = function (vnode, hydrating) {\n    var vm = this;\n    if (vm._isMounted) {\n      callHook(vm, 'beforeUpdate');\n    }\n    var prevEl = vm.$el;\n    var prevVnode = vm._vnode;\n    var prevActiveInstance = activeInstance;\n    activeInstance = vm;\n    vm._vnode = vnode;\n    // Vue.prototype.__patch__ is injected in entry points\n    // based on the rendering backend used.\n    if (!prevVnode) {\n      // initial render\n      vm.$el = vm.__patch__(\n        vm.$el, vnode, hydrating, false /* removeOnly */,\n        vm.$options._parentElm,\n        vm.$options._refElm\n      );\n      // no need for the ref nodes after initial patch\n      // this prevents keeping a detached DOM tree in memory (#5851)\n      vm.$options._parentElm = vm.$options._refElm = null;\n    } else {\n      // updates\n      vm.$el = vm.__patch__(prevVnode, vnode);\n    }\n    activeInstance = prevActiveInstance;\n    // update __vue__ reference\n    if (prevEl) {\n      prevEl.__vue__ = null;\n    }\n    if (vm.$el) {\n      vm.$el.__vue__ = vm;\n    }\n    // if parent is an HOC, update its $el as well\n    if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {\n      vm.$parent.$el = vm.$el;\n    }\n    // updated hook is called by the scheduler to ensure that children are\n    // updated in a parent's updated hook.\n  };\n\n  Vue.prototype.$forceUpdate = function () {\n    var vm = this;\n    if (vm._watcher) {\n      vm._watcher.update();\n    }\n  };\n\n  Vue.prototype.$destroy = function () {\n    var vm = this;\n    if (vm._isBeingDestroyed) {\n      return\n    }\n    callHook(vm, 'beforeDestroy');\n    vm._isBeingDestroyed = true;\n    // remove self from parent\n    var parent = vm.$parent;\n    if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {\n      remove(parent.$children, vm);\n    }\n    // teardown watchers\n    if (vm._watcher) {\n      vm._watcher.teardown();\n    }\n    var i = vm._watchers.length;\n    while (i--) {\n      vm._watchers[i].teardown();\n    }\n    // remove reference from data ob\n    // frozen object may not have observer.\n    if (vm._data.__ob__) {\n      vm._data.__ob__.vmCount--;\n    }\n    // call the last hook...\n    vm._isDestroyed = true;\n    // invoke destroy hooks on current rendered tree\n    vm.__patch__(vm._vnode, null);\n    // fire destroyed hook\n    callHook(vm, 'destroyed');\n    // turn off all instance listeners.\n    vm.$off();\n    // remove __vue__ reference\n    if (vm.$el) {\n      vm.$el.__vue__ = null;\n    }\n  };\n}\n\nfunction mountComponent (\n  vm,\n  el,\n  hydrating\n) {\n  vm.$el = el;\n  if (!vm.$options.render) {\n    vm.$options.render = createEmptyVNode;\n    {\n      /* istanbul ignore if */\n      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||\n        vm.$options.el || el) {\n        warn(\n          'You are using the runtime-only build of Vue where the template ' +\n          'compiler is not available. Either pre-compile the templates into ' +\n          'render functions, or use the compiler-included build.',\n          vm\n        );\n      } else {\n        warn(\n          'Failed to mount component: template or render function not defined.',\n          vm\n        );\n      }\n    }\n  }\n  callHook(vm, 'beforeMount');\n\n  var updateComponent;\n  /* istanbul ignore if */\n  if (\"development\" !== 'production' && config.performance && mark) {\n    updateComponent = function () {\n      var name = vm._name;\n      var id = vm._uid;\n      var startTag = \"vue-perf-start:\" + id;\n      var endTag = \"vue-perf-end:\" + id;\n\n      mark(startTag);\n      var vnode = vm._render();\n      mark(endTag);\n      measure((name + \" render\"), startTag, endTag);\n\n      mark(startTag);\n      vm._update(vnode, hydrating);\n      mark(endTag);\n      measure((name + \" patch\"), startTag, endTag);\n    };\n  } else {\n    updateComponent = function () {\n      vm._update(vm._render(), hydrating);\n    };\n  }\n\n  vm._watcher = new Watcher(vm, updateComponent, noop);\n  hydrating = false;\n\n  // manually mounted instance, call mounted on self\n  // mounted is called for render-created child components in its inserted hook\n  if (vm.$vnode == null) {\n    vm._isMounted = true;\n    callHook(vm, 'mounted');\n  }\n  return vm\n}\n\nfunction updateChildComponent (\n  vm,\n  propsData,\n  listeners,\n  parentVnode,\n  renderChildren\n) {\n  {\n    isUpdatingChildComponent = true;\n  }\n\n  // determine whether component has slot children\n  // we need to do this before overwriting $options._renderChildren\n  var hasChildren = !!(\n    renderChildren ||               // has new static slots\n    vm.$options._renderChildren ||  // has old static slots\n    parentVnode.data.scopedSlots || // has new scoped slots\n    vm.$scopedSlots !== emptyObject // has old scoped slots\n  );\n\n  vm.$options._parentVnode = parentVnode;\n  vm.$vnode = parentVnode; // update vm's placeholder node without re-render\n\n  if (vm._vnode) { // update child tree's parent\n    vm._vnode.parent = parentVnode;\n  }\n  vm.$options._renderChildren = renderChildren;\n\n  // update $attrs and $listeners hash\n  // these are also reactive so they may trigger child update if the child\n  // used them during render\n  vm.$attrs = (parentVnode.data && parentVnode.data.attrs) || emptyObject;\n  vm.$listeners = listeners || emptyObject;\n\n  // update props\n  if (propsData && vm.$options.props) {\n    observerState.shouldConvert = false;\n    var props = vm._props;\n    var propKeys = vm.$options._propKeys || [];\n    for (var i = 0; i < propKeys.length; i++) {\n      var key = propKeys[i];\n      props[key] = validateProp(key, vm.$options.props, propsData, vm);\n    }\n    observerState.shouldConvert = true;\n    // keep a copy of raw propsData\n    vm.$options.propsData = propsData;\n  }\n\n  // update listeners\n  if (listeners) {\n    var oldListeners = vm.$options._parentListeners;\n    vm.$options._parentListeners = listeners;\n    updateComponentListeners(vm, listeners, oldListeners);\n  }\n  // resolve slots + force update if has children\n  if (hasChildren) {\n    vm.$slots = resolveSlots(renderChildren, parentVnode.context);\n    vm.$forceUpdate();\n  }\n\n  {\n    isUpdatingChildComponent = false;\n  }\n}\n\nfunction isInInactiveTree (vm) {\n  while (vm && (vm = vm.$parent)) {\n    if (vm._inactive) { return true }\n  }\n  return false\n}\n\nfunction activateChildComponent (vm, direct) {\n  if (direct) {\n    vm._directInactive = false;\n    if (isInInactiveTree(vm)) {\n      return\n    }\n  } else if (vm._directInactive) {\n    return\n  }\n  if (vm._inactive || vm._inactive === null) {\n    vm._inactive = false;\n    for (var i = 0; i < vm.$children.length; i++) {\n      activateChildComponent(vm.$children[i]);\n    }\n    callHook(vm, 'activated');\n  }\n}\n\nfunction deactivateChildComponent (vm, direct) {\n  if (direct) {\n    vm._directInactive = true;\n    if (isInInactiveTree(vm)) {\n      return\n    }\n  }\n  if (!vm._inactive) {\n    vm._inactive = true;\n    for (var i = 0; i < vm.$children.length; i++) {\n      deactivateChildComponent(vm.$children[i]);\n    }\n    callHook(vm, 'deactivated');\n  }\n}\n\nfunction callHook (vm, hook) {\n  var handlers = vm.$options[hook];\n  if (handlers) {\n    for (var i = 0, j = handlers.length; i < j; i++) {\n      try {\n        handlers[i].call(vm);\n      } catch (e) {\n        handleError(e, vm, (hook + \" hook\"));\n      }\n    }\n  }\n  if (vm._hasHookEvent) {\n    vm.$emit('hook:' + hook);\n  }\n}\n\n/*  */\n\n\nvar MAX_UPDATE_COUNT = 100;\n\nvar queue = [];\nvar activatedChildren = [];\nvar has = {};\nvar circular = {};\nvar waiting = false;\nvar flushing = false;\nvar index = 0;\n\n/**\n * Reset the scheduler's state.\n */\nfunction resetSchedulerState () {\n  index = queue.length = activatedChildren.length = 0;\n  has = {};\n  {\n    circular = {};\n  }\n  waiting = flushing = false;\n}\n\n/**\n * Flush both queues and run the watchers.\n */\nfunction flushSchedulerQueue () {\n  flushing = true;\n  var watcher, id;\n\n  // Sort queue before flush.\n  // This ensures that:\n  // 1. Components are updated from parent to child. (because parent is always\n  //    created before the child)\n  // 2. A component's user watchers are run before its render watcher (because\n  //    user watchers are created before the render watcher)\n  // 3. If a component is destroyed during a parent component's watcher run,\n  //    its watchers can be skipped.\n  queue.sort(function (a, b) { return a.id - b.id; });\n\n  // do not cache length because more watchers might be pushed\n  // as we run existing watchers\n  for (index = 0; index < queue.length; index++) {\n    watcher = queue[index];\n    id = watcher.id;\n    has[id] = null;\n    watcher.run();\n    // in dev build, check and stop circular updates.\n    if (\"development\" !== 'production' && has[id] != null) {\n      circular[id] = (circular[id] || 0) + 1;\n      if (circular[id] > MAX_UPDATE_COUNT) {\n        warn(\n          'You may have an infinite update loop ' + (\n            watcher.user\n              ? (\"in watcher with expression \\\"\" + (watcher.expression) + \"\\\"\")\n              : \"in a component render function.\"\n          ),\n          watcher.vm\n        );\n        break\n      }\n    }\n  }\n\n  // keep copies of post queues before resetting state\n  var activatedQueue = activatedChildren.slice();\n  var updatedQueue = queue.slice();\n\n  resetSchedulerState();\n\n  // call component updated and activated hooks\n  callActivatedHooks(activatedQueue);\n  callUpdatedHooks(updatedQueue);\n\n  // devtool hook\n  /* istanbul ignore if */\n  if (devtools && config.devtools) {\n    devtools.emit('flush');\n  }\n}\n\nfunction callUpdatedHooks (queue) {\n  var i = queue.length;\n  while (i--) {\n    var watcher = queue[i];\n    var vm = watcher.vm;\n    if (vm._watcher === watcher && vm._isMounted) {\n      callHook(vm, 'updated');\n    }\n  }\n}\n\n/**\n * Queue a kept-alive component that was activated during patch.\n * The queue will be processed after the entire tree has been patched.\n */\nfunction queueActivatedComponent (vm) {\n  // setting _inactive to false here so that a render function can\n  // rely on checking whether it's in an inactive tree (e.g. router-view)\n  vm._inactive = false;\n  activatedChildren.push(vm);\n}\n\nfunction callActivatedHooks (queue) {\n  for (var i = 0; i < queue.length; i++) {\n    queue[i]._inactive = true;\n    activateChildComponent(queue[i], true /* true */);\n  }\n}\n\n/**\n * Push a watcher into the watcher queue.\n * Jobs with duplicate IDs will be skipped unless it's\n * pushed when the queue is being flushed.\n */\nfunction queueWatcher (watcher) {\n  var id = watcher.id;\n  if (has[id] == null) {\n    has[id] = true;\n    if (!flushing) {\n      queue.push(watcher);\n    } else {\n      // if already flushing, splice the watcher based on its id\n      // if already past its id, it will be run next immediately.\n      var i = queue.length - 1;\n      while (i > index && queue[i].id > watcher.id) {\n        i--;\n      }\n      queue.splice(i + 1, 0, watcher);\n    }\n    // queue the flush\n    if (!waiting) {\n      waiting = true;\n      nextTick(flushSchedulerQueue);\n    }\n  }\n}\n\n/*  */\n\nvar uid$2 = 0;\n\n/**\n * A watcher parses an expression, collects dependencies,\n * and fires callback when the expression value changes.\n * This is used for both the $watch() api and directives.\n */\nvar Watcher = function Watcher (\n  vm,\n  expOrFn,\n  cb,\n  options\n) {\n  this.vm = vm;\n  vm._watchers.push(this);\n  // options\n  if (options) {\n    this.deep = !!options.deep;\n    this.user = !!options.user;\n    this.lazy = !!options.lazy;\n    this.sync = !!options.sync;\n  } else {\n    this.deep = this.user = this.lazy = this.sync = false;\n  }\n  this.cb = cb;\n  this.id = ++uid$2; // uid for batching\n  this.active = true;\n  this.dirty = this.lazy; // for lazy watchers\n  this.deps = [];\n  this.newDeps = [];\n  this.depIds = new _Set();\n  this.newDepIds = new _Set();\n  this.expression = expOrFn.toString();\n  // parse expression for getter\n  if (typeof expOrFn === 'function') {\n    this.getter = expOrFn;\n  } else {\n    this.getter = parsePath(expOrFn);\n    if (!this.getter) {\n      this.getter = function () {};\n      \"development\" !== 'production' && warn(\n        \"Failed watching path: \\\"\" + expOrFn + \"\\\" \" +\n        'Watcher only accepts simple dot-delimited paths. ' +\n        'For full control, use a function instead.',\n        vm\n      );\n    }\n  }\n  this.value = this.lazy\n    ? undefined\n    : this.get();\n};\n\n/**\n * Evaluate the getter, and re-collect dependencies.\n */\nWatcher.prototype.get = function get () {\n  pushTarget(this);\n  var value;\n  var vm = this.vm;\n  try {\n    value = this.getter.call(vm, vm);\n  } catch (e) {\n    if (this.user) {\n      handleError(e, vm, (\"getter for watcher \\\"\" + (this.expression) + \"\\\"\"));\n    } else {\n      throw e\n    }\n  } finally {\n    // \"touch\" every property so they are all tracked as\n    // dependencies for deep watching\n    if (this.deep) {\n      traverse(value);\n    }\n    popTarget();\n    this.cleanupDeps();\n  }\n  return value\n};\n\n/**\n * Add a dependency to this directive.\n */\nWatcher.prototype.addDep = function addDep (dep) {\n  var id = dep.id;\n  if (!this.newDepIds.has(id)) {\n    this.newDepIds.add(id);\n    this.newDeps.push(dep);\n    if (!this.depIds.has(id)) {\n      dep.addSub(this);\n    }\n  }\n};\n\n/**\n * Clean up for dependency collection.\n */\nWatcher.prototype.cleanupDeps = function cleanupDeps () {\n    var this$1 = this;\n\n  var i = this.deps.length;\n  while (i--) {\n    var dep = this$1.deps[i];\n    if (!this$1.newDepIds.has(dep.id)) {\n      dep.removeSub(this$1);\n    }\n  }\n  var tmp = this.depIds;\n  this.depIds = this.newDepIds;\n  this.newDepIds = tmp;\n  this.newDepIds.clear();\n  tmp = this.deps;\n  this.deps = this.newDeps;\n  this.newDeps = tmp;\n  this.newDeps.length = 0;\n};\n\n/**\n * Subscriber interface.\n * Will be called when a dependency changes.\n */\nWatcher.prototype.update = function update () {\n  /* istanbul ignore else */\n  if (this.lazy) {\n    this.dirty = true;\n  } else if (this.sync) {\n    this.run();\n  } else {\n    queueWatcher(this);\n  }\n};\n\n/**\n * Scheduler job interface.\n * Will be called by the scheduler.\n */\nWatcher.prototype.run = function run () {\n  if (this.active) {\n    var value = this.get();\n    if (\n      value !== this.value ||\n      // Deep watchers and watchers on Object/Arrays should fire even\n      // when the value is the same, because the value may\n      // have mutated.\n      isObject(value) ||\n      this.deep\n    ) {\n      // set new value\n      var oldValue = this.value;\n      this.value = value;\n      if (this.user) {\n        try {\n          this.cb.call(this.vm, value, oldValue);\n        } catch (e) {\n          handleError(e, this.vm, (\"callback for watcher \\\"\" + (this.expression) + \"\\\"\"));\n        }\n      } else {\n        this.cb.call(this.vm, value, oldValue);\n      }\n    }\n  }\n};\n\n/**\n * Evaluate the value of the watcher.\n * This only gets called for lazy watchers.\n */\nWatcher.prototype.evaluate = function evaluate () {\n  this.value = this.get();\n  this.dirty = false;\n};\n\n/**\n * Depend on all deps collected by this watcher.\n */\nWatcher.prototype.depend = function depend () {\n    var this$1 = this;\n\n  var i = this.deps.length;\n  while (i--) {\n    this$1.deps[i].depend();\n  }\n};\n\n/**\n * Remove self from all dependencies' subscriber list.\n */\nWatcher.prototype.teardown = function teardown () {\n    var this$1 = this;\n\n  if (this.active) {\n    // remove self from vm's watcher list\n    // this is a somewhat expensive operation so we skip it\n    // if the vm is being destroyed.\n    if (!this.vm._isBeingDestroyed) {\n      remove(this.vm._watchers, this);\n    }\n    var i = this.deps.length;\n    while (i--) {\n      this$1.deps[i].removeSub(this$1);\n    }\n    this.active = false;\n  }\n};\n\n/**\n * Recursively traverse an object to evoke all converted\n * getters, so that every nested property inside the object\n * is collected as a \"deep\" dependency.\n */\nvar seenObjects = new _Set();\nfunction traverse (val) {\n  seenObjects.clear();\n  _traverse(val, seenObjects);\n}\n\nfunction _traverse (val, seen) {\n  var i, keys;\n  var isA = Array.isArray(val);\n  if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {\n    return\n  }\n  if (val.__ob__) {\n    var depId = val.__ob__.dep.id;\n    if (seen.has(depId)) {\n      return\n    }\n    seen.add(depId);\n  }\n  if (isA) {\n    i = val.length;\n    while (i--) { _traverse(val[i], seen); }\n  } else {\n    keys = Object.keys(val);\n    i = keys.length;\n    while (i--) { _traverse(val[keys[i]], seen); }\n  }\n}\n\n/*  */\n\nvar sharedPropertyDefinition = {\n  enumerable: true,\n  configurable: true,\n  get: noop,\n  set: noop\n};\n\nfunction proxy (target, sourceKey, key) {\n  sharedPropertyDefinition.get = function proxyGetter () {\n    return this[sourceKey][key]\n  };\n  sharedPropertyDefinition.set = function proxySetter (val) {\n    this[sourceKey][key] = val;\n  };\n  Object.defineProperty(target, key, sharedPropertyDefinition);\n}\n\nfunction initState (vm) {\n  vm._watchers = [];\n  var opts = vm.$options;\n  if (opts.props) { initProps(vm, opts.props); }\n  if (opts.methods) { initMethods(vm, opts.methods); }\n  if (opts.data) {\n    initData(vm);\n  } else {\n    observe(vm._data = {}, true /* asRootData */);\n  }\n  if (opts.computed) { initComputed(vm, opts.computed); }\n  if (opts.watch && opts.watch !== nativeWatch) {\n    initWatch(vm, opts.watch);\n  }\n}\n\nfunction checkOptionType (vm, name) {\n  var option = vm.$options[name];\n  if (!isPlainObject(option)) {\n    warn(\n      (\"component option \\\"\" + name + \"\\\" should be an object.\"),\n      vm\n    );\n  }\n}\n\nfunction initProps (vm, propsOptions) {\n  var propsData = vm.$options.propsData || {};\n  var props = vm._props = {};\n  // cache prop keys so that future props updates can iterate using Array\n  // instead of dynamic object key enumeration.\n  var keys = vm.$options._propKeys = [];\n  var isRoot = !vm.$parent;\n  // root instance props should be converted\n  observerState.shouldConvert = isRoot;\n  var loop = function ( key ) {\n    keys.push(key);\n    var value = validateProp(key, propsOptions, propsData, vm);\n    /* istanbul ignore else */\n    {\n      if (isReservedAttribute(key) || config.isReservedAttr(key)) {\n        warn(\n          (\"\\\"\" + key + \"\\\" is a reserved attribute and cannot be used as component prop.\"),\n          vm\n        );\n      }\n      defineReactive$$1(props, key, value, function () {\n        if (vm.$parent && !isUpdatingChildComponent) {\n          warn(\n            \"Avoid mutating a prop directly since the value will be \" +\n            \"overwritten whenever the parent component re-renders. \" +\n            \"Instead, use a data or computed property based on the prop's \" +\n            \"value. Prop being mutated: \\\"\" + key + \"\\\"\",\n            vm\n          );\n        }\n      });\n    }\n    // static props are already proxied on the component's prototype\n    // during Vue.extend(). We only need to proxy props defined at\n    // instantiation here.\n    if (!(key in vm)) {\n      proxy(vm, \"_props\", key);\n    }\n  };\n\n  for (var key in propsOptions) loop( key );\n  observerState.shouldConvert = true;\n}\n\nfunction initData (vm) {\n  var data = vm.$options.data;\n  data = vm._data = typeof data === 'function'\n    ? getData(data, vm)\n    : data || {};\n  if (!isPlainObject(data)) {\n    data = {};\n    \"development\" !== 'production' && warn(\n      'data functions should return an object:\\n' +\n      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',\n      vm\n    );\n  }\n  // proxy data on instance\n  var keys = Object.keys(data);\n  var props = vm.$options.props;\n  var methods = vm.$options.methods;\n  var i = keys.length;\n  while (i--) {\n    var key = keys[i];\n    {\n      if (methods && hasOwn(methods, key)) {\n        warn(\n          (\"Method \\\"\" + key + \"\\\" has already been defined as a data property.\"),\n          vm\n        );\n      }\n    }\n    if (props && hasOwn(props, key)) {\n      \"development\" !== 'production' && warn(\n        \"The data property \\\"\" + key + \"\\\" is already declared as a prop. \" +\n        \"Use prop default value instead.\",\n        vm\n      );\n    } else if (!isReserved(key)) {\n      proxy(vm, \"_data\", key);\n    }\n  }\n  // observe data\n  observe(data, true /* asRootData */);\n}\n\nfunction getData (data, vm) {\n  try {\n    return data.call(vm)\n  } catch (e) {\n    handleError(e, vm, \"data()\");\n    return {}\n  }\n}\n\nvar computedWatcherOptions = { lazy: true };\n\nfunction initComputed (vm, computed) {\n  \"development\" !== 'production' && checkOptionType(vm, 'computed');\n  var watchers = vm._computedWatchers = Object.create(null);\n  // computed properties are just getters during SSR\n  var isSSR = isServerRendering();\n\n  for (var key in computed) {\n    var userDef = computed[key];\n    var getter = typeof userDef === 'function' ? userDef : userDef.get;\n    if (\"development\" !== 'production' && getter == null) {\n      warn(\n        (\"Getter is missing for computed property \\\"\" + key + \"\\\".\"),\n        vm\n      );\n    }\n\n    if (!isSSR) {\n      // create internal watcher for the computed property.\n      watchers[key] = new Watcher(\n        vm,\n        getter || noop,\n        noop,\n        computedWatcherOptions\n      );\n    }\n\n    // component-defined computed properties are already defined on the\n    // component prototype. We only need to define computed properties defined\n    // at instantiation here.\n    if (!(key in vm)) {\n      defineComputed(vm, key, userDef);\n    } else {\n      if (key in vm.$data) {\n        warn((\"The computed property \\\"\" + key + \"\\\" is already defined in data.\"), vm);\n      } else if (vm.$options.props && key in vm.$options.props) {\n        warn((\"The computed property \\\"\" + key + \"\\\" is already defined as a prop.\"), vm);\n      }\n    }\n  }\n}\n\nfunction defineComputed (\n  target,\n  key,\n  userDef\n) {\n  var shouldCache = !isServerRendering();\n  if (typeof userDef === 'function') {\n    sharedPropertyDefinition.get = shouldCache\n      ? createComputedGetter(key)\n      : userDef;\n    sharedPropertyDefinition.set = noop;\n  } else {\n    sharedPropertyDefinition.get = userDef.get\n      ? shouldCache && userDef.cache !== false\n        ? createComputedGetter(key)\n        : userDef.get\n      : noop;\n    sharedPropertyDefinition.set = userDef.set\n      ? userDef.set\n      : noop;\n  }\n  if (\"development\" !== 'production' &&\n      sharedPropertyDefinition.set === noop) {\n    sharedPropertyDefinition.set = function () {\n      warn(\n        (\"Computed property \\\"\" + key + \"\\\" was assigned to but it has no setter.\"),\n        this\n      );\n    };\n  }\n  Object.defineProperty(target, key, sharedPropertyDefinition);\n}\n\nfunction createComputedGetter (key) {\n  return function computedGetter () {\n    var watcher = this._computedWatchers && this._computedWatchers[key];\n    if (watcher) {\n      if (watcher.dirty) {\n        watcher.evaluate();\n      }\n      if (Dep.target) {\n        watcher.depend();\n      }\n      return watcher.value\n    }\n  }\n}\n\nfunction initMethods (vm, methods) {\n  \"development\" !== 'production' && checkOptionType(vm, 'methods');\n  var props = vm.$options.props;\n  for (var key in methods) {\n    {\n      if (methods[key] == null) {\n        warn(\n          \"Method \\\"\" + key + \"\\\" has an undefined value in the component definition. \" +\n          \"Did you reference the function correctly?\",\n          vm\n        );\n      }\n      if (props && hasOwn(props, key)) {\n        warn(\n          (\"Method \\\"\" + key + \"\\\" has already been defined as a prop.\"),\n          vm\n        );\n      }\n      if ((key in vm) && isReserved(key)) {\n        warn(\n          \"Method \\\"\" + key + \"\\\" conflicts with an existing Vue instance method. \" +\n          \"Avoid defining component methods that start with _ or $.\"\n        );\n      }\n    }\n    vm[key] = methods[key] == null ? noop : bind(methods[key], vm);\n  }\n}\n\nfunction initWatch (vm, watch) {\n  \"development\" !== 'production' && checkOptionType(vm, 'watch');\n  for (var key in watch) {\n    var handler = watch[key];\n    if (Array.isArray(handler)) {\n      for (var i = 0; i < handler.length; i++) {\n        createWatcher(vm, key, handler[i]);\n      }\n    } else {\n      createWatcher(vm, key, handler);\n    }\n  }\n}\n\nfunction createWatcher (\n  vm,\n  keyOrFn,\n  handler,\n  options\n) {\n  if (isPlainObject(handler)) {\n    options = handler;\n    handler = handler.handler;\n  }\n  if (typeof handler === 'string') {\n    handler = vm[handler];\n  }\n  return vm.$watch(keyOrFn, handler, options)\n}\n\nfunction stateMixin (Vue) {\n  // flow somehow has problems with directly declared definition object\n  // when using Object.defineProperty, so we have to procedurally build up\n  // the object here.\n  var dataDef = {};\n  dataDef.get = function () { return this._data };\n  var propsDef = {};\n  propsDef.get = function () { return this._props };\n  {\n    dataDef.set = function (newData) {\n      warn(\n        'Avoid replacing instance root $data. ' +\n        'Use nested data properties instead.',\n        this\n      );\n    };\n    propsDef.set = function () {\n      warn(\"$props is readonly.\", this);\n    };\n  }\n  Object.defineProperty(Vue.prototype, '$data', dataDef);\n  Object.defineProperty(Vue.prototype, '$props', propsDef);\n\n  Vue.prototype.$set = set;\n  Vue.prototype.$delete = del;\n\n  Vue.prototype.$watch = function (\n    expOrFn,\n    cb,\n    options\n  ) {\n    var vm = this;\n    if (isPlainObject(cb)) {\n      return createWatcher(vm, expOrFn, cb, options)\n    }\n    options = options || {};\n    options.user = true;\n    var watcher = new Watcher(vm, expOrFn, cb, options);\n    if (options.immediate) {\n      cb.call(vm, watcher.value);\n    }\n    return function unwatchFn () {\n      watcher.teardown();\n    }\n  };\n}\n\n/*  */\n\nfunction initProvide (vm) {\n  var provide = vm.$options.provide;\n  if (provide) {\n    vm._provided = typeof provide === 'function'\n      ? provide.call(vm)\n      : provide;\n  }\n}\n\nfunction initInjections (vm) {\n  var result = resolveInject(vm.$options.inject, vm);\n  if (result) {\n    observerState.shouldConvert = false;\n    Object.keys(result).forEach(function (key) {\n      /* istanbul ignore else */\n      {\n        defineReactive$$1(vm, key, result[key], function () {\n          warn(\n            \"Avoid mutating an injected value directly since the changes will be \" +\n            \"overwritten whenever the provided component re-renders. \" +\n            \"injection being mutated: \\\"\" + key + \"\\\"\",\n            vm\n          );\n        });\n      }\n    });\n    observerState.shouldConvert = true;\n  }\n}\n\nfunction resolveInject (inject, vm) {\n  if (inject) {\n    // inject is :any because flow is not smart enough to figure out cached\n    var result = Object.create(null);\n    var keys = hasSymbol\n        ? Reflect.ownKeys(inject).filter(function (key) {\n          /* istanbul ignore next */\n          return Object.getOwnPropertyDescriptor(inject, key).enumerable\n        })\n        : Object.keys(inject);\n\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n      var provideKey = inject[key];\n      var source = vm;\n      while (source) {\n        if (source._provided && provideKey in source._provided) {\n          result[key] = source._provided[provideKey];\n          break\n        }\n        source = source.$parent;\n      }\n      if (\"development\" !== 'production' && !source) {\n        warn((\"Injection \\\"\" + key + \"\\\" not found\"), vm);\n      }\n    }\n    return result\n  }\n}\n\n/*  */\n\nfunction createFunctionalComponent (\n  Ctor,\n  propsData,\n  data,\n  context,\n  children\n) {\n  var props = {};\n  var propOptions = Ctor.options.props;\n  if (isDef(propOptions)) {\n    for (var key in propOptions) {\n      props[key] = validateProp(key, propOptions, propsData || emptyObject);\n    }\n  } else {\n    if (isDef(data.attrs)) { mergeProps(props, data.attrs); }\n    if (isDef(data.props)) { mergeProps(props, data.props); }\n  }\n  // ensure the createElement function in functional components\n  // gets a unique context - this is necessary for correct named slot check\n  var _context = Object.create(context);\n  var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };\n  var vnode = Ctor.options.render.call(null, h, {\n    data: data,\n    props: props,\n    children: children,\n    parent: context,\n    listeners: data.on || emptyObject,\n    injections: resolveInject(Ctor.options.inject, context),\n    slots: function () { return resolveSlots(children, context); }\n  });\n  if (vnode instanceof VNode) {\n    vnode.functionalContext = context;\n    vnode.functionalOptions = Ctor.options;\n    if (data.slot) {\n      (vnode.data || (vnode.data = {})).slot = data.slot;\n    }\n  }\n  return vnode\n}\n\nfunction mergeProps (to, from) {\n  for (var key in from) {\n    to[camelize(key)] = from[key];\n  }\n}\n\n/*  */\n\n// hooks to be invoked on component VNodes during patch\nvar componentVNodeHooks = {\n  init: function init (\n    vnode,\n    hydrating,\n    parentElm,\n    refElm\n  ) {\n    if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {\n      var child = vnode.componentInstance = createComponentInstanceForVnode(\n        vnode,\n        activeInstance,\n        parentElm,\n        refElm\n      );\n      child.$mount(hydrating ? vnode.elm : undefined, hydrating);\n    } else if (vnode.data.keepAlive) {\n      // kept-alive components, treat as a patch\n      var mountedNode = vnode; // work around flow\n      componentVNodeHooks.prepatch(mountedNode, mountedNode);\n    }\n  },\n\n  prepatch: function prepatch (oldVnode, vnode) {\n    var options = vnode.componentOptions;\n    var child = vnode.componentInstance = oldVnode.componentInstance;\n    updateChildComponent(\n      child,\n      options.propsData, // updated props\n      options.listeners, // updated listeners\n      vnode, // new parent vnode\n      options.children // new children\n    );\n  },\n\n  insert: function insert (vnode) {\n    var context = vnode.context;\n    var componentInstance = vnode.componentInstance;\n    if (!componentInstance._isMounted) {\n      componentInstance._isMounted = true;\n      callHook(componentInstance, 'mounted');\n    }\n    if (vnode.data.keepAlive) {\n      if (context._isMounted) {\n        // vue-router#1212\n        // During updates, a kept-alive component's child components may\n        // change, so directly walking the tree here may call activated hooks\n        // on incorrect children. Instead we push them into a queue which will\n        // be processed after the whole patch process ended.\n        queueActivatedComponent(componentInstance);\n      } else {\n        activateChildComponent(componentInstance, true /* direct */);\n      }\n    }\n  },\n\n  destroy: function destroy (vnode) {\n    var componentInstance = vnode.componentInstance;\n    if (!componentInstance._isDestroyed) {\n      if (!vnode.data.keepAlive) {\n        componentInstance.$destroy();\n      } else {\n        deactivateChildComponent(componentInstance, true /* direct */);\n      }\n    }\n  }\n};\n\nvar hooksToMerge = Object.keys(componentVNodeHooks);\n\nfunction createComponent (\n  Ctor,\n  data,\n  context,\n  children,\n  tag\n) {\n  if (isUndef(Ctor)) {\n    return\n  }\n\n  var baseCtor = context.$options._base;\n\n  // plain options object: turn it into a constructor\n  if (isObject(Ctor)) {\n    Ctor = baseCtor.extend(Ctor);\n  }\n\n  // if at this stage it's not a constructor or an async component factory,\n  // reject.\n  if (typeof Ctor !== 'function') {\n    {\n      warn((\"Invalid Component definition: \" + (String(Ctor))), context);\n    }\n    return\n  }\n\n  // async component\n  var asyncFactory;\n  if (isUndef(Ctor.cid)) {\n    asyncFactory = Ctor;\n    Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context);\n    if (Ctor === undefined) {\n      // return a placeholder node for async component, which is rendered\n      // as a comment node but preserves all the raw information for the node.\n      // the information will be used for async server-rendering and hydration.\n      return createAsyncPlaceholder(\n        asyncFactory,\n        data,\n        context,\n        children,\n        tag\n      )\n    }\n  }\n\n  data = data || {};\n\n  // resolve constructor options in case global mixins are applied after\n  // component constructor creation\n  resolveConstructorOptions(Ctor);\n\n  // transform component v-model data into props & events\n  if (isDef(data.model)) {\n    transformModel(Ctor.options, data);\n  }\n\n  // extract props\n  var propsData = extractPropsFromVNodeData(data, Ctor, tag);\n\n  // functional component\n  if (isTrue(Ctor.options.functional)) {\n    return createFunctionalComponent(Ctor, propsData, data, context, children)\n  }\n\n  // extract listeners, since these needs to be treated as\n  // child component listeners instead of DOM listeners\n  var listeners = data.on;\n  // replace with listeners with .native modifier\n  // so it gets processed during parent component patch.\n  data.on = data.nativeOn;\n\n  if (isTrue(Ctor.options.abstract)) {\n    // abstract components do not keep anything\n    // other than props & listeners & slot\n\n    // work around flow\n    var slot = data.slot;\n    data = {};\n    if (slot) {\n      data.slot = slot;\n    }\n  }\n\n  // merge component management hooks onto the placeholder node\n  mergeHooks(data);\n\n  // return a placeholder vnode\n  var name = Ctor.options.name || tag;\n  var vnode = new VNode(\n    (\"vue-component-\" + (Ctor.cid) + (name ? (\"-\" + name) : '')),\n    data, undefined, undefined, undefined, context,\n    { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },\n    asyncFactory\n  );\n  return vnode\n}\n\nfunction createComponentInstanceForVnode (\n  vnode, // we know it's MountedComponentVNode but flow doesn't\n  parent, // activeInstance in lifecycle state\n  parentElm,\n  refElm\n) {\n  var vnodeComponentOptions = vnode.componentOptions;\n  var options = {\n    _isComponent: true,\n    parent: parent,\n    propsData: vnodeComponentOptions.propsData,\n    _componentTag: vnodeComponentOptions.tag,\n    _parentVnode: vnode,\n    _parentListeners: vnodeComponentOptions.listeners,\n    _renderChildren: vnodeComponentOptions.children,\n    _parentElm: parentElm || null,\n    _refElm: refElm || null\n  };\n  // check inline-template render functions\n  var inlineTemplate = vnode.data.inlineTemplate;\n  if (isDef(inlineTemplate)) {\n    options.render = inlineTemplate.render;\n    options.staticRenderFns = inlineTemplate.staticRenderFns;\n  }\n  return new vnodeComponentOptions.Ctor(options)\n}\n\nfunction mergeHooks (data) {\n  if (!data.hook) {\n    data.hook = {};\n  }\n  for (var i = 0; i < hooksToMerge.length; i++) {\n    var key = hooksToMerge[i];\n    var fromParent = data.hook[key];\n    var ours = componentVNodeHooks[key];\n    data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;\n  }\n}\n\nfunction mergeHook$1 (one, two) {\n  return function (a, b, c, d) {\n    one(a, b, c, d);\n    two(a, b, c, d);\n  }\n}\n\n// transform component v-model info (value and callback) into\n// prop and event handler respectively.\nfunction transformModel (options, data) {\n  var prop = (options.model && options.model.prop) || 'value';\n  var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value;\n  var on = data.on || (data.on = {});\n  if (isDef(on[event])) {\n    on[event] = [data.model.callback].concat(on[event]);\n  } else {\n    on[event] = data.model.callback;\n  }\n}\n\n/*  */\n\nvar SIMPLE_NORMALIZE = 1;\nvar ALWAYS_NORMALIZE = 2;\n\n// wrapper function for providing a more flexible interface\n// without getting yelled at by flow\nfunction createElement (\n  context,\n  tag,\n  data,\n  children,\n  normalizationType,\n  alwaysNormalize\n) {\n  if (Array.isArray(data) || isPrimitive(data)) {\n    normalizationType = children;\n    children = data;\n    data = undefined;\n  }\n  if (isTrue(alwaysNormalize)) {\n    normalizationType = ALWAYS_NORMALIZE;\n  }\n  return _createElement(context, tag, data, children, normalizationType)\n}\n\nfunction _createElement (\n  context,\n  tag,\n  data,\n  children,\n  normalizationType\n) {\n  if (isDef(data) && isDef((data).__ob__)) {\n    \"development\" !== 'production' && warn(\n      \"Avoid using observed data object as vnode data: \" + (JSON.stringify(data)) + \"\\n\" +\n      'Always create fresh vnode data objects in each render!',\n      context\n    );\n    return createEmptyVNode()\n  }\n  // object syntax in v-bind\n  if (isDef(data) && isDef(data.is)) {\n    tag = data.is;\n  }\n  if (!tag) {\n    // in case of component :is set to falsy value\n    return createEmptyVNode()\n  }\n  // warn against non-primitive key\n  if (\"development\" !== 'production' &&\n    isDef(data) && isDef(data.key) && !isPrimitive(data.key)\n  ) {\n    warn(\n      'Avoid using non-primitive value as key, ' +\n      'use string/number value instead.',\n      context\n    );\n  }\n  // support single function children as default scoped slot\n  if (Array.isArray(children) &&\n    typeof children[0] === 'function'\n  ) {\n    data = data || {};\n    data.scopedSlots = { default: children[0] };\n    children.length = 0;\n  }\n  if (normalizationType === ALWAYS_NORMALIZE) {\n    children = normalizeChildren(children);\n  } else if (normalizationType === SIMPLE_NORMALIZE) {\n    children = simpleNormalizeChildren(children);\n  }\n  var vnode, ns;\n  if (typeof tag === 'string') {\n    var Ctor;\n    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);\n    if (config.isReservedTag(tag)) {\n      // platform built-in elements\n      vnode = new VNode(\n        config.parsePlatformTagName(tag), data, children,\n        undefined, undefined, context\n      );\n    } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {\n      // component\n      vnode = createComponent(Ctor, data, context, children, tag);\n    } else {\n      // unknown or unlisted namespaced elements\n      // check at runtime because it may get assigned a namespace when its\n      // parent normalizes children\n      vnode = new VNode(\n        tag, data, children,\n        undefined, undefined, context\n      );\n    }\n  } else {\n    // direct component options / constructor\n    vnode = createComponent(tag, data, context, children);\n  }\n  if (isDef(vnode)) {\n    if (ns) { applyNS(vnode, ns); }\n    return vnode\n  } else {\n    return createEmptyVNode()\n  }\n}\n\nfunction applyNS (vnode, ns) {\n  vnode.ns = ns;\n  if (vnode.tag === 'foreignObject') {\n    // use default namespace inside foreignObject\n    return\n  }\n  if (isDef(vnode.children)) {\n    for (var i = 0, l = vnode.children.length; i < l; i++) {\n      var child = vnode.children[i];\n      if (isDef(child.tag) && isUndef(child.ns)) {\n        applyNS(child, ns);\n      }\n    }\n  }\n}\n\n/*  */\n\n/**\n * Runtime helper for rendering v-for lists.\n */\nfunction renderList (\n  val,\n  render\n) {\n  var ret, i, l, keys, key;\n  if (Array.isArray(val) || typeof val === 'string') {\n    ret = new Array(val.length);\n    for (i = 0, l = val.length; i < l; i++) {\n      ret[i] = render(val[i], i);\n    }\n  } else if (typeof val === 'number') {\n    ret = new Array(val);\n    for (i = 0; i < val; i++) {\n      ret[i] = render(i + 1, i);\n    }\n  } else if (isObject(val)) {\n    keys = Object.keys(val);\n    ret = new Array(keys.length);\n    for (i = 0, l = keys.length; i < l; i++) {\n      key = keys[i];\n      ret[i] = render(val[key], key, i);\n    }\n  }\n  if (isDef(ret)) {\n    (ret)._isVList = true;\n  }\n  return ret\n}\n\n/*  */\n\n/**\n * Runtime helper for rendering <slot>\n */\nfunction renderSlot (\n  name,\n  fallback,\n  props,\n  bindObject\n) {\n  var scopedSlotFn = this.$scopedSlots[name];\n  if (scopedSlotFn) { // scoped slot\n    props = props || {};\n    if (bindObject) {\n      props = extend(extend({}, bindObject), props);\n    }\n    return scopedSlotFn(props) || fallback\n  } else {\n    var slotNodes = this.$slots[name];\n    // warn duplicate slot usage\n    if (slotNodes && \"development\" !== 'production') {\n      slotNodes._rendered && warn(\n        \"Duplicate presence of slot \\\"\" + name + \"\\\" found in the same render tree \" +\n        \"- this will likely cause render errors.\",\n        this\n      );\n      slotNodes._rendered = true;\n    }\n    return slotNodes || fallback\n  }\n}\n\n/*  */\n\n/**\n * Runtime helper for resolving filters\n */\nfunction resolveFilter (id) {\n  return resolveAsset(this.$options, 'filters', id, true) || identity\n}\n\n/*  */\n\n/**\n * Runtime helper for checking keyCodes from config.\n */\nfunction checkKeyCodes (\n  eventKeyCode,\n  key,\n  builtInAlias\n) {\n  var keyCodes = config.keyCodes[key] || builtInAlias;\n  if (Array.isArray(keyCodes)) {\n    return keyCodes.indexOf(eventKeyCode) === -1\n  } else {\n    return keyCodes !== eventKeyCode\n  }\n}\n\n/*  */\n\n/**\n * Runtime helper for merging v-bind=\"object\" into a VNode's data.\n */\nfunction bindObjectProps (\n  data,\n  tag,\n  value,\n  asProp,\n  isSync\n) {\n  if (value) {\n    if (!isObject(value)) {\n      \"development\" !== 'production' && warn(\n        'v-bind without argument expects an Object or Array value',\n        this\n      );\n    } else {\n      if (Array.isArray(value)) {\n        value = toObject(value);\n      }\n      var hash;\n      var loop = function ( key ) {\n        if (\n          key === 'class' ||\n          key === 'style' ||\n          isReservedAttribute(key)\n        ) {\n          hash = data;\n        } else {\n          var type = data.attrs && data.attrs.type;\n          hash = asProp || config.mustUseProp(tag, type, key)\n            ? data.domProps || (data.domProps = {})\n            : data.attrs || (data.attrs = {});\n        }\n        if (!(key in hash)) {\n          hash[key] = value[key];\n\n          if (isSync) {\n            var on = data.on || (data.on = {});\n            on[(\"update:\" + key)] = function ($event) {\n              value[key] = $event;\n            };\n          }\n        }\n      };\n\n      for (var key in value) loop( key );\n    }\n  }\n  return data\n}\n\n/*  */\n\n/**\n * Runtime helper for rendering static trees.\n */\nfunction renderStatic (\n  index,\n  isInFor\n) {\n  var tree = this._staticTrees[index];\n  // if has already-rendered static tree and not inside v-for,\n  // we can reuse the same tree by doing a shallow clone.\n  if (tree && !isInFor) {\n    return Array.isArray(tree)\n      ? cloneVNodes(tree)\n      : cloneVNode(tree)\n  }\n  // otherwise, render a fresh tree.\n  tree = this._staticTrees[index] =\n    this.$options.staticRenderFns[index].call(this._renderProxy);\n  markStatic(tree, (\"__static__\" + index), false);\n  return tree\n}\n\n/**\n * Runtime helper for v-once.\n * Effectively it means marking the node as static with a unique key.\n */\nfunction markOnce (\n  tree,\n  index,\n  key\n) {\n  markStatic(tree, (\"__once__\" + index + (key ? (\"_\" + key) : \"\")), true);\n  return tree\n}\n\nfunction markStatic (\n  tree,\n  key,\n  isOnce\n) {\n  if (Array.isArray(tree)) {\n    for (var i = 0; i < tree.length; i++) {\n      if (tree[i] && typeof tree[i] !== 'string') {\n        markStaticNode(tree[i], (key + \"_\" + i), isOnce);\n      }\n    }\n  } else {\n    markStaticNode(tree, key, isOnce);\n  }\n}\n\nfunction markStaticNode (node, key, isOnce) {\n  node.isStatic = true;\n  node.key = key;\n  node.isOnce = isOnce;\n}\n\n/*  */\n\nfunction bindObjectListeners (data, value) {\n  if (value) {\n    if (!isPlainObject(value)) {\n      \"development\" !== 'production' && warn(\n        'v-on without argument expects an Object value',\n        this\n      );\n    } else {\n      var on = data.on = data.on ? extend({}, data.on) : {};\n      for (var key in value) {\n        var existing = on[key];\n        var ours = value[key];\n        on[key] = existing ? [].concat(ours, existing) : ours;\n      }\n    }\n  }\n  return data\n}\n\n/*  */\n\nfunction initRender (vm) {\n  vm._vnode = null; // the root of the child tree\n  vm._staticTrees = null;\n  var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree\n  var renderContext = parentVnode && parentVnode.context;\n  vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);\n  vm.$scopedSlots = emptyObject;\n  // bind the createElement fn to this instance\n  // so that we get proper render context inside it.\n  // args order: tag, data, children, normalizationType, alwaysNormalize\n  // internal version is used by render functions compiled from templates\n  vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };\n  // normalization is always applied for the public version, used in\n  // user-written render functions.\n  vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };\n\n  // $attrs & $listeners are exposed for easier HOC creation.\n  // they need to be reactive so that HOCs using them are always updated\n  var parentData = parentVnode && parentVnode.data;\n\n  /* istanbul ignore else */\n  {\n    defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {\n      !isUpdatingChildComponent && warn(\"$attrs is readonly.\", vm);\n    }, true);\n    defineReactive$$1(vm, '$listeners', vm.$options._parentListeners || emptyObject, function () {\n      !isUpdatingChildComponent && warn(\"$listeners is readonly.\", vm);\n    }, true);\n  }\n}\n\nfunction renderMixin (Vue) {\n  Vue.prototype.$nextTick = function (fn) {\n    return nextTick(fn, this)\n  };\n\n  Vue.prototype._render = function () {\n    var vm = this;\n    var ref = vm.$options;\n    var render = ref.render;\n    var staticRenderFns = ref.staticRenderFns;\n    var _parentVnode = ref._parentVnode;\n\n    if (vm._isMounted) {\n      // if the parent didn't update, the slot nodes will be the ones from\n      // last render. They need to be cloned to ensure \"freshness\" for this render.\n      for (var key in vm.$slots) {\n        var slot = vm.$slots[key];\n        if (slot._rendered) {\n          vm.$slots[key] = cloneVNodes(slot, true /* deep */);\n        }\n      }\n    }\n\n    vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject;\n\n    if (staticRenderFns && !vm._staticTrees) {\n      vm._staticTrees = [];\n    }\n    // set parent vnode. this allows render functions to have access\n    // to the data on the placeholder node.\n    vm.$vnode = _parentVnode;\n    // render self\n    var vnode;\n    try {\n      vnode = render.call(vm._renderProxy, vm.$createElement);\n    } catch (e) {\n      handleError(e, vm, \"render function\");\n      // return error render result,\n      // or previous vnode to prevent render error causing blank component\n      /* istanbul ignore else */\n      {\n        vnode = vm.$options.renderError\n          ? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)\n          : vm._vnode;\n      }\n    }\n    // return empty vnode in case the render function errored out\n    if (!(vnode instanceof VNode)) {\n      if (\"development\" !== 'production' && Array.isArray(vnode)) {\n        warn(\n          'Multiple root nodes returned from render function. Render function ' +\n          'should return a single root node.',\n          vm\n        );\n      }\n      vnode = createEmptyVNode();\n    }\n    // set parent\n    vnode.parent = _parentVnode;\n    return vnode\n  };\n\n  // internal render helpers.\n  // these are exposed on the instance prototype to reduce generated render\n  // code size.\n  Vue.prototype._o = markOnce;\n  Vue.prototype._n = toNumber;\n  Vue.prototype._s = toString;\n  Vue.prototype._l = renderList;\n  Vue.prototype._t = renderSlot;\n  Vue.prototype._q = looseEqual;\n  Vue.prototype._i = looseIndexOf;\n  Vue.prototype._m = renderStatic;\n  Vue.prototype._f = resolveFilter;\n  Vue.prototype._k = checkKeyCodes;\n  Vue.prototype._b = bindObjectProps;\n  Vue.prototype._v = createTextVNode;\n  Vue.prototype._e = createEmptyVNode;\n  Vue.prototype._u = resolveScopedSlots;\n  Vue.prototype._g = bindObjectListeners;\n}\n\n/*  */\n\nvar uid$1 = 0;\n\nfunction initMixin (Vue) {\n  Vue.prototype._init = function (options) {\n    var vm = this;\n    // a uid\n    vm._uid = uid$1++;\n\n    var startTag, endTag;\n    /* istanbul ignore if */\n    if (\"development\" !== 'production' && config.performance && mark) {\n      startTag = \"vue-perf-init:\" + (vm._uid);\n      endTag = \"vue-perf-end:\" + (vm._uid);\n      mark(startTag);\n    }\n\n    // a flag to avoid this being observed\n    vm._isVue = true;\n    // merge options\n    if (options && options._isComponent) {\n      // optimize internal component instantiation\n      // since dynamic options merging is pretty slow, and none of the\n      // internal component options needs special treatment.\n      initInternalComponent(vm, options);\n    } else {\n      vm.$options = mergeOptions(\n        resolveConstructorOptions(vm.constructor),\n        options || {},\n        vm\n      );\n    }\n    /* istanbul ignore else */\n    {\n      initProxy(vm);\n    }\n    // expose real self\n    vm._self = vm;\n    initLifecycle(vm);\n    initEvents(vm);\n    initRender(vm);\n    callHook(vm, 'beforeCreate');\n    initInjections(vm); // resolve injections before data/props\n    initState(vm);\n    initProvide(vm); // resolve provide after data/props\n    callHook(vm, 'created');\n\n    /* istanbul ignore if */\n    if (\"development\" !== 'production' && config.performance && mark) {\n      vm._name = formatComponentName(vm, false);\n      mark(endTag);\n      measure(((vm._name) + \" init\"), startTag, endTag);\n    }\n\n    if (vm.$options.el) {\n      vm.$mount(vm.$options.el);\n    }\n  };\n}\n\nfunction initInternalComponent (vm, options) {\n  var opts = vm.$options = Object.create(vm.constructor.options);\n  // doing this because it's faster than dynamic enumeration.\n  opts.parent = options.parent;\n  opts.propsData = options.propsData;\n  opts._parentVnode = options._parentVnode;\n  opts._parentListeners = options._parentListeners;\n  opts._renderChildren = options._renderChildren;\n  opts._componentTag = options._componentTag;\n  opts._parentElm = options._parentElm;\n  opts._refElm = options._refElm;\n  if (options.render) {\n    opts.render = options.render;\n    opts.staticRenderFns = options.staticRenderFns;\n  }\n}\n\nfunction resolveConstructorOptions (Ctor) {\n  var options = Ctor.options;\n  if (Ctor.super) {\n    var superOptions = resolveConstructorOptions(Ctor.super);\n    var cachedSuperOptions = Ctor.superOptions;\n    if (superOptions !== cachedSuperOptions) {\n      // super option changed,\n      // need to resolve new options.\n      Ctor.superOptions = superOptions;\n      // check if there are any late-modified/attached options (#4976)\n      var modifiedOptions = resolveModifiedOptions(Ctor);\n      // update base extend options\n      if (modifiedOptions) {\n        extend(Ctor.extendOptions, modifiedOptions);\n      }\n      options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);\n      if (options.name) {\n        options.components[options.name] = Ctor;\n      }\n    }\n  }\n  return options\n}\n\nfunction resolveModifiedOptions (Ctor) {\n  var modified;\n  var latest = Ctor.options;\n  var extended = Ctor.extendOptions;\n  var sealed = Ctor.sealedOptions;\n  for (var key in latest) {\n    if (latest[key] !== sealed[key]) {\n      if (!modified) { modified = {}; }\n      modified[key] = dedupe(latest[key], extended[key], sealed[key]);\n    }\n  }\n  return modified\n}\n\nfunction dedupe (latest, extended, sealed) {\n  // compare latest and sealed to ensure lifecycle hooks won't be duplicated\n  // between merges\n  if (Array.isArray(latest)) {\n    var res = [];\n    sealed = Array.isArray(sealed) ? sealed : [sealed];\n    extended = Array.isArray(extended) ? extended : [extended];\n    for (var i = 0; i < latest.length; i++) {\n      // push original options and not sealed options to exclude duplicated options\n      if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {\n        res.push(latest[i]);\n      }\n    }\n    return res\n  } else {\n    return latest\n  }\n}\n\nfunction Vue$3 (options) {\n  if (\"development\" !== 'production' &&\n    !(this instanceof Vue$3)\n  ) {\n    warn('Vue is a constructor and should be called with the `new` keyword');\n  }\n  this._init(options);\n}\n\ninitMixin(Vue$3);\nstateMixin(Vue$3);\neventsMixin(Vue$3);\nlifecycleMixin(Vue$3);\nrenderMixin(Vue$3);\n\n/*  */\n\nfunction initUse (Vue) {\n  Vue.use = function (plugin) {\n    var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));\n    if (installedPlugins.indexOf(plugin) > -1) {\n      return this\n    }\n\n    // additional parameters\n    var args = toArray(arguments, 1);\n    args.unshift(this);\n    if (typeof plugin.install === 'function') {\n      plugin.install.apply(plugin, args);\n    } else if (typeof plugin === 'function') {\n      plugin.apply(null, args);\n    }\n    installedPlugins.push(plugin);\n    return this\n  };\n}\n\n/*  */\n\nfunction initMixin$1 (Vue) {\n  Vue.mixin = function (mixin) {\n    this.options = mergeOptions(this.options, mixin);\n    return this\n  };\n}\n\n/*  */\n\nfunction initExtend (Vue) {\n  /**\n   * Each instance constructor, including Vue, has a unique\n   * cid. This enables us to create wrapped \"child\n   * constructors\" for prototypal inheritance and cache them.\n   */\n  Vue.cid = 0;\n  var cid = 1;\n\n  /**\n   * Class inheritance\n   */\n  Vue.extend = function (extendOptions) {\n    extendOptions = extendOptions || {};\n    var Super = this;\n    var SuperId = Super.cid;\n    var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});\n    if (cachedCtors[SuperId]) {\n      return cachedCtors[SuperId]\n    }\n\n    var name = extendOptions.name || Super.options.name;\n    {\n      if (!/^[a-zA-Z][\\w-]*$/.test(name)) {\n        warn(\n          'Invalid component name: \"' + name + '\". Component names ' +\n          'can only contain alphanumeric characters and the hyphen, ' +\n          'and must start with a letter.'\n        );\n      }\n    }\n\n    var Sub = function VueComponent (options) {\n      this._init(options);\n    };\n    Sub.prototype = Object.create(Super.prototype);\n    Sub.prototype.constructor = Sub;\n    Sub.cid = cid++;\n    Sub.options = mergeOptions(\n      Super.options,\n      extendOptions\n    );\n    Sub['super'] = Super;\n\n    // For props and computed properties, we define the proxy getters on\n    // the Vue instances at extension time, on the extended prototype. This\n    // avoids Object.defineProperty calls for each instance created.\n    if (Sub.options.props) {\n      initProps$1(Sub);\n    }\n    if (Sub.options.computed) {\n      initComputed$1(Sub);\n    }\n\n    // allow further extension/mixin/plugin usage\n    Sub.extend = Super.extend;\n    Sub.mixin = Super.mixin;\n    Sub.use = Super.use;\n\n    // create asset registers, so extended classes\n    // can have their private assets too.\n    ASSET_TYPES.forEach(function (type) {\n      Sub[type] = Super[type];\n    });\n    // enable recursive self-lookup\n    if (name) {\n      Sub.options.components[name] = Sub;\n    }\n\n    // keep a reference to the super options at extension time.\n    // later at instantiation we can check if Super's options have\n    // been updated.\n    Sub.superOptions = Super.options;\n    Sub.extendOptions = extendOptions;\n    Sub.sealedOptions = extend({}, Sub.options);\n\n    // cache constructor\n    cachedCtors[SuperId] = Sub;\n    return Sub\n  };\n}\n\nfunction initProps$1 (Comp) {\n  var props = Comp.options.props;\n  for (var key in props) {\n    proxy(Comp.prototype, \"_props\", key);\n  }\n}\n\nfunction initComputed$1 (Comp) {\n  var computed = Comp.options.computed;\n  for (var key in computed) {\n    defineComputed(Comp.prototype, key, computed[key]);\n  }\n}\n\n/*  */\n\nfunction initAssetRegisters (Vue) {\n  /**\n   * Create asset registration methods.\n   */\n  ASSET_TYPES.forEach(function (type) {\n    Vue[type] = function (\n      id,\n      definition\n    ) {\n      if (!definition) {\n        return this.options[type + 's'][id]\n      } else {\n        /* istanbul ignore if */\n        {\n          if (type === 'component' && config.isReservedTag(id)) {\n            warn(\n              'Do not use built-in or reserved HTML elements as component ' +\n              'id: ' + id\n            );\n          }\n        }\n        if (type === 'component' && isPlainObject(definition)) {\n          definition.name = definition.name || id;\n          definition = this.options._base.extend(definition);\n        }\n        if (type === 'directive' && typeof definition === 'function') {\n          definition = { bind: definition, update: definition };\n        }\n        this.options[type + 's'][id] = definition;\n        return definition\n      }\n    };\n  });\n}\n\n/*  */\n\nvar patternTypes = [String, RegExp, Array];\n\nfunction getComponentName (opts) {\n  return opts && (opts.Ctor.options.name || opts.tag)\n}\n\nfunction matches (pattern, name) {\n  if (Array.isArray(pattern)) {\n    return pattern.indexOf(name) > -1\n  } else if (typeof pattern === 'string') {\n    return pattern.split(',').indexOf(name) > -1\n  } else if (isRegExp(pattern)) {\n    return pattern.test(name)\n  }\n  /* istanbul ignore next */\n  return false\n}\n\nfunction pruneCache (cache, current, filter) {\n  for (var key in cache) {\n    var cachedNode = cache[key];\n    if (cachedNode) {\n      var name = getComponentName(cachedNode.componentOptions);\n      if (name && !filter(name)) {\n        if (cachedNode !== current) {\n          pruneCacheEntry(cachedNode);\n        }\n        cache[key] = null;\n      }\n    }\n  }\n}\n\nfunction pruneCacheEntry (vnode) {\n  if (vnode) {\n    vnode.componentInstance.$destroy();\n  }\n}\n\nvar KeepAlive = {\n  name: 'keep-alive',\n  abstract: true,\n\n  props: {\n    include: patternTypes,\n    exclude: patternTypes\n  },\n\n  created: function created () {\n    this.cache = Object.create(null);\n  },\n\n  destroyed: function destroyed () {\n    var this$1 = this;\n\n    for (var key in this$1.cache) {\n      pruneCacheEntry(this$1.cache[key]);\n    }\n  },\n\n  watch: {\n    include: function include (val) {\n      pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); });\n    },\n    exclude: function exclude (val) {\n      pruneCache(this.cache, this._vnode, function (name) { return !matches(val, name); });\n    }\n  },\n\n  render: function render () {\n    var vnode = getFirstComponentChild(this.$slots.default);\n    var componentOptions = vnode && vnode.componentOptions;\n    if (componentOptions) {\n      // check pattern\n      var name = getComponentName(componentOptions);\n      if (name && (\n        (this.include && !matches(this.include, name)) ||\n        (this.exclude && matches(this.exclude, name))\n      )) {\n        return vnode\n      }\n      var key = vnode.key == null\n        // same constructor may get registered as different local components\n        // so cid alone is not enough (#3269)\n        ? componentOptions.Ctor.cid + (componentOptions.tag ? (\"::\" + (componentOptions.tag)) : '')\n        : vnode.key;\n      if (this.cache[key]) {\n        vnode.componentInstance = this.cache[key].componentInstance;\n      } else {\n        this.cache[key] = vnode;\n      }\n      vnode.data.keepAlive = true;\n    }\n    return vnode\n  }\n};\n\nvar builtInComponents = {\n  KeepAlive: KeepAlive\n};\n\n/*  */\n\nfunction initGlobalAPI (Vue) {\n  // config\n  var configDef = {};\n  configDef.get = function () { return config; };\n  {\n    configDef.set = function () {\n      warn(\n        'Do not replace the Vue.config object, set individual fields instead.'\n      );\n    };\n  }\n  Object.defineProperty(Vue, 'config', configDef);\n\n  // exposed util methods.\n  // NOTE: these are not considered part of the public API - avoid relying on\n  // them unless you are aware of the risk.\n  Vue.util = {\n    warn: warn,\n    extend: extend,\n    mergeOptions: mergeOptions,\n    defineReactive: defineReactive$$1\n  };\n\n  Vue.set = set;\n  Vue.delete = del;\n  Vue.nextTick = nextTick;\n\n  Vue.options = Object.create(null);\n  ASSET_TYPES.forEach(function (type) {\n    Vue.options[type + 's'] = Object.create(null);\n  });\n\n  // this is used to identify the \"base\" constructor to extend all plain-object\n  // components with in Weex's multi-instance scenarios.\n  Vue.options._base = Vue;\n\n  extend(Vue.options.components, builtInComponents);\n\n  initUse(Vue);\n  initMixin$1(Vue);\n  initExtend(Vue);\n  initAssetRegisters(Vue);\n}\n\ninitGlobalAPI(Vue$3);\n\nObject.defineProperty(Vue$3.prototype, '$isServer', {\n  get: isServerRendering\n});\n\nObject.defineProperty(Vue$3.prototype, '$ssrContext', {\n  get: function get () {\n    /* istanbul ignore next */\n    return this.$vnode && this.$vnode.ssrContext\n  }\n});\n\nVue$3.version = '2.4.4';\n\n/*  */\n\n// these are reserved for web because they are directly compiled away\n// during template compilation\nvar isReservedAttr = makeMap('style,class');\n\n// attributes that should be using props for binding\nvar acceptValue = makeMap('input,textarea,option,select,progress');\nvar mustUseProp = function (tag, type, attr) {\n  return (\n    (attr === 'value' && acceptValue(tag)) && type !== 'button' ||\n    (attr === 'selected' && tag === 'option') ||\n    (attr === 'checked' && tag === 'input') ||\n    (attr === 'muted' && tag === 'video')\n  )\n};\n\nvar isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');\n\nvar isBooleanAttr = makeMap(\n  'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +\n  'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +\n  'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +\n  'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +\n  'required,reversed,scoped,seamless,selected,sortable,translate,' +\n  'truespeed,typemustmatch,visible'\n);\n\nvar xlinkNS = 'http://www.w3.org/1999/xlink';\n\nvar isXlink = function (name) {\n  return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'\n};\n\nvar getXlinkProp = function (name) {\n  return isXlink(name) ? name.slice(6, name.length) : ''\n};\n\nvar isFalsyAttrValue = function (val) {\n  return val == null || val === false\n};\n\n/*  */\n\nfunction genClassForVnode (vnode) {\n  var data = vnode.data;\n  var parentNode = vnode;\n  var childNode = vnode;\n  while (isDef(childNode.componentInstance)) {\n    childNode = childNode.componentInstance._vnode;\n    if (childNode.data) {\n      data = mergeClassData(childNode.data, data);\n    }\n  }\n  while (isDef(parentNode = parentNode.parent)) {\n    if (parentNode.data) {\n      data = mergeClassData(data, parentNode.data);\n    }\n  }\n  return renderClass(data.staticClass, data.class)\n}\n\nfunction mergeClassData (child, parent) {\n  return {\n    staticClass: concat(child.staticClass, parent.staticClass),\n    class: isDef(child.class)\n      ? [child.class, parent.class]\n      : parent.class\n  }\n}\n\nfunction renderClass (\n  staticClass,\n  dynamicClass\n) {\n  if (isDef(staticClass) || isDef(dynamicClass)) {\n    return concat(staticClass, stringifyClass(dynamicClass))\n  }\n  /* istanbul ignore next */\n  return ''\n}\n\nfunction concat (a, b) {\n  return a ? b ? (a + ' ' + b) : a : (b || '')\n}\n\nfunction stringifyClass (value) {\n  if (Array.isArray(value)) {\n    return stringifyArray(value)\n  }\n  if (isObject(value)) {\n    return stringifyObject(value)\n  }\n  if (typeof value === 'string') {\n    return value\n  }\n  /* istanbul ignore next */\n  return ''\n}\n\nfunction stringifyArray (value) {\n  var res = '';\n  var stringified;\n  for (var i = 0, l = value.length; i < l; i++) {\n    if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {\n      if (res) { res += ' '; }\n      res += stringified;\n    }\n  }\n  return res\n}\n\nfunction stringifyObject (value) {\n  var res = '';\n  for (var key in value) {\n    if (value[key]) {\n      if (res) { res += ' '; }\n      res += key;\n    }\n  }\n  return res\n}\n\n/*  */\n\nvar namespaceMap = {\n  svg: 'http://www.w3.org/2000/svg',\n  math: 'http://www.w3.org/1998/Math/MathML'\n};\n\nvar isHTMLTag = makeMap(\n  'html,body,base,head,link,meta,style,title,' +\n  'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +\n  'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +\n  'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +\n  's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +\n  'embed,object,param,source,canvas,script,noscript,del,ins,' +\n  'caption,col,colgroup,table,thead,tbody,td,th,tr,' +\n  'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +\n  'output,progress,select,textarea,' +\n  'details,dialog,menu,menuitem,summary,' +\n  'content,element,shadow,template,blockquote,iframe,tfoot'\n);\n\n// this map is intentionally selective, only covering SVG elements that may\n// contain child elements.\nvar isSVG = makeMap(\n  'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +\n  'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +\n  'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',\n  true\n);\n\nvar isPreTag = function (tag) { return tag === 'pre'; };\n\nvar isReservedTag = function (tag) {\n  return isHTMLTag(tag) || isSVG(tag)\n};\n\nfunction getTagNamespace (tag) {\n  if (isSVG(tag)) {\n    return 'svg'\n  }\n  // basic support for MathML\n  // note it doesn't support other MathML elements being component roots\n  if (tag === 'math') {\n    return 'math'\n  }\n}\n\nvar unknownElementCache = Object.create(null);\nfunction isUnknownElement (tag) {\n  /* istanbul ignore if */\n  if (!inBrowser) {\n    return true\n  }\n  if (isReservedTag(tag)) {\n    return false\n  }\n  tag = tag.toLowerCase();\n  /* istanbul ignore if */\n  if (unknownElementCache[tag] != null) {\n    return unknownElementCache[tag]\n  }\n  var el = document.createElement(tag);\n  if (tag.indexOf('-') > -1) {\n    // http://stackoverflow.com/a/28210364/1070244\n    return (unknownElementCache[tag] = (\n      el.constructor === window.HTMLUnknownElement ||\n      el.constructor === window.HTMLElement\n    ))\n  } else {\n    return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))\n  }\n}\n\nvar isTextInputType = makeMap('text,number,password,search,email,tel,url');\n\n/*  */\n\n/**\n * Query an element selector if it's not an element already.\n */\nfunction query (el) {\n  if (typeof el === 'string') {\n    var selected = document.querySelector(el);\n    if (!selected) {\n      \"development\" !== 'production' && warn(\n        'Cannot find element: ' + el\n      );\n      return document.createElement('div')\n    }\n    return selected\n  } else {\n    return el\n  }\n}\n\n/*  */\n\nfunction createElement$1 (tagName, vnode) {\n  var elm = document.createElement(tagName);\n  if (tagName !== 'select') {\n    return elm\n  }\n  // false or null will remove the attribute but undefined will not\n  if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {\n    elm.setAttribute('multiple', 'multiple');\n  }\n  return elm\n}\n\nfunction createElementNS (namespace, tagName) {\n  return document.createElementNS(namespaceMap[namespace], tagName)\n}\n\nfunction createTextNode (text) {\n  return document.createTextNode(text)\n}\n\nfunction createComment (text) {\n  return document.createComment(text)\n}\n\nfunction insertBefore (parentNode, newNode, referenceNode) {\n  parentNode.insertBefore(newNode, referenceNode);\n}\n\nfunction removeChild (node, child) {\n  node.removeChild(child);\n}\n\nfunction appendChild (node, child) {\n  node.appendChild(child);\n}\n\nfunction parentNode (node) {\n  return node.parentNode\n}\n\nfunction nextSibling (node) {\n  return node.nextSibling\n}\n\nfunction tagName (node) {\n  return node.tagName\n}\n\nfunction setTextContent (node, text) {\n  node.textContent = text;\n}\n\nfunction setAttribute (node, key, val) {\n  node.setAttribute(key, val);\n}\n\n\nvar nodeOps = Object.freeze({\n\tcreateElement: createElement$1,\n\tcreateElementNS: createElementNS,\n\tcreateTextNode: createTextNode,\n\tcreateComment: createComment,\n\tinsertBefore: insertBefore,\n\tremoveChild: removeChild,\n\tappendChild: appendChild,\n\tparentNode: parentNode,\n\tnextSibling: nextSibling,\n\ttagName: tagName,\n\tsetTextContent: setTextContent,\n\tsetAttribute: setAttribute\n});\n\n/*  */\n\nvar ref = {\n  create: function create (_, vnode) {\n    registerRef(vnode);\n  },\n  update: function update (oldVnode, vnode) {\n    if (oldVnode.data.ref !== vnode.data.ref) {\n      registerRef(oldVnode, true);\n      registerRef(vnode);\n    }\n  },\n  destroy: function destroy (vnode) {\n    registerRef(vnode, true);\n  }\n};\n\nfunction registerRef (vnode, isRemoval) {\n  var key = vnode.data.ref;\n  if (!key) { return }\n\n  var vm = vnode.context;\n  var ref = vnode.componentInstance || vnode.elm;\n  var refs = vm.$refs;\n  if (isRemoval) {\n    if (Array.isArray(refs[key])) {\n      remove(refs[key], ref);\n    } else if (refs[key] === ref) {\n      refs[key] = undefined;\n    }\n  } else {\n    if (vnode.data.refInFor) {\n      if (!Array.isArray(refs[key])) {\n        refs[key] = [ref];\n      } else if (refs[key].indexOf(ref) < 0) {\n        // $flow-disable-line\n        refs[key].push(ref);\n      }\n    } else {\n      refs[key] = ref;\n    }\n  }\n}\n\n/**\n * Virtual DOM patching algorithm based on Snabbdom by\n * Simon Friis Vindum (@paldepind)\n * Licensed under the MIT License\n * https://github.com/paldepind/snabbdom/blob/master/LICENSE\n *\n * modified by Evan You (@yyx990803)\n *\n * Not type-checking this because this file is perf-critical and the cost\n * of making flow understand it is not worth it.\n */\n\nvar emptyNode = new VNode('', {}, []);\n\nvar hooks = ['create', 'activate', 'update', 'remove', 'destroy'];\n\nfunction sameVnode (a, b) {\n  return (\n    a.key === b.key && (\n      (\n        a.tag === b.tag &&\n        a.isComment === b.isComment &&\n        isDef(a.data) === isDef(b.data) &&\n        sameInputType(a, b)\n      ) || (\n        isTrue(a.isAsyncPlaceholder) &&\n        a.asyncFactory === b.asyncFactory &&\n        isUndef(b.asyncFactory.error)\n      )\n    )\n  )\n}\n\nfunction sameInputType (a, b) {\n  if (a.tag !== 'input') { return true }\n  var i;\n  var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;\n  var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;\n  return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)\n}\n\nfunction createKeyToOldIdx (children, beginIdx, endIdx) {\n  var i, key;\n  var map = {};\n  for (i = beginIdx; i <= endIdx; ++i) {\n    key = children[i].key;\n    if (isDef(key)) { map[key] = i; }\n  }\n  return map\n}\n\nfunction createPatchFunction (backend) {\n  var i, j;\n  var cbs = {};\n\n  var modules = backend.modules;\n  var nodeOps = backend.nodeOps;\n\n  for (i = 0; i < hooks.length; ++i) {\n    cbs[hooks[i]] = [];\n    for (j = 0; j < modules.length; ++j) {\n      if (isDef(modules[j][hooks[i]])) {\n        cbs[hooks[i]].push(modules[j][hooks[i]]);\n      }\n    }\n  }\n\n  function emptyNodeAt (elm) {\n    return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)\n  }\n\n  function createRmCb (childElm, listeners) {\n    function remove$$1 () {\n      if (--remove$$1.listeners === 0) {\n        removeNode(childElm);\n      }\n    }\n    remove$$1.listeners = listeners;\n    return remove$$1\n  }\n\n  function removeNode (el) {\n    var parent = nodeOps.parentNode(el);\n    // element may have already been removed due to v-html / v-text\n    if (isDef(parent)) {\n      nodeOps.removeChild(parent, el);\n    }\n  }\n\n  var inPre = 0;\n  function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {\n    vnode.isRootInsert = !nested; // for transition enter check\n    if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {\n      return\n    }\n\n    var data = vnode.data;\n    var children = vnode.children;\n    var tag = vnode.tag;\n    if (isDef(tag)) {\n      {\n        if (data && data.pre) {\n          inPre++;\n        }\n        if (\n          !inPre &&\n          !vnode.ns &&\n          !(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) &&\n          config.isUnknownElement(tag)\n        ) {\n          warn(\n            'Unknown custom element: <' + tag + '> - did you ' +\n            'register the component correctly? For recursive components, ' +\n            'make sure to provide the \"name\" option.',\n            vnode.context\n          );\n        }\n      }\n      vnode.elm = vnode.ns\n        ? nodeOps.createElementNS(vnode.ns, tag)\n        : nodeOps.createElement(tag, vnode);\n      setScope(vnode);\n\n      /* istanbul ignore if */\n      {\n        createChildren(vnode, children, insertedVnodeQueue);\n        if (isDef(data)) {\n          invokeCreateHooks(vnode, insertedVnodeQueue);\n        }\n        insert(parentElm, vnode.elm, refElm);\n      }\n\n      if (\"development\" !== 'production' && data && data.pre) {\n        inPre--;\n      }\n    } else if (isTrue(vnode.isComment)) {\n      vnode.elm = nodeOps.createComment(vnode.text);\n      insert(parentElm, vnode.elm, refElm);\n    } else {\n      vnode.elm = nodeOps.createTextNode(vnode.text);\n      insert(parentElm, vnode.elm, refElm);\n    }\n  }\n\n  function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {\n    var i = vnode.data;\n    if (isDef(i)) {\n      var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;\n      if (isDef(i = i.hook) && isDef(i = i.init)) {\n        i(vnode, false /* hydrating */, parentElm, refElm);\n      }\n      // after calling the init hook, if the vnode is a child component\n      // it should've created a child instance and mounted it. the child\n      // component also has set the placeholder vnode's elm.\n      // in that case we can just return the element and be done.\n      if (isDef(vnode.componentInstance)) {\n        initComponent(vnode, insertedVnodeQueue);\n        if (isTrue(isReactivated)) {\n          reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);\n        }\n        return true\n      }\n    }\n  }\n\n  function initComponent (vnode, insertedVnodeQueue) {\n    if (isDef(vnode.data.pendingInsert)) {\n      insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);\n      vnode.data.pendingInsert = null;\n    }\n    vnode.elm = vnode.componentInstance.$el;\n    if (isPatchable(vnode)) {\n      invokeCreateHooks(vnode, insertedVnodeQueue);\n      setScope(vnode);\n    } else {\n      // empty component root.\n      // skip all element-related modules except for ref (#3455)\n      registerRef(vnode);\n      // make sure to invoke the insert hook\n      insertedVnodeQueue.push(vnode);\n    }\n  }\n\n  function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {\n    var i;\n    // hack for #4339: a reactivated component with inner transition\n    // does not trigger because the inner node's created hooks are not called\n    // again. It's not ideal to involve module-specific logic in here but\n    // there doesn't seem to be a better way to do it.\n    var innerNode = vnode;\n    while (innerNode.componentInstance) {\n      innerNode = innerNode.componentInstance._vnode;\n      if (isDef(i = innerNode.data) && isDef(i = i.transition)) {\n        for (i = 0; i < cbs.activate.length; ++i) {\n          cbs.activate[i](emptyNode, innerNode);\n        }\n        insertedVnodeQueue.push(innerNode);\n        break\n      }\n    }\n    // unlike a newly created component,\n    // a reactivated keep-alive component doesn't insert itself\n    insert(parentElm, vnode.elm, refElm);\n  }\n\n  function insert (parent, elm, ref$$1) {\n    if (isDef(parent)) {\n      if (isDef(ref$$1)) {\n        if (ref$$1.parentNode === parent) {\n          nodeOps.insertBefore(parent, elm, ref$$1);\n        }\n      } else {\n        nodeOps.appendChild(parent, elm);\n      }\n    }\n  }\n\n  function createChildren (vnode, children, insertedVnodeQueue) {\n    if (Array.isArray(children)) {\n      for (var i = 0; i < children.length; ++i) {\n        createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);\n      }\n    } else if (isPrimitive(vnode.text)) {\n      nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));\n    }\n  }\n\n  function isPatchable (vnode) {\n    while (vnode.componentInstance) {\n      vnode = vnode.componentInstance._vnode;\n    }\n    return isDef(vnode.tag)\n  }\n\n  function invokeCreateHooks (vnode, insertedVnodeQueue) {\n    for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {\n      cbs.create[i$1](emptyNode, vnode);\n    }\n    i = vnode.data.hook; // Reuse variable\n    if (isDef(i)) {\n      if (isDef(i.create)) { i.create(emptyNode, vnode); }\n      if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }\n    }\n  }\n\n  // set scope id attribute for scoped CSS.\n  // this is implemented as a special case to avoid the overhead\n  // of going through the normal attribute patching process.\n  function setScope (vnode) {\n    var i;\n    var ancestor = vnode;\n    while (ancestor) {\n      if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n        nodeOps.setAttribute(vnode.elm, i, '');\n      }\n      ancestor = ancestor.parent;\n    }\n    // for slot content they should also get the scopeId from the host instance.\n    if (isDef(i = activeInstance) &&\n      i !== vnode.context &&\n      isDef(i = i.$options._scopeId)\n    ) {\n      nodeOps.setAttribute(vnode.elm, i, '');\n    }\n  }\n\n  function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {\n    for (; startIdx <= endIdx; ++startIdx) {\n      createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);\n    }\n  }\n\n  function invokeDestroyHook (vnode) {\n    var i, j;\n    var data = vnode.data;\n    if (isDef(data)) {\n      if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }\n      for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }\n    }\n    if (isDef(i = vnode.children)) {\n      for (j = 0; j < vnode.children.length; ++j) {\n        invokeDestroyHook(vnode.children[j]);\n      }\n    }\n  }\n\n  function removeVnodes (parentElm, vnodes, startIdx, endIdx) {\n    for (; startIdx <= endIdx; ++startIdx) {\n      var ch = vnodes[startIdx];\n      if (isDef(ch)) {\n        if (isDef(ch.tag)) {\n          removeAndInvokeRemoveHook(ch);\n          invokeDestroyHook(ch);\n        } else { // Text node\n          removeNode(ch.elm);\n        }\n      }\n    }\n  }\n\n  function removeAndInvokeRemoveHook (vnode, rm) {\n    if (isDef(rm) || isDef(vnode.data)) {\n      var i;\n      var listeners = cbs.remove.length + 1;\n      if (isDef(rm)) {\n        // we have a recursively passed down rm callback\n        // increase the listeners count\n        rm.listeners += listeners;\n      } else {\n        // directly removing\n        rm = createRmCb(vnode.elm, listeners);\n      }\n      // recursively invoke hooks on child component root node\n      if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {\n        removeAndInvokeRemoveHook(i, rm);\n      }\n      for (i = 0; i < cbs.remove.length; ++i) {\n        cbs.remove[i](vnode, rm);\n      }\n      if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {\n        i(vnode, rm);\n      } else {\n        rm();\n      }\n    } else {\n      removeNode(vnode.elm);\n    }\n  }\n\n  function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {\n    var oldStartIdx = 0;\n    var newStartIdx = 0;\n    var oldEndIdx = oldCh.length - 1;\n    var oldStartVnode = oldCh[0];\n    var oldEndVnode = oldCh[oldEndIdx];\n    var newEndIdx = newCh.length - 1;\n    var newStartVnode = newCh[0];\n    var newEndVnode = newCh[newEndIdx];\n    var oldKeyToIdx, idxInOld, elmToMove, refElm;\n\n    // removeOnly is a special flag used only by <transition-group>\n    // to ensure removed elements stay in correct relative positions\n    // during leaving transitions\n    var canMove = !removeOnly;\n\n    while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n      if (isUndef(oldStartVnode)) {\n        oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left\n      } else if (isUndef(oldEndVnode)) {\n        oldEndVnode = oldCh[--oldEndIdx];\n      } else if (sameVnode(oldStartVnode, newStartVnode)) {\n        patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);\n        oldStartVnode = oldCh[++oldStartIdx];\n        newStartVnode = newCh[++newStartIdx];\n      } else if (sameVnode(oldEndVnode, newEndVnode)) {\n        patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);\n        oldEndVnode = oldCh[--oldEndIdx];\n        newEndVnode = newCh[--newEndIdx];\n      } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right\n        patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);\n        canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));\n        oldStartVnode = oldCh[++oldStartIdx];\n        newEndVnode = newCh[--newEndIdx];\n      } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left\n        patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);\n        canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);\n        oldEndVnode = oldCh[--oldEndIdx];\n        newStartVnode = newCh[++newStartIdx];\n      } else {\n        if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }\n        idxInOld = isDef(newStartVnode.key)\n          ? oldKeyToIdx[newStartVnode.key]\n          : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx);\n        if (isUndef(idxInOld)) { // New element\n          createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);\n        } else {\n          elmToMove = oldCh[idxInOld];\n          /* istanbul ignore if */\n          if (\"development\" !== 'production' && !elmToMove) {\n            warn(\n              'It seems there are duplicate keys that is causing an update error. ' +\n              'Make sure each v-for item has a unique key.'\n            );\n          }\n          if (sameVnode(elmToMove, newStartVnode)) {\n            patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);\n            oldCh[idxInOld] = undefined;\n            canMove && nodeOps.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);\n          } else {\n            // same key but different element. treat as new element\n            createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);\n          }\n        }\n        newStartVnode = newCh[++newStartIdx];\n      }\n    }\n    if (oldStartIdx > oldEndIdx) {\n      refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;\n      addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);\n    } else if (newStartIdx > newEndIdx) {\n      removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);\n    }\n  }\n\n  function findIdxInOld (node, oldCh, start, end) {\n    for (var i = start; i < end; i++) {\n      var c = oldCh[i];\n      if (isDef(c) && sameVnode(node, c)) { return i }\n    }\n  }\n\n  function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {\n    if (oldVnode === vnode) {\n      return\n    }\n\n    var elm = vnode.elm = oldVnode.elm;\n\n    if (isTrue(oldVnode.isAsyncPlaceholder)) {\n      if (isDef(vnode.asyncFactory.resolved)) {\n        hydrate(oldVnode.elm, vnode, insertedVnodeQueue);\n      } else {\n        vnode.isAsyncPlaceholder = true;\n      }\n      return\n    }\n\n    // reuse element for static trees.\n    // note we only do this if the vnode is cloned -\n    // if the new node is not cloned it means the render functions have been\n    // reset by the hot-reload-api and we need to do a proper re-render.\n    if (isTrue(vnode.isStatic) &&\n      isTrue(oldVnode.isStatic) &&\n      vnode.key === oldVnode.key &&\n      (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))\n    ) {\n      vnode.componentInstance = oldVnode.componentInstance;\n      return\n    }\n\n    var i;\n    var data = vnode.data;\n    if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {\n      i(oldVnode, vnode);\n    }\n\n    var oldCh = oldVnode.children;\n    var ch = vnode.children;\n    if (isDef(data) && isPatchable(vnode)) {\n      for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }\n      if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }\n    }\n    if (isUndef(vnode.text)) {\n      if (isDef(oldCh) && isDef(ch)) {\n        if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }\n      } else if (isDef(ch)) {\n        if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }\n        addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);\n      } else if (isDef(oldCh)) {\n        removeVnodes(elm, oldCh, 0, oldCh.length - 1);\n      } else if (isDef(oldVnode.text)) {\n        nodeOps.setTextContent(elm, '');\n      }\n    } else if (oldVnode.text !== vnode.text) {\n      nodeOps.setTextContent(elm, vnode.text);\n    }\n    if (isDef(data)) {\n      if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }\n    }\n  }\n\n  function invokeInsertHook (vnode, queue, initial) {\n    // delay insert hooks for component root nodes, invoke them after the\n    // element is really inserted\n    if (isTrue(initial) && isDef(vnode.parent)) {\n      vnode.parent.data.pendingInsert = queue;\n    } else {\n      for (var i = 0; i < queue.length; ++i) {\n        queue[i].data.hook.insert(queue[i]);\n      }\n    }\n  }\n\n  var bailed = false;\n  // list of modules that can skip create hook during hydration because they\n  // are already rendered on the client or has no need for initialization\n  var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');\n\n  // Note: this is a browser-only function so we can assume elms are DOM nodes.\n  function hydrate (elm, vnode, insertedVnodeQueue) {\n    if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {\n      vnode.elm = elm;\n      vnode.isAsyncPlaceholder = true;\n      return true\n    }\n    {\n      if (!assertNodeMatch(elm, vnode)) {\n        return false\n      }\n    }\n    vnode.elm = elm;\n    var tag = vnode.tag;\n    var data = vnode.data;\n    var children = vnode.children;\n    if (isDef(data)) {\n      if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }\n      if (isDef(i = vnode.componentInstance)) {\n        // child component. it should have hydrated its own tree.\n        initComponent(vnode, insertedVnodeQueue);\n        return true\n      }\n    }\n    if (isDef(tag)) {\n      if (isDef(children)) {\n        // empty element, allow client to pick up and populate children\n        if (!elm.hasChildNodes()) {\n          createChildren(vnode, children, insertedVnodeQueue);\n        } else {\n          // v-html and domProps: innerHTML\n          if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {\n            if (i !== elm.innerHTML) {\n              /* istanbul ignore if */\n              if (\"development\" !== 'production' &&\n                typeof console !== 'undefined' &&\n                !bailed\n              ) {\n                bailed = true;\n                console.warn('Parent: ', elm);\n                console.warn('server innerHTML: ', i);\n                console.warn('client innerHTML: ', elm.innerHTML);\n              }\n              return false\n            }\n          } else {\n            // iterate and compare children lists\n            var childrenMatch = true;\n            var childNode = elm.firstChild;\n            for (var i$1 = 0; i$1 < children.length; i$1++) {\n              if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) {\n                childrenMatch = false;\n                break\n              }\n              childNode = childNode.nextSibling;\n            }\n            // if childNode is not null, it means the actual childNodes list is\n            // longer than the virtual children list.\n            if (!childrenMatch || childNode) {\n              /* istanbul ignore if */\n              if (\"development\" !== 'production' &&\n                typeof console !== 'undefined' &&\n                !bailed\n              ) {\n                bailed = true;\n                console.warn('Parent: ', elm);\n                console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);\n              }\n              return false\n            }\n          }\n        }\n      }\n      if (isDef(data)) {\n        for (var key in data) {\n          if (!isRenderedModule(key)) {\n            invokeCreateHooks(vnode, insertedVnodeQueue);\n            break\n          }\n        }\n      }\n    } else if (elm.data !== vnode.text) {\n      elm.data = vnode.text;\n    }\n    return true\n  }\n\n  function assertNodeMatch (node, vnode) {\n    if (isDef(vnode.tag)) {\n      return (\n        vnode.tag.indexOf('vue-component') === 0 ||\n        vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())\n      )\n    } else {\n      return node.nodeType === (vnode.isComment ? 8 : 3)\n    }\n  }\n\n  return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {\n    if (isUndef(vnode)) {\n      if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }\n      return\n    }\n\n    var isInitialPatch = false;\n    var insertedVnodeQueue = [];\n\n    if (isUndef(oldVnode)) {\n      // empty mount (likely as component), create new root element\n      isInitialPatch = true;\n      createElm(vnode, insertedVnodeQueue, parentElm, refElm);\n    } else {\n      var isRealElement = isDef(oldVnode.nodeType);\n      if (!isRealElement && sameVnode(oldVnode, vnode)) {\n        // patch existing root node\n        patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);\n      } else {\n        if (isRealElement) {\n          // mounting to a real element\n          // check if this is server-rendered content and if we can perform\n          // a successful hydration.\n          if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {\n            oldVnode.removeAttribute(SSR_ATTR);\n            hydrating = true;\n          }\n          if (isTrue(hydrating)) {\n            if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {\n              invokeInsertHook(vnode, insertedVnodeQueue, true);\n              return oldVnode\n            } else {\n              warn(\n                'The client-side rendered virtual DOM tree is not matching ' +\n                'server-rendered content. This is likely caused by incorrect ' +\n                'HTML markup, for example nesting block-level elements inside ' +\n                '<p>, or missing <tbody>. Bailing hydration and performing ' +\n                'full client-side render.'\n              );\n            }\n          }\n          // either not server-rendered, or hydration failed.\n          // create an empty node and replace it\n          oldVnode = emptyNodeAt(oldVnode);\n        }\n        // replacing existing element\n        var oldElm = oldVnode.elm;\n        var parentElm$1 = nodeOps.parentNode(oldElm);\n        createElm(\n          vnode,\n          insertedVnodeQueue,\n          // extremely rare edge case: do not insert if old element is in a\n          // leaving transition. Only happens when combining transition +\n          // keep-alive + HOCs. (#4590)\n          oldElm._leaveCb ? null : parentElm$1,\n          nodeOps.nextSibling(oldElm)\n        );\n\n        if (isDef(vnode.parent)) {\n          // component root element replaced.\n          // update parent placeholder node element, recursively\n          var ancestor = vnode.parent;\n          var patchable = isPatchable(vnode);\n          while (ancestor) {\n            for (var i = 0; i < cbs.destroy.length; ++i) {\n              cbs.destroy[i](ancestor);\n            }\n            ancestor.elm = vnode.elm;\n            if (patchable) {\n              for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {\n                cbs.create[i$1](emptyNode, ancestor);\n              }\n              // #6513\n              // invoke insert hooks that may have been merged by create hooks.\n              // e.g. for directives that uses the \"inserted\" hook.\n              var insert = ancestor.data.hook.insert;\n              if (insert.merged) {\n                // start at index 1 to avoid re-invoking component mounted hook\n                for (var i$2 = 1; i$2 < insert.fns.length; i$2++) {\n                  insert.fns[i$2]();\n                }\n              }\n            }\n            ancestor = ancestor.parent;\n          }\n        }\n\n        if (isDef(parentElm$1)) {\n          removeVnodes(parentElm$1, [oldVnode], 0, 0);\n        } else if (isDef(oldVnode.tag)) {\n          invokeDestroyHook(oldVnode);\n        }\n      }\n    }\n\n    invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);\n    return vnode.elm\n  }\n}\n\n/*  */\n\nvar directives = {\n  create: updateDirectives,\n  update: updateDirectives,\n  destroy: function unbindDirectives (vnode) {\n    updateDirectives(vnode, emptyNode);\n  }\n};\n\nfunction updateDirectives (oldVnode, vnode) {\n  if (oldVnode.data.directives || vnode.data.directives) {\n    _update(oldVnode, vnode);\n  }\n}\n\nfunction _update (oldVnode, vnode) {\n  var isCreate = oldVnode === emptyNode;\n  var isDestroy = vnode === emptyNode;\n  var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);\n  var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);\n\n  var dirsWithInsert = [];\n  var dirsWithPostpatch = [];\n\n  var key, oldDir, dir;\n  for (key in newDirs) {\n    oldDir = oldDirs[key];\n    dir = newDirs[key];\n    if (!oldDir) {\n      // new directive, bind\n      callHook$1(dir, 'bind', vnode, oldVnode);\n      if (dir.def && dir.def.inserted) {\n        dirsWithInsert.push(dir);\n      }\n    } else {\n      // existing directive, update\n      dir.oldValue = oldDir.value;\n      callHook$1(dir, 'update', vnode, oldVnode);\n      if (dir.def && dir.def.componentUpdated) {\n        dirsWithPostpatch.push(dir);\n      }\n    }\n  }\n\n  if (dirsWithInsert.length) {\n    var callInsert = function () {\n      for (var i = 0; i < dirsWithInsert.length; i++) {\n        callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);\n      }\n    };\n    if (isCreate) {\n      mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert);\n    } else {\n      callInsert();\n    }\n  }\n\n  if (dirsWithPostpatch.length) {\n    mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {\n      for (var i = 0; i < dirsWithPostpatch.length; i++) {\n        callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);\n      }\n    });\n  }\n\n  if (!isCreate) {\n    for (key in oldDirs) {\n      if (!newDirs[key]) {\n        // no longer present, unbind\n        callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);\n      }\n    }\n  }\n}\n\nvar emptyModifiers = Object.create(null);\n\nfunction normalizeDirectives$1 (\n  dirs,\n  vm\n) {\n  var res = Object.create(null);\n  if (!dirs) {\n    return res\n  }\n  var i, dir;\n  for (i = 0; i < dirs.length; i++) {\n    dir = dirs[i];\n    if (!dir.modifiers) {\n      dir.modifiers = emptyModifiers;\n    }\n    res[getRawDirName(dir)] = dir;\n    dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);\n  }\n  return res\n}\n\nfunction getRawDirName (dir) {\n  return dir.rawName || ((dir.name) + \".\" + (Object.keys(dir.modifiers || {}).join('.')))\n}\n\nfunction callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {\n  var fn = dir.def && dir.def[hook];\n  if (fn) {\n    try {\n      fn(vnode.elm, dir, vnode, oldVnode, isDestroy);\n    } catch (e) {\n      handleError(e, vnode.context, (\"directive \" + (dir.name) + \" \" + hook + \" hook\"));\n    }\n  }\n}\n\nvar baseModules = [\n  ref,\n  directives\n];\n\n/*  */\n\nfunction updateAttrs (oldVnode, vnode) {\n  var opts = vnode.componentOptions;\n  if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) {\n    return\n  }\n  if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {\n    return\n  }\n  var key, cur, old;\n  var elm = vnode.elm;\n  var oldAttrs = oldVnode.data.attrs || {};\n  var attrs = vnode.data.attrs || {};\n  // clone observed objects, as the user probably wants to mutate it\n  if (isDef(attrs.__ob__)) {\n    attrs = vnode.data.attrs = extend({}, attrs);\n  }\n\n  for (key in attrs) {\n    cur = attrs[key];\n    old = oldAttrs[key];\n    if (old !== cur) {\n      setAttr(elm, key, cur);\n    }\n  }\n  // #4391: in IE9, setting type can reset value for input[type=radio]\n  /* istanbul ignore if */\n  if (isIE9 && attrs.value !== oldAttrs.value) {\n    setAttr(elm, 'value', attrs.value);\n  }\n  for (key in oldAttrs) {\n    if (isUndef(attrs[key])) {\n      if (isXlink(key)) {\n        elm.removeAttributeNS(xlinkNS, getXlinkProp(key));\n      } else if (!isEnumeratedAttr(key)) {\n        elm.removeAttribute(key);\n      }\n    }\n  }\n}\n\nfunction setAttr (el, key, value) {\n  if (isBooleanAttr(key)) {\n    // set attribute for blank value\n    // e.g. <option disabled>Select one</option>\n    if (isFalsyAttrValue(value)) {\n      el.removeAttribute(key);\n    } else {\n      // technically allowfullscreen is a boolean attribute for <iframe>,\n      // but Flash expects a value of \"true\" when used on <embed> tag\n      value = key === 'allowfullscreen' && el.tagName === 'EMBED'\n        ? 'true'\n        : key;\n      el.setAttribute(key, value);\n    }\n  } else if (isEnumeratedAttr(key)) {\n    el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');\n  } else if (isXlink(key)) {\n    if (isFalsyAttrValue(value)) {\n      el.removeAttributeNS(xlinkNS, getXlinkProp(key));\n    } else {\n      el.setAttributeNS(xlinkNS, key, value);\n    }\n  } else {\n    if (isFalsyAttrValue(value)) {\n      el.removeAttribute(key);\n    } else {\n      el.setAttribute(key, value);\n    }\n  }\n}\n\nvar attrs = {\n  create: updateAttrs,\n  update: updateAttrs\n};\n\n/*  */\n\nfunction updateClass (oldVnode, vnode) {\n  var el = vnode.elm;\n  var data = vnode.data;\n  var oldData = oldVnode.data;\n  if (\n    isUndef(data.staticClass) &&\n    isUndef(data.class) && (\n      isUndef(oldData) || (\n        isUndef(oldData.staticClass) &&\n        isUndef(oldData.class)\n      )\n    )\n  ) {\n    return\n  }\n\n  var cls = genClassForVnode(vnode);\n\n  // handle transition classes\n  var transitionClass = el._transitionClasses;\n  if (isDef(transitionClass)) {\n    cls = concat(cls, stringifyClass(transitionClass));\n  }\n\n  // set the class\n  if (cls !== el._prevClass) {\n    el.setAttribute('class', cls);\n    el._prevClass = cls;\n  }\n}\n\nvar klass = {\n  create: updateClass,\n  update: updateClass\n};\n\n/*  */\n\nvar validDivisionCharRE = /[\\w).+\\-_$\\]]/;\n\nfunction parseFilters (exp) {\n  var inSingle = false;\n  var inDouble = false;\n  var inTemplateString = false;\n  var inRegex = false;\n  var curly = 0;\n  var square = 0;\n  var paren = 0;\n  var lastFilterIndex = 0;\n  var c, prev, i, expression, filters;\n\n  for (i = 0; i < exp.length; i++) {\n    prev = c;\n    c = exp.charCodeAt(i);\n    if (inSingle) {\n      if (c === 0x27 && prev !== 0x5C) { inSingle = false; }\n    } else if (inDouble) {\n      if (c === 0x22 && prev !== 0x5C) { inDouble = false; }\n    } else if (inTemplateString) {\n      if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }\n    } else if (inRegex) {\n      if (c === 0x2f && prev !== 0x5C) { inRegex = false; }\n    } else if (\n      c === 0x7C && // pipe\n      exp.charCodeAt(i + 1) !== 0x7C &&\n      exp.charCodeAt(i - 1) !== 0x7C &&\n      !curly && !square && !paren\n    ) {\n      if (expression === undefined) {\n        // first filter, end of expression\n        lastFilterIndex = i + 1;\n        expression = exp.slice(0, i).trim();\n      } else {\n        pushFilter();\n      }\n    } else {\n      switch (c) {\n        case 0x22: inDouble = true; break         // \"\n        case 0x27: inSingle = true; break         // '\n        case 0x60: inTemplateString = true; break // `\n        case 0x28: paren++; break                 // (\n        case 0x29: paren--; break                 // )\n        case 0x5B: square++; break                // [\n        case 0x5D: square--; break                // ]\n        case 0x7B: curly++; break                 // {\n        case 0x7D: curly--; break                 // }\n      }\n      if (c === 0x2f) { // /\n        var j = i - 1;\n        var p = (void 0);\n        // find first non-whitespace prev char\n        for (; j >= 0; j--) {\n          p = exp.charAt(j);\n          if (p !== ' ') { break }\n        }\n        if (!p || !validDivisionCharRE.test(p)) {\n          inRegex = true;\n        }\n      }\n    }\n  }\n\n  if (expression === undefined) {\n    expression = exp.slice(0, i).trim();\n  } else if (lastFilterIndex !== 0) {\n    pushFilter();\n  }\n\n  function pushFilter () {\n    (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());\n    lastFilterIndex = i + 1;\n  }\n\n  if (filters) {\n    for (i = 0; i < filters.length; i++) {\n      expression = wrapFilter(expression, filters[i]);\n    }\n  }\n\n  return expression\n}\n\nfunction wrapFilter (exp, filter) {\n  var i = filter.indexOf('(');\n  if (i < 0) {\n    // _f: resolveFilter\n    return (\"_f(\\\"\" + filter + \"\\\")(\" + exp + \")\")\n  } else {\n    var name = filter.slice(0, i);\n    var args = filter.slice(i + 1);\n    return (\"_f(\\\"\" + name + \"\\\")(\" + exp + \",\" + args)\n  }\n}\n\n/*  */\n\nfunction baseWarn (msg) {\n  console.error((\"[Vue compiler]: \" + msg));\n}\n\nfunction pluckModuleFunction (\n  modules,\n  key\n) {\n  return modules\n    ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })\n    : []\n}\n\nfunction addProp (el, name, value) {\n  (el.props || (el.props = [])).push({ name: name, value: value });\n}\n\nfunction addAttr (el, name, value) {\n  (el.attrs || (el.attrs = [])).push({ name: name, value: value });\n}\n\nfunction addDirective (\n  el,\n  name,\n  rawName,\n  value,\n  arg,\n  modifiers\n) {\n  (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });\n}\n\nfunction addHandler (\n  el,\n  name,\n  value,\n  modifiers,\n  important,\n  warn\n) {\n  // warn prevent and passive modifier\n  /* istanbul ignore if */\n  if (\n    \"development\" !== 'production' && warn &&\n    modifiers && modifiers.prevent && modifiers.passive\n  ) {\n    warn(\n      'passive and prevent can\\'t be used together. ' +\n      'Passive handler can\\'t prevent default event.'\n    );\n  }\n  // check capture modifier\n  if (modifiers && modifiers.capture) {\n    delete modifiers.capture;\n    name = '!' + name; // mark the event as captured\n  }\n  if (modifiers && modifiers.once) {\n    delete modifiers.once;\n    name = '~' + name; // mark the event as once\n  }\n  /* istanbul ignore if */\n  if (modifiers && modifiers.passive) {\n    delete modifiers.passive;\n    name = '&' + name; // mark the event as passive\n  }\n  var events;\n  if (modifiers && modifiers.native) {\n    delete modifiers.native;\n    events = el.nativeEvents || (el.nativeEvents = {});\n  } else {\n    events = el.events || (el.events = {});\n  }\n  var newHandler = { value: value, modifiers: modifiers };\n  var handlers = events[name];\n  /* istanbul ignore if */\n  if (Array.isArray(handlers)) {\n    important ? handlers.unshift(newHandler) : handlers.push(newHandler);\n  } else if (handlers) {\n    events[name] = important ? [newHandler, handlers] : [handlers, newHandler];\n  } else {\n    events[name] = newHandler;\n  }\n}\n\nfunction getBindingAttr (\n  el,\n  name,\n  getStatic\n) {\n  var dynamicValue =\n    getAndRemoveAttr(el, ':' + name) ||\n    getAndRemoveAttr(el, 'v-bind:' + name);\n  if (dynamicValue != null) {\n    return parseFilters(dynamicValue)\n  } else if (getStatic !== false) {\n    var staticValue = getAndRemoveAttr(el, name);\n    if (staticValue != null) {\n      return JSON.stringify(staticValue)\n    }\n  }\n}\n\nfunction getAndRemoveAttr (el, name) {\n  var val;\n  if ((val = el.attrsMap[name]) != null) {\n    var list = el.attrsList;\n    for (var i = 0, l = list.length; i < l; i++) {\n      if (list[i].name === name) {\n        list.splice(i, 1);\n        break\n      }\n    }\n  }\n  return val\n}\n\n/*  */\n\n/**\n * Cross-platform code generation for component v-model\n */\nfunction genComponentModel (\n  el,\n  value,\n  modifiers\n) {\n  var ref = modifiers || {};\n  var number = ref.number;\n  var trim = ref.trim;\n\n  var baseValueExpression = '$$v';\n  var valueExpression = baseValueExpression;\n  if (trim) {\n    valueExpression =\n      \"(typeof \" + baseValueExpression + \" === 'string'\" +\n        \"? \" + baseValueExpression + \".trim()\" +\n        \": \" + baseValueExpression + \")\";\n  }\n  if (number) {\n    valueExpression = \"_n(\" + valueExpression + \")\";\n  }\n  var assignment = genAssignmentCode(value, valueExpression);\n\n  el.model = {\n    value: (\"(\" + value + \")\"),\n    expression: (\"\\\"\" + value + \"\\\"\"),\n    callback: (\"function (\" + baseValueExpression + \") {\" + assignment + \"}\")\n  };\n}\n\n/**\n * Cross-platform codegen helper for generating v-model value assignment code.\n */\nfunction genAssignmentCode (\n  value,\n  assignment\n) {\n  var modelRs = parseModel(value);\n  if (modelRs.idx === null) {\n    return (value + \"=\" + assignment)\n  } else {\n    return (\"$set(\" + (modelRs.exp) + \", \" + (modelRs.idx) + \", \" + assignment + \")\")\n  }\n}\n\n/**\n * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)\n *\n * for loop possible cases:\n *\n * - test\n * - test[idx]\n * - test[test1[idx]]\n * - test[\"a\"][idx]\n * - xxx.test[a[a].test1[idx]]\n * - test.xxx.a[\"asa\"][test1[idx]]\n *\n */\n\nvar len;\nvar str;\nvar chr;\nvar index$1;\nvar expressionPos;\nvar expressionEndPos;\n\nfunction parseModel (val) {\n  str = val;\n  len = str.length;\n  index$1 = expressionPos = expressionEndPos = 0;\n\n  if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {\n    return {\n      exp: val,\n      idx: null\n    }\n  }\n\n  while (!eof()) {\n    chr = next();\n    /* istanbul ignore if */\n    if (isStringStart(chr)) {\n      parseString(chr);\n    } else if (chr === 0x5B) {\n      parseBracket(chr);\n    }\n  }\n\n  return {\n    exp: val.substring(0, expressionPos),\n    idx: val.substring(expressionPos + 1, expressionEndPos)\n  }\n}\n\nfunction next () {\n  return str.charCodeAt(++index$1)\n}\n\nfunction eof () {\n  return index$1 >= len\n}\n\nfunction isStringStart (chr) {\n  return chr === 0x22 || chr === 0x27\n}\n\nfunction parseBracket (chr) {\n  var inBracket = 1;\n  expressionPos = index$1;\n  while (!eof()) {\n    chr = next();\n    if (isStringStart(chr)) {\n      parseString(chr);\n      continue\n    }\n    if (chr === 0x5B) { inBracket++; }\n    if (chr === 0x5D) { inBracket--; }\n    if (inBracket === 0) {\n      expressionEndPos = index$1;\n      break\n    }\n  }\n}\n\nfunction parseString (chr) {\n  var stringQuote = chr;\n  while (!eof()) {\n    chr = next();\n    if (chr === stringQuote) {\n      break\n    }\n  }\n}\n\n/*  */\n\nvar warn$1;\n\n// in some cases, the event used has to be determined at runtime\n// so we used some reserved tokens during compile.\nvar RANGE_TOKEN = '__r';\nvar CHECKBOX_RADIO_TOKEN = '__c';\n\nfunction model (\n  el,\n  dir,\n  _warn\n) {\n  warn$1 = _warn;\n  var value = dir.value;\n  var modifiers = dir.modifiers;\n  var tag = el.tag;\n  var type = el.attrsMap.type;\n\n  {\n    var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];\n    if (tag === 'input' && dynamicType) {\n      warn$1(\n        \"<input :type=\\\"\" + dynamicType + \"\\\" v-model=\\\"\" + value + \"\\\">:\\n\" +\n        \"v-model does not support dynamic input types. Use v-if branches instead.\"\n      );\n    }\n    // inputs with type=\"file\" are read only and setting the input's\n    // value will throw an error.\n    if (tag === 'input' && type === 'file') {\n      warn$1(\n        \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\" type=\\\"file\\\">:\\n\" +\n        \"File inputs are read only. Use a v-on:change listener instead.\"\n      );\n    }\n  }\n\n  if (el.component) {\n    genComponentModel(el, value, modifiers);\n    // component v-model doesn't need extra runtime\n    return false\n  } else if (tag === 'select') {\n    genSelect(el, value, modifiers);\n  } else if (tag === 'input' && type === 'checkbox') {\n    genCheckboxModel(el, value, modifiers);\n  } else if (tag === 'input' && type === 'radio') {\n    genRadioModel(el, value, modifiers);\n  } else if (tag === 'input' || tag === 'textarea') {\n    genDefaultModel(el, value, modifiers);\n  } else if (!config.isReservedTag(tag)) {\n    genComponentModel(el, value, modifiers);\n    // component v-model doesn't need extra runtime\n    return false\n  } else {\n    warn$1(\n      \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\">: \" +\n      \"v-model is not supported on this element type. \" +\n      'If you are working with contenteditable, it\\'s recommended to ' +\n      'wrap a library dedicated for that purpose inside a custom component.'\n    );\n  }\n\n  // ensure runtime directive metadata\n  return true\n}\n\nfunction genCheckboxModel (\n  el,\n  value,\n  modifiers\n) {\n  var number = modifiers && modifiers.number;\n  var valueBinding = getBindingAttr(el, 'value') || 'null';\n  var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';\n  var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';\n  addProp(el, 'checked',\n    \"Array.isArray(\" + value + \")\" +\n      \"?_i(\" + value + \",\" + valueBinding + \")>-1\" + (\n        trueValueBinding === 'true'\n          ? (\":(\" + value + \")\")\n          : (\":_q(\" + value + \",\" + trueValueBinding + \")\")\n      )\n  );\n  addHandler(el, CHECKBOX_RADIO_TOKEN,\n    \"var $$a=\" + value + \",\" +\n        '$$el=$event.target,' +\n        \"$$c=$$el.checked?(\" + trueValueBinding + \"):(\" + falseValueBinding + \");\" +\n    'if(Array.isArray($$a)){' +\n      \"var $$v=\" + (number ? '_n(' + valueBinding + ')' : valueBinding) + \",\" +\n          '$$i=_i($$a,$$v);' +\n      \"if($$el.checked){$$i<0&&(\" + value + \"=$$a.concat([$$v]))}\" +\n      \"else{$$i>-1&&(\" + value + \"=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}\" +\n    \"}else{\" + (genAssignmentCode(value, '$$c')) + \"}\",\n    null, true\n  );\n}\n\nfunction genRadioModel (\n    el,\n    value,\n    modifiers\n) {\n  var number = modifiers && modifiers.number;\n  var valueBinding = getBindingAttr(el, 'value') || 'null';\n  valueBinding = number ? (\"_n(\" + valueBinding + \")\") : valueBinding;\n  addProp(el, 'checked', (\"_q(\" + value + \",\" + valueBinding + \")\"));\n  addHandler(el, CHECKBOX_RADIO_TOKEN, genAssignmentCode(value, valueBinding), null, true);\n}\n\nfunction genSelect (\n    el,\n    value,\n    modifiers\n) {\n  var number = modifiers && modifiers.number;\n  var selectedVal = \"Array.prototype.filter\" +\n    \".call($event.target.options,function(o){return o.selected})\" +\n    \".map(function(o){var val = \\\"_value\\\" in o ? o._value : o.value;\" +\n    \"return \" + (number ? '_n(val)' : 'val') + \"})\";\n\n  var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';\n  var code = \"var $$selectedVal = \" + selectedVal + \";\";\n  code = code + \" \" + (genAssignmentCode(value, assignment));\n  addHandler(el, 'change', code, null, true);\n}\n\nfunction genDefaultModel (\n  el,\n  value,\n  modifiers\n) {\n  var type = el.attrsMap.type;\n  var ref = modifiers || {};\n  var lazy = ref.lazy;\n  var number = ref.number;\n  var trim = ref.trim;\n  var needCompositionGuard = !lazy && type !== 'range';\n  var event = lazy\n    ? 'change'\n    : type === 'range'\n      ? RANGE_TOKEN\n      : 'input';\n\n  var valueExpression = '$event.target.value';\n  if (trim) {\n    valueExpression = \"$event.target.value.trim()\";\n  }\n  if (number) {\n    valueExpression = \"_n(\" + valueExpression + \")\";\n  }\n\n  var code = genAssignmentCode(value, valueExpression);\n  if (needCompositionGuard) {\n    code = \"if($event.target.composing)return;\" + code;\n  }\n\n  addProp(el, 'value', (\"(\" + value + \")\"));\n  addHandler(el, event, code, null, true);\n  if (trim || number) {\n    addHandler(el, 'blur', '$forceUpdate()');\n  }\n}\n\n/*  */\n\n// normalize v-model event tokens that can only be determined at runtime.\n// it's important to place the event as the first in the array because\n// the whole point is ensuring the v-model callback gets called before\n// user-attached handlers.\nfunction normalizeEvents (on) {\n  var event;\n  /* istanbul ignore if */\n  if (isDef(on[RANGE_TOKEN])) {\n    // IE input[type=range] only supports `change` event\n    event = isIE ? 'change' : 'input';\n    on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);\n    delete on[RANGE_TOKEN];\n  }\n  if (isDef(on[CHECKBOX_RADIO_TOKEN])) {\n    // Chrome fires microtasks in between click/change, leads to #4521\n    event = isChrome ? 'click' : 'change';\n    on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []);\n    delete on[CHECKBOX_RADIO_TOKEN];\n  }\n}\n\nvar target$1;\n\nfunction add$1 (\n  event,\n  handler,\n  once$$1,\n  capture,\n  passive\n) {\n  if (once$$1) {\n    var oldHandler = handler;\n    var _target = target$1; // save current target element in closure\n    handler = function (ev) {\n      var res = arguments.length === 1\n        ? oldHandler(ev)\n        : oldHandler.apply(null, arguments);\n      if (res !== null) {\n        remove$2(event, handler, capture, _target);\n      }\n    };\n  }\n  target$1.addEventListener(\n    event,\n    handler,\n    supportsPassive\n      ? { capture: capture, passive: passive }\n      : capture\n  );\n}\n\nfunction remove$2 (\n  event,\n  handler,\n  capture,\n  _target\n) {\n  (_target || target$1).removeEventListener(event, handler, capture);\n}\n\nfunction updateDOMListeners (oldVnode, vnode) {\n  if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {\n    return\n  }\n  var on = vnode.data.on || {};\n  var oldOn = oldVnode.data.on || {};\n  target$1 = vnode.elm;\n  normalizeEvents(on);\n  updateListeners(on, oldOn, add$1, remove$2, vnode.context);\n}\n\nvar events = {\n  create: updateDOMListeners,\n  update: updateDOMListeners\n};\n\n/*  */\n\nfunction updateDOMProps (oldVnode, vnode) {\n  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {\n    return\n  }\n  var key, cur;\n  var elm = vnode.elm;\n  var oldProps = oldVnode.data.domProps || {};\n  var props = vnode.data.domProps || {};\n  // clone observed objects, as the user probably wants to mutate it\n  if (isDef(props.__ob__)) {\n    props = vnode.data.domProps = extend({}, props);\n  }\n\n  for (key in oldProps) {\n    if (isUndef(props[key])) {\n      elm[key] = '';\n    }\n  }\n  for (key in props) {\n    cur = props[key];\n    // ignore children if the node has textContent or innerHTML,\n    // as these will throw away existing DOM nodes and cause removal errors\n    // on subsequent patches (#3360)\n    if (key === 'textContent' || key === 'innerHTML') {\n      if (vnode.children) { vnode.children.length = 0; }\n      if (cur === oldProps[key]) { continue }\n    }\n\n    if (key === 'value') {\n      // store value as _value as well since\n      // non-string values will be stringified\n      elm._value = cur;\n      // avoid resetting cursor position when value is the same\n      var strCur = isUndef(cur) ? '' : String(cur);\n      if (shouldUpdateValue(elm, vnode, strCur)) {\n        elm.value = strCur;\n      }\n    } else {\n      elm[key] = cur;\n    }\n  }\n}\n\n// check platforms/web/util/attrs.js acceptValue\n\n\nfunction shouldUpdateValue (\n  elm,\n  vnode,\n  checkVal\n) {\n  return (!elm.composing && (\n    vnode.tag === 'option' ||\n    isDirty(elm, checkVal) ||\n    isInputChanged(elm, checkVal)\n  ))\n}\n\nfunction isDirty (elm, checkVal) {\n  // return true when textbox (.number and .trim) loses focus and its value is\n  // not equal to the updated value\n  var notInFocus = true;\n  // #6157\n  // work around IE bug when accessing document.activeElement in an iframe\n  try { notInFocus = document.activeElement !== elm; } catch (e) {}\n  return notInFocus && elm.value !== checkVal\n}\n\nfunction isInputChanged (elm, newVal) {\n  var value = elm.value;\n  var modifiers = elm._vModifiers; // injected by v-model runtime\n  if (isDef(modifiers) && modifiers.number) {\n    return toNumber(value) !== toNumber(newVal)\n  }\n  if (isDef(modifiers) && modifiers.trim) {\n    return value.trim() !== newVal.trim()\n  }\n  return value !== newVal\n}\n\nvar domProps = {\n  create: updateDOMProps,\n  update: updateDOMProps\n};\n\n/*  */\n\nvar parseStyleText = cached(function (cssText) {\n  var res = {};\n  var listDelimiter = /;(?![^(]*\\))/g;\n  var propertyDelimiter = /:(.+)/;\n  cssText.split(listDelimiter).forEach(function (item) {\n    if (item) {\n      var tmp = item.split(propertyDelimiter);\n      tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());\n    }\n  });\n  return res\n});\n\n// merge static and dynamic style data on the same vnode\nfunction normalizeStyleData (data) {\n  var style = normalizeStyleBinding(data.style);\n  // static style is pre-processed into an object during compilation\n  // and is always a fresh object, so it's safe to merge into it\n  return data.staticStyle\n    ? extend(data.staticStyle, style)\n    : style\n}\n\n// normalize possible array / string values into Object\nfunction normalizeStyleBinding (bindingStyle) {\n  if (Array.isArray(bindingStyle)) {\n    return toObject(bindingStyle)\n  }\n  if (typeof bindingStyle === 'string') {\n    return parseStyleText(bindingStyle)\n  }\n  return bindingStyle\n}\n\n/**\n * parent component style should be after child's\n * so that parent component's style could override it\n */\nfunction getStyle (vnode, checkChild) {\n  var res = {};\n  var styleData;\n\n  if (checkChild) {\n    var childNode = vnode;\n    while (childNode.componentInstance) {\n      childNode = childNode.componentInstance._vnode;\n      if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {\n        extend(res, styleData);\n      }\n    }\n  }\n\n  if ((styleData = normalizeStyleData(vnode.data))) {\n    extend(res, styleData);\n  }\n\n  var parentNode = vnode;\n  while ((parentNode = parentNode.parent)) {\n    if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {\n      extend(res, styleData);\n    }\n  }\n  return res\n}\n\n/*  */\n\nvar cssVarRE = /^--/;\nvar importantRE = /\\s*!important$/;\nvar setProp = function (el, name, val) {\n  /* istanbul ignore if */\n  if (cssVarRE.test(name)) {\n    el.style.setProperty(name, val);\n  } else if (importantRE.test(val)) {\n    el.style.setProperty(name, val.replace(importantRE, ''), 'important');\n  } else {\n    var normalizedName = normalize(name);\n    if (Array.isArray(val)) {\n      // Support values array created by autoprefixer, e.g.\n      // {display: [\"-webkit-box\", \"-ms-flexbox\", \"flex\"]}\n      // Set them one by one, and the browser will only set those it can recognize\n      for (var i = 0, len = val.length; i < len; i++) {\n        el.style[normalizedName] = val[i];\n      }\n    } else {\n      el.style[normalizedName] = val;\n    }\n  }\n};\n\nvar vendorNames = ['Webkit', 'Moz', 'ms'];\n\nvar emptyStyle;\nvar normalize = cached(function (prop) {\n  emptyStyle = emptyStyle || document.createElement('div').style;\n  prop = camelize(prop);\n  if (prop !== 'filter' && (prop in emptyStyle)) {\n    return prop\n  }\n  var capName = prop.charAt(0).toUpperCase() + prop.slice(1);\n  for (var i = 0; i < vendorNames.length; i++) {\n    var name = vendorNames[i] + capName;\n    if (name in emptyStyle) {\n      return name\n    }\n  }\n});\n\nfunction updateStyle (oldVnode, vnode) {\n  var data = vnode.data;\n  var oldData = oldVnode.data;\n\n  if (isUndef(data.staticStyle) && isUndef(data.style) &&\n    isUndef(oldData.staticStyle) && isUndef(oldData.style)\n  ) {\n    return\n  }\n\n  var cur, name;\n  var el = vnode.elm;\n  var oldStaticStyle = oldData.staticStyle;\n  var oldStyleBinding = oldData.normalizedStyle || oldData.style || {};\n\n  // if static style exists, stylebinding already merged into it when doing normalizeStyleData\n  var oldStyle = oldStaticStyle || oldStyleBinding;\n\n  var style = normalizeStyleBinding(vnode.data.style) || {};\n\n  // store normalized style under a different key for next diff\n  // make sure to clone it if it's reactive, since the user likely wants\n  // to mutate it.\n  vnode.data.normalizedStyle = isDef(style.__ob__)\n    ? extend({}, style)\n    : style;\n\n  var newStyle = getStyle(vnode, true);\n\n  for (name in oldStyle) {\n    if (isUndef(newStyle[name])) {\n      setProp(el, name, '');\n    }\n  }\n  for (name in newStyle) {\n    cur = newStyle[name];\n    if (cur !== oldStyle[name]) {\n      // ie9 setting to null has no effect, must use empty string\n      setProp(el, name, cur == null ? '' : cur);\n    }\n  }\n}\n\nvar style = {\n  create: updateStyle,\n  update: updateStyle\n};\n\n/*  */\n\n/**\n * Add class with compatibility for SVG since classList is not supported on\n * SVG elements in IE\n */\nfunction addClass (el, cls) {\n  /* istanbul ignore if */\n  if (!cls || !(cls = cls.trim())) {\n    return\n  }\n\n  /* istanbul ignore else */\n  if (el.classList) {\n    if (cls.indexOf(' ') > -1) {\n      cls.split(/\\s+/).forEach(function (c) { return el.classList.add(c); });\n    } else {\n      el.classList.add(cls);\n    }\n  } else {\n    var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n    if (cur.indexOf(' ' + cls + ' ') < 0) {\n      el.setAttribute('class', (cur + cls).trim());\n    }\n  }\n}\n\n/**\n * Remove class with compatibility for SVG since classList is not supported on\n * SVG elements in IE\n */\nfunction removeClass (el, cls) {\n  /* istanbul ignore if */\n  if (!cls || !(cls = cls.trim())) {\n    return\n  }\n\n  /* istanbul ignore else */\n  if (el.classList) {\n    if (cls.indexOf(' ') > -1) {\n      cls.split(/\\s+/).forEach(function (c) { return el.classList.remove(c); });\n    } else {\n      el.classList.remove(cls);\n    }\n    if (!el.classList.length) {\n      el.removeAttribute('class');\n    }\n  } else {\n    var cur = \" \" + (el.getAttribute('class') || '') + \" \";\n    var tar = ' ' + cls + ' ';\n    while (cur.indexOf(tar) >= 0) {\n      cur = cur.replace(tar, ' ');\n    }\n    cur = cur.trim();\n    if (cur) {\n      el.setAttribute('class', cur);\n    } else {\n      el.removeAttribute('class');\n    }\n  }\n}\n\n/*  */\n\nfunction resolveTransition (def$$1) {\n  if (!def$$1) {\n    return\n  }\n  /* istanbul ignore else */\n  if (typeof def$$1 === 'object') {\n    var res = {};\n    if (def$$1.css !== false) {\n      extend(res, autoCssTransition(def$$1.name || 'v'));\n    }\n    extend(res, def$$1);\n    return res\n  } else if (typeof def$$1 === 'string') {\n    return autoCssTransition(def$$1)\n  }\n}\n\nvar autoCssTransition = cached(function (name) {\n  return {\n    enterClass: (name + \"-enter\"),\n    enterToClass: (name + \"-enter-to\"),\n    enterActiveClass: (name + \"-enter-active\"),\n    leaveClass: (name + \"-leave\"),\n    leaveToClass: (name + \"-leave-to\"),\n    leaveActiveClass: (name + \"-leave-active\")\n  }\n});\n\nvar hasTransition = inBrowser && !isIE9;\nvar TRANSITION = 'transition';\nvar ANIMATION = 'animation';\n\n// Transition property/event sniffing\nvar transitionProp = 'transition';\nvar transitionEndEvent = 'transitionend';\nvar animationProp = 'animation';\nvar animationEndEvent = 'animationend';\nif (hasTransition) {\n  /* istanbul ignore if */\n  if (window.ontransitionend === undefined &&\n    window.onwebkittransitionend !== undefined\n  ) {\n    transitionProp = 'WebkitTransition';\n    transitionEndEvent = 'webkitTransitionEnd';\n  }\n  if (window.onanimationend === undefined &&\n    window.onwebkitanimationend !== undefined\n  ) {\n    animationProp = 'WebkitAnimation';\n    animationEndEvent = 'webkitAnimationEnd';\n  }\n}\n\n// binding to window is necessary to make hot reload work in IE in strict mode\nvar raf = inBrowser && window.requestAnimationFrame\n  ? window.requestAnimationFrame.bind(window)\n  : setTimeout;\n\nfunction nextFrame (fn) {\n  raf(function () {\n    raf(fn);\n  });\n}\n\nfunction addTransitionClass (el, cls) {\n  var transitionClasses = el._transitionClasses || (el._transitionClasses = []);\n  if (transitionClasses.indexOf(cls) < 0) {\n    transitionClasses.push(cls);\n    addClass(el, cls);\n  }\n}\n\nfunction removeTransitionClass (el, cls) {\n  if (el._transitionClasses) {\n    remove(el._transitionClasses, cls);\n  }\n  removeClass(el, cls);\n}\n\nfunction whenTransitionEnds (\n  el,\n  expectedType,\n  cb\n) {\n  var ref = getTransitionInfo(el, expectedType);\n  var type = ref.type;\n  var timeout = ref.timeout;\n  var propCount = ref.propCount;\n  if (!type) { return cb() }\n  var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;\n  var ended = 0;\n  var end = function () {\n    el.removeEventListener(event, onEnd);\n    cb();\n  };\n  var onEnd = function (e) {\n    if (e.target === el) {\n      if (++ended >= propCount) {\n        end();\n      }\n    }\n  };\n  setTimeout(function () {\n    if (ended < propCount) {\n      end();\n    }\n  }, timeout + 1);\n  el.addEventListener(event, onEnd);\n}\n\nvar transformRE = /\\b(transform|all)(,|$)/;\n\nfunction getTransitionInfo (el, expectedType) {\n  var styles = window.getComputedStyle(el);\n  var transitionDelays = styles[transitionProp + 'Delay'].split(', ');\n  var transitionDurations = styles[transitionProp + 'Duration'].split(', ');\n  var transitionTimeout = getTimeout(transitionDelays, transitionDurations);\n  var animationDelays = styles[animationProp + 'Delay'].split(', ');\n  var animationDurations = styles[animationProp + 'Duration'].split(', ');\n  var animationTimeout = getTimeout(animationDelays, animationDurations);\n\n  var type;\n  var timeout = 0;\n  var propCount = 0;\n  /* istanbul ignore if */\n  if (expectedType === TRANSITION) {\n    if (transitionTimeout > 0) {\n      type = TRANSITION;\n      timeout = transitionTimeout;\n      propCount = transitionDurations.length;\n    }\n  } else if (expectedType === ANIMATION) {\n    if (animationTimeout > 0) {\n      type = ANIMATION;\n      timeout = animationTimeout;\n      propCount = animationDurations.length;\n    }\n  } else {\n    timeout = Math.max(transitionTimeout, animationTimeout);\n    type = timeout > 0\n      ? transitionTimeout > animationTimeout\n        ? TRANSITION\n        : ANIMATION\n      : null;\n    propCount = type\n      ? type === TRANSITION\n        ? transitionDurations.length\n        : animationDurations.length\n      : 0;\n  }\n  var hasTransform =\n    type === TRANSITION &&\n    transformRE.test(styles[transitionProp + 'Property']);\n  return {\n    type: type,\n    timeout: timeout,\n    propCount: propCount,\n    hasTransform: hasTransform\n  }\n}\n\nfunction getTimeout (delays, durations) {\n  /* istanbul ignore next */\n  while (delays.length < durations.length) {\n    delays = delays.concat(delays);\n  }\n\n  return Math.max.apply(null, durations.map(function (d, i) {\n    return toMs(d) + toMs(delays[i])\n  }))\n}\n\nfunction toMs (s) {\n  return Number(s.slice(0, -1)) * 1000\n}\n\n/*  */\n\nfunction enter (vnode, toggleDisplay) {\n  var el = vnode.elm;\n\n  // call leave callback now\n  if (isDef(el._leaveCb)) {\n    el._leaveCb.cancelled = true;\n    el._leaveCb();\n  }\n\n  var data = resolveTransition(vnode.data.transition);\n  if (isUndef(data)) {\n    return\n  }\n\n  /* istanbul ignore if */\n  if (isDef(el._enterCb) || el.nodeType !== 1) {\n    return\n  }\n\n  var css = data.css;\n  var type = data.type;\n  var enterClass = data.enterClass;\n  var enterToClass = data.enterToClass;\n  var enterActiveClass = data.enterActiveClass;\n  var appearClass = data.appearClass;\n  var appearToClass = data.appearToClass;\n  var appearActiveClass = data.appearActiveClass;\n  var beforeEnter = data.beforeEnter;\n  var enter = data.enter;\n  var afterEnter = data.afterEnter;\n  var enterCancelled = data.enterCancelled;\n  var beforeAppear = data.beforeAppear;\n  var appear = data.appear;\n  var afterAppear = data.afterAppear;\n  var appearCancelled = data.appearCancelled;\n  var duration = data.duration;\n\n  // activeInstance will always be the <transition> component managing this\n  // transition. One edge case to check is when the <transition> is placed\n  // as the root node of a child component. In that case we need to check\n  // <transition>'s parent for appear check.\n  var context = activeInstance;\n  var transitionNode = activeInstance.$vnode;\n  while (transitionNode && transitionNode.parent) {\n    transitionNode = transitionNode.parent;\n    context = transitionNode.context;\n  }\n\n  var isAppear = !context._isMounted || !vnode.isRootInsert;\n\n  if (isAppear && !appear && appear !== '') {\n    return\n  }\n\n  var startClass = isAppear && appearClass\n    ? appearClass\n    : enterClass;\n  var activeClass = isAppear && appearActiveClass\n    ? appearActiveClass\n    : enterActiveClass;\n  var toClass = isAppear && appearToClass\n    ? appearToClass\n    : enterToClass;\n\n  var beforeEnterHook = isAppear\n    ? (beforeAppear || beforeEnter)\n    : beforeEnter;\n  var enterHook = isAppear\n    ? (typeof appear === 'function' ? appear : enter)\n    : enter;\n  var afterEnterHook = isAppear\n    ? (afterAppear || afterEnter)\n    : afterEnter;\n  var enterCancelledHook = isAppear\n    ? (appearCancelled || enterCancelled)\n    : enterCancelled;\n\n  var explicitEnterDuration = toNumber(\n    isObject(duration)\n      ? duration.enter\n      : duration\n  );\n\n  if (\"development\" !== 'production' && explicitEnterDuration != null) {\n    checkDuration(explicitEnterDuration, 'enter', vnode);\n  }\n\n  var expectsCSS = css !== false && !isIE9;\n  var userWantsControl = getHookArgumentsLength(enterHook);\n\n  var cb = el._enterCb = once(function () {\n    if (expectsCSS) {\n      removeTransitionClass(el, toClass);\n      removeTransitionClass(el, activeClass);\n    }\n    if (cb.cancelled) {\n      if (expectsCSS) {\n        removeTransitionClass(el, startClass);\n      }\n      enterCancelledHook && enterCancelledHook(el);\n    } else {\n      afterEnterHook && afterEnterHook(el);\n    }\n    el._enterCb = null;\n  });\n\n  if (!vnode.data.show) {\n    // remove pending leave element on enter by injecting an insert hook\n    mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {\n      var parent = el.parentNode;\n      var pendingNode = parent && parent._pending && parent._pending[vnode.key];\n      if (pendingNode &&\n        pendingNode.tag === vnode.tag &&\n        pendingNode.elm._leaveCb\n      ) {\n        pendingNode.elm._leaveCb();\n      }\n      enterHook && enterHook(el, cb);\n    });\n  }\n\n  // start enter transition\n  beforeEnterHook && beforeEnterHook(el);\n  if (expectsCSS) {\n    addTransitionClass(el, startClass);\n    addTransitionClass(el, activeClass);\n    nextFrame(function () {\n      addTransitionClass(el, toClass);\n      removeTransitionClass(el, startClass);\n      if (!cb.cancelled && !userWantsControl) {\n        if (isValidDuration(explicitEnterDuration)) {\n          setTimeout(cb, explicitEnterDuration);\n        } else {\n          whenTransitionEnds(el, type, cb);\n        }\n      }\n    });\n  }\n\n  if (vnode.data.show) {\n    toggleDisplay && toggleDisplay();\n    enterHook && enterHook(el, cb);\n  }\n\n  if (!expectsCSS && !userWantsControl) {\n    cb();\n  }\n}\n\nfunction leave (vnode, rm) {\n  var el = vnode.elm;\n\n  // call enter callback now\n  if (isDef(el._enterCb)) {\n    el._enterCb.cancelled = true;\n    el._enterCb();\n  }\n\n  var data = resolveTransition(vnode.data.transition);\n  if (isUndef(data)) {\n    return rm()\n  }\n\n  /* istanbul ignore if */\n  if (isDef(el._leaveCb) || el.nodeType !== 1) {\n    return\n  }\n\n  var css = data.css;\n  var type = data.type;\n  var leaveClass = data.leaveClass;\n  var leaveToClass = data.leaveToClass;\n  var leaveActiveClass = data.leaveActiveClass;\n  var beforeLeave = data.beforeLeave;\n  var leave = data.leave;\n  var afterLeave = data.afterLeave;\n  var leaveCancelled = data.leaveCancelled;\n  var delayLeave = data.delayLeave;\n  var duration = data.duration;\n\n  var expectsCSS = css !== false && !isIE9;\n  var userWantsControl = getHookArgumentsLength(leave);\n\n  var explicitLeaveDuration = toNumber(\n    isObject(duration)\n      ? duration.leave\n      : duration\n  );\n\n  if (\"development\" !== 'production' && isDef(explicitLeaveDuration)) {\n    checkDuration(explicitLeaveDuration, 'leave', vnode);\n  }\n\n  var cb = el._leaveCb = once(function () {\n    if (el.parentNode && el.parentNode._pending) {\n      el.parentNode._pending[vnode.key] = null;\n    }\n    if (expectsCSS) {\n      removeTransitionClass(el, leaveToClass);\n      removeTransitionClass(el, leaveActiveClass);\n    }\n    if (cb.cancelled) {\n      if (expectsCSS) {\n        removeTransitionClass(el, leaveClass);\n      }\n      leaveCancelled && leaveCancelled(el);\n    } else {\n      rm();\n      afterLeave && afterLeave(el);\n    }\n    el._leaveCb = null;\n  });\n\n  if (delayLeave) {\n    delayLeave(performLeave);\n  } else {\n    performLeave();\n  }\n\n  function performLeave () {\n    // the delayed leave may have already been cancelled\n    if (cb.cancelled) {\n      return\n    }\n    // record leaving element\n    if (!vnode.data.show) {\n      (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode;\n    }\n    beforeLeave && beforeLeave(el);\n    if (expectsCSS) {\n      addTransitionClass(el, leaveClass);\n      addTransitionClass(el, leaveActiveClass);\n      nextFrame(function () {\n        addTransitionClass(el, leaveToClass);\n        removeTransitionClass(el, leaveClass);\n        if (!cb.cancelled && !userWantsControl) {\n          if (isValidDuration(explicitLeaveDuration)) {\n            setTimeout(cb, explicitLeaveDuration);\n          } else {\n            whenTransitionEnds(el, type, cb);\n          }\n        }\n      });\n    }\n    leave && leave(el, cb);\n    if (!expectsCSS && !userWantsControl) {\n      cb();\n    }\n  }\n}\n\n// only used in dev mode\nfunction checkDuration (val, name, vnode) {\n  if (typeof val !== 'number') {\n    warn(\n      \"<transition> explicit \" + name + \" duration is not a valid number - \" +\n      \"got \" + (JSON.stringify(val)) + \".\",\n      vnode.context\n    );\n  } else if (isNaN(val)) {\n    warn(\n      \"<transition> explicit \" + name + \" duration is NaN - \" +\n      'the duration expression might be incorrect.',\n      vnode.context\n    );\n  }\n}\n\nfunction isValidDuration (val) {\n  return typeof val === 'number' && !isNaN(val)\n}\n\n/**\n * Normalize a transition hook's argument length. The hook may be:\n * - a merged hook (invoker) with the original in .fns\n * - a wrapped component method (check ._length)\n * - a plain function (.length)\n */\nfunction getHookArgumentsLength (fn) {\n  if (isUndef(fn)) {\n    return false\n  }\n  var invokerFns = fn.fns;\n  if (isDef(invokerFns)) {\n    // invoker\n    return getHookArgumentsLength(\n      Array.isArray(invokerFns)\n        ? invokerFns[0]\n        : invokerFns\n    )\n  } else {\n    return (fn._length || fn.length) > 1\n  }\n}\n\nfunction _enter (_, vnode) {\n  if (vnode.data.show !== true) {\n    enter(vnode);\n  }\n}\n\nvar transition = inBrowser ? {\n  create: _enter,\n  activate: _enter,\n  remove: function remove$$1 (vnode, rm) {\n    /* istanbul ignore else */\n    if (vnode.data.show !== true) {\n      leave(vnode, rm);\n    } else {\n      rm();\n    }\n  }\n} : {};\n\nvar platformModules = [\n  attrs,\n  klass,\n  events,\n  domProps,\n  style,\n  transition\n];\n\n/*  */\n\n// the directive module should be applied last, after all\n// built-in modules have been applied.\nvar modules = platformModules.concat(baseModules);\n\nvar patch = createPatchFunction({ nodeOps: nodeOps, modules: modules });\n\n/**\n * Not type checking this file because flow doesn't like attaching\n * properties to Elements.\n */\n\n/* istanbul ignore if */\nif (isIE9) {\n  // http://www.matts411.com/post/internet-explorer-9-oninput/\n  document.addEventListener('selectionchange', function () {\n    var el = document.activeElement;\n    if (el && el.vmodel) {\n      trigger(el, 'input');\n    }\n  });\n}\n\nvar model$1 = {\n  inserted: function inserted (el, binding, vnode) {\n    if (vnode.tag === 'select') {\n      setSelected(el, binding, vnode.context);\n      el._vOptions = [].map.call(el.options, getValue);\n    } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) {\n      el._vModifiers = binding.modifiers;\n      if (!binding.modifiers.lazy) {\n        // Safari < 10.2 & UIWebView doesn't fire compositionend when\n        // switching focus before confirming composition choice\n        // this also fixes the issue where some browsers e.g. iOS Chrome\n        // fires \"change\" instead of \"input\" on autocomplete.\n        el.addEventListener('change', onCompositionEnd);\n        if (!isAndroid) {\n          el.addEventListener('compositionstart', onCompositionStart);\n          el.addEventListener('compositionend', onCompositionEnd);\n        }\n        /* istanbul ignore if */\n        if (isIE9) {\n          el.vmodel = true;\n        }\n      }\n    }\n  },\n  componentUpdated: function componentUpdated (el, binding, vnode) {\n    if (vnode.tag === 'select') {\n      setSelected(el, binding, vnode.context);\n      // in case the options rendered by v-for have changed,\n      // it's possible that the value is out-of-sync with the rendered options.\n      // detect such cases and filter out values that no longer has a matching\n      // option in the DOM.\n      var prevOptions = el._vOptions;\n      var curOptions = el._vOptions = [].map.call(el.options, getValue);\n      if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) {\n        // trigger change event if\n        // no matching option found for at least one value\n        var needReset = el.multiple\n          ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); })\n          : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions);\n        if (needReset) {\n          trigger(el, 'change');\n        }\n      }\n    }\n  }\n};\n\nfunction setSelected (el, binding, vm) {\n  actuallySetSelected(el, binding, vm);\n  /* istanbul ignore if */\n  if (isIE || isEdge) {\n    setTimeout(function () {\n      actuallySetSelected(el, binding, vm);\n    }, 0);\n  }\n}\n\nfunction actuallySetSelected (el, binding, vm) {\n  var value = binding.value;\n  var isMultiple = el.multiple;\n  if (isMultiple && !Array.isArray(value)) {\n    \"development\" !== 'production' && warn(\n      \"<select multiple v-model=\\\"\" + (binding.expression) + \"\\\"> \" +\n      \"expects an Array value for its binding, but got \" + (Object.prototype.toString.call(value).slice(8, -1)),\n      vm\n    );\n    return\n  }\n  var selected, option;\n  for (var i = 0, l = el.options.length; i < l; i++) {\n    option = el.options[i];\n    if (isMultiple) {\n      selected = looseIndexOf(value, getValue(option)) > -1;\n      if (option.selected !== selected) {\n        option.selected = selected;\n      }\n    } else {\n      if (looseEqual(getValue(option), value)) {\n        if (el.selectedIndex !== i) {\n          el.selectedIndex = i;\n        }\n        return\n      }\n    }\n  }\n  if (!isMultiple) {\n    el.selectedIndex = -1;\n  }\n}\n\nfunction hasNoMatchingOption (value, options) {\n  return options.every(function (o) { return !looseEqual(o, value); })\n}\n\nfunction getValue (option) {\n  return '_value' in option\n    ? option._value\n    : option.value\n}\n\nfunction onCompositionStart (e) {\n  e.target.composing = true;\n}\n\nfunction onCompositionEnd (e) {\n  // prevent triggering an input event for no reason\n  if (!e.target.composing) { return }\n  e.target.composing = false;\n  trigger(e.target, 'input');\n}\n\nfunction trigger (el, type) {\n  var e = document.createEvent('HTMLEvents');\n  e.initEvent(type, true, true);\n  el.dispatchEvent(e);\n}\n\n/*  */\n\n// recursively search for possible transition defined inside the component root\nfunction locateNode (vnode) {\n  return vnode.componentInstance && (!vnode.data || !vnode.data.transition)\n    ? locateNode(vnode.componentInstance._vnode)\n    : vnode\n}\n\nvar show = {\n  bind: function bind (el, ref, vnode) {\n    var value = ref.value;\n\n    vnode = locateNode(vnode);\n    var transition$$1 = vnode.data && vnode.data.transition;\n    var originalDisplay = el.__vOriginalDisplay =\n      el.style.display === 'none' ? '' : el.style.display;\n    if (value && transition$$1) {\n      vnode.data.show = true;\n      enter(vnode, function () {\n        el.style.display = originalDisplay;\n      });\n    } else {\n      el.style.display = value ? originalDisplay : 'none';\n    }\n  },\n\n  update: function update (el, ref, vnode) {\n    var value = ref.value;\n    var oldValue = ref.oldValue;\n\n    /* istanbul ignore if */\n    if (value === oldValue) { return }\n    vnode = locateNode(vnode);\n    var transition$$1 = vnode.data && vnode.data.transition;\n    if (transition$$1) {\n      vnode.data.show = true;\n      if (value) {\n        enter(vnode, function () {\n          el.style.display = el.__vOriginalDisplay;\n        });\n      } else {\n        leave(vnode, function () {\n          el.style.display = 'none';\n        });\n      }\n    } else {\n      el.style.display = value ? el.__vOriginalDisplay : 'none';\n    }\n  },\n\n  unbind: function unbind (\n    el,\n    binding,\n    vnode,\n    oldVnode,\n    isDestroy\n  ) {\n    if (!isDestroy) {\n      el.style.display = el.__vOriginalDisplay;\n    }\n  }\n};\n\nvar platformDirectives = {\n  model: model$1,\n  show: show\n};\n\n/*  */\n\n// Provides transition support for a single element/component.\n// supports transition mode (out-in / in-out)\n\nvar transitionProps = {\n  name: String,\n  appear: Boolean,\n  css: Boolean,\n  mode: String,\n  type: String,\n  enterClass: String,\n  leaveClass: String,\n  enterToClass: String,\n  leaveToClass: String,\n  enterActiveClass: String,\n  leaveActiveClass: String,\n  appearClass: String,\n  appearActiveClass: String,\n  appearToClass: String,\n  duration: [Number, String, Object]\n};\n\n// in case the child is also an abstract component, e.g. <keep-alive>\n// we want to recursively retrieve the real component to be rendered\nfunction getRealChild (vnode) {\n  var compOptions = vnode && vnode.componentOptions;\n  if (compOptions && compOptions.Ctor.options.abstract) {\n    return getRealChild(getFirstComponentChild(compOptions.children))\n  } else {\n    return vnode\n  }\n}\n\nfunction extractTransitionData (comp) {\n  var data = {};\n  var options = comp.$options;\n  // props\n  for (var key in options.propsData) {\n    data[key] = comp[key];\n  }\n  // events.\n  // extract listeners and pass them directly to the transition methods\n  var listeners = options._parentListeners;\n  for (var key$1 in listeners) {\n    data[camelize(key$1)] = listeners[key$1];\n  }\n  return data\n}\n\nfunction placeholder (h, rawChild) {\n  if (/\\d-keep-alive$/.test(rawChild.tag)) {\n    return h('keep-alive', {\n      props: rawChild.componentOptions.propsData\n    })\n  }\n}\n\nfunction hasParentTransition (vnode) {\n  while ((vnode = vnode.parent)) {\n    if (vnode.data.transition) {\n      return true\n    }\n  }\n}\n\nfunction isSameChild (child, oldChild) {\n  return oldChild.key === child.key && oldChild.tag === child.tag\n}\n\nvar Transition = {\n  name: 'transition',\n  props: transitionProps,\n  abstract: true,\n\n  render: function render (h) {\n    var this$1 = this;\n\n    var children = this.$options._renderChildren;\n    if (!children) {\n      return\n    }\n\n    // filter out text nodes (possible whitespaces)\n    children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); });\n    /* istanbul ignore if */\n    if (!children.length) {\n      return\n    }\n\n    // warn multiple elements\n    if (\"development\" !== 'production' && children.length > 1) {\n      warn(\n        '<transition> can only be used on a single element. Use ' +\n        '<transition-group> for lists.',\n        this.$parent\n      );\n    }\n\n    var mode = this.mode;\n\n    // warn invalid mode\n    if (\"development\" !== 'production' &&\n      mode && mode !== 'in-out' && mode !== 'out-in'\n    ) {\n      warn(\n        'invalid <transition> mode: ' + mode,\n        this.$parent\n      );\n    }\n\n    var rawChild = children[0];\n\n    // if this is a component root node and the component's\n    // parent container node also has transition, skip.\n    if (hasParentTransition(this.$vnode)) {\n      return rawChild\n    }\n\n    // apply transition data to child\n    // use getRealChild() to ignore abstract components e.g. keep-alive\n    var child = getRealChild(rawChild);\n    /* istanbul ignore if */\n    if (!child) {\n      return rawChild\n    }\n\n    if (this._leaving) {\n      return placeholder(h, rawChild)\n    }\n\n    // ensure a key that is unique to the vnode type and to this transition\n    // component instance. This key will be used to remove pending leaving nodes\n    // during entering.\n    var id = \"__transition-\" + (this._uid) + \"-\";\n    child.key = child.key == null\n      ? child.isComment\n        ? id + 'comment'\n        : id + child.tag\n      : isPrimitive(child.key)\n        ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)\n        : child.key;\n\n    var data = (child.data || (child.data = {})).transition = extractTransitionData(this);\n    var oldRawChild = this._vnode;\n    var oldChild = getRealChild(oldRawChild);\n\n    // mark v-show\n    // so that the transition module can hand over the control to the directive\n    if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {\n      child.data.show = true;\n    }\n\n    if (\n      oldChild &&\n      oldChild.data &&\n      !isSameChild(child, oldChild) &&\n      !isAsyncPlaceholder(oldChild)\n    ) {\n      // replace old child transition data with fresh one\n      // important for dynamic transitions!\n      var oldData = oldChild && (oldChild.data.transition = extend({}, data));\n      // handle transition mode\n      if (mode === 'out-in') {\n        // return placeholder node and queue update when leave finishes\n        this._leaving = true;\n        mergeVNodeHook(oldData, 'afterLeave', function () {\n          this$1._leaving = false;\n          this$1.$forceUpdate();\n        });\n        return placeholder(h, rawChild)\n      } else if (mode === 'in-out') {\n        if (isAsyncPlaceholder(child)) {\n          return oldRawChild\n        }\n        var delayedLeave;\n        var performLeave = function () { delayedLeave(); };\n        mergeVNodeHook(data, 'afterEnter', performLeave);\n        mergeVNodeHook(data, 'enterCancelled', performLeave);\n        mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; });\n      }\n    }\n\n    return rawChild\n  }\n};\n\n/*  */\n\n// Provides transition support for list items.\n// supports move transitions using the FLIP technique.\n\n// Because the vdom's children update algorithm is \"unstable\" - i.e.\n// it doesn't guarantee the relative positioning of removed elements,\n// we force transition-group to update its children into two passes:\n// in the first pass, we remove all nodes that need to be removed,\n// triggering their leaving transition; in the second pass, we insert/move\n// into the final desired state. This way in the second pass removed\n// nodes will remain where they should be.\n\nvar props = extend({\n  tag: String,\n  moveClass: String\n}, transitionProps);\n\ndelete props.mode;\n\nvar TransitionGroup = {\n  props: props,\n\n  render: function render (h) {\n    var tag = this.tag || this.$vnode.data.tag || 'span';\n    var map = Object.create(null);\n    var prevChildren = this.prevChildren = this.children;\n    var rawChildren = this.$slots.default || [];\n    var children = this.children = [];\n    var transitionData = extractTransitionData(this);\n\n    for (var i = 0; i < rawChildren.length; i++) {\n      var c = rawChildren[i];\n      if (c.tag) {\n        if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {\n          children.push(c);\n          map[c.key] = c\n          ;(c.data || (c.data = {})).transition = transitionData;\n        } else {\n          var opts = c.componentOptions;\n          var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;\n          warn((\"<transition-group> children must be keyed: <\" + name + \">\"));\n        }\n      }\n    }\n\n    if (prevChildren) {\n      var kept = [];\n      var removed = [];\n      for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {\n        var c$1 = prevChildren[i$1];\n        c$1.data.transition = transitionData;\n        c$1.data.pos = c$1.elm.getBoundingClientRect();\n        if (map[c$1.key]) {\n          kept.push(c$1);\n        } else {\n          removed.push(c$1);\n        }\n      }\n      this.kept = h(tag, null, kept);\n      this.removed = removed;\n    }\n\n    return h(tag, null, children)\n  },\n\n  beforeUpdate: function beforeUpdate () {\n    // force removing pass\n    this.__patch__(\n      this._vnode,\n      this.kept,\n      false, // hydrating\n      true // removeOnly (!important, avoids unnecessary moves)\n    );\n    this._vnode = this.kept;\n  },\n\n  updated: function updated () {\n    var children = this.prevChildren;\n    var moveClass = this.moveClass || ((this.name || 'v') + '-move');\n    if (!children.length || !this.hasMove(children[0].elm, moveClass)) {\n      return\n    }\n\n    // we divide the work into three loops to avoid mixing DOM reads and writes\n    // in each iteration - which helps prevent layout thrashing.\n    children.forEach(callPendingCbs);\n    children.forEach(recordPosition);\n    children.forEach(applyTranslation);\n\n    // force reflow to put everything in position\n    var body = document.body;\n    var f = body.offsetHeight; // eslint-disable-line\n\n    children.forEach(function (c) {\n      if (c.data.moved) {\n        var el = c.elm;\n        var s = el.style;\n        addTransitionClass(el, moveClass);\n        s.transform = s.WebkitTransform = s.transitionDuration = '';\n        el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {\n          if (!e || /transform$/.test(e.propertyName)) {\n            el.removeEventListener(transitionEndEvent, cb);\n            el._moveCb = null;\n            removeTransitionClass(el, moveClass);\n          }\n        });\n      }\n    });\n  },\n\n  methods: {\n    hasMove: function hasMove (el, moveClass) {\n      /* istanbul ignore if */\n      if (!hasTransition) {\n        return false\n      }\n      /* istanbul ignore if */\n      if (this._hasMove) {\n        return this._hasMove\n      }\n      // Detect whether an element with the move class applied has\n      // CSS transitions. Since the element may be inside an entering\n      // transition at this very moment, we make a clone of it and remove\n      // all other transition classes applied to ensure only the move class\n      // is applied.\n      var clone = el.cloneNode();\n      if (el._transitionClasses) {\n        el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); });\n      }\n      addClass(clone, moveClass);\n      clone.style.display = 'none';\n      this.$el.appendChild(clone);\n      var info = getTransitionInfo(clone);\n      this.$el.removeChild(clone);\n      return (this._hasMove = info.hasTransform)\n    }\n  }\n};\n\nfunction callPendingCbs (c) {\n  /* istanbul ignore if */\n  if (c.elm._moveCb) {\n    c.elm._moveCb();\n  }\n  /* istanbul ignore if */\n  if (c.elm._enterCb) {\n    c.elm._enterCb();\n  }\n}\n\nfunction recordPosition (c) {\n  c.data.newPos = c.elm.getBoundingClientRect();\n}\n\nfunction applyTranslation (c) {\n  var oldPos = c.data.pos;\n  var newPos = c.data.newPos;\n  var dx = oldPos.left - newPos.left;\n  var dy = oldPos.top - newPos.top;\n  if (dx || dy) {\n    c.data.moved = true;\n    var s = c.elm.style;\n    s.transform = s.WebkitTransform = \"translate(\" + dx + \"px,\" + dy + \"px)\";\n    s.transitionDuration = '0s';\n  }\n}\n\nvar platformComponents = {\n  Transition: Transition,\n  TransitionGroup: TransitionGroup\n};\n\n/*  */\n\n// install platform specific utils\nVue$3.config.mustUseProp = mustUseProp;\nVue$3.config.isReservedTag = isReservedTag;\nVue$3.config.isReservedAttr = isReservedAttr;\nVue$3.config.getTagNamespace = getTagNamespace;\nVue$3.config.isUnknownElement = isUnknownElement;\n\n// install platform runtime directives & components\nextend(Vue$3.options.directives, platformDirectives);\nextend(Vue$3.options.components, platformComponents);\n\n// install platform patch function\nVue$3.prototype.__patch__ = inBrowser ? patch : noop;\n\n// public mount method\nVue$3.prototype.$mount = function (\n  el,\n  hydrating\n) {\n  el = el && inBrowser ? query(el) : undefined;\n  return mountComponent(this, el, hydrating)\n};\n\n// devtools global hook\n/* istanbul ignore next */\nsetTimeout(function () {\n  if (config.devtools) {\n    if (devtools) {\n      devtools.emit('init', Vue$3);\n    } else if (\"development\" !== 'production' && isChrome) {\n      console[console.info ? 'info' : 'log'](\n        'Download the Vue Devtools extension for a better development experience:\\n' +\n        'https://github.com/vuejs/vue-devtools'\n      );\n    }\n  }\n  if (\"development\" !== 'production' &&\n    config.productionTip !== false &&\n    inBrowser && typeof console !== 'undefined'\n  ) {\n    console[console.info ? 'info' : 'log'](\n      \"You are running Vue in development mode.\\n\" +\n      \"Make sure to turn on production mode when deploying for production.\\n\" +\n      \"See more tips at https://vuejs.org/guide/deployment.html\"\n    );\n  }\n}, 0);\n\n/*  */\n\n// check whether current browser encodes a char inside attribute values\nfunction shouldDecode (content, encoded) {\n  var div = document.createElement('div');\n  div.innerHTML = \"<div a=\\\"\" + content + \"\\\"/>\";\n  return div.innerHTML.indexOf(encoded) > 0\n}\n\n// #3663\n// IE encodes newlines inside attribute values while other browsers don't\nvar shouldDecodeNewlines = inBrowser ? shouldDecode('\\n', '&#10;') : false;\n\n/*  */\n\nvar defaultTagRE = /\\{\\{((?:.|\\n)+?)\\}\\}/g;\nvar regexEscapeRE = /[-.*+?^${}()|[\\]\\/\\\\]/g;\n\nvar buildRegex = cached(function (delimiters) {\n  var open = delimiters[0].replace(regexEscapeRE, '\\\\$&');\n  var close = delimiters[1].replace(regexEscapeRE, '\\\\$&');\n  return new RegExp(open + '((?:.|\\\\n)+?)' + close, 'g')\n});\n\nfunction parseText (\n  text,\n  delimiters\n) {\n  var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;\n  if (!tagRE.test(text)) {\n    return\n  }\n  var tokens = [];\n  var lastIndex = tagRE.lastIndex = 0;\n  var match, index;\n  while ((match = tagRE.exec(text))) {\n    index = match.index;\n    // push text token\n    if (index > lastIndex) {\n      tokens.push(JSON.stringify(text.slice(lastIndex, index)));\n    }\n    // tag token\n    var exp = parseFilters(match[1].trim());\n    tokens.push((\"_s(\" + exp + \")\"));\n    lastIndex = index + match[0].length;\n  }\n  if (lastIndex < text.length) {\n    tokens.push(JSON.stringify(text.slice(lastIndex)));\n  }\n  return tokens.join('+')\n}\n\n/*  */\n\nfunction transformNode (el, options) {\n  var warn = options.warn || baseWarn;\n  var staticClass = getAndRemoveAttr(el, 'class');\n  if (\"development\" !== 'production' && staticClass) {\n    var expression = parseText(staticClass, options.delimiters);\n    if (expression) {\n      warn(\n        \"class=\\\"\" + staticClass + \"\\\": \" +\n        'Interpolation inside attributes has been removed. ' +\n        'Use v-bind or the colon shorthand instead. For example, ' +\n        'instead of <div class=\"{{ val }}\">, use <div :class=\"val\">.'\n      );\n    }\n  }\n  if (staticClass) {\n    el.staticClass = JSON.stringify(staticClass);\n  }\n  var classBinding = getBindingAttr(el, 'class', false /* getStatic */);\n  if (classBinding) {\n    el.classBinding = classBinding;\n  }\n}\n\nfunction genData (el) {\n  var data = '';\n  if (el.staticClass) {\n    data += \"staticClass:\" + (el.staticClass) + \",\";\n  }\n  if (el.classBinding) {\n    data += \"class:\" + (el.classBinding) + \",\";\n  }\n  return data\n}\n\nvar klass$1 = {\n  staticKeys: ['staticClass'],\n  transformNode: transformNode,\n  genData: genData\n};\n\n/*  */\n\nfunction transformNode$1 (el, options) {\n  var warn = options.warn || baseWarn;\n  var staticStyle = getAndRemoveAttr(el, 'style');\n  if (staticStyle) {\n    /* istanbul ignore if */\n    {\n      var expression = parseText(staticStyle, options.delimiters);\n      if (expression) {\n        warn(\n          \"style=\\\"\" + staticStyle + \"\\\": \" +\n          'Interpolation inside attributes has been removed. ' +\n          'Use v-bind or the colon shorthand instead. For example, ' +\n          'instead of <div style=\"{{ val }}\">, use <div :style=\"val\">.'\n        );\n      }\n    }\n    el.staticStyle = JSON.stringify(parseStyleText(staticStyle));\n  }\n\n  var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);\n  if (styleBinding) {\n    el.styleBinding = styleBinding;\n  }\n}\n\nfunction genData$1 (el) {\n  var data = '';\n  if (el.staticStyle) {\n    data += \"staticStyle:\" + (el.staticStyle) + \",\";\n  }\n  if (el.styleBinding) {\n    data += \"style:(\" + (el.styleBinding) + \"),\";\n  }\n  return data\n}\n\nvar style$1 = {\n  staticKeys: ['staticStyle'],\n  transformNode: transformNode$1,\n  genData: genData$1\n};\n\nvar modules$1 = [\n  klass$1,\n  style$1\n];\n\n/*  */\n\nfunction text (el, dir) {\n  if (dir.value) {\n    addProp(el, 'textContent', (\"_s(\" + (dir.value) + \")\"));\n  }\n}\n\n/*  */\n\nfunction html (el, dir) {\n  if (dir.value) {\n    addProp(el, 'innerHTML', (\"_s(\" + (dir.value) + \")\"));\n  }\n}\n\nvar directives$1 = {\n  model: model,\n  text: text,\n  html: html\n};\n\n/*  */\n\nvar isUnaryTag = makeMap(\n  'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +\n  'link,meta,param,source,track,wbr'\n);\n\n// Elements that you can, intentionally, leave open\n// (and which close themselves)\nvar canBeLeftOpenTag = makeMap(\n  'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'\n);\n\n// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3\n// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content\nvar isNonPhrasingTag = makeMap(\n  'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +\n  'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +\n  'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +\n  'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +\n  'title,tr,track'\n);\n\n/*  */\n\nvar baseOptions = {\n  expectHTML: true,\n  modules: modules$1,\n  directives: directives$1,\n  isPreTag: isPreTag,\n  isUnaryTag: isUnaryTag,\n  mustUseProp: mustUseProp,\n  canBeLeftOpenTag: canBeLeftOpenTag,\n  isReservedTag: isReservedTag,\n  getTagNamespace: getTagNamespace,\n  staticKeys: genStaticKeys(modules$1)\n};\n\n/*  */\n\nvar decoder;\n\nvar he = {\n  decode: function decode (html) {\n    decoder = decoder || document.createElement('div');\n    decoder.innerHTML = html;\n    return decoder.textContent\n  }\n};\n\n/**\n * Not type-checking this file because it's mostly vendor code.\n */\n\n/*!\n * HTML Parser By John Resig (ejohn.org)\n * Modified by Juriy \"kangax\" Zaytsev\n * Original code by Erik Arvidsson, Mozilla Public License\n * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js\n */\n\n// Regular Expressions for parsing tags and attributes\nvar attribute = /^\\s*([^\\s\"'<>\\/=]+)(?:\\s*(=)\\s*(?:\"([^\"]*)\"+|'([^']*)'+|([^\\s\"'=<>`]+)))?/;\n// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName\n// but for Vue templates we can enforce a simple charset\nvar ncname = '[a-zA-Z_][\\\\w\\\\-\\\\.]*';\nvar qnameCapture = \"((?:\" + ncname + \"\\\\:)?\" + ncname + \")\";\nvar startTagOpen = new RegExp((\"^<\" + qnameCapture));\nvar startTagClose = /^\\s*(\\/?)>/;\nvar endTag = new RegExp((\"^<\\\\/\" + qnameCapture + \"[^>]*>\"));\nvar doctype = /^<!DOCTYPE [^>]+>/i;\nvar comment = /^<!--/;\nvar conditionalComment = /^<!\\[/;\n\nvar IS_REGEX_CAPTURING_BROKEN = false;\n'x'.replace(/x(.)?/g, function (m, g) {\n  IS_REGEX_CAPTURING_BROKEN = g === '';\n});\n\n// Special Elements (can contain anything)\nvar isPlainTextElement = makeMap('script,style,textarea', true);\nvar reCache = {};\n\nvar decodingMap = {\n  '&lt;': '<',\n  '&gt;': '>',\n  '&quot;': '\"',\n  '&amp;': '&',\n  '&#10;': '\\n'\n};\nvar encodedAttr = /&(?:lt|gt|quot|amp);/g;\nvar encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g;\n\n// #5992\nvar isIgnoreNewlineTag = makeMap('pre,textarea', true);\nvar shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'; };\n\nfunction decodeAttr (value, shouldDecodeNewlines) {\n  var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;\n  return value.replace(re, function (match) { return decodingMap[match]; })\n}\n\nfunction parseHTML (html, options) {\n  var stack = [];\n  var expectHTML = options.expectHTML;\n  var isUnaryTag$$1 = options.isUnaryTag || no;\n  var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;\n  var index = 0;\n  var last, lastTag;\n  while (html) {\n    last = html;\n    // Make sure we're not in a plaintext content element like script/style\n    if (!lastTag || !isPlainTextElement(lastTag)) {\n      var textEnd = html.indexOf('<');\n      if (textEnd === 0) {\n        // Comment:\n        if (comment.test(html)) {\n          var commentEnd = html.indexOf('-->');\n\n          if (commentEnd >= 0) {\n            if (options.shouldKeepComment) {\n              options.comment(html.substring(4, commentEnd));\n            }\n            advance(commentEnd + 3);\n            continue\n          }\n        }\n\n        // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment\n        if (conditionalComment.test(html)) {\n          var conditionalEnd = html.indexOf(']>');\n\n          if (conditionalEnd >= 0) {\n            advance(conditionalEnd + 2);\n            continue\n          }\n        }\n\n        // Doctype:\n        var doctypeMatch = html.match(doctype);\n        if (doctypeMatch) {\n          advance(doctypeMatch[0].length);\n          continue\n        }\n\n        // End tag:\n        var endTagMatch = html.match(endTag);\n        if (endTagMatch) {\n          var curIndex = index;\n          advance(endTagMatch[0].length);\n          parseEndTag(endTagMatch[1], curIndex, index);\n          continue\n        }\n\n        // Start tag:\n        var startTagMatch = parseStartTag();\n        if (startTagMatch) {\n          handleStartTag(startTagMatch);\n          if (shouldIgnoreFirstNewline(lastTag, html)) {\n            advance(1);\n          }\n          continue\n        }\n      }\n\n      var text = (void 0), rest = (void 0), next = (void 0);\n      if (textEnd >= 0) {\n        rest = html.slice(textEnd);\n        while (\n          !endTag.test(rest) &&\n          !startTagOpen.test(rest) &&\n          !comment.test(rest) &&\n          !conditionalComment.test(rest)\n        ) {\n          // < in plain text, be forgiving and treat it as text\n          next = rest.indexOf('<', 1);\n          if (next < 0) { break }\n          textEnd += next;\n          rest = html.slice(textEnd);\n        }\n        text = html.substring(0, textEnd);\n        advance(textEnd);\n      }\n\n      if (textEnd < 0) {\n        text = html;\n        html = '';\n      }\n\n      if (options.chars && text) {\n        options.chars(text);\n      }\n    } else {\n      var endTagLength = 0;\n      var stackedTag = lastTag.toLowerCase();\n      var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\\\s\\\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));\n      var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {\n        endTagLength = endTag.length;\n        if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {\n          text = text\n            .replace(/<!--([\\s\\S]*?)-->/g, '$1')\n            .replace(/<!\\[CDATA\\[([\\s\\S]*?)]]>/g, '$1');\n        }\n        if (shouldIgnoreFirstNewline(stackedTag, text)) {\n          text = text.slice(1);\n        }\n        if (options.chars) {\n          options.chars(text);\n        }\n        return ''\n      });\n      index += html.length - rest$1.length;\n      html = rest$1;\n      parseEndTag(stackedTag, index - endTagLength, index);\n    }\n\n    if (html === last) {\n      options.chars && options.chars(html);\n      if (\"development\" !== 'production' && !stack.length && options.warn) {\n        options.warn((\"Mal-formatted tag at end of template: \\\"\" + html + \"\\\"\"));\n      }\n      break\n    }\n  }\n\n  // Clean up any remaining tags\n  parseEndTag();\n\n  function advance (n) {\n    index += n;\n    html = html.substring(n);\n  }\n\n  function parseStartTag () {\n    var start = html.match(startTagOpen);\n    if (start) {\n      var match = {\n        tagName: start[1],\n        attrs: [],\n        start: index\n      };\n      advance(start[0].length);\n      var end, attr;\n      while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {\n        advance(attr[0].length);\n        match.attrs.push(attr);\n      }\n      if (end) {\n        match.unarySlash = end[1];\n        advance(end[0].length);\n        match.end = index;\n        return match\n      }\n    }\n  }\n\n  function handleStartTag (match) {\n    var tagName = match.tagName;\n    var unarySlash = match.unarySlash;\n\n    if (expectHTML) {\n      if (lastTag === 'p' && isNonPhrasingTag(tagName)) {\n        parseEndTag(lastTag);\n      }\n      if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {\n        parseEndTag(tagName);\n      }\n    }\n\n    var unary = isUnaryTag$$1(tagName) || !!unarySlash;\n\n    var l = match.attrs.length;\n    var attrs = new Array(l);\n    for (var i = 0; i < l; i++) {\n      var args = match.attrs[i];\n      // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778\n      if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('\"\"') === -1) {\n        if (args[3] === '') { delete args[3]; }\n        if (args[4] === '') { delete args[4]; }\n        if (args[5] === '') { delete args[5]; }\n      }\n      var value = args[3] || args[4] || args[5] || '';\n      attrs[i] = {\n        name: args[1],\n        value: decodeAttr(\n          value,\n          options.shouldDecodeNewlines\n        )\n      };\n    }\n\n    if (!unary) {\n      stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });\n      lastTag = tagName;\n    }\n\n    if (options.start) {\n      options.start(tagName, attrs, unary, match.start, match.end);\n    }\n  }\n\n  function parseEndTag (tagName, start, end) {\n    var pos, lowerCasedTagName;\n    if (start == null) { start = index; }\n    if (end == null) { end = index; }\n\n    if (tagName) {\n      lowerCasedTagName = tagName.toLowerCase();\n    }\n\n    // Find the closest opened tag of the same type\n    if (tagName) {\n      for (pos = stack.length - 1; pos >= 0; pos--) {\n        if (stack[pos].lowerCasedTag === lowerCasedTagName) {\n          break\n        }\n      }\n    } else {\n      // If no tag name is provided, clean shop\n      pos = 0;\n    }\n\n    if (pos >= 0) {\n      // Close all the open elements, up the stack\n      for (var i = stack.length - 1; i >= pos; i--) {\n        if (\"development\" !== 'production' &&\n          (i > pos || !tagName) &&\n          options.warn\n        ) {\n          options.warn(\n            (\"tag <\" + (stack[i].tag) + \"> has no matching end tag.\")\n          );\n        }\n        if (options.end) {\n          options.end(stack[i].tag, start, end);\n        }\n      }\n\n      // Remove the open elements from the stack\n      stack.length = pos;\n      lastTag = pos && stack[pos - 1].tag;\n    } else if (lowerCasedTagName === 'br') {\n      if (options.start) {\n        options.start(tagName, [], true, start, end);\n      }\n    } else if (lowerCasedTagName === 'p') {\n      if (options.start) {\n        options.start(tagName, [], false, start, end);\n      }\n      if (options.end) {\n        options.end(tagName, start, end);\n      }\n    }\n  }\n}\n\n/*  */\n\nvar onRE = /^@|^v-on:/;\nvar dirRE = /^v-|^@|^:/;\nvar forAliasRE = /(.*?)\\s+(?:in|of)\\s+(.*)/;\nvar forIteratorRE = /\\((\\{[^}]*\\}|[^,]*),([^,]*)(?:,([^,]*))?\\)/;\n\nvar argRE = /:(.*)$/;\nvar bindRE = /^:|^v-bind:/;\nvar modifierRE = /\\.[^.]+/g;\n\nvar decodeHTMLCached = cached(he.decode);\n\n// configurable state\nvar warn$2;\nvar delimiters;\nvar transforms;\nvar preTransforms;\nvar postTransforms;\nvar platformIsPreTag;\nvar platformMustUseProp;\nvar platformGetTagNamespace;\n\n/**\n * Convert HTML string to AST.\n */\nfunction parse (\n  template,\n  options\n) {\n  warn$2 = options.warn || baseWarn;\n\n  platformIsPreTag = options.isPreTag || no;\n  platformMustUseProp = options.mustUseProp || no;\n  platformGetTagNamespace = options.getTagNamespace || no;\n\n  transforms = pluckModuleFunction(options.modules, 'transformNode');\n  preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');\n  postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');\n\n  delimiters = options.delimiters;\n\n  var stack = [];\n  var preserveWhitespace = options.preserveWhitespace !== false;\n  var root;\n  var currentParent;\n  var inVPre = false;\n  var inPre = false;\n  var warned = false;\n\n  function warnOnce (msg) {\n    if (!warned) {\n      warned = true;\n      warn$2(msg);\n    }\n  }\n\n  function endPre (element) {\n    // check pre state\n    if (element.pre) {\n      inVPre = false;\n    }\n    if (platformIsPreTag(element.tag)) {\n      inPre = false;\n    }\n  }\n\n  parseHTML(template, {\n    warn: warn$2,\n    expectHTML: options.expectHTML,\n    isUnaryTag: options.isUnaryTag,\n    canBeLeftOpenTag: options.canBeLeftOpenTag,\n    shouldDecodeNewlines: options.shouldDecodeNewlines,\n    shouldKeepComment: options.comments,\n    start: function start (tag, attrs, unary) {\n      // check namespace.\n      // inherit parent ns if there is one\n      var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);\n\n      // handle IE svg bug\n      /* istanbul ignore if */\n      if (isIE && ns === 'svg') {\n        attrs = guardIESVGBug(attrs);\n      }\n\n      var element = {\n        type: 1,\n        tag: tag,\n        attrsList: attrs,\n        attrsMap: makeAttrsMap(attrs),\n        parent: currentParent,\n        children: []\n      };\n      if (ns) {\n        element.ns = ns;\n      }\n\n      if (isForbiddenTag(element) && !isServerRendering()) {\n        element.forbidden = true;\n        \"development\" !== 'production' && warn$2(\n          'Templates should only be responsible for mapping the state to the ' +\n          'UI. Avoid placing tags with side-effects in your templates, such as ' +\n          \"<\" + tag + \">\" + ', as they will not be parsed.'\n        );\n      }\n\n      // apply pre-transforms\n      for (var i = 0; i < preTransforms.length; i++) {\n        preTransforms[i](element, options);\n      }\n\n      if (!inVPre) {\n        processPre(element);\n        if (element.pre) {\n          inVPre = true;\n        }\n      }\n      if (platformIsPreTag(element.tag)) {\n        inPre = true;\n      }\n      if (inVPre) {\n        processRawAttrs(element);\n      } else {\n        processFor(element);\n        processIf(element);\n        processOnce(element);\n        processKey(element);\n\n        // determine whether this is a plain element after\n        // removing structural attributes\n        element.plain = !element.key && !attrs.length;\n\n        processRef(element);\n        processSlot(element);\n        processComponent(element);\n        for (var i$1 = 0; i$1 < transforms.length; i$1++) {\n          transforms[i$1](element, options);\n        }\n        processAttrs(element);\n      }\n\n      function checkRootConstraints (el) {\n        {\n          if (el.tag === 'slot' || el.tag === 'template') {\n            warnOnce(\n              \"Cannot use <\" + (el.tag) + \"> as component root element because it may \" +\n              'contain multiple nodes.'\n            );\n          }\n          if (el.attrsMap.hasOwnProperty('v-for')) {\n            warnOnce(\n              'Cannot use v-for on stateful component root element because ' +\n              'it renders multiple elements.'\n            );\n          }\n        }\n      }\n\n      // tree management\n      if (!root) {\n        root = element;\n        checkRootConstraints(root);\n      } else if (!stack.length) {\n        // allow root elements with v-if, v-else-if and v-else\n        if (root.if && (element.elseif || element.else)) {\n          checkRootConstraints(element);\n          addIfCondition(root, {\n            exp: element.elseif,\n            block: element\n          });\n        } else {\n          warnOnce(\n            \"Component template should contain exactly one root element. \" +\n            \"If you are using v-if on multiple elements, \" +\n            \"use v-else-if to chain them instead.\"\n          );\n        }\n      }\n      if (currentParent && !element.forbidden) {\n        if (element.elseif || element.else) {\n          processIfConditions(element, currentParent);\n        } else if (element.slotScope) { // scoped slot\n          currentParent.plain = false;\n          var name = element.slotTarget || '\"default\"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;\n        } else {\n          currentParent.children.push(element);\n          element.parent = currentParent;\n        }\n      }\n      if (!unary) {\n        currentParent = element;\n        stack.push(element);\n      } else {\n        endPre(element);\n      }\n      // apply post-transforms\n      for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {\n        postTransforms[i$2](element, options);\n      }\n    },\n\n    end: function end () {\n      // remove trailing whitespace\n      var element = stack[stack.length - 1];\n      var lastNode = element.children[element.children.length - 1];\n      if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {\n        element.children.pop();\n      }\n      // pop stack\n      stack.length -= 1;\n      currentParent = stack[stack.length - 1];\n      endPre(element);\n    },\n\n    chars: function chars (text) {\n      if (!currentParent) {\n        {\n          if (text === template) {\n            warnOnce(\n              'Component template requires a root element, rather than just text.'\n            );\n          } else if ((text = text.trim())) {\n            warnOnce(\n              (\"text \\\"\" + text + \"\\\" outside root element will be ignored.\")\n            );\n          }\n        }\n        return\n      }\n      // IE textarea placeholder bug\n      /* istanbul ignore if */\n      if (isIE &&\n        currentParent.tag === 'textarea' &&\n        currentParent.attrsMap.placeholder === text\n      ) {\n        return\n      }\n      var children = currentParent.children;\n      text = inPre || text.trim()\n        ? isTextTag(currentParent) ? text : decodeHTMLCached(text)\n        // only preserve whitespace if its not right after a starting tag\n        : preserveWhitespace && children.length ? ' ' : '';\n      if (text) {\n        var expression;\n        if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {\n          children.push({\n            type: 2,\n            expression: expression,\n            text: text\n          });\n        } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {\n          children.push({\n            type: 3,\n            text: text\n          });\n        }\n      }\n    },\n    comment: function comment (text) {\n      currentParent.children.push({\n        type: 3,\n        text: text,\n        isComment: true\n      });\n    }\n  });\n  return root\n}\n\nfunction processPre (el) {\n  if (getAndRemoveAttr(el, 'v-pre') != null) {\n    el.pre = true;\n  }\n}\n\nfunction processRawAttrs (el) {\n  var l = el.attrsList.length;\n  if (l) {\n    var attrs = el.attrs = new Array(l);\n    for (var i = 0; i < l; i++) {\n      attrs[i] = {\n        name: el.attrsList[i].name,\n        value: JSON.stringify(el.attrsList[i].value)\n      };\n    }\n  } else if (!el.pre) {\n    // non root node in pre blocks with no attributes\n    el.plain = true;\n  }\n}\n\nfunction processKey (el) {\n  var exp = getBindingAttr(el, 'key');\n  if (exp) {\n    if (\"development\" !== 'production' && el.tag === 'template') {\n      warn$2(\"<template> cannot be keyed. Place the key on real elements instead.\");\n    }\n    el.key = exp;\n  }\n}\n\nfunction processRef (el) {\n  var ref = getBindingAttr(el, 'ref');\n  if (ref) {\n    el.ref = ref;\n    el.refInFor = checkInFor(el);\n  }\n}\n\nfunction processFor (el) {\n  var exp;\n  if ((exp = getAndRemoveAttr(el, 'v-for'))) {\n    var inMatch = exp.match(forAliasRE);\n    if (!inMatch) {\n      \"development\" !== 'production' && warn$2(\n        (\"Invalid v-for expression: \" + exp)\n      );\n      return\n    }\n    el.for = inMatch[2].trim();\n    var alias = inMatch[1].trim();\n    var iteratorMatch = alias.match(forIteratorRE);\n    if (iteratorMatch) {\n      el.alias = iteratorMatch[1].trim();\n      el.iterator1 = iteratorMatch[2].trim();\n      if (iteratorMatch[3]) {\n        el.iterator2 = iteratorMatch[3].trim();\n      }\n    } else {\n      el.alias = alias;\n    }\n  }\n}\n\nfunction processIf (el) {\n  var exp = getAndRemoveAttr(el, 'v-if');\n  if (exp) {\n    el.if = exp;\n    addIfCondition(el, {\n      exp: exp,\n      block: el\n    });\n  } else {\n    if (getAndRemoveAttr(el, 'v-else') != null) {\n      el.else = true;\n    }\n    var elseif = getAndRemoveAttr(el, 'v-else-if');\n    if (elseif) {\n      el.elseif = elseif;\n    }\n  }\n}\n\nfunction processIfConditions (el, parent) {\n  var prev = findPrevElement(parent.children);\n  if (prev && prev.if) {\n    addIfCondition(prev, {\n      exp: el.elseif,\n      block: el\n    });\n  } else {\n    warn$2(\n      \"v-\" + (el.elseif ? ('else-if=\"' + el.elseif + '\"') : 'else') + \" \" +\n      \"used on element <\" + (el.tag) + \"> without corresponding v-if.\"\n    );\n  }\n}\n\nfunction findPrevElement (children) {\n  var i = children.length;\n  while (i--) {\n    if (children[i].type === 1) {\n      return children[i]\n    } else {\n      if (\"development\" !== 'production' && children[i].text !== ' ') {\n        warn$2(\n          \"text \\\"\" + (children[i].text.trim()) + \"\\\" between v-if and v-else(-if) \" +\n          \"will be ignored.\"\n        );\n      }\n      children.pop();\n    }\n  }\n}\n\nfunction addIfCondition (el, condition) {\n  if (!el.ifConditions) {\n    el.ifConditions = [];\n  }\n  el.ifConditions.push(condition);\n}\n\nfunction processOnce (el) {\n  var once$$1 = getAndRemoveAttr(el, 'v-once');\n  if (once$$1 != null) {\n    el.once = true;\n  }\n}\n\nfunction processSlot (el) {\n  if (el.tag === 'slot') {\n    el.slotName = getBindingAttr(el, 'name');\n    if (\"development\" !== 'production' && el.key) {\n      warn$2(\n        \"`key` does not work on <slot> because slots are abstract outlets \" +\n        \"and can possibly expand into multiple elements. \" +\n        \"Use the key on a wrapping element instead.\"\n      );\n    }\n  } else {\n    var slotTarget = getBindingAttr(el, 'slot');\n    if (slotTarget) {\n      el.slotTarget = slotTarget === '\"\"' ? '\"default\"' : slotTarget;\n      // preserve slot as an attribute for native shadow DOM compat\n      addAttr(el, 'slot', slotTarget);\n    }\n    if (el.tag === 'template') {\n      el.slotScope = getAndRemoveAttr(el, 'scope');\n    }\n  }\n}\n\nfunction processComponent (el) {\n  var binding;\n  if ((binding = getBindingAttr(el, 'is'))) {\n    el.component = binding;\n  }\n  if (getAndRemoveAttr(el, 'inline-template') != null) {\n    el.inlineTemplate = true;\n  }\n}\n\nfunction processAttrs (el) {\n  var list = el.attrsList;\n  var i, l, name, rawName, value, modifiers, isProp;\n  for (i = 0, l = list.length; i < l; i++) {\n    name = rawName = list[i].name;\n    value = list[i].value;\n    if (dirRE.test(name)) {\n      // mark element as dynamic\n      el.hasBindings = true;\n      // modifiers\n      modifiers = parseModifiers(name);\n      if (modifiers) {\n        name = name.replace(modifierRE, '');\n      }\n      if (bindRE.test(name)) { // v-bind\n        name = name.replace(bindRE, '');\n        value = parseFilters(value);\n        isProp = false;\n        if (modifiers) {\n          if (modifiers.prop) {\n            isProp = true;\n            name = camelize(name);\n            if (name === 'innerHtml') { name = 'innerHTML'; }\n          }\n          if (modifiers.camel) {\n            name = camelize(name);\n          }\n          if (modifiers.sync) {\n            addHandler(\n              el,\n              (\"update:\" + (camelize(name))),\n              genAssignmentCode(value, \"$event\")\n            );\n          }\n        }\n        if (isProp || (\n          !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)\n        )) {\n          addProp(el, name, value);\n        } else {\n          addAttr(el, name, value);\n        }\n      } else if (onRE.test(name)) { // v-on\n        name = name.replace(onRE, '');\n        addHandler(el, name, value, modifiers, false, warn$2);\n      } else { // normal directives\n        name = name.replace(dirRE, '');\n        // parse arg\n        var argMatch = name.match(argRE);\n        var arg = argMatch && argMatch[1];\n        if (arg) {\n          name = name.slice(0, -(arg.length + 1));\n        }\n        addDirective(el, name, rawName, value, arg, modifiers);\n        if (\"development\" !== 'production' && name === 'model') {\n          checkForAliasModel(el, value);\n        }\n      }\n    } else {\n      // literal attribute\n      {\n        var expression = parseText(value, delimiters);\n        if (expression) {\n          warn$2(\n            name + \"=\\\"\" + value + \"\\\": \" +\n            'Interpolation inside attributes has been removed. ' +\n            'Use v-bind or the colon shorthand instead. For example, ' +\n            'instead of <div id=\"{{ val }}\">, use <div :id=\"val\">.'\n          );\n        }\n      }\n      addAttr(el, name, JSON.stringify(value));\n    }\n  }\n}\n\nfunction checkInFor (el) {\n  var parent = el;\n  while (parent) {\n    if (parent.for !== undefined) {\n      return true\n    }\n    parent = parent.parent;\n  }\n  return false\n}\n\nfunction parseModifiers (name) {\n  var match = name.match(modifierRE);\n  if (match) {\n    var ret = {};\n    match.forEach(function (m) { ret[m.slice(1)] = true; });\n    return ret\n  }\n}\n\nfunction makeAttrsMap (attrs) {\n  var map = {};\n  for (var i = 0, l = attrs.length; i < l; i++) {\n    if (\n      \"development\" !== 'production' &&\n      map[attrs[i].name] && !isIE && !isEdge\n    ) {\n      warn$2('duplicate attribute: ' + attrs[i].name);\n    }\n    map[attrs[i].name] = attrs[i].value;\n  }\n  return map\n}\n\n// for script (e.g. type=\"x/template\") or style, do not decode content\nfunction isTextTag (el) {\n  return el.tag === 'script' || el.tag === 'style'\n}\n\nfunction isForbiddenTag (el) {\n  return (\n    el.tag === 'style' ||\n    (el.tag === 'script' && (\n      !el.attrsMap.type ||\n      el.attrsMap.type === 'text/javascript'\n    ))\n  )\n}\n\nvar ieNSBug = /^xmlns:NS\\d+/;\nvar ieNSPrefix = /^NS\\d+:/;\n\n/* istanbul ignore next */\nfunction guardIESVGBug (attrs) {\n  var res = [];\n  for (var i = 0; i < attrs.length; i++) {\n    var attr = attrs[i];\n    if (!ieNSBug.test(attr.name)) {\n      attr.name = attr.name.replace(ieNSPrefix, '');\n      res.push(attr);\n    }\n  }\n  return res\n}\n\nfunction checkForAliasModel (el, value) {\n  var _el = el;\n  while (_el) {\n    if (_el.for && _el.alias === value) {\n      warn$2(\n        \"<\" + (el.tag) + \" v-model=\\\"\" + value + \"\\\">: \" +\n        \"You are binding v-model directly to a v-for iteration alias. \" +\n        \"This will not be able to modify the v-for source array because \" +\n        \"writing to the alias is like modifying a function local variable. \" +\n        \"Consider using an array of objects and use v-model on an object property instead.\"\n      );\n    }\n    _el = _el.parent;\n  }\n}\n\n/*  */\n\nvar isStaticKey;\nvar isPlatformReservedTag;\n\nvar genStaticKeysCached = cached(genStaticKeys$1);\n\n/**\n * Goal of the optimizer: walk the generated template AST tree\n * and detect sub-trees that are purely static, i.e. parts of\n * the DOM that never needs to change.\n *\n * Once we detect these sub-trees, we can:\n *\n * 1. Hoist them into constants, so that we no longer need to\n *    create fresh nodes for them on each re-render;\n * 2. Completely skip them in the patching process.\n */\nfunction optimize (root, options) {\n  if (!root) { return }\n  isStaticKey = genStaticKeysCached(options.staticKeys || '');\n  isPlatformReservedTag = options.isReservedTag || no;\n  // first pass: mark all non-static nodes.\n  markStatic$1(root);\n  // second pass: mark static roots.\n  markStaticRoots(root, false);\n}\n\nfunction genStaticKeys$1 (keys) {\n  return makeMap(\n    'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +\n    (keys ? ',' + keys : '')\n  )\n}\n\nfunction markStatic$1 (node) {\n  node.static = isStatic(node);\n  if (node.type === 1) {\n    // do not make component slot content static. this avoids\n    // 1. components not able to mutate slot nodes\n    // 2. static slot content fails for hot-reloading\n    if (\n      !isPlatformReservedTag(node.tag) &&\n      node.tag !== 'slot' &&\n      node.attrsMap['inline-template'] == null\n    ) {\n      return\n    }\n    for (var i = 0, l = node.children.length; i < l; i++) {\n      var child = node.children[i];\n      markStatic$1(child);\n      if (!child.static) {\n        node.static = false;\n      }\n    }\n    if (node.ifConditions) {\n      for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n        var block = node.ifConditions[i$1].block;\n        markStatic$1(block);\n        if (!block.static) {\n          node.static = false;\n        }\n      }\n    }\n  }\n}\n\nfunction markStaticRoots (node, isInFor) {\n  if (node.type === 1) {\n    if (node.static || node.once) {\n      node.staticInFor = isInFor;\n    }\n    // For a node to qualify as a static root, it should have children that\n    // are not just static text. Otherwise the cost of hoisting out will\n    // outweigh the benefits and it's better off to just always render it fresh.\n    if (node.static && node.children.length && !(\n      node.children.length === 1 &&\n      node.children[0].type === 3\n    )) {\n      node.staticRoot = true;\n      return\n    } else {\n      node.staticRoot = false;\n    }\n    if (node.children) {\n      for (var i = 0, l = node.children.length; i < l; i++) {\n        markStaticRoots(node.children[i], isInFor || !!node.for);\n      }\n    }\n    if (node.ifConditions) {\n      for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {\n        markStaticRoots(node.ifConditions[i$1].block, isInFor);\n      }\n    }\n  }\n}\n\nfunction isStatic (node) {\n  if (node.type === 2) { // expression\n    return false\n  }\n  if (node.type === 3) { // text\n    return true\n  }\n  return !!(node.pre || (\n    !node.hasBindings && // no dynamic bindings\n    !node.if && !node.for && // not v-if or v-for or v-else\n    !isBuiltInTag(node.tag) && // not a built-in\n    isPlatformReservedTag(node.tag) && // not a component\n    !isDirectChildOfTemplateFor(node) &&\n    Object.keys(node).every(isStaticKey)\n  ))\n}\n\nfunction isDirectChildOfTemplateFor (node) {\n  while (node.parent) {\n    node = node.parent;\n    if (node.tag !== 'template') {\n      return false\n    }\n    if (node.for) {\n      return true\n    }\n  }\n  return false\n}\n\n/*  */\n\nvar fnExpRE = /^\\s*([\\w$_]+|\\([^)]*?\\))\\s*=>|^function\\s*\\(/;\nvar simplePathRE = /^\\s*[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*|\\['.*?']|\\[\".*?\"]|\\[\\d+]|\\[[A-Za-z_$][\\w$]*])*\\s*$/;\n\n// keyCode aliases\nvar keyCodes = {\n  esc: 27,\n  tab: 9,\n  enter: 13,\n  space: 32,\n  up: 38,\n  left: 37,\n  right: 39,\n  down: 40,\n  'delete': [8, 46]\n};\n\n// #4868: modifiers that prevent the execution of the listener\n// need to explicitly return null so that we can determine whether to remove\n// the listener for .once\nvar genGuard = function (condition) { return (\"if(\" + condition + \")return null;\"); };\n\nvar modifierCode = {\n  stop: '$event.stopPropagation();',\n  prevent: '$event.preventDefault();',\n  self: genGuard(\"$event.target !== $event.currentTarget\"),\n  ctrl: genGuard(\"!$event.ctrlKey\"),\n  shift: genGuard(\"!$event.shiftKey\"),\n  alt: genGuard(\"!$event.altKey\"),\n  meta: genGuard(\"!$event.metaKey\"),\n  left: genGuard(\"'button' in $event && $event.button !== 0\"),\n  middle: genGuard(\"'button' in $event && $event.button !== 1\"),\n  right: genGuard(\"'button' in $event && $event.button !== 2\")\n};\n\nfunction genHandlers (\n  events,\n  isNative,\n  warn\n) {\n  var res = isNative ? 'nativeOn:{' : 'on:{';\n  for (var name in events) {\n    var handler = events[name];\n    // #5330: warn click.right, since right clicks do not actually fire click events.\n    if (\"development\" !== 'production' &&\n      name === 'click' &&\n      handler && handler.modifiers && handler.modifiers.right\n    ) {\n      warn(\n        \"Use \\\"contextmenu\\\" instead of \\\"click.right\\\" since right clicks \" +\n        \"do not actually fire \\\"click\\\" events.\"\n      );\n    }\n    res += \"\\\"\" + name + \"\\\":\" + (genHandler(name, handler)) + \",\";\n  }\n  return res.slice(0, -1) + '}'\n}\n\nfunction genHandler (\n  name,\n  handler\n) {\n  if (!handler) {\n    return 'function(){}'\n  }\n\n  if (Array.isArray(handler)) {\n    return (\"[\" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + \"]\")\n  }\n\n  var isMethodPath = simplePathRE.test(handler.value);\n  var isFunctionExpression = fnExpRE.test(handler.value);\n\n  if (!handler.modifiers) {\n    return isMethodPath || isFunctionExpression\n      ? handler.value\n      : (\"function($event){\" + (handler.value) + \"}\") // inline statement\n  } else {\n    var code = '';\n    var genModifierCode = '';\n    var keys = [];\n    for (var key in handler.modifiers) {\n      if (modifierCode[key]) {\n        genModifierCode += modifierCode[key];\n        // left/right\n        if (keyCodes[key]) {\n          keys.push(key);\n        }\n      } else {\n        keys.push(key);\n      }\n    }\n    if (keys.length) {\n      code += genKeyFilter(keys);\n    }\n    // Make sure modifiers like prevent and stop get executed after key filtering\n    if (genModifierCode) {\n      code += genModifierCode;\n    }\n    var handlerCode = isMethodPath\n      ? handler.value + '($event)'\n      : isFunctionExpression\n        ? (\"(\" + (handler.value) + \")($event)\")\n        : handler.value;\n    return (\"function($event){\" + code + handlerCode + \"}\")\n  }\n}\n\nfunction genKeyFilter (keys) {\n  return (\"if(!('button' in $event)&&\" + (keys.map(genFilterCode).join('&&')) + \")return null;\")\n}\n\nfunction genFilterCode (key) {\n  var keyVal = parseInt(key, 10);\n  if (keyVal) {\n    return (\"$event.keyCode!==\" + keyVal)\n  }\n  var alias = keyCodes[key];\n  return (\"_k($event.keyCode,\" + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + \")\")\n}\n\n/*  */\n\nfunction on (el, dir) {\n  if (\"development\" !== 'production' && dir.modifiers) {\n    warn(\"v-on without argument does not support modifiers.\");\n  }\n  el.wrapListeners = function (code) { return (\"_g(\" + code + \",\" + (dir.value) + \")\"); };\n}\n\n/*  */\n\nfunction bind$1 (el, dir) {\n  el.wrapData = function (code) {\n    return (\"_b(\" + code + \",'\" + (el.tag) + \"',\" + (dir.value) + \",\" + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + \")\")\n  };\n}\n\n/*  */\n\nvar baseDirectives = {\n  on: on,\n  bind: bind$1,\n  cloak: noop\n};\n\n/*  */\n\nvar CodegenState = function CodegenState (options) {\n  this.options = options;\n  this.warn = options.warn || baseWarn;\n  this.transforms = pluckModuleFunction(options.modules, 'transformCode');\n  this.dataGenFns = pluckModuleFunction(options.modules, 'genData');\n  this.directives = extend(extend({}, baseDirectives), options.directives);\n  var isReservedTag = options.isReservedTag || no;\n  this.maybeComponent = function (el) { return !isReservedTag(el.tag); };\n  this.onceId = 0;\n  this.staticRenderFns = [];\n};\n\n\n\nfunction generate (\n  ast,\n  options\n) {\n  var state = new CodegenState(options);\n  var code = ast ? genElement(ast, state) : '_c(\"div\")';\n  return {\n    render: (\"with(this){return \" + code + \"}\"),\n    staticRenderFns: state.staticRenderFns\n  }\n}\n\nfunction genElement (el, state) {\n  if (el.staticRoot && !el.staticProcessed) {\n    return genStatic(el, state)\n  } else if (el.once && !el.onceProcessed) {\n    return genOnce(el, state)\n  } else if (el.for && !el.forProcessed) {\n    return genFor(el, state)\n  } else if (el.if && !el.ifProcessed) {\n    return genIf(el, state)\n  } else if (el.tag === 'template' && !el.slotTarget) {\n    return genChildren(el, state) || 'void 0'\n  } else if (el.tag === 'slot') {\n    return genSlot(el, state)\n  } else {\n    // component or element\n    var code;\n    if (el.component) {\n      code = genComponent(el.component, el, state);\n    } else {\n      var data = el.plain ? undefined : genData$2(el, state);\n\n      var children = el.inlineTemplate ? null : genChildren(el, state, true);\n      code = \"_c('\" + (el.tag) + \"'\" + (data ? (\",\" + data) : '') + (children ? (\",\" + children) : '') + \")\";\n    }\n    // module transforms\n    for (var i = 0; i < state.transforms.length; i++) {\n      code = state.transforms[i](el, code);\n    }\n    return code\n  }\n}\n\n// hoist static sub-trees out\nfunction genStatic (el, state) {\n  el.staticProcessed = true;\n  state.staticRenderFns.push((\"with(this){return \" + (genElement(el, state)) + \"}\"));\n  return (\"_m(\" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + \")\")\n}\n\n// v-once\nfunction genOnce (el, state) {\n  el.onceProcessed = true;\n  if (el.if && !el.ifProcessed) {\n    return genIf(el, state)\n  } else if (el.staticInFor) {\n    var key = '';\n    var parent = el.parent;\n    while (parent) {\n      if (parent.for) {\n        key = parent.key;\n        break\n      }\n      parent = parent.parent;\n    }\n    if (!key) {\n      \"development\" !== 'production' && state.warn(\n        \"v-once can only be used inside v-for that is keyed. \"\n      );\n      return genElement(el, state)\n    }\n    return (\"_o(\" + (genElement(el, state)) + \",\" + (state.onceId++) + \",\" + key + \")\")\n  } else {\n    return genStatic(el, state)\n  }\n}\n\nfunction genIf (\n  el,\n  state,\n  altGen,\n  altEmpty\n) {\n  el.ifProcessed = true; // avoid recursion\n  return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)\n}\n\nfunction genIfConditions (\n  conditions,\n  state,\n  altGen,\n  altEmpty\n) {\n  if (!conditions.length) {\n    return altEmpty || '_e()'\n  }\n\n  var condition = conditions.shift();\n  if (condition.exp) {\n    return (\"(\" + (condition.exp) + \")?\" + (genTernaryExp(condition.block)) + \":\" + (genIfConditions(conditions, state, altGen, altEmpty)))\n  } else {\n    return (\"\" + (genTernaryExp(condition.block)))\n  }\n\n  // v-if with v-once should generate code like (a)?_m(0):_m(1)\n  function genTernaryExp (el) {\n    return altGen\n      ? altGen(el, state)\n      : el.once\n        ? genOnce(el, state)\n        : genElement(el, state)\n  }\n}\n\nfunction genFor (\n  el,\n  state,\n  altGen,\n  altHelper\n) {\n  var exp = el.for;\n  var alias = el.alias;\n  var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n  var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n\n  if (\"development\" !== 'production' &&\n    state.maybeComponent(el) &&\n    el.tag !== 'slot' &&\n    el.tag !== 'template' &&\n    !el.key\n  ) {\n    state.warn(\n      \"<\" + (el.tag) + \" v-for=\\\"\" + alias + \" in \" + exp + \"\\\">: component lists rendered with \" +\n      \"v-for should have explicit keys. \" +\n      \"See https://vuejs.org/guide/list.html#key for more info.\",\n      true /* tip */\n    );\n  }\n\n  el.forProcessed = true; // avoid recursion\n  return (altHelper || '_l') + \"((\" + exp + \"),\" +\n    \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n      \"return \" + ((altGen || genElement)(el, state)) +\n    '})'\n}\n\nfunction genData$2 (el, state) {\n  var data = '{';\n\n  // directives first.\n  // directives may mutate the el's other properties before they are generated.\n  var dirs = genDirectives(el, state);\n  if (dirs) { data += dirs + ','; }\n\n  // key\n  if (el.key) {\n    data += \"key:\" + (el.key) + \",\";\n  }\n  // ref\n  if (el.ref) {\n    data += \"ref:\" + (el.ref) + \",\";\n  }\n  if (el.refInFor) {\n    data += \"refInFor:true,\";\n  }\n  // pre\n  if (el.pre) {\n    data += \"pre:true,\";\n  }\n  // record original tag name for components using \"is\" attribute\n  if (el.component) {\n    data += \"tag:\\\"\" + (el.tag) + \"\\\",\";\n  }\n  // module data generation functions\n  for (var i = 0; i < state.dataGenFns.length; i++) {\n    data += state.dataGenFns[i](el);\n  }\n  // attributes\n  if (el.attrs) {\n    data += \"attrs:{\" + (genProps(el.attrs)) + \"},\";\n  }\n  // DOM props\n  if (el.props) {\n    data += \"domProps:{\" + (genProps(el.props)) + \"},\";\n  }\n  // event handlers\n  if (el.events) {\n    data += (genHandlers(el.events, false, state.warn)) + \",\";\n  }\n  if (el.nativeEvents) {\n    data += (genHandlers(el.nativeEvents, true, state.warn)) + \",\";\n  }\n  // slot target\n  if (el.slotTarget) {\n    data += \"slot:\" + (el.slotTarget) + \",\";\n  }\n  // scoped slots\n  if (el.scopedSlots) {\n    data += (genScopedSlots(el.scopedSlots, state)) + \",\";\n  }\n  // component v-model\n  if (el.model) {\n    data += \"model:{value:\" + (el.model.value) + \",callback:\" + (el.model.callback) + \",expression:\" + (el.model.expression) + \"},\";\n  }\n  // inline-template\n  if (el.inlineTemplate) {\n    var inlineTemplate = genInlineTemplate(el, state);\n    if (inlineTemplate) {\n      data += inlineTemplate + \",\";\n    }\n  }\n  data = data.replace(/,$/, '') + '}';\n  // v-bind data wrap\n  if (el.wrapData) {\n    data = el.wrapData(data);\n  }\n  // v-on data wrap\n  if (el.wrapListeners) {\n    data = el.wrapListeners(data);\n  }\n  return data\n}\n\nfunction genDirectives (el, state) {\n  var dirs = el.directives;\n  if (!dirs) { return }\n  var res = 'directives:[';\n  var hasRuntime = false;\n  var i, l, dir, needRuntime;\n  for (i = 0, l = dirs.length; i < l; i++) {\n    dir = dirs[i];\n    needRuntime = true;\n    var gen = state.directives[dir.name];\n    if (gen) {\n      // compile-time directive that manipulates AST.\n      // returns true if it also needs a runtime counterpart.\n      needRuntime = !!gen(el, dir, state.warn);\n    }\n    if (needRuntime) {\n      hasRuntime = true;\n      res += \"{name:\\\"\" + (dir.name) + \"\\\",rawName:\\\"\" + (dir.rawName) + \"\\\"\" + (dir.value ? (\",value:(\" + (dir.value) + \"),expression:\" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (\",arg:\\\"\" + (dir.arg) + \"\\\"\") : '') + (dir.modifiers ? (\",modifiers:\" + (JSON.stringify(dir.modifiers))) : '') + \"},\";\n    }\n  }\n  if (hasRuntime) {\n    return res.slice(0, -1) + ']'\n  }\n}\n\nfunction genInlineTemplate (el, state) {\n  var ast = el.children[0];\n  if (\"development\" !== 'production' && (\n    el.children.length > 1 || ast.type !== 1\n  )) {\n    state.warn('Inline-template components must have exactly one child element.');\n  }\n  if (ast.type === 1) {\n    var inlineRenderFns = generate(ast, state.options);\n    return (\"inlineTemplate:{render:function(){\" + (inlineRenderFns.render) + \"},staticRenderFns:[\" + (inlineRenderFns.staticRenderFns.map(function (code) { return (\"function(){\" + code + \"}\"); }).join(',')) + \"]}\")\n  }\n}\n\nfunction genScopedSlots (\n  slots,\n  state\n) {\n  return (\"scopedSlots:_u([\" + (Object.keys(slots).map(function (key) {\n      return genScopedSlot(key, slots[key], state)\n    }).join(',')) + \"])\")\n}\n\nfunction genScopedSlot (\n  key,\n  el,\n  state\n) {\n  if (el.for && !el.forProcessed) {\n    return genForScopedSlot(key, el, state)\n  }\n  return \"{key:\" + key + \",fn:function(\" + (String(el.attrsMap.scope)) + \"){\" +\n    \"return \" + (el.tag === 'template'\n      ? genChildren(el, state) || 'void 0'\n      : genElement(el, state)) + \"}}\"\n}\n\nfunction genForScopedSlot (\n  key,\n  el,\n  state\n) {\n  var exp = el.for;\n  var alias = el.alias;\n  var iterator1 = el.iterator1 ? (\",\" + (el.iterator1)) : '';\n  var iterator2 = el.iterator2 ? (\",\" + (el.iterator2)) : '';\n  el.forProcessed = true; // avoid recursion\n  return \"_l((\" + exp + \"),\" +\n    \"function(\" + alias + iterator1 + iterator2 + \"){\" +\n      \"return \" + (genScopedSlot(key, el, state)) +\n    '})'\n}\n\nfunction genChildren (\n  el,\n  state,\n  checkSkip,\n  altGenElement,\n  altGenNode\n) {\n  var children = el.children;\n  if (children.length) {\n    var el$1 = children[0];\n    // optimize single v-for\n    if (children.length === 1 &&\n      el$1.for &&\n      el$1.tag !== 'template' &&\n      el$1.tag !== 'slot'\n    ) {\n      return (altGenElement || genElement)(el$1, state)\n    }\n    var normalizationType = checkSkip\n      ? getNormalizationType(children, state.maybeComponent)\n      : 0;\n    var gen = altGenNode || genNode;\n    return (\"[\" + (children.map(function (c) { return gen(c, state); }).join(',')) + \"]\" + (normalizationType ? (\",\" + normalizationType) : ''))\n  }\n}\n\n// determine the normalization needed for the children array.\n// 0: no normalization needed\n// 1: simple normalization needed (possible 1-level deep nested array)\n// 2: full normalization needed\nfunction getNormalizationType (\n  children,\n  maybeComponent\n) {\n  var res = 0;\n  for (var i = 0; i < children.length; i++) {\n    var el = children[i];\n    if (el.type !== 1) {\n      continue\n    }\n    if (needsNormalization(el) ||\n        (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {\n      res = 2;\n      break\n    }\n    if (maybeComponent(el) ||\n        (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {\n      res = 1;\n    }\n  }\n  return res\n}\n\nfunction needsNormalization (el) {\n  return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'\n}\n\nfunction genNode (node, state) {\n  if (node.type === 1) {\n    return genElement(node, state)\n  } if (node.type === 3 && node.isComment) {\n    return genComment(node)\n  } else {\n    return genText(node)\n  }\n}\n\nfunction genText (text) {\n  return (\"_v(\" + (text.type === 2\n    ? text.expression // no need for () because already wrapped in _s()\n    : transformSpecialNewlines(JSON.stringify(text.text))) + \")\")\n}\n\nfunction genComment (comment) {\n  return (\"_e(\" + (JSON.stringify(comment.text)) + \")\")\n}\n\nfunction genSlot (el, state) {\n  var slotName = el.slotName || '\"default\"';\n  var children = genChildren(el, state);\n  var res = \"_t(\" + slotName + (children ? (\",\" + children) : '');\n  var attrs = el.attrs && (\"{\" + (el.attrs.map(function (a) { return ((camelize(a.name)) + \":\" + (a.value)); }).join(',')) + \"}\");\n  var bind$$1 = el.attrsMap['v-bind'];\n  if ((attrs || bind$$1) && !children) {\n    res += \",null\";\n  }\n  if (attrs) {\n    res += \",\" + attrs;\n  }\n  if (bind$$1) {\n    res += (attrs ? '' : ',null') + \",\" + bind$$1;\n  }\n  return res + ')'\n}\n\n// componentName is el.component, take it as argument to shun flow's pessimistic refinement\nfunction genComponent (\n  componentName,\n  el,\n  state\n) {\n  var children = el.inlineTemplate ? null : genChildren(el, state, true);\n  return (\"_c(\" + componentName + \",\" + (genData$2(el, state)) + (children ? (\",\" + children) : '') + \")\")\n}\n\nfunction genProps (props) {\n  var res = '';\n  for (var i = 0; i < props.length; i++) {\n    var prop = props[i];\n    res += \"\\\"\" + (prop.name) + \"\\\":\" + (transformSpecialNewlines(prop.value)) + \",\";\n  }\n  return res.slice(0, -1)\n}\n\n// #3895, #4268\nfunction transformSpecialNewlines (text) {\n  return text\n    .replace(/\\u2028/g, '\\\\u2028')\n    .replace(/\\u2029/g, '\\\\u2029')\n}\n\n/*  */\n\n// these keywords should not appear inside expressions, but operators like\n// typeof, instanceof and in are allowed\nvar prohibitedKeywordRE = new RegExp('\\\\b' + (\n  'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +\n  'super,throw,while,yield,delete,export,import,return,switch,default,' +\n  'extends,finally,continue,debugger,function,arguments'\n).split(',').join('\\\\b|\\\\b') + '\\\\b');\n\n// these unary operators should not be used as property/method names\nvar unaryOperatorsRE = new RegExp('\\\\b' + (\n  'delete,typeof,void'\n).split(',').join('\\\\s*\\\\([^\\\\)]*\\\\)|\\\\b') + '\\\\s*\\\\([^\\\\)]*\\\\)');\n\n// check valid identifier for v-for\nvar identRE = /[A-Za-z_$][\\w$]*/;\n\n// strip strings in expressions\nvar stripStringRE = /'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*\\$\\{|\\}(?:[^`\\\\]|\\\\.)*`|`(?:[^`\\\\]|\\\\.)*`/g;\n\n// detect problematic expressions in a template\nfunction detectErrors (ast) {\n  var errors = [];\n  if (ast) {\n    checkNode(ast, errors);\n  }\n  return errors\n}\n\nfunction checkNode (node, errors) {\n  if (node.type === 1) {\n    for (var name in node.attrsMap) {\n      if (dirRE.test(name)) {\n        var value = node.attrsMap[name];\n        if (value) {\n          if (name === 'v-for') {\n            checkFor(node, (\"v-for=\\\"\" + value + \"\\\"\"), errors);\n          } else if (onRE.test(name)) {\n            checkEvent(value, (name + \"=\\\"\" + value + \"\\\"\"), errors);\n          } else {\n            checkExpression(value, (name + \"=\\\"\" + value + \"\\\"\"), errors);\n          }\n        }\n      }\n    }\n    if (node.children) {\n      for (var i = 0; i < node.children.length; i++) {\n        checkNode(node.children[i], errors);\n      }\n    }\n  } else if (node.type === 2) {\n    checkExpression(node.expression, node.text, errors);\n  }\n}\n\nfunction checkEvent (exp, text, errors) {\n  var stipped = exp.replace(stripStringRE, '');\n  var keywordMatch = stipped.match(unaryOperatorsRE);\n  if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {\n    errors.push(\n      \"avoid using JavaScript unary operator as property name: \" +\n      \"\\\"\" + (keywordMatch[0]) + \"\\\" in expression \" + (text.trim())\n    );\n  }\n  checkExpression(exp, text, errors);\n}\n\nfunction checkFor (node, text, errors) {\n  checkExpression(node.for || '', text, errors);\n  checkIdentifier(node.alias, 'v-for alias', text, errors);\n  checkIdentifier(node.iterator1, 'v-for iterator', text, errors);\n  checkIdentifier(node.iterator2, 'v-for iterator', text, errors);\n}\n\nfunction checkIdentifier (ident, type, text, errors) {\n  if (typeof ident === 'string' && !identRE.test(ident)) {\n    errors.push((\"invalid \" + type + \" \\\"\" + ident + \"\\\" in expression: \" + (text.trim())));\n  }\n}\n\nfunction checkExpression (exp, text, errors) {\n  try {\n    new Function((\"return \" + exp));\n  } catch (e) {\n    var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);\n    if (keywordMatch) {\n      errors.push(\n        \"avoid using JavaScript keyword as property name: \" +\n        \"\\\"\" + (keywordMatch[0]) + \"\\\" in expression \" + (text.trim())\n      );\n    } else {\n      errors.push((\"invalid expression: \" + (text.trim())));\n    }\n  }\n}\n\n/*  */\n\nfunction createFunction (code, errors) {\n  try {\n    return new Function(code)\n  } catch (err) {\n    errors.push({ err: err, code: code });\n    return noop\n  }\n}\n\nfunction createCompileToFunctionFn (compile) {\n  var cache = Object.create(null);\n\n  return function compileToFunctions (\n    template,\n    options,\n    vm\n  ) {\n    options = options || {};\n\n    /* istanbul ignore if */\n    {\n      // detect possible CSP restriction\n      try {\n        new Function('return 1');\n      } catch (e) {\n        if (e.toString().match(/unsafe-eval|CSP/)) {\n          warn(\n            'It seems you are using the standalone build of Vue.js in an ' +\n            'environment with Content Security Policy that prohibits unsafe-eval. ' +\n            'The template compiler cannot work in this environment. Consider ' +\n            'relaxing the policy to allow unsafe-eval or pre-compiling your ' +\n            'templates into render functions.'\n          );\n        }\n      }\n    }\n\n    // check cache\n    var key = options.delimiters\n      ? String(options.delimiters) + template\n      : template;\n    if (cache[key]) {\n      return cache[key]\n    }\n\n    // compile\n    var compiled = compile(template, options);\n\n    // check compilation errors/tips\n    {\n      if (compiled.errors && compiled.errors.length) {\n        warn(\n          \"Error compiling template:\\n\\n\" + template + \"\\n\\n\" +\n          compiled.errors.map(function (e) { return (\"- \" + e); }).join('\\n') + '\\n',\n          vm\n        );\n      }\n      if (compiled.tips && compiled.tips.length) {\n        compiled.tips.forEach(function (msg) { return tip(msg, vm); });\n      }\n    }\n\n    // turn code into functions\n    var res = {};\n    var fnGenErrors = [];\n    res.render = createFunction(compiled.render, fnGenErrors);\n    res.staticRenderFns = compiled.staticRenderFns.map(function (code) {\n      return createFunction(code, fnGenErrors)\n    });\n\n    // check function generation errors.\n    // this should only happen if there is a bug in the compiler itself.\n    // mostly for codegen development use\n    /* istanbul ignore if */\n    {\n      if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {\n        warn(\n          \"Failed to generate render function:\\n\\n\" +\n          fnGenErrors.map(function (ref) {\n            var err = ref.err;\n            var code = ref.code;\n\n            return ((err.toString()) + \" in\\n\\n\" + code + \"\\n\");\n        }).join('\\n'),\n          vm\n        );\n      }\n    }\n\n    return (cache[key] = res)\n  }\n}\n\n/*  */\n\nfunction createCompilerCreator (baseCompile) {\n  return function createCompiler (baseOptions) {\n    function compile (\n      template,\n      options\n    ) {\n      var finalOptions = Object.create(baseOptions);\n      var errors = [];\n      var tips = [];\n      finalOptions.warn = function (msg, tip) {\n        (tip ? tips : errors).push(msg);\n      };\n\n      if (options) {\n        // merge custom modules\n        if (options.modules) {\n          finalOptions.modules =\n            (baseOptions.modules || []).concat(options.modules);\n        }\n        // merge custom directives\n        if (options.directives) {\n          finalOptions.directives = extend(\n            Object.create(baseOptions.directives),\n            options.directives\n          );\n        }\n        // copy other options\n        for (var key in options) {\n          if (key !== 'modules' && key !== 'directives') {\n            finalOptions[key] = options[key];\n          }\n        }\n      }\n\n      var compiled = baseCompile(template, finalOptions);\n      {\n        errors.push.apply(errors, detectErrors(compiled.ast));\n      }\n      compiled.errors = errors;\n      compiled.tips = tips;\n      return compiled\n    }\n\n    return {\n      compile: compile,\n      compileToFunctions: createCompileToFunctionFn(compile)\n    }\n  }\n}\n\n/*  */\n\n// `createCompilerCreator` allows creating compilers that use alternative\n// parser/optimizer/codegen, e.g the SSR optimizing compiler.\n// Here we just export a default compiler using the default parts.\nvar createCompiler = createCompilerCreator(function baseCompile (\n  template,\n  options\n) {\n  var ast = parse(template.trim(), options);\n  optimize(ast, options);\n  var code = generate(ast, options);\n  return {\n    ast: ast,\n    render: code.render,\n    staticRenderFns: code.staticRenderFns\n  }\n});\n\n/*  */\n\nvar ref$1 = createCompiler(baseOptions);\nvar compileToFunctions = ref$1.compileToFunctions;\n\n/*  */\n\nvar idToTemplate = cached(function (id) {\n  var el = query(id);\n  return el && el.innerHTML\n});\n\nvar mount = Vue$3.prototype.$mount;\nVue$3.prototype.$mount = function (\n  el,\n  hydrating\n) {\n  el = el && query(el);\n\n  /* istanbul ignore if */\n  if (el === document.body || el === document.documentElement) {\n    \"development\" !== 'production' && warn(\n      \"Do not mount Vue to <html> or <body> - mount to normal elements instead.\"\n    );\n    return this\n  }\n\n  var options = this.$options;\n  // resolve template/el and convert to render function\n  if (!options.render) {\n    var template = options.template;\n    if (template) {\n      if (typeof template === 'string') {\n        if (template.charAt(0) === '#') {\n          template = idToTemplate(template);\n          /* istanbul ignore if */\n          if (\"development\" !== 'production' && !template) {\n            warn(\n              (\"Template element not found or is empty: \" + (options.template)),\n              this\n            );\n          }\n        }\n      } else if (template.nodeType) {\n        template = template.innerHTML;\n      } else {\n        {\n          warn('invalid template option:' + template, this);\n        }\n        return this\n      }\n    } else if (el) {\n      template = getOuterHTML(el);\n    }\n    if (template) {\n      /* istanbul ignore if */\n      if (\"development\" !== 'production' && config.performance && mark) {\n        mark('compile');\n      }\n\n      var ref = compileToFunctions(template, {\n        shouldDecodeNewlines: shouldDecodeNewlines,\n        delimiters: options.delimiters,\n        comments: options.comments\n      }, this);\n      var render = ref.render;\n      var staticRenderFns = ref.staticRenderFns;\n      options.render = render;\n      options.staticRenderFns = staticRenderFns;\n\n      /* istanbul ignore if */\n      if (\"development\" !== 'production' && config.performance && mark) {\n        mark('compile end');\n        measure(((this._name) + \" compile\"), 'compile', 'compile end');\n      }\n    }\n  }\n  return mount.call(this, el, hydrating)\n};\n\n/**\n * Get outerHTML of elements, taking care\n * of SVG elements in IE as well.\n */\nfunction getOuterHTML (el) {\n  if (el.outerHTML) {\n    return el.outerHTML\n  } else {\n    var container = document.createElement('div');\n    container.appendChild(el.cloneNode(true));\n    return container.innerHTML\n  }\n}\n\nVue$3.compile = compileToFunctions;\n\nreturn Vue$3;\n\n})));\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/base.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    {% block head %}\n    <title>{% block title %}{% endblock %} - webmacs</title>\n    {% endblock %}\n  </head>\n  <body>\n    <div id=\"content\">{% block content %}{% endblock %}</div>\n  </body>\n</html>\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/bindings.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}Bindings{% endblock %}\n{% block content %}\n<h1>Webmacs bindings</h1>\n{% for name, keymap in keymaps|dictsort %}\n{% set km = keymap.all_bindings(with_parent=False) %}\n{% if km %}\n<h2>In <a href=\"webmacs://keymap/{{name}}\">{{name}}</a> keymap:</h2>\n<p>{{keymap.brief_doc}}</p>\n{% if keymap.parent %}\n<p>Parent keymap: <a href=\"webmacs://keymap/{{keymap.parent.name}}\">{{keymap.parent.name}}</a></p>\n{% endif %}\n<table>\n{% for prefix, command in km|sort %}\n  <tr>\n    <td>{{prefix}}</td>\n    <td><a href=\"webmacs://command/{{command}}\">{{command}}</a></td>\n  </tr>\n  {% endfor %}\n</table>\n{% endif %}\n{% endfor %}\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/command.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}{{command_name}} command{% endblock %}\n{% block content %}\n<h1>Command: {{command_name}}</h1>\n\n<p>See the <a href=\"{{command_src_url}}\">source code</a>.</p>\n<p><pre>{{command.getdoc()}}</pre></p>\n\n{% if used_in_keymaps %}\n<h2>This command is bound to:</h2>\n<table>\n  <tr><th>binding</th><th>keymap</th></tr>\n  {% for binding, keymap in used_in_keymaps %}\n  <tr><td>{{binding}}</td><td><a href=\"webmacs://keymap/{{keymap}}\">{{keymap}}</a></td></tr>\n  {% endfor %}\n</table>\n{% endif %}\n\n<p>See <a href=\"webmacs://commands\">all commands</a>\n  or <a href=\"webmacs://bindings\">all key bindings</a> .</p>\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/commands.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}Available commands{% endblock %}\n{% block content %}\n<h1>Webmacs commands</h1>\n<table>\n{% for name, command in commands|dictsort %}\n  {% if command.visible %}\n  <tr>\n    <td><a href=\"webmacs://command/{{name}}\">{{name}}</a></td>\n    <td>{{command.getdoc().splitlines()[0]}}</td>\n  </tr>\n  {% endif %}\n{% endfor %}\n</table>\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/downloads.html",
    "content": "{% extends \"base.html\" %}\n\n{% block head %}\n<style>\n .progress { width: 100%; background-color: #ddd }\n .bar { height: 30px; background-color: #0066ff; text-align: center }\n td.state { width: 100px; }\n</style>\n<script src=\"webmacs:///js/vue.js\"></script>\n{% raw %}\n<script>\n var app = null;\n window.onload = function() {\n     app = new Vue({\n         el: \"#app\",\n         data: {\n             downloads: []\n         }\n     });\n }\n function add_download(dl) {\n     app.downloads.push(dl);\n }\n\n function download(id) {\n     for (let dl of app.downloads) {\n         if (dl.id == id) { return dl; }\n     }\n     return null;\n }\n\n function update_download(dl) {\n     var index = app.downloads.indexOf(download(dl.id));\n     if (index != -1) {\n         Vue.set(app.downloads, index, dl);\n     }\n }\n</script>\n{% endraw %}\n{% endblock %}\n\n{% block title %}Downloads{% endblock %}\n\n{% block content %}\n\n<table id=\"app\">\n  {% raw %}\n  <tr v-for=\"download in downloads\">\n    <td v-if=\"download.isFinished\" class=\"state\">\n      {{download.state}}\n    </td>\n    <td v-else class=\"state\">\n      <div class=\"progress\">\n        <div class=\"bar\" v-bind:style=\"{width: download.progress + '%'}\">{{download.progress}}%</div>\n      </div>\n    </td>\n    <td>\n      {{download.path}}\n    </td>\n  </tr>\n  {% endraw %}\n</table>\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/key.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}key {{key}} on {{keymap}}{% endblock %}\n{% block content %}\n<p>{{key}} run the command\n  {% if named_command %}\n  <a href=\"webmacs://command/{{command_name}}\">{{command_name}}</a>\n  {% else %}\n  {{command_name}}\n  {% endif %}\n  (found in <a href=\"webmacs://keymap/{{keymap}}\">{{keymap}} keymap</a>),\n  which is\n  {% if named_command %}\n  an interactive command\n  {% else %}\n  a raw python function\n  {% endif %}\n   defined in <a href=\"{{command_src_url}}\">{{modname}}</a>.\n</p>\n\n<p>\n  It is bound to {{all_keys|join(', ')}}.\n</p>\n\n<p>{{command_doc}}</p>\n\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/keymap.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}Keymap {{name}}{% endblock %}\n{% block content %}\n<h1>Keymap: {{name}}</h1>\n<pre>{{keymap.doc}}<pre>\n\n{% for k, g in bindings %}\n{% if k %}\n<h3>From parent keymap <a href=\"webmacs://keymap/{{k}}\">{{k}}</a>:</h3>\n{% endif %}\n<table>\n{% for prefix, command, _ in g %}\n<tr>\n  <td>{{prefix}}</td>\n  <td><a href=\"webmacs://command/{{command}}\">{{command}}</a></td>\n</tr>\n{% endfor %}\n</table>\n{% endfor %}\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/variable.html",
    "content": "{% macro var_type(v) -%}\n{% set desc = {\"Type\": v.type.describe()}.items() %}\n{%- for k, v in desc recursive %}\n{% set outer_loop = loop %}\n<ul {% if outer_loop.depth == 1 %} style=\"list-style:none;padding:0;margin:0\"  {% endif %}>\n  <li>{{k}}: {{v[0]}}({{ v[1]|join(', ') }})\n    {% for sv in v[2:] %}\n    {{ outer_loop(sv.items()) }}\n    {% endfor %}\n  </li>\n</ul>\n{% endfor %}\n{%- endmacro %}\n\n{% extends \"base.html\" %}\n\n{% block title %}Variable {{variable.name}}{% endblock %}\n{% block content %}\n<h1>Variable <strong>{{variable.name}}</strong></h1>\n\n{{var_type(variable)}}\n\n<p>Its current value is <pre>{{variable.value}}.</pre></p>\n\n<p>{{variable.doc}}</p>\n\nSee <a href=\"webmacs://variables\">all variables</a>.\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/variables.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}Available variables{% endblock %}\n{% block content %}\n<h1>Webmacs variables</h1>\n<table>\n  <tr>\n    <th>name</th><th>documentation</th>\n  </tr>\n{% for name, variable in variables|dictsort %}\n  <tr>\n    <td><a href=\"webmacs://variable/{{name}}\">{{name}}</a></td><td>{{variable.doc}}</td>\n  </tr>\n  {% endfor %}\n</table>\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scheme_handlers/webmacs/templates/version.html",
    "content": "{% extends \"base.html\" %}\n\n{% block title %}Version{% endblock %}\n{% block content %}\n<table>\n  {% for name, version in versions %}\n  <tr>\n    <td>{{name}}:</td><td>{{version}}</td>\n  </tr>\n  {% endfor %}\n</table>\n{% endblock %}\n"
  },
  {
    "path": "webmacs/scripts/caret_browsing.js",
    "content": "// eslint-disable-line max-lines\n/**\n * Copyright 2016-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n *\n * This file is part of qutebrowser.\n *\n * qutebrowser is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * qutebrowser is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/**\n * Ported chrome-caretbrowsing extension.\n * Create and control div caret, which listen commands from qutebrowser,\n * change document selection model and div caret position.\n */\n\n// see https://cs.chromium.org/chromium/src/ui/accessibility/extensions/caretbrowsing/\n\n\"use strict\";\n\nconst axs = {};\n\naxs.dom = {};\n\naxs.color = {};\n\naxs.utils = {};\n\naxs.dom.parentElement = function(node) {\n    if (!node) {\n        return null;\n    }\n    const composedNode = axs.dom.composedParentNode(node);\n    if (!composedNode) {\n        return null;\n    }\n    switch (composedNode.nodeType) {\n    case Node.ELEMENT_NODE:\n        return composedNode;\n    default:\n        return axs.dom.parentElement(composedNode);\n    }\n};\n\naxs.dom.shadowHost = function(node) {\n    if (\"host\" in node) {\n        return node.host;\n    }\n    return null;\n};\n\naxs.dom.composedParentNode = function(node) {\n    if (!node) {\n        return null;\n    }\n    if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n        return axs.dom.shadowHost(node);\n    }\n    const parentNode = node.parentNode;\n    if (!parentNode) {\n        return null;\n    }\n    if (parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n        return axs.dom.shadowHost(parentNode);\n    }\n    if (!parentNode.shadowRoot) {\n        return parentNode;\n    }\n    const points = node.getDestinationInsertionPoints();\n    if (points.length > 0) {\n        return axs.dom.composedParentNode(points[points.length - 1]);\n    }\n    return null;\n};\n\naxs.color.Color = function(red, green, blue, alpha) { // eslint-disable-line max-params,max-len\n    this.red = red;\n    this.green = green;\n    this.blue = blue;\n    this.alpha = alpha;\n};\n\naxs.color.parseColor = function(colorText) {\n    if (colorText === \"transparent\") {\n        return new axs.color.Color(0, 0, 0, 0);\n    }\n    let match = colorText.match(/^rgb\\((\\d+), (\\d+), (\\d+)\\)$/);\n    if (match) {\n        const blue = parseInt(match[3], 10);\n        const green = parseInt(match[2], 10);\n        const red = parseInt(match[1], 10);\n        return new axs.color.Color(red, green, blue, 1);\n    }\n    match = colorText.match(/^rgba\\((\\d+), (\\d+), (\\d+), (\\d*(\\.\\d+)?)\\)/);\n    if (match) {\n        const red = parseInt(match[1], 10);\n        const green = parseInt(match[2], 10);\n        const blue = parseInt(match[3], 10);\n        const alpha = parseFloat(match[4]);\n        return new axs.color.Color(red, green, blue, alpha);\n    }\n    return null;\n};\n\naxs.color.flattenColors = function(color1, color2) {\n    const colorAlpha = color1.alpha;\n    return new axs.color.Color(\n        ((1 - colorAlpha) * color2.red) + (colorAlpha * color1.red),\n        ((1 - colorAlpha) * color2.green) + (colorAlpha * color1.green),\n        ((1 - colorAlpha) * color2.blue) + (colorAlpha * color2.blue),\n        color1.alpha + (color2.alpha * (1 - color1.alpha)));\n};\n\naxs.utils.getParentBgColor = function(_el) {\n    let el = _el;\n    let el2 = el;\n    let iter = null;\n    el = [];\n    for (iter = null; (el2 = axs.dom.parentElement(el2));) {\n        const style = window.getComputedStyle(el2, null);\n        if (style) {\n            const color = axs.color.parseColor(style.backgroundColor);\n            if (color &&\n                (style.opacity < 1 &&\n                 (color.alpha *= style.opacity),\n                 color.alpha !== 0 &&\n                 (el.push(color), color.alpha === 1))) {\n                iter = !0;\n                break;\n            }\n        }\n    }\n    if (!iter) {\n        el.push(new axs.color.Color(255, 255, 255, 1));\n    }\n    for (el2 = el.pop(); el.length;) {\n        iter = el.pop();\n        el2 = axs.color.flattenColors(iter, el2);\n    }\n    return el2;\n};\n\naxs.utils.getFgColor = function(el, el2, color) {\n    let color2 = axs.color.parseColor(el.color);\n    if (!color2) {\n        return null;\n    }\n    if (color2.alpha < 1) {\n        color2 = axs.color.flattenColors(color2, color);\n    }\n    if (el.opacity < 1) {\n        const el3 = axs.utils.getParentBgColor(el2);\n        color2.alpha *= el.opacity;\n        color2 = axs.color.flattenColors(color2, el3);\n    }\n    return color2;\n};\n\naxs.utils.getBgColor = function(el, elParent) {\n    let color = axs.color.parseColor(el.backgroundColor);\n    if (!color) {\n        return null;\n    }\n    if (el.opacity < 1) {\n        color.alpha *= el.opacity;\n    }\n    if (color.alpha < 1) {\n        const bgColor = axs.utils.getParentBgColor(elParent);\n        if (bgColor === null) {\n            return null;\n        }\n        color = axs.color.flattenColors(color, bgColor);\n    }\n    return color;\n};\n\naxs.color.colorChannelToString = function(_color) {\n    const color = Math.round(_color);\n    if (color < 15) {\n        return `0${color.toString(16)}`;\n    }\n    return color.toString(16);\n};\n\naxs.color.colorToString = function(color) {\n    if (color.alpha === 1) {\n        const red = axs.color.colorChannelToString(color.red);\n        const green = axs.color.colorChannelToString(color.green);\n        const blue = axs.color.colorChannelToString(color.blue);\n        return `#${red}${green}${blue}`;\n    }\n    const arr = [color.red, color.green, color.blue, color.alpha].join();\n    return `rgba(${arr})`;\n};\n\nconst Cursor = function(node, index, text) { // eslint-disable-line func-style,max-len\n    this.node = node;\n    this.index = index;\n    this.text = text;\n};\n\nCursor.prototype.clone = function() {\n    return new Cursor(this.node, this.index, this.text);\n};\n\nCursor.prototype.copyFrom = function(otherCursor) {\n    this.node = otherCursor.node;\n    this.index = otherCursor.index;\n    this.text = otherCursor.text;\n};\n\nconst TraverseUtil = {};\n\nTraverseUtil.getNodeText = function(node) {\n    if (node.constructor === Text) {\n        return node.data;\n    }\n    return \"\";\n};\n\nTraverseUtil.treatAsLeafNode = function(node) {\n    return node.childNodes.length === 0 ||\n        node.nodeName === \"SELECT\" ||\n        node.nodeName === \"OBJECT\";\n};\n\nTraverseUtil.isWhitespace = function(ch) {\n    return (ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\");\n};\n\nTraverseUtil.isVisible = function(node) {\n    if (!node.style) {\n        return true;\n    }\n    const style = window.getComputedStyle(node, null);\n    return (Boolean(style) &&\n            style.display !== \"none\" &&\n            style.visibility !== \"hidden\");\n};\n\nTraverseUtil.isSkipped = function(_node) {\n    let node = _node;\n    if (node.constructor === Text) {\n        node = node.parentElement;\n    }\n    if (node.className === \"CaretBrowsing_Caret\" ||\n        node.className === \"CaretBrowsing_AnimateCaret\") {\n        return true;\n    }\n    return false;\n};\n\nTraverseUtil.forwardsChar = function(cursor, nodesCrossed) { // eslint-disable-line max-statements,max-len\n    for (;;) {\n        let childNode = null;\n        if (!TraverseUtil.treatAsLeafNode(cursor.node)) {\n            for (let i = cursor.index;\n                 i < cursor.node.childNodes.length;\n                 i++) {\n                const node = cursor.node.childNodes[i];\n                if (TraverseUtil.isSkipped(node)) {\n                    nodesCrossed.push(node);\n                } else if (TraverseUtil.isVisible(node)) {\n                    childNode = node;\n                    break;\n                }\n            }\n        }\n        if (childNode) {\n            cursor.node = childNode;\n            cursor.index = 0;\n            cursor.text = TraverseUtil.getNodeText(cursor.node);\n            if (cursor.node.constructor !== Text) {\n                nodesCrossed.push(cursor.node);\n            }\n        } else {\n            if (cursor.index < cursor.text.length) {\n                return cursor.text[cursor.index++];\n            }\n\n            while (cursor.node !== null) {\n                let siblingNode = null;\n                for (let node = cursor.node.nextSibling;\n                     node !== null;\n                     node = node.nextSibling) {\n                    if (TraverseUtil.isSkipped(node)) {\n                        nodesCrossed.push(node);\n                    } else if (TraverseUtil.isVisible(node)) {\n                        siblingNode = node;\n                        break;\n                    }\n                }\n                if (siblingNode) {\n                    cursor.node = siblingNode;\n                    cursor.text = TraverseUtil.getNodeText(siblingNode);\n                    cursor.index = 0;\n\n                    if (cursor.node.constructor !== Text) {\n                        nodesCrossed.push(cursor.node);\n                    }\n\n                    break;\n                }\n\n                const parentNode = cursor.node.parentNode;\n                if (parentNode &&\n                    parentNode.constructor !== HTMLBodyElement) {\n                    cursor.node = cursor.node.parentNode;\n                    cursor.text = null;\n                    cursor.index = 0;\n                } else {\n                    return null;\n                }\n            }\n        }\n    }\n};\n\nTraverseUtil.getNextChar = function( // eslint-disable-line max-params\n    startCursor, endCursor, nodesCrossed, skipWhitespace) {\n    startCursor.copyFrom(endCursor);\n    let fChar = TraverseUtil.forwardsChar(endCursor, nodesCrossed);\n    if (fChar === null) {\n        return null;\n    }\n\n    const initialWhitespace = TraverseUtil.isWhitespace(fChar);\n\n    while ((TraverseUtil.isWhitespace(fChar)) ||\n           (TraverseUtil.isSkipped(endCursor.node))) {\n        fChar = TraverseUtil.forwardsChar(endCursor, nodesCrossed);\n        if (fChar === null) {\n            return null;\n        }\n    }\n    if (skipWhitespace || !initialWhitespace) {\n        startCursor.copyFrom(endCursor);\n        startCursor.index--;\n        return fChar;\n    }\n\n    for (let i = 0; i < nodesCrossed.length; i++) {\n        if (TraverseUtil.isSkipped(nodesCrossed[i])) {\n            endCursor.index--;\n            startCursor.copyFrom(endCursor);\n            startCursor.index--;\n            return \" \";\n        }\n    }\n    endCursor.index--;\n    return \" \";\n};\n\nTraverseUtil.backwardsChar = function(cursor, nodesCrossed) {\n    while (true) {\n        // Move down until we get to a leaf node.\n        var childNode = null;\n        if (!TraverseUtil.treatAsLeafNode(cursor.node)) {\n            for (var i = cursor.index - 1; i >= 0; i--) {\n                var node = cursor.node.childNodes[i];\n                if (TraverseUtil.isSkipped(node)) {\n                    nodesCrossed.push(node);\n                    continue;\n                }\n                if (TraverseUtil.isVisible(node)) {\n                    childNode = node;\n                    break;\n                }\n            }\n        }\n        if (childNode) {\n            cursor.node = childNode;\n            cursor.text = TraverseUtil.getNodeText(cursor.node);\n            if (cursor.text.length)\n                cursor.index = cursor.text.length;\n            else\n                cursor.index = cursor.node.childNodes.length;\n            if (cursor.node.constructor != Text)\n                nodesCrossed.push(cursor.node);\n            continue;\n        }\n\n        // Return the previous character from this leaf node.\n        if (cursor.text.length > 0 && cursor.index > 0) {\n            return cursor.text[--cursor.index];\n        }\n\n        // Move to the previous sibling, going up the tree as necessary.\n        while (true) {\n            // Try to move to the previous sibling.\n            var siblingNode = null;\n            for (var node = cursor.node.previousSibling;\n                 node != null;\n                 node = node.previousSibling) {\n                if (TraverseUtil.isSkipped(node)) {\n                    nodesCrossed.push(node);\n                    continue;\n                }\n                if (TraverseUtil.isVisible(node)) {\n                    siblingNode = node;\n                    break;\n                }\n            }\n            if (siblingNode) {\n                cursor.node = siblingNode;\n                cursor.text = TraverseUtil.getNodeText(siblingNode);\n                if (cursor.text.length)\n                    cursor.index = cursor.text.length;\n                else\n                    cursor.index = cursor.node.childNodes.length;\n                if (cursor.node.constructor != Text)\n                    nodesCrossed.push(cursor.node);\n                break;\n            }\n\n            // Otherwise, move to the parent.\n            if (cursor.node.parentNode &&\n                cursor.node.parentNode.constructor != HTMLBodyElement) {\n                cursor.node = cursor.node.parentNode;\n                cursor.text = null;\n                cursor.index = 0;\n            } else {\n                return null;\n            }\n        }\n    }\n};\n\nTraverseUtil.getNextWord = function(startCursor, endCursor,\n    nodesCrossed) {\n\n  // Find the first non-whitespace or non-skipped character.\n  var cursor = endCursor.clone();\n  var c = TraverseUtil.forwardsChar(cursor, nodesCrossed);\n  if (c == null)\n    return null;\n  while ((TraverseUtil.isWhitespace(c)) ||\n      (TraverseUtil.isSkipped(cursor.node))) {\n    c = TraverseUtil.forwardsChar(cursor, nodesCrossed);\n    if (c == null)\n      return null;\n  }\n\n  // Set startCursor to the position immediately before the first\n  // character in our word. It's safe to decrement |index| because\n  // forwardsChar guarantees that the cursor will be immediately to the\n  // right of the returned character on exit.\n  startCursor.copyFrom(cursor);\n  startCursor.index--;\n\n  // Keep building up our word until we reach a whitespace character or\n  // would cross a tag.  Don't actually return any tags crossed, because this\n  // word goes up until the tag boundary but not past it.\n  endCursor.copyFrom(cursor);\n  var word = c;\n  var newNodesCrossed = [];\n  c = TraverseUtil.forwardsChar(cursor, newNodesCrossed);\n  if (c == null) {\n    return word;\n  }\n  while (!TraverseUtil.isWhitespace(c) &&\n     newNodesCrossed.length == 0) {\n    word += c;\n    endCursor.copyFrom(cursor);\n    c = TraverseUtil.forwardsChar(cursor, newNodesCrossed);\n    if (c == null) {\n      return word;\n    }\n  }\n  return word;\n};\n\nTraverseUtil.getPreviousWord = function(startCursor, endCursor,\n    nodesCrossed) {\n  // Find the first non-whitespace or non-skipped character.\n  var cursor = startCursor.clone();\n  var c = TraverseUtil.backwardsChar(cursor, nodesCrossed);\n  if (c == null)\n    return null;\n  while ((TraverseUtil.isWhitespace(c) ||\n      (TraverseUtil.isSkipped(cursor.node)))) {\n    c = TraverseUtil.backwardsChar(cursor, nodesCrossed);\n    if (c == null)\n      return null;\n  }\n\n  // Set endCursor to the position immediately after the first\n  // character we've found (the last character of the word, since we're\n  // searching backwards).\n  endCursor.copyFrom(cursor);\n  endCursor.index++;\n\n  // Keep building up our word until we reach a whitespace character or\n  // would cross a tag.  Don't actually return any tags crossed, because this\n  // word goes up until the tag boundary but not past it.\n  startCursor.copyFrom(cursor);\n  var word = c;\n  var newNodesCrossed = [];\n  c = TraverseUtil.backwardsChar(cursor, newNodesCrossed);\n  if (c == null)\n    return word;\n  while (!TraverseUtil.isWhitespace(c) &&\n      newNodesCrossed.length == 0) {\n    word = c + word;\n    startCursor.copyFrom(cursor);\n    c = TraverseUtil.backwardsChar(cursor, newNodesCrossed);\n    if (c == null)\n      return word;\n  }\n\n  return word;\n};\n\nconst CaretBrowsing = {};\n\nCaretBrowsing.isEnabled = false;\n\nCaretBrowsing.onEnable = \"flash\";\n\nCaretBrowsing.onJump = \"flash\";\n\nCaretBrowsing.isWindowFocused = false;\n\nCaretBrowsing.isCaretVisible = false;\n\nCaretBrowsing.caretElement = undefined;\n\nCaretBrowsing.caretX = 0;\n\nCaretBrowsing.caretY = 0;\n\nCaretBrowsing.caretWidth = 0;\n\nCaretBrowsing.caretHeight = 0;\n\nCaretBrowsing.caretForeground = \"#000\";\n\nCaretBrowsing.caretBackground = \"#fff\";\n\nCaretBrowsing.isSelectionCollapsed = false;\n\nCaretBrowsing.blinkFunctionId = null;\n\nCaretBrowsing.targetX = null;\n\nCaretBrowsing.blinkFlag = true;\n\nCaretBrowsing.markEnabled = false;\n\nCaretBrowsing.positionCaret = function() {\n    var start = new Cursor(document.body, 0, '');\n    var end = new Cursor(document.body, 0, '');\n    var nodesCrossed = [];\n    var result = TraverseUtil.getNextChar(start, end, nodesCrossed, true);\n    if (result == null) {\n        return;\n    }\n    CaretBrowsing.setAndValidateSelection(start, start);\n}\n\nCaretBrowsing.isFocusable = function(targetNode) {\n    if (!targetNode || typeof (targetNode.tabIndex) !== \"number\") {\n        return false;\n    }\n\n    if (targetNode.tabIndex >= 0) {\n        return true;\n    }\n\n    if (targetNode.hasAttribute &&\n        targetNode.hasAttribute(\"tabindex\") &&\n        targetNode.getAttribute(\"tabindex\") === \"-1\") {\n        return true;\n    }\n\n    return false;\n}\n\nCaretBrowsing.isControlThatNeedsArrowKeys = function(node) { // eslint-disable-line complexity,max-len\n    if (!node) {\n        return false;\n    }\n\n    if (node === document.body || node !== document.activeElement) {\n        return false;\n    }\n\n    if (node.constructor === HTMLSelectElement) {\n        return true;\n    }\n\n    if (node.constructor === HTMLInputElement) {\n        switch (node.type) { // eslint-disable-line default-case\n        case \"email\":\n        case \"number\":\n        case \"password\":\n        case \"search\":\n        case \"text\":\n        case \"tel\":\n        case \"url\":\n        case \"\":\n            return true;\n        case \"datetime\":\n        case \"datetime-local\":\n        case \"date\":\n        case \"month\":\n        case \"radio\":\n        case \"range\":\n        case \"week\":\n            return true;\n        }\n    }\n\n    if (node.getAttribute && CaretBrowsing.isFocusable(node)) {\n        const role = node.getAttribute(\"role\");\n        switch (role) { // eslint-disable-line default-case\n        case \"combobox\":\n        case \"grid\":\n        case \"gridcell\":\n        case \"listbox\":\n        case \"menu\":\n        case \"menubar\":\n        case \"menuitem\":\n        case \"menuitemcheckbox\":\n        case \"menuitemradio\":\n        case \"option\":\n        case \"radiogroup\":\n        case \"scrollbar\":\n        case \"slider\":\n        case \"spinbutton\":\n        case \"tab\":\n        case \"tablist\":\n        case \"textbox\":\n        case \"tree\":\n        case \"treegrid\":\n        case \"treeitem\":\n            return true;\n        }\n    }\n\n    return false;\n};\n\nCaretBrowsing.injectCaretStyles = function() {\n    const style = \".CaretBrowsing_Caret {\" +\n          \"  position: absolute;\" +\n          \"  z-index: 2147483647;\" +\n          \"  min-height: 10px;\" +\n          \"  background-color: #000;\" +\n          \"}\" +\n          \".CaretBrowsing_AnimateCaret {\" +\n          \"  position: absolute;\" +\n          \"  z-index: 2147483647;\" +\n          \"  min-height: 10px;\" +\n          \"}\" +\n          \".CaretBrowsing_FlashVert {\" +\n          \"  position: absolute;\" +\n          \"  z-index: 2147483647;\" +\n          \"  background: linear-gradient(\" +\n          \"      270deg,\" +\n          \"      rgba(128, 128, 255, 0) 0%,\" +\n          \"      rgba(128, 128, 255, 0.3) 45%,\" +\n          \"      rgba(128, 128, 255, 0.8) 50%,\" +\n          \"      rgba(128, 128, 255, 0.3) 65%,\" +\n          \"      rgba(128, 128, 255, 0) 100%);\" +\n          \"}\";\n    const node = document.createElement(\"style\");\n    node.innerHTML = style;\n    document.body.appendChild(node);\n};\n\nCaretBrowsing.setInitialCursor = function() {\n    if (CaretBrowsing.post_message_down(\"CaretBrowsing.setInitialCursor\")) {\n        return;\n    }\n    const sel = window.getSelection();\n    if (!CaretBrowsing.initiated) {\n        if (sel.rangeCount == 0) {\n            CaretBrowsing.positionCaret();\n        }\n\n        CaretBrowsing.injectCaretStyles();\n        CaretBrowsing.initiated = true;\n    }\n\n    CaretBrowsing.toggle();\n    if (CaretBrowsing.isEnabled) {\n        // when doing an i-search, the selection is totally cleared (sigh)\n        if (sel.rangeCount == 0) {\n            CaretBrowsing.positionCaret();\n        }\n        // do not handle previous selection for now, just removes it.\n        CaretBrowsing.markEnabled = sel.type == \"Range\";\n        if (CaretBrowsing.markEnabled) {\n            CaretBrowsing.markEnabled = false;\n            sel.collapse(sel.anchorNode, sel.anchorOffset);\n            window.setTimeout(() => {\n                CaretBrowsing.updateCaretOrSelection(true);\n            }, 0);\n        }\n    }\n};\n\nCaretBrowsing.shutdown = function() {\n    if (CaretBrowsing.post_message_down(\"CaretBrowsing.shutdown\")) {\n        return;\n    }\n    CaretBrowsing.toggle(false);\n}\n\nCaretBrowsing.setAndValidateSelection = function(start, end) {\n    const sel = window.getSelection();\n    sel.setBaseAndExtent(start.node, start.index, end.node, end.index);\n\n    if (sel.rangeCount !== 1) {\n        return false;\n    }\n\n    return (sel.anchorNode === start.node &&\n            sel.anchorOffset === start.index &&\n            sel.focusNode === end.node &&\n            sel.focusOffset === end.index);\n};\n\n\nCaretBrowsing.setCaretElementNormalStyle = function() {\n    const element = CaretBrowsing.caretElement;\n    element.className = \"CaretBrowsing_Caret\";\n    if (CaretBrowsing.isSelectionCollapsed) {\n        element.style.opacity = \"1.0\";\n    } else {\n        element.style.opacity = \"0.0\";\n    }\n    element.style.left = `${CaretBrowsing.caretX}px`;\n    element.style.top = `${CaretBrowsing.caretY}px`;\n    element.style.width = `${CaretBrowsing.caretWidth}px`;\n    element.style.height = `${CaretBrowsing.caretHeight}px`;\n    element.style.color = CaretBrowsing.caretForeground;\n};\n\nCaretBrowsing.animateCaretElement = function() {\n    const element = CaretBrowsing.caretElement;\n    element.style.left = `${CaretBrowsing.caretX - 50}px`;\n    element.style.top = `${CaretBrowsing.caretY - 100}px`;\n    element.style.width = `${CaretBrowsing.caretWidth + 100}px`;\n    element.style.height = `${CaretBrowsing.caretHeight + 200}px`;\n    element.className = \"CaretBrowsing_AnimateCaret\";\n\n    window.setTimeout(() => {\n        if (!CaretBrowsing.caretElement) {\n            return;\n        }\n        CaretBrowsing.setCaretElementNormalStyle();\n        element.style.transition = \"all 0.8s ease-in\";\n        function listener() {\n            element.removeEventListener(\n                \"transitionend\", listener, false);\n            element.style.transition = \"none\";\n        }\n        element.addEventListener(\n            \"transitionend\", listener, false);\n    }, 0);\n};\n\nCaretBrowsing.flashCaretElement = function() {\n    const x = CaretBrowsing.caretX;\n    const y = CaretBrowsing.caretY;\n\n    const vert = document.createElement(\"div\");\n    vert.className = \"CaretBrowsing_FlashVert\";\n    vert.style.left = `${x - 6}px`;\n    vert.style.top = `${y - 100}px`;\n    vert.style.width = \"11px\";\n    vert.style.height = `${200}px`;\n    document.body.appendChild(vert);\n\n    window.setTimeout(() => {\n        document.body.removeChild(vert);\n        if (CaretBrowsing.caretElement) {\n            CaretBrowsing.setCaretElementNormalStyle();\n        }\n    }, 250);\n};\n\nCaretBrowsing.createCaretElement = function() {\n    const element = document.createElement(\"div\");\n    element.className = \"CaretBrowsing_Caret\";\n    document.body.appendChild(element);\n    CaretBrowsing.caretElement = element;\n\n    if (CaretBrowsing.onEnable === \"anim\") {\n        CaretBrowsing.animateCaretElement();\n    } else if (CaretBrowsing.onEnable === \"flash\") {\n        CaretBrowsing.flashCaretElement();\n    } else {\n        CaretBrowsing.setCaretElementNormalStyle();\n    }\n};\n\nCaretBrowsing.getCursorRect = function(cursor) { // eslint-disable-line max-statements,max-len\n    let node = cursor.node;\n    const index = cursor.index;\n    const rect = {\n        \"left\": 0,\n        \"top\": 0,\n        \"width\": 1,\n        \"height\": 0,\n    };\n    if (node.constructor === Text) {\n        let left = index;\n        let right = index;\n        const max = node.data.length;\n        const newRange = document.createRange();\n        while (left > 0 || right < max) {\n            if (left > 0) {\n                left--;\n                newRange.setStart(node, left);\n                newRange.setEnd(node, index);\n                const rangeRect = newRange.getBoundingClientRect();\n                if (rangeRect && rangeRect.width && rangeRect.height) {\n                    rect.left = rangeRect.right;\n                    rect.top = rangeRect.top;\n                    rect.height = rangeRect.height;\n                    break;\n                }\n            }\n            if (right < max) {\n                right++;\n                newRange.setStart(node, index);\n                newRange.setEnd(node, right);\n                const rangeRect = newRange.getBoundingClientRect();\n                if (rangeRect && rangeRect.width && rangeRect.height) {\n                    rect.left = rangeRect.left;\n                    rect.top = rangeRect.top;\n                    rect.height = rangeRect.height;\n                    break;\n                }\n            }\n        }\n    } else {\n        rect.height = node.offsetHeight;\n        while (node !== null) {\n            rect.left += node.offsetLeft;\n            rect.top += node.offsetTop;\n            node = node.offsetParent;\n        }\n    }\n    rect.left += window.pageXOffset;\n    rect.top += window.pageYOffset;\n    return rect;\n};\n\nCaretBrowsing.updateCaretOrSelection =\n    function(scrollToSelection) { // eslint-disable-line max-statements\n            const previousX = CaretBrowsing.caretX;\n        const previousY = CaretBrowsing.caretY;\n\n        const sel = window.getSelection();\n        if (sel.rangeCount === 0) {\n            if (CaretBrowsing.caretElement) {\n                CaretBrowsing.isSelectionCollapsed = false;\n                CaretBrowsing.caretElement.style.opacity = \"0.0\";\n            }\n            return;\n        }\n\n        const range = sel.getRangeAt(0);\n        if (!range) {\n            if (CaretBrowsing.caretElement) {\n                CaretBrowsing.isSelectionCollapsed = false;\n                CaretBrowsing.caretElement.style.opacity = \"0.0\";\n            }\n            return;\n        }\n\n        if (CaretBrowsing.isControlThatNeedsArrowKeys(\n            document.activeElement)) {\n            let node = document.activeElement;\n            CaretBrowsing.caretWidth = node.offsetWidth;\n            CaretBrowsing.caretHeight = node.offsetHeight;\n            CaretBrowsing.caretX = 0;\n            CaretBrowsing.caretY = 0;\n            while (node.offsetParent) {\n                CaretBrowsing.caretX += node.offsetLeft;\n                CaretBrowsing.caretY += node.offsetTop;\n                node = node.offsetParent;\n            }\n            CaretBrowsing.isSelectionCollapsed = false;\n        } else if (range.startOffset !== range.endOffset ||\n                   range.startContainer !== range.endContainer) {\n            const rect = range.getBoundingClientRect();\n            if (!rect) {\n                return;\n            }\n            CaretBrowsing.caretX = rect.left + window.pageXOffset;\n            CaretBrowsing.caretY = rect.top + window.pageYOffset;\n            CaretBrowsing.caretWidth = rect.width;\n            CaretBrowsing.caretHeight = rect.height;\n            CaretBrowsing.isSelectionCollapsed = false;\n        } else {\n            const rect = CaretBrowsing.getCursorRect(\n                new Cursor(range.startContainer,\n                           range.startOffset,\n                           TraverseUtil.getNodeText(range.startContainer)));\n            CaretBrowsing.caretX = rect.left;\n            CaretBrowsing.caretY = rect.top;\n            CaretBrowsing.caretWidth = rect.width;\n            CaretBrowsing.caretHeight = rect.height;\n            CaretBrowsing.isSelectionCollapsed = true;\n        }\n\n        if (CaretBrowsing.caretElement) {\n            const element = CaretBrowsing.caretElement;\n            if (CaretBrowsing.isSelectionCollapsed) {\n                element.style.opacity = \"1.0\";\n                element.style.left = `${CaretBrowsing.caretX}px`;\n                element.style.top = `${CaretBrowsing.caretY}px`;\n                element.style.width = `${CaretBrowsing.caretWidth}px`;\n                element.style.height = `${CaretBrowsing.caretHeight}px`;\n            } else {\n                element.style.opacity = \"0.0\";\n            }\n        } else {\n            CaretBrowsing.createCaretElement();\n        }\n\n        let elem = range.startContainer;\n        if (elem.constructor === Text) {\n            elem = elem.parentElement;\n        }\n        const style = window.getComputedStyle(elem);\n        const bg = axs.utils.getBgColor(style, elem);\n        const fg = axs.utils.getFgColor(style, elem, bg);\n        CaretBrowsing.caretBackground = axs.color.colorToString(bg);\n        CaretBrowsing.caretForeground = axs.color.colorToString(fg);\n\n        if (scrollToSelection) {\n            const rect = CaretBrowsing.getCursorRect(\n                new Cursor(sel.focusNode, sel.focusOffset,\n                           TraverseUtil.getNodeText(sel.focusNode)));\n\n            const yscroll = window.pageYOffset;\n            const pageHeight = window.innerHeight;\n            const caretY = rect.top;\n            const caretHeight = Math.min(rect.height, 30);\n            if (yscroll + pageHeight < caretY + caretHeight) {\n                window.scroll(0, (caretY + caretHeight - pageHeight + 100));\n            } else if (caretY < yscroll) {\n                window.scroll(0, (caretY - 100));\n            }\n        }\n\n        if (Math.abs(previousX - CaretBrowsing.caretX) > 500 ||\n            Math.abs(previousY - CaretBrowsing.caretY) > 100) {\n            if (CaretBrowsing.onJump === \"anim\") {\n                CaretBrowsing.animateCaretElement();\n            } else if (CaretBrowsing.onJump === \"flash\") {\n                CaretBrowsing.flashCaretElement();\n            }\n        }\n    };\n\nCaretBrowsing.toggle = function(enabled) {\n    if (enabled == undefined) {\n        enabled = !CaretBrowsing.isEnabled;\n    }\n\n    CaretBrowsing.isEnabled = enabled;\n    const obj = {};\n    obj.enabled = CaretBrowsing.isEnabled;\n    CaretBrowsing.updateIsCaretVisible();\n    post_webmacs_message(\"onCaretBrowsing\", [obj.enabled]);\n    if (!obj.enabled) {\n        var sel = window.getSelection();\n        sel.collapse(sel.focusNode, sel.focusOffset);\n    }\n};\n\nCaretBrowsing.onClick = function() {\n    if (!CaretBrowsing.isEnabled) {\n        return true;\n    }\n    window.setTimeout(() => {\n        CaretBrowsing.targetX = null;\n        CaretBrowsing.updateCaretOrSelection(false);\n    }, 0);\n    return true;\n};\n\nCaretBrowsing.caretBlinkFunction = function() {\n    if (CaretBrowsing.caretElement) {\n        if (CaretBrowsing.blinkFlag) {\n            CaretBrowsing.caretElement.style.backgroundColor =\n                CaretBrowsing.caretForeground;\n            CaretBrowsing.blinkFlag = false;\n        } else {\n            CaretBrowsing.caretElement.style.backgroundColor =\n                CaretBrowsing.caretBackground;\n            CaretBrowsing.blinkFlag = true;\n        }\n    }\n};\n\nCaretBrowsing.updateIsCaretVisible = function() {\n    CaretBrowsing.isCaretVisible =\n        (CaretBrowsing.isEnabled && CaretBrowsing.isWindowFocused);\n    if (CaretBrowsing.isCaretVisible && !CaretBrowsing.caretElement) {\n        // CaretBrowsing.setInitialCursor();\n        CaretBrowsing.updateCaretOrSelection(true);\n        if (CaretBrowsing.caretElement) {\n            CaretBrowsing.blinkFunctionId = window.setInterval(\n                CaretBrowsing.caretBlinkFunction, 500);\n        }\n    } else if (!CaretBrowsing.isCaretVisible &&\n               CaretBrowsing.caretElement) {\n        window.clearInterval(CaretBrowsing.blinkFunctionId);\n        if (CaretBrowsing.caretElement) {\n            CaretBrowsing.isSelectionCollapsed = false;\n            CaretBrowsing.caretElement.parentElement.removeChild(\n                CaretBrowsing.caretElement);\n            CaretBrowsing.caretElement = null;\n        }\n    }\n};\n\nCaretBrowsing.onWindowFocus = function() {\n    CaretBrowsing.isWindowFocused = true;\n    CaretBrowsing.updateIsCaretVisible();\n};\n\nCaretBrowsing.onWindowBlur = function() {\n    CaretBrowsing.isWindowFocused = false;\n    CaretBrowsing.updateIsCaretVisible();\n};\n\nCaretBrowsing.init = function() {\n    CaretBrowsing.isWindowFocused = document.hasFocus();\n\n    document.addEventListener(\"click\", CaretBrowsing.onClick, false);\n    window.addEventListener(\"focus\", CaretBrowsing.onWindowFocus, false);\n    window.addEventListener(\"blur\", CaretBrowsing.onWindowBlur, false);\n};\n\nwindow.setTimeout(() => {\n    if (!window.caretBrowsingLoaded) {\n        window.caretBrowsingLoaded = true;\n        CaretBrowsing.init();\n    }\n}, 0);\n\n\nCaretBrowsing.move = function(direction, granularity) {\n    if (CaretBrowsing.post_message_down(\"CaretBrowsing.move\",\n                                        [direction, granularity])) {\n        return;\n    }\n    var sel = window.getSelection();\n    var action = CaretBrowsing.markEnabled ? \"extend\" : \"move\";\n    sel.modify(action, direction, granularity);\n    window.setTimeout(() => {\n        CaretBrowsing.updateCaretOrSelection(true);\n    }, 0);\n};\n\n\nCaretBrowsing.toggleMark = function() {\n    if (CaretBrowsing.post_message_down(\"CaretBrowsing.toggleMark\")) {\n        return;\n    }\n    CaretBrowsing.markEnabled = !CaretBrowsing.markEnabled;\n    if (!CaretBrowsing.markEnabled) {\n        var sel = window.getSelection();\n        sel.collapse(sel.focusNode, sel.focusOffset);\n        window.setTimeout(() => {\n            CaretBrowsing.updateCaretOrSelection(true);\n        }, 0);\n    }\n};\n\nCaretBrowsing.cutSelection = function() {\n    if (CaretBrowsing.post_message_down(\"CaretBrowsing.cutSelection\")) {\n        return;\n    }\n    post_webmacs_message(\"copyToClipboard\",\n                         [window.getSelection().toString()]);\n    // clear the current selection\n    if (CaretBrowsing.markEnabled) { CaretBrowsing.toggleMark(); }\n};\n\nCaretBrowsing.post_message_down = function(message_name, arg) {\n    if (document.activeElement.tagName === \"IFRAME\") {\n        post_message(document.activeElement.contentWindow, message_name, arg);\n        return true;\n    }\n    return false;\n}\n\nif (self !== top) {\n    register_message_handler(\"CaretBrowsing.setInitialCursor\",\n                             CaretBrowsing.setInitialCursor);\n    register_message_handler(\"CaretBrowsing.shutdown\",\n                             CaretBrowsing.shutdown);\n    register_message_handler(\"CaretBrowsing.move\", function (args) {\n        CaretBrowsing.move(args[0], args[1]);\n    });\n    register_message_handler(\"CaretBrowsing.toggleMark\",\n                             CaretBrowsing.toggleMark);\n    register_message_handler(\"CaretBrowsing.cutSelection\",\n                             CaretBrowsing.cutSelection);\n}\n"
  },
  {
    "path": "webmacs/scripts/hint.js",
    "content": "function clickLike(elem) {\n    elem.focus();\n    var doc = elem.ownerDocument;\n    var view = doc.defaultView;\n\n    var evt = doc.createEvent(\"MouseEvents\");\n    evt.initMouseEvent(\"mousedown\", true, true, view, 1, 0, 0, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,\n                       /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);\n    elem.dispatchEvent(evt);\n\n    evt = doc.createEvent(\"MouseEvents\");\n    evt.initMouseEvent(\"click\", true, true, view, 1, 0, 0, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,\n                       /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);\n    elem.dispatchEvent(evt);\n\n    evt = doc.createEvent(\"MouseEvents\");\n    evt.initMouseEvent(\"mouseup\", true, true, view, 1, 0, 0, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,\n                       /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);\n    elem.dispatchEvent(evt);\n}\n\nfunction rectElementInViewport(elem, w) {  // eslint-disable-line complexity\n    var win = elem.ownerDocument.defaultView;\n    var rect = elem.getBoundingClientRect();\n    w = w || window;\n\n    if (!rect ||\n        rect.top > w.innerHeight ||\n        rect.bottom < 0 ||\n        rect.left > w.innerWidth ||\n        rect.right < 0) {\n        return null;\n    }\n\n    rect = elem.getClientRects()[0];\n    if (!rect) {\n        return null;\n    }\n\n    var style = win.getComputedStyle(elem, null);\n    if (style.getPropertyValue(\"visibility\") !== \"visible\" ||\n        style.getPropertyValue(\"display\") === \"none\" ||\n        style.getPropertyValue(\"opacity\") === \"0\") {\n        return null;\n    }\n    return rect;\n}\n\nfunction escapeRegExp(str) {\n    return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, \"\\\\$&\");\n}\n\nclass BaseHint {\n    constructor(obj, manager, index, rect) {\n        this.obj = obj;\n        this.manager = manager;\n        this.index = index;\n        this.hint = document.createElement(\"div\");\n        for (var prop in manager.options.hint) {\n            this.hint.style[prop] = manager.options.hint[prop];\n        }\n        this.hint.style.left = (rect.left + window.scrollX) + \"px\";\n        this.hint.style.top = (rect.top + window.scrollY) + \"px\";\n        this.hint.style.position = \"absolute\";\n        this.hint.style.display = \"block\";\n        this.hint.style.zIndex = \"2147483647\";\n        this.hint.textContent = index;\n    }\n\n    text() {\n        if (this.obj.textContent) {\n            return this.obj.textContent;\n        }\n        return null;\n    }\n\n    url() {\n        if (this.obj.href) {\n            return this.obj.href;\n        }\n        return null;\n    }\n\n    id() {\n        return this.index;\n    }\n\n    serialize() {\n        return JSON.stringify({\n            nodeName: this.obj.nodeName,\n            text: this.text(),\n            id: this.id(),\n            url: this.url()\n        });\n    }\n\n    remove() {\n        this.hint.parentNode.removeChild(this.hint);\n    }\n\n    setVisible(on) {\n        this.hint.style.display = on ? \"initial\" : \"none\";\n    }\n\n    isVisible() {\n        return this.hint.style.display != \"none\";\n    }\n\n    refresh() {}\n}\n\nclass Hint extends BaseHint {\n    constructor(obj, manager, rect, index) {\n        super(obj, manager, index, rect);\n        this.objBackground = obj.style.background;\n        this.objColor = obj.style.color;\n        obj.style.background = manager.options.background;\n        obj.style.color = manager.options.text_color;\n    }\n\n    remove() {\n        this.obj.style.background = this.objBackground;\n        this.obj.style.color = this.objColor;\n        super.remove();\n    }\n\n    setVisible(on) {\n        super.setVisible(on);\n        this.refresh();\n    }\n\n    refresh() {\n        if (this.isVisible()) {\n            if (this.manager.activeHint == this) {\n                this.obj.style.background = this.manager.options.background_active;\n            } else {\n                this.obj.style.background = this.manager.options.background;\n            }\n            this.obj.style.color = this.manager.options.text_color;\n        } else {\n            this.obj.style.background = this.objBackground;\n            this.obj.style.color = this.objColor;\n        }\n    }\n\n    id() {\n        return this.hint.textContent;\n    }\n}\n\nclass AlphabetHint extends BaseHint {\n    constructor(obj, manager, rect, index) {\n        super(obj, manager, index, rect);\n    }\n}\n\nclass HintFrame {\n    constructor(frame) {\n        this.frame = frame;\n    }\n\n    remove() {\n        post_message(this.frame.contentWindow, \"hints.select_clear\", null);\n    }\n}\n\n\n// took from conkeror\nXPATH_NS = {\n    xhtml: \"http://www.w3.org/1999/xhtml\",\n    m: \"http://www.w3.org/1998/Math/MathML\",\n    xul: \"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\",\n    svg: \"http://www.w3.org/2000/svg\"\n};\n\nfunction xpath_lookup_namespace (prefix) {\n    return XPATH_NS[prefix] || null;\n}\n\nclass Hinter {\n    init(selector, method, options) {\n        this.selector = selector;\n        this.xres = document.evaluate(selector, document, xpath_lookup_namespace,\n                                      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n                                      null);\n        this.fragment = document.createDocumentFragment();\n        this.index = 0;\n        this.hints = [];\n        this.activeHint = null;\n        this.method = method;\n        this.options = options || {};\n    }\n\n    lookup(hint_index) {\n        // has been cleared.\n        if (this.hints === null) {\n            return;\n        }\n\n        for (; this.index < this.xres.snapshotLength; this.index++) {\n            let obj = this.xres.snapshotItem(this.index);\n            let rect = rectElementInViewport(obj, window);\n            if (!rect) {\n                continue;\n            }\n            if (obj.tagName == \"IFRAME\") {\n                post_message(obj.contentWindow, \"hints.lookup_in_iframe_start\",\n                             {selector: this.selector, hint_index: hint_index,\n                              method: this.method, options: this.options});\n                this.hints.push(new HintFrame(obj));\n                this.index+=1;\n                return;\n            }\n            hint_index += 1;\n            var hint;\n            if (this.method == \"filter\") {\n                hint = new Hint(obj, this, rect, hint_index);\n            } else {\n                hint = new AlphabetHint(obj, this, rect, hint_index);\n                hint.setVisible(false);\n            }\n            this.hints.push(hint);\n            this.fragment.appendChild(hint.hint);\n        }\n        document.documentElement.appendChild(this.fragment);\n\n        if (self !== top) {\n            post_message(parent, \"hints.lookup_in_iframe_end\", hint_index);\n        } else {\n            if (this.method == \"alphabet\") {\n                this.hintsCreated(hint_index);\n            } else {\n                // hints are ready\n                post_webmacs_message(\"_browserObjectActivated\", [\"null\"]);\n            }\n        }\n    }\n\n    // alphabet only\n    hintsCreated(count) {\n        // took from vimium\n        let hints = [\"\"];\n        let offset = 0;\n        while ((hints.length - offset) < count || hints.length == 1) {\n            let hint = hints[offset++];\n            for (var ch of this.options.characters) {\n                hints.push(ch + hint);\n            }\n        }\n        hints = hints.slice(offset, offset+count).sort().map(e => {\n            return e.split(\"\").reverse().join(\"\");\n        });\n\n        this.configure_hints(0, hints, []);\n    }\n\n    // alphabet only\n    configure_hints(index, labels, parent_indexes) {\n        let label_index = 0;\n        for (; index < this.hints.length; index++) {\n            let hint = this.hints[index];\n            if (hint instanceof HintFrame) {\n                post_message(hint.frame.contentWindow, \"hints.frame_configure_hints\",\n                             {index: 0, labels: labels.slice(label_index),\n                              parent_indexes: [index + 1].concat(parent_indexes)});\n                return;\n            } else {\n                hint.chars = labels[label_index];\n                hint.hint.textContent = hint.chars;\n                hint.setVisible(true);\n                label_index++;\n            }\n        }\n        if (self !== top) {\n            post_message(parent, \"hints.frame_configure_hints\", {\n                index: parent_indexes[0],\n                parent_indexes: parent_indexes.slice(1),\n                labels: labels.slice(label_index),\n            });\n        } else {\n            // hints are ready\n            post_webmacs_message(\"_browserObjectActivated\", [\"null\"]);\n        }\n    }\n\n    // alphabet only\n    frame_configure_hints(args) {\n        this.configure_hints(args.index, args.labels, args.parent_indexes);\n    }\n\n    selectBrowserObjects(selector, method, options) {\n        this.init(selector, method, JSON.parse(options));\n        this.lookup(0);\n        if (method === \"filter\") {\n            this.activateNextHint(false);\n        }\n    }\n\n    clearBrowserObjects() {\n        // has been cleared.\n        if (this.hints === null) {\n            return;\n        }\n        for (var hint of this.hints) {\n            hint.remove();\n        }\n        this.hints = null;\n    }\n\n    frameUpActivateHint(indexes) {\n        let hint = null;\n        if (indexes !== null) {\n            let index = indexes.shift();\n            hint = this.hints[index];\n        }\n        let prev = this.activeHint;\n\n\n        if (hint === prev) {\n            return hint;\n        }\n        this.clearFrameSelection();\n\n        this.activeHint = hint;\n        if (top != self) {\n            post_message(parent, \"hints.frameUpActivateHint\", indexes);\n        }\n        return hint;\n    }\n\n    clearFrameSelection() {\n        let prevHint = this.activeHint;\n        if (! prevHint) {\n            return;\n        }\n        this.activeHint = null;\n        if (prevHint instanceof BaseHint) {\n            prevHint.refresh();\n        } else {\n            post_message(prevHint.frame.contentWindow,\n                         \"hints.clearFrameSelection\");\n        }\n    }\n\n    setCurrentActiveHint(indexes) {\n        let hint = this.frameUpActivateHint(indexes);\n        if (hint) {\n            // refresh the hint style to make it appear activated.\n            hint.refresh();\n            post_webmacs_message(\"_browserObjectActivated\", [hint.serialize()]);\n        }\n    }\n\n    frameActivateNextHint(args) {\n        if (this.method !== \"filter\") {\n            return;\n        }\n        let traverse = function(hinter, index) {\n            let hint = hinter.hints[index];\n            if (hint instanceof BaseHint) {\n                if (hint.isVisible()) {\n                    hinter.setCurrentActiveHint([index].concat(args.parent_indexes));\n                    return true;\n                }\n            } else {\n                let parent_indexes = args.parent_indexes;\n                // this is a hint frame, so go down that frame\n                post_message(hint.frame.contentWindow,\n                             \"hints.frameActivateNextHint\", {\n                                 // a list of ordered indexes of the calling\n                                 // frame hint\n                                 parent_indexes: [index].concat(args.parent_indexes),\n                                 way: args.way\n                             });\n                return true;\n            }\n            return false;\n        };\n\n\n        let index = args.index;\n        if (index === undefined) {\n            if (this.activeHint) {\n                // just go down on the current hint if it is a frame\n                index = this.hints.indexOf(this.activeHint);\n\n                // else, activate the next hint\n                if (this.activeHint instanceof BaseHint) {\n                    index += args.way;\n                }\n            } else {\n                // if no selection, select the first one\n                index = args.way == 1 ? 0: this.hints.length - 1;\n            }\n        }\n\n        if (args.way === 1) {\n            for (; index < this.hints.length; index++) {\n                if (traverse(this, index)) {\n                    return;\n                }\n            }\n        } else {\n            for (; index >= 0; index--) {\n                if (traverse(this, index)) {\n                    return;\n                }\n            }\n        }\n\n        // we found no selection if we are here\n        if (self !== top) {\n            // recall the parent frame\n            post_message(parent, \"hints.frameActivateNextHint\", {\n                index: args.parent_indexes[0] + args.way,\n                way: args.way\n            });\n        } else {\n            // on the main frame, clear the selection and recall this function\n            // to loop.\n            if (this.hints) {\n                this.setCurrentActiveHint(null);\n                this.frameActivateNextHint({way: args.way, parent_indexes: []});\n            }\n        }\n    }\n\n    activateNextHint(backward) {\n        this.frameActivateNextHint({\n            way: backward ? -1 : 1,\n            parent_indexes: [],\n        });\n    }\n\n    followCurrentLink() {\n        if (this.activeHint) {\n            if (this.activeHint instanceof BaseHint) {\n                clickLike(this.activeHint.obj);\n            } else {\n                post_message(this.activeHint.frame.contentWindow,\n                             \"hints.followCurrentLink\");\n            }\n        }\n    }\n\n    frameSelectVisibleHint(args) {\n        let frameHint = null;\n        let index = args.index;\n\n        for (let hint_index=0; hint_index < this.hints.length; hint_index++) {\n            let hint = this.hints[hint_index];\n            if (hint instanceof BaseHint) {\n                if (! hint.isVisible()) {\n                    continue;\n                }\n                let nb = parseInt(hint.hint.textContent);\n                if (nb === index) {\n                    this.setCurrentActiveHint([hint_index].concat(args.parent_indexes));\n                    return;\n                } else if (nb > index) {\n\t\t    break;\n                }\n            } else {\n                frameHint = {window: hint.frame.contentWindow, index: hint_index};\n            }\n        }\n\t      if (frameHint) {\n\t          post_message(\n\t\t            frameHint.window,\n\t\t            \"hints.frameSelectVisibleHint\", {\n                    index: index,\n                    parent_indexes: [frameHint.index].concat(args.parent_indexes)\n\t\t            }\n\t          );\n\t      }\n    }\n\n    selectVisibleHint(index) {\n        if (this.method !== \"filter\") {\n            return;\n        }\n        this.frameSelectVisibleHint({index: parseInt(index), parent_indexes: []});\n    }\n\n    frameFilterSelection(args) {\n        let hint_index = args.hint_index;\n\n        // match everything when text selector is empty\n        let match_hint = hint => true;\n\n        if (args.text) {\n            if (this.method == \"filter\") {\n                // fuzzy-match on the hint text\n                let parts = args.text.split(/\\s+/).map(escapeRegExp);\n                let re = new RegExp(\".*\" + parts.join(\".*\") + \".*\", \"i\");\n                match_hint = function(hint) {\n                    let text = hint.text();\n                    if (text !== null) {\n                        return (text.match(re) !== null);\n                    }\n                    return false;\n                };\n            } else {\n                match_hint = function(hint) {\n                    return hint.chars.startsWith(args.text);\n                };\n            }\n        }\n\n        for (let index = args.index; index < this.hints.length; index++) {\n            let hint = this.hints[index];\n            if (hint instanceof HintFrame) {\n                // iframe, let's go down\n                post_message(hint.frame.contentWindow, \"hints.frameFilterSelection\", {\n                    text: args.text,\n                    index: 0,\n                    parent_indexes: [index].concat(args.parent_indexes),\n                    hint_index: hint_index\n                });\n                return;\n            }\n\n            // else see if we match the hint, and update its visibility\n            if (match_hint(hint)) {\n                hint_index +=1;\n                hint.setVisible(true);\n                if (this.method == \"filter\") {\n                    hint.hint.textContent = hint_index;\n                } else {\n                    if (hint.chars == args.text) {\n                        // alphabet always set the active hint when we found the\n                        // final hint.\n                        this.setCurrentActiveHint(\n                            [index].concat(args.parent_indexes)\n                        );\n                        return;\n                    }\n                }\n            } else {\n                hint.setVisible(false);\n                if (hint == this.activeHint) {\n                    this.setCurrentActiveHint(null);\n                }\n            }\n        }\n\n        if (self !== top) {\n            // if we are in a sub frame, we call back the parent so he will\n            // continue.\n            post_message(parent, \"hints.frameFilterSelection\", {\n                text: args.text,\n                index: args.parent_indexes[0] + 1,\n                hint_index: hint_index,\n                parent_indexes: args.parent_indexes.slice(1)\n            });\n        } else {\n            // else if we lose the selection, put it back to the first hint.\n            if (this.activeHint === null && this.method == \"filter\") {\n                this.activateNextHint(false);\n            }\n        }\n    }\n\n    filterSelection(text) {\n        this.frameFilterSelection({\n            text: text,\n            index: 0,\n            hint_index: 0,\n            parent_indexes: [],\n        });\n    }\n}\n\nvar hints = new Hinter();\n\nfunction currentLinkUrl() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"A\") {\n        post_webmacs_message(\"currentLinkUrl\", [elt.href]);\n    } else if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"hints.foundCurrentLinkUrl\", null);\n    } else {\n        post_webmacs_message(\"currentLinkUrl\", [\"\"]);\n    }\n\n}\n\nif (self !== top) {\n    register_message_handler(\"hints.lookup_in_iframe_start\", function(args) {\n        hints.init(args.selector, args.method, args.options);\n        hints.lookup(args.hint_index);\n    });\n    register_message_handler(\"hints.select_clear\",\n                             _ => hints.clearBrowserObjects());\n    register_message_handler(\"hints.clearFrameSelection\",\n                             _ => hints.clearFrameSelection());\n    register_message_handler(\"hints.frameSelectVisibleHint\",\n                             args => hints.frameSelectVisibleHint(args));\n    register_message_handler(\"hints.foundCurrentLinkUrl\",\n                             _ => currentLinkUrl());\n}\nregister_message_handler(\"hints.lookup_in_iframe_end\",\n                         hint_index => hints.lookup(hint_index));\nregister_message_handler(\"hints.frameActivateNextHint\",\n                         args => hints.frameActivateNextHint(args));\nregister_message_handler(\"hints.followCurrentLink\",\n                         _ => hints.followCurrentLink());\nregister_message_handler(\"hints.frameFilterSelection\",\n                         args => hints.frameFilterSelection(args));\nregister_message_handler(\"hints.frameUpActivateHint\",\n                         args => hints.frameUpActivateHint(args));\nregister_message_handler(\"hints.frame_configure_hints\",\n                         args => hints.frame_configure_hints(args));\n"
  },
  {
    "path": "webmacs/scripts/password_manager.js",
    "content": "// This file is part of webmacs.\n//\n// webmacs is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// webmacs is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nvar password_manager = {};\n\npassword_manager.create_fake_event = function(typeArg) {\n    if (['keydown', 'keyup', 'keypress'].includes(typeArg)) {\n        return new KeyboardEvent(typeArg, {\n            'key': ' ',\n            'code': ' ',\n            'charCode': ' '.charCodeAt(0),\n            'keyCode': ' '.charCodeAt(0),\n            'which': ' '.charCodeAt(0),\n            'bubbles': true,\n            'composed': true,\n            'cancelable': true\n        });\n    } else if (['input', 'change'].includes(typeArg)) {\n        return new InputEvent(typeArg, {\n            'bubbles': true,\n            'composed': true,\n            'cancelable': true\n        });\n    } else if (['focus', 'blur'].includes(typeArg)) {\n        return new FocusEvent(typeArg, {\n            'bubbles': true,\n            'composed': true,\n            'cancelable': true\n        });\n    } else {\n        console.log.error(\"password_manager.create_fake_event: Unknown event type: \" + typeArg);\n        return null;\n    }\n}\n\n\npassword_manager.set_input_value = function(input, value) {\n    input.value = value;\n    for (let action of ['focus', 'keydown', 'keyup', 'keypress',\n                        'input', 'change', 'blur']) {\n        input.dispatchEvent(password_manager.create_fake_event(action));\n        input.value = value;\n    }\n}\n\npassword_manager.allowedInputTypeForName = ['text', 'email', 'tel'];\n\npassword_manager.complete_form_data = function(data) {\n    var allowedUserAttrib = [\"name\", \"id\", \"autocomplete\", \"placeholder\"];\n    var allowedInputTypeForName = ['text', 'email', 'tel'];\n\n    var inputs = document.getElementsByTagName('input');\n    var focusedElem = document.activeElement;\n\n    for (var i=0; i < inputs.length; ++i) {\n        var input = inputs[i];\n        // don't fill if element is invisible\n        if (input.offsetHeight === 0 || input.offsetParent === null) {\n            continue;\n        }\n        var type = input.type.toLowerCase();\n\n        if (data.password !== null && type === 'password') {\n            password_manager.set_input_value(input, data.password);\n        } else if (data.username !== null && password_manager.allowedInputTypeForName.includes(type)) {\n            password_manager.set_input_value(input, data.username);\n        }\n        for (const j in allowedUserAttrib) {\n            var attribName = allowedUserAttrib[j];\n            var attrib = input.getAttribute(attribName);\n            for (const field in data.fields) {\n                if (attrib == field) {\n                    password_manager.set_input_value(input, data.fields[field]);\n                    break;\n                }\n            }\n        }\n    }\n\n    if (focusedElem) {\n        focusedElem.focus();    // get back the focus\n    }\n}\n"
  },
  {
    "path": "webmacs/scripts/setup.js",
    "content": "// This file is part of webmacs.\n//\n// webmacs is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// webmacs is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\n// per frame handlers for the message sent with window.postMessage.\nlet MESSAGE_HANDLERS = {};\n\n\n/*\n  Use window.postMessage to send a cross-origin message.\n\n  This allow to bypass the same origin policy in frames. An id is injected\n  in the message sent, to be more secure.\n\n  w: the window to send to.\n  name: the message name.\n  args: the message parameters.\n*/\nfunction post_message(w, name, args) {\n    w.postMessage({\n        webmacsid: WEBMACS_SECURE_ID,\n        name: name,\n        args: args\n    }, \"*\");\n}\n\n// register sent messages on each frame.\nwindow.addEventListener(\"message\", function(e) {\n    let data = e.data;\n    if (typeof(data) == \"object\"\n        && data.webmacsid === WEBMACS_SECURE_ID) {\n        let handler = MESSAGE_HANDLERS[data.name];\n        if (handler !== undefined) {\n            handler(data.args);\n        }\n    }\n})\n\n/*\n  register a message handler in the current frame.\n*/\nfunction register_message_handler(name, func) {\n    MESSAGE_HANDLERS[name] = func;\n}\n\n/*\n  Post a message on the webmacs python side, using the qtwebchannel.\n\n  This use post_message if we are not on the main_frame, as only the main frame\n  posses the __webmacsHandler__ web channel object.\n*/\nfunction post_webmacs_message(name, args) {\n    if (self === top) {\n        __webmacsHandler__[name].apply(__webmacsHandler__, args);\n    } else {\n        post_message(top, name, args);\n    }\n}\n\nfunction isTextInput(node) {\n    return node.isContentEditable\n        || node.nodeName == \"INPUT\" || node.nodeName == \"TEXTAREA\";\n}\n\n// register focus in and out event on each frame.\ndocument.addEventListener(\"focusin\", function(e) {\n    if (isTextInput(e.target)) {\n        post_webmacs_message(\"onTextFocus\", [true]);\n    }\n}, true);\n\ndocument.addEventListener(\"focusout\", function(e) {\n    if (isTextInput(e.target)) {\n        post_webmacs_message(\"onTextFocus\", [false]);\n    }\n}, true);\n\n\nif (self === top) {\n    // for post_webmacs_message to works when called from iframes.\n    register_message_handler(\"onTextFocus\",\n                             args => post_webmacs_message(\"onTextFocus\", args));\n    register_message_handler(\"copyToClipboard\",\n                             args => post_webmacs_message(\"copyToClipboard\",\n                                                          args));\n    register_message_handler(\"openExternalEditor\",\n                             args => post_webmacs_message(\"openExternalEditor\",\n                                                          args));\n    register_message_handler(\"onCaretBrowsing\",\n                             args => post_webmacs_message(\"onCaretBrowsing\",\n                                                          args));\n    register_message_handler(\"currentLinkUrl\",\n                             args => post_webmacs_message(\"currentLinkUrl\",\n                                                          args));\n    register_message_handler(\"_browserObjectActivated\",\n                             args => post_webmacs_message(\"_browserObjectActivated\",\n                                                          args));\n\n    // and now, register the web channel on the top frame.\n    function registerWebmacs(w) {\n        // only called in main frame\n        console.log(\"registering...\");\n        window.__webmacsHandler__ = w;\n\n        // force the focus on the current web content\n        post_webmacs_message(\n            \"onTextFocus\",\n            [!!(document.activeElement && isTextInput(document.activeElement))]\n        );\n\n        var event = document.createEvent('Event');\n        event.initEvent('_webmacs_external_created', true, true);\n        document.dispatchEvent(event);\n    }\n\n    function registerWebChannel() {\n        try {\n            new QWebChannel(\n                qt.webChannelTransport,\n                channel => registerWebmacs(channel.objects.contentHandler)\n            );\n        } catch (e) {\n            setTimeout(registerWebChannel, 50);\n        }\n    }\n\n    registerWebChannel();\n}\n"
  },
  {
    "path": "webmacs/scripts/textedit.js",
    "content": "// This file is part of webmacs.\n//\n// webmacs is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// webmacs is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nvar textedit = {};\ntextedit.EXTERNAL_EDITOR_REQUESTS = {};\n\n\ntextedit.clear_mark = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.clear_mark\", null);\n    } else {\n        if (! elt.isContentEditable) {\n\t          var pos = elt.selectionDirection == \"forward\" ? elt.selectionEnd : elt.selectionStart;\n\t          elt.setSelectionRange(pos, pos);\n        } else {\n\t          let sel = document.getSelection();\n\t          if (! sel.isCollapsed) {\n\t              sel.collapse(sel.focusNode, sel.focusOffset);\n\t          }\n        }\n    }\n}\n\ntextedit.blur = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.blur\", null);\n    } else {\n        elt.blur();\n    }\n}\n\ntextedit.copy_text = function(reset_selection) {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.copy_text\", null);\n    } else {\n        let sel = document.getSelection();\n        if (sel.type !== 'Range') {\n\t          return;\n        }\n        post_webmacs_message(\"copyToClipboard\", [sel.toString()]);\n        if (reset_selection) {\n\t          textedit.clear_mark();\n        }\n    }\n}\n\ntextedit.select_text = function(direction, granularity) {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.select_text\", [direction, granularity]);\n    } else {\n        textedit.clear_mark();\n        if (!direction && !granularity) {\n            elt.select();\n        } else {\n            document.getSelection().modify(\"extend\", direction, granularity);\n        }\n    }\n}\n\ntextedit._change_next_word_case = function(fn) {\n    let elt = document.activeElement;\n    textedit.select_text('forward', 'word');\n    if (elt.isContentEditable) {\n\t      return;\n    }\n    var pos = elt.selectionStart;\n    var txt = elt.value;\n    var nextpos = elt.selectionEnd;\n    elt.value = txt.slice(0, pos) + fn(txt.slice(pos, nextpos))\n\t      + txt.slice(nextpos);\n    elt.setSelectionRange(nextpos, nextpos);\n}\n\ntextedit.upcase_word = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.upcase_word\", null);\n    } else {\n        textedit._change_next_word_case(function(t) {\n\t          return t.toUpperCase();\n        });\n    }\n}\n\ntextedit.downcase_word = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.downcase_word\", null);\n    } else {\n        textedit._change_next_word_case(function(t) {\n\t          return t.toLowerCase();\n        });\n    }\n}\n\ntextedit.capitalize_word = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.capitalize_word\", null);\n    } else {\n        textedit._change_next_word_case(function(t) {\n\t          return t.toLowerCase().replace(/(?:^|\\s)\\S/g, function(a) {\n\t              return a.toUpperCase();\n\t          });\n        });\n    }\n}\n\ntextedit.external_editor_open = function() {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.external_editor_open\", null);\n    } else {\n        var id = new Date().getUTCMilliseconds() + \"\";\n        let txt = (elt.isContentEditable) ?\n\t          elt.innerText : elt.value;\n        post_webmacs_message(\"openExternalEditor\", [id, txt]);\n        textedit.EXTERNAL_EDITOR_REQUESTS[id] = elt;\n    }\n}\n\ntextedit.external_editor_finish = function(id, content) {\n    let elt = document.activeElement;\n    if (elt.tagName == \"IFRAME\") {\n        post_message(elt.contentWindow, \"textedit.external_editor_finish\", [id, content]);\n    } else {\n        textedit._external_editor_finish([id, content]);\n    }\n}\n\ntextedit._external_editor_finish = function(args) {\n    let id = args[0];\n    let content = args[1];\n\n    if (content !== false) {\n\t      let e = textedit.EXTERNAL_EDITOR_REQUESTS[id];\n\t      if (e.isContentEditable) {\n\t          e.innerText = content;\n\t      } else {\n\t          e.value = content;\n\t      }\n    }\n    delete textedit.EXTERNAL_EDITOR_REQUESTS[id];\n}\n\nif (self !== top) {\n    register_message_handler(\"textedit.clear_mark\", textedit.clear_mark);\n    register_message_handler(\"textedit.blur\", textedit.blur);\n    register_message_handler(\"textedit.copy_text\", textedit.copy_text);\n    register_message_handler(\"textedit.select_text\", textedit.select_text);\n    register_message_handler(\"textedit.upcase_word\", textedit.upcase_word);\n    register_message_handler(\"textedit.downcase_word\", textedit.downcase_word);\n    register_message_handler(\"textedit.external_editor_open\",\n                             textedit.external_editor_open);\n    register_message_handler(\"textedit.external_editor_finish\",\n                             textedit._external_editor_finish);\n}\n"
  },
  {
    "path": "webmacs/scripts/textzoom.js",
    "content": "var textzoom = {};\n\ntextzoom.totalRatio = 1;\n\ntextzoom.IGNORED_TAGS = /SCRIPT|NOSCRIPT|LINK|BR|EMBED|IFRAME|IMG|VIDEO|CANVAS|STYLE/;\n\ntextzoom.multiplyByRatio = function(value, multiplier) {\n  return (parseFloat(value) * multiplier) + 'px';\n};\n\ntextzoom.addImportantStyle = function(el, name, value) {\n  return el.style.cssText += name + \": \" + value + \" !important;\";\n};\n\ntextzoom.isBlank = function(str) {\n    return !str || /^\\s*$/.test(str)\n}\n\ntextzoom.resetChangeFont = function() {\n    for (let i=0; i<window.frames.length; i++) {\n        post_message(window.frames[i], \"textzoom.resetChangeFont\");\n    }\n    textzoom.totalRatio = 1;\n    textzoom.changeFont(0, true);\n    return textzoom.totalRatio;\n}\n\n\ntextzoom.changeFont = function(ratioDiff, prevent) {\n    let prevRatio = textzoom.totalRatio;\n    textzoom.totalRatio += ratioDiff;\n    textzoom.totalRatio = Math.round(textzoom.totalRatio * 10) / 10;\n    let multiplier = textzoom.totalRatio / prevRatio;\n    let relevantElements = document.querySelectorAll('body, body *');\n\n    if (!prevent) {\n        for (let i=0; i<window.frames.length; i++) {\n            post_message(window.frames[i], \"textzoom.changeFont\", ratioDiff);\n        }\n    }\n\n    if (textzoom.totalRatio === 1) {\n\t      for (let el of relevantElements) {\n\t          el.style['transition'] = null;\n\t          el.style['font-size'] = null;\n\t          el.style['line-height'] = null;\n\t      }\n    }\n    for (let el of relevantElements) {\n\t      if (el.tagName.match(textzoom.IGNORED_TAGS)) {\n\t          continue;\n\t      }\n        let lineHeight = null;\n\t      let computedStyle = getComputedStyle(el);\n\t      if (!textzoom.isBlank(el.innerText) || (el.tagName === 'TEXTAREA')) {\n\t          if (computedStyle.lineHeight.indexOf('px') !== -1) {\n\t\t            lineHeight = textzoom.multiplyByRatio(computedStyle.lineHeight,\n                                                      multiplier);\n\t          }\n\t      }\n\t      let fontSize = textzoom.multiplyByRatio(computedStyle.fontSize, multiplier);\n\n\t      el.style['transition'] = 'font 0s';\n\t      textzoom.addImportantStyle(el, 'font-size', fontSize);\n\t      if (lineHeight !== null) {\n\t\t        textzoom.addImportantStyle(el, 'line-height', lineHeight);\n\t      }\n    }\n    return textzoom.totalRatio;\n}\n\n\nif (self !== top) {\n    register_message_handler(\"textzoom.changeFont\", textzoom.changeFont);\n    register_message_handler(\"textzoom.resetChangeFont\",\n                             textzoom.resetChangeFont);\n}\n"
  },
  {
    "path": "webmacs/session.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport json\nimport logging\n\nfrom .import BUFFERS, windows, current_window\nfrom .webbuffer import create_buffer, QUrl, DelayedLoadingUrl, close_buffer\nfrom .window import Window\n\n\nFORMAT_VERSION = 2\n\n\ndef _session_load(stream):\n    data = json.load(stream)\n    version = data.get(\"version\", 0)\n    urls = data[\"urls\"]\n    if version < 2:\n        urls = reversed(urls)\n\n    # apply the session config\n\n    # now, load urls in buffers\n    for url in urls:\n        if isinstance(url, str):\n            # old format, no delay loading support\n            # TODO must be removed after some time\n            create_buffer(url)\n        else:\n            # new format, url must be a dict\n            buff = create_buffer(DelayedLoadingUrl(\n                url=QUrl(url[\"url\"]),\n                title=url[\"title\"]\n            ))\n            if version >= 2:\n                buff.last_use = url[\"last_use\"]\n\n    if version > 0:\n        def create_window(wdata):\n            win = Window()\n            win.restore_state(wdata, version)\n            win.show()\n\n        current_index = data.get(\"current-window\", 0)\n        for i, wdata in enumerate(data[\"windows\"]):\n            if i != current_index:\n                create_window(wdata)\n\n        # create the current last, so it has focus and is on top\n        create_window(data[\"windows\"][current_index])\n\n    else:\n        cwin = Window()\n        cwin.showMaximized()\n\n        # and open the first buffer in the view\n        if BUFFERS:\n            cwin.current_webview().setBuffer(BUFFERS[0])\n\n\ndef _session_save(stream):\n    urls = [{\n        \"url\": b.url().toString(),\n        \"title\": b.title(),\n        \"last_use\": b.last_use,\n    } for b in BUFFERS]\n\n    json.dump({\n        \"version\": FORMAT_VERSION,\n        \"urls\": urls,\n        \"windows\": [w.dump_state() for w in windows()],\n        \"current-window\": windows().index(current_window()),\n    }, stream)\n\n\ndef session_clean():\n    # clean every opened buffers and windows\n    for window in windows():\n        window.quit_if_last_closed = False\n        window.close()\n        for view in window.webviews():\n            view.setBuffer(None)\n\n    for buffer in BUFFERS:\n        close_buffer(buffer)\n\n\ndef session_load(session_file):\n    \"\"\"\n    Try to load the session, given the profile.\n\n    Must be called at application startup, when no buffers nor views is set up\n    already.\n    \"\"\"\n    if session_file is None:\n        return\n    try:\n        with open(session_file, \"r\") as f:\n            _session_load(f)\n    except Exception:\n        logging.exception(\"Unable to load the session from %s.\",\n                          session_file)\n        session_clean()\n        raise\n\n\ndef session_save(session_file):\n    if session_file is None:\n        return\n    \"\"\"\n    Save the session for the given profile.\n    \"\"\"\n    with open(session_file, \"w\") as f:\n        _session_save(f)\n"
  },
  {
    "path": "webmacs/spell_checking.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom . import variables\nfrom .task import Task\n\nfrom PyQt6.QtNetwork import QNetworkRequest, QNetworkReply\nfrom PyQt6.QtCore import QUrl\n\nimport os\nimport re\nimport json\nimport logging\nimport base64\nfrom collections import namedtuple\n\n\nRemoteBdic = namedtuple(\"RemoteBdic\", (\"name\", \"version\", \"extension\"))\n\nBDIC_FILES_URL = \"https://chromium.googlesource.com/chromium/deps/hunspell_dictionaries.git/+/master/\" # noqa\n\n\nspell_checking_dictionaries = variables.define_variable(\n    \"spell-checking-dictionaries\",\n    \"List of dictionaries to use for spell checking.\",\n    (),\n    type=variables.List(variables.String()),\n)\n\n\nclass Versions(dict):\n    @classmethod\n    def from_file(cls, path):\n        if os.path.isfile(path):\n            with open(path) as f:\n                return cls(**json.load(f))\n        else:\n            return cls()\n\n    def get_version(self, name):\n        return self.get(name, [0, 0])\n\n    def write(self, path):\n        with open(path, \"w\") as f:\n            json.dump(dict(**self), f)\n\n\nclass SpellCheckingTask(Task):\n    def __init__(self, app, path):\n        Task.__init__(self)\n        self.app = app\n        self.path = path\n        self.__versions_path = os.path.join(self.path, \"versions.json\")\n        self.__versions = None\n        self.__modified = False\n        self.__bdic_replies = {}\n\n    def start(self):\n        if not os.path.isdir(self.path):\n            try:\n                os.makedirs(self.path)\n            except Exception as exc:\n                logging.warning(\"Can not initialize spell checking dir %s: %s\"\n                                % (self.path, exc))\n                return False\n        self.__versions = Versions.from_file(self.__versions_path)\n        self.__bdic_replies.clear()\n\n        reply = self.app.network_manager.get(\n            QNetworkRequest(QUrl(BDIC_FILES_URL + \"?format=json\")))\n        reply.finished.connect(self._on_bdic_files_list)\n\n    def _on_bdic_files_list(self):\n        reply = self.sender()\n        # A special 5-byte prefix must be stripped from the response\n        # See: https://github.com/google/gitiles/issues/22\n        #      https://github.com/google/gitiles/issues/82\n        json_data = json.loads(bytes(reply.readAll())[5:].decode(\"utf-8\"))\n\n        re_bdic = re.compile(r\"(.*)-(\\d+-\\d+)(\\.bdic)$\")\n        remotes = {}\n        for entry in json_data[\"entries\"]:\n            res = re_bdic.match(entry[\"name\"])\n            if res:\n                name, version, extension = (res.group(1), res.group(2),\n                                            res.group(3))\n                version = [int(e) for e in version.split(\"-\")]\n\n                remotes[name] = RemoteBdic(name, version, extension)\n\n        local_files = set(os.path.splitext(f)[0] for f in os.listdir(self.path)\n                          if f.endswith(\".bdic\"))\n\n        for name in spell_checking_dictionaries.value:\n            try:\n                r = remotes[name]\n            except KeyError:\n                logging.warning(\n                    \"No spell checking dict for %s. \\nAvailable: %s\"\n                    % (name, list(remotes))\n                )\n                continue\n            if name not in local_files:\n                logging.info(\"Downloading dict %s\" % name)\n                self._install(r)\n\n            elif r.version > self.__versions.get(name, [0, 0]):\n                logging.info(\"Updating dict %s\" % name)\n                self._install(r)\n\n        if not self.__bdic_replies:\n            self.finished.emit()\n\n    def _install(self, r):\n        url = \"{}{}-{}{}?format=TEXT\".format(\n            BDIC_FILES_URL,\n            r.name,\n            \"-\".join(str(v) for v in r.version),\n            r.extension\n        )\n        dest = os.path.join(self.path, \"{}{}\".format(r.name, r.extension))\n\n        reply = self.app.network_manager.get(QNetworkRequest(QUrl(url)))\n        self.__bdic_replies[reply] = {\"bdic\": r, \"dest\": dest, \"data\": b\"\"}\n        reply.readyRead.connect(self._bdic_ready_read)\n        reply.finished.connect(self._bdic_finished)\n\n    def _bdic_ready_read(self):\n        reply = self.sender()\n        self.__bdic_replies[reply][\"data\"] += bytes(reply.readAll())\n\n    def _bdic_finished(self):\n        reply = self.sender()\n        data = self.__bdic_replies.pop(reply)\n        if reply.error() != QNetworkReply.NetworkError.NoError:\n            if not self.error():\n                self.set_error_message(reply.errorString())\n                # abort other replies\n                for r in self.__bdic_replies:\n                    r.abort()\n            if not self.__bdic_replies:\n                self.finished.emit()\n            return\n        with open(data[\"dest\"], 'bw') as f:\n            f.write(base64.decodebytes(data[\"data\"]))\n\n        self.__versions[data[\"bdic\"].name] = data[\"bdic\"].version\n\n        if not self.__bdic_replies:\n            self.__versions.write(self.__versions_path)\n            self.finished.emit()\n"
  },
  {
    "path": "webmacs/task.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport logging\n\nfrom PyQt6.QtCore import QObject, pyqtSignal as Signal, pyqtSlot as Slot\n\nfrom . import call_later\n\n\nclass Task(QObject):\n    \"\"\"\n    A long running task.\n\n    Note it is designed to be asynchronous - using signals, and if any thread\n    is needed, QThreadPool might be used but each subclass must deal with\n    concurrency.\n    \"\"\"\n    finished = Signal()\n    description = None\n\n    def __init__(self):\n        QObject.__init__(self)\n        self.__error = None\n\n    @Slot()\n    def start(self):\n        \"\"\"\n        Start the task.\n        \"\"\"\n\n    @Slot()\n    def abort(self):\n        \"\"\"\n        Abort the task.\n        \"\"\"\n\n    def error(self):\n        \"\"\"\n        True if there was an error.\n        \"\"\"\n        return bool(self.__error)\n\n    def error_message(self):\n        \"\"\"\n        Description of the error if any.\n        \"\"\"\n        return self.__error\n\n    def set_error(self, message):\n        self.__error = message\n\n    def __str__(self):\n        return self.description or self.__class__.__name__\n\n\nclass TaskRunner(QObject):\n    def __init__(self):\n        QObject.__init__(self)\n        self.running_tasks = set()\n\n    def run(self, task):\n        \"\"\"\n        Run the task in the next main loop iteration.\n        \"\"\"\n        task.finished.connect(self._on_task_finished)\n        call_later(task.start)\n        logging.info(f\"Starting task {task}\")\n        self.running_tasks.add(task)\n\n    @Slot()\n    def stop(self):\n        for task in self.running_tasks:\n            task.abort()\n\n    def _on_task_finished(self):\n        task = self.sender()\n        if not task.error():\n            logging.info(f\"Task {task}: finished.\")\n        else:\n            logging.error(f\"Task {task}: Error {task.error_message()}\")\n\n        self.running_tasks.remove(task)\n"
  },
  {
    "path": "webmacs/url_opener.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom .webbuffer import create_buffer\nfrom .window import Window\n\n\ndef url_open(ctx, url, instance=None, new_window=False, new_buffer=False):\n    \"\"\"\n    Open an url.\n    \"\"\"\n    assert instance is None  # TODO FIXME implement later\n\n    buffer = None\n\n    if new_buffer or new_window:\n        buffer = create_buffer()\n        if new_window:\n            w = Window()\n            w.current_webview().setBuffer(buffer)\n            buffer.load(url)  # load before showing\n            w.show()\n            w.activateWindow()\n            return\n        else:\n            ctx.view.setBuffer(buffer)\n    else:\n        buffer = ctx.buffer\n\n    buffer.load(url)\n"
  },
  {
    "path": "webmacs/variables.py",
    "content": "VARIABLES = {}\n\n\nclass VariableConditionError(Exception):\n    \"Raised when a variable condition is not fulfilled\"\n\n\ndef condition(func, doc):\n    def _condition(value):\n        if not func(value):\n            assert False, doc\n\n    _condition.__doc__ = doc\n    return _condition\n\n\nclass Variable(object):\n    __slots__ = (\"name\", \"doc\", \"value\", \"conditions\", \"callbacks\", \"type\")\n\n    def __init__(self, name, doc, value, conditions=(), callbacks=(),\n                 type=None):\n        self.name = name\n        self.doc = doc\n        self.conditions = conditions\n        assert isinstance(type, Type)\n        self.type = type\n        self.validate(value)\n        self.value = value\n        self.callbacks = callbacks\n\n    def validate(self, value):\n        self.type.validate(value)\n        for cond in self.conditions:\n            try:\n                cond(value)\n            except Exception as exc:\n                raise VariableConditionError(\n                    \"Condition failed for variable {} with value {}: {}\"\n                    .format(self.name, repr(value), exc)\n                ) from None\n\n    def set_value(self, value):\n        if value != self.value:\n            self.validate(value)\n            self.value = value\n            for callback in self.callbacks:\n                callback(self)\n\n    def add_callback(self, callback):\n        if not isinstance(self.callbacks, list):\n            self.callbacks = list(self.callbacks)\n        self.callbacks.append(callback)\n\n\nclass Type(object):\n    def validate(self, value):\n        pass\n\n    def _describe(self, result):\n        pass\n\n    def type_name(self):\n        return \"\"\n\n    def describe(self):\n        result = [self.type_name(), []]\n        self._describe(result[1])\n        return result\n\n\nclass ChoiceMixin(object):\n    def __init__(self, choices=None, **kwargs):\n        super().__init__(**kwargs)\n        self.choices = choices\n\n    def validate(self, value):\n        super().validate(value)\n        if self.choices and value not in self.choices:\n            raise VariableConditionError(\"Must be one of %r\"\n                                         % (tuple(self.choices),))\n\n    def _describe(self, result):\n        if self.choices:\n            result.append(\"one of %r\" % (tuple(self.choices),))\n        super()._describe(result)\n\n\nclass RangeMixin(object):\n    def __init__(self, min=None, max=None, **kwargs):\n        super().__init__(**kwargs)\n        self.min = min\n        self.max = max\n\n    def validate(self, value):\n        super().validate(value)\n        if self.min is not None and value < self.min:\n            raise VariableConditionError(\n                \"Must be greater or equal to %s\" % self.min\n            )\n        if self.max is not None and value > self.max:\n            raise VariableConditionError(\n                \"Must be lesser or equal to %s\" % self.max\n            )\n\n    def _describe(self, result):\n        if self.min is not None:\n            result.append(\">= %s\" % self.min)\n        if self.max is not None:\n            result.append(\"<= %s\" % self.max)\n        super()._describe(result)\n\n\nclass String(ChoiceMixin, Type):\n    def validate(self, value):\n        if not isinstance(value, str):\n            raise VariableConditionError(\"Must be a string\")\n        super().validate(value)\n\n    def type_name(self):\n        return \"String\"\n\n\nclass Int(ChoiceMixin, RangeMixin, Type):\n    def validate(self, value):\n        if not isinstance(value, int):\n            raise VariableConditionError(\"Must be an integer\")\n        super().validate(value)\n\n    def type_name(self):\n        return \"Int\"\n\n\nclass Float(ChoiceMixin, RangeMixin, Type):\n    def validate(self, value):\n        if not isinstance(value, float):\n            raise VariableConditionError(\"Must be a float\")\n        super().validate(value)\n\n    def type_name(self):\n        return \"Float\"\n\n\nclass Bool(Type):\n    def validate(self, value):\n        if not isinstance(value, bool):\n            raise VariableConditionError(\"Must be True or False\")\n\n    def type_name(self):\n        return \"Bool\"\n\n\nclass List(Type):\n    def __init__(self, type):\n        self.type = type\n\n    def validate(self, value):\n        if not isinstance(value, (tuple, list)):\n            raise VariableConditionError(\"Must be a list\")\n\n        for i, v in enumerate(value):\n            try:\n                self.type.validate(v)\n            except VariableConditionError as exc:\n                raise VariableConditionError(\"List at position %d: %s\"\n                                             % (i, exc)) from None\n\n    def type_name(self):\n        return \"List\"\n\n    def describe(self):\n        result = super().describe()\n        result.append({\"of\": self.type.describe()})\n        return result\n\n\nclass Tuple(Type):\n    def __init__(self, *types):\n        self.types = types\n\n    def validate(self, value):\n        if not (isinstance(value, (tuple, list))\n                and len(self.types) == len(value)):\n            raise VariableConditionError(\"Must be a tuple of size %d\"\n                                         % len(self.types))\n        for i, v in enumerate(value):\n            try:\n                self.types[i].validate(value[i])\n            except VariableConditionError as exc:\n                raise VariableConditionError(\"Tuple at position %d: %s\"\n                                             % (i, exc)) from None\n\n    def type_name(self):\n        return \"Tuple\"\n\n    def describe(self):\n        result = super().describe()\n        for i, t in enumerate(self.types):\n            result.append({\"at index %i\" % i: t.describe()})\n        return result\n\n\nclass Dict(Type):\n    def __init__(self, key_type, value_type):\n        self.key_type = key_type\n        self.value_type = value_type\n\n    def validate(self, value):\n        if not (isinstance(value, dict)):\n            raise VariableConditionError(\"Must be a dict\")\n        for k, v in value.items():\n            try:\n                self.key_type.validate(k)\n            except VariableConditionError as exc:\n                raise VariableConditionError(\"Key %r: %s\" % (k, exc))\n            try:\n                self.value_type.validate(v)\n            except VariableConditionError as exc:\n                raise VariableConditionError(\"Value for key %r: %s\" % (k, exc))\n\n    def type_name(self):\n        return \"Dict\"\n\n    def describe(self):\n        result = super().describe()\n        result.append({\"key\": self.key_type.describe()})\n        result.append({\"value\": self.key_type.describe()})\n        return result\n\n\ndef define_variable(name, doc, value, **kwargs):\n    var = Variable(name, doc, value, **kwargs)\n    VARIABLES[name] = var\n    return var\n\n\ndef get_variable(name):\n    try:\n        return VARIABLES[name]\n    except KeyError:\n        raise KeyError(\"No such variable %s\" % name)\n\n\ndef get(name):\n    \"\"\"\n    Returns the variable value.\n\n    :param name: the name of the variable.\n    \"\"\"\n    return get_variable(name).value\n\n\ndef set(name, value):\n    \"\"\"\n    Set a value for a variable.\n\n    :param name: the name of the variable.\n    :param value: the new value.\n    :raises: KeyError if the variable does not exists, or\n             :class:`VariableConditionError` if the value is incorrect.\n    \"\"\"\n    get_variable(name).set_value(value)\n\n\ndefine_variable(\n    \"home-page\",\n    \"Defines the url to use when webmacs starts. If set to the empty\"\n    \" string, the last session will be loaded. You can set it to\"\n    \" 'about:blank' if you want an empty page.\",\n    \"\",\n    type=String(),\n)\n\ndefine_variable(\n    \"home-page-in-new-window\",\n    \"Use the home page when creating a new window with *make-window*.\"\n    \" Default to False.\",\n    False,\n    type=Bool()\n)\n"
  },
  {
    "path": "webmacs/version.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport os\nimport sys\nimport logging\nimport re\nimport subprocess\n\nfrom PyQt6.QtWebEngineCore import QWebEngineProfile\nfrom PyQt6.QtCore import (QT_VERSION_STR, PYQT_VERSION_STR,  # noqa: F401\n                          QT_VERSION, PYQT_VERSION)\nfrom . import __version__ as WEBMACS_VERSION_STR  # noqa: F401\n\n\nis_mac = sys.platform.startswith('darwin')\nis_linux = sys.platform.startswith('linux')\nis_windows = sys.platform.startswith('win')\nis_posix = os.name == 'posix'\n# this is required as we mock extension modules to generate the doc and\n# sometimes that needs manual work for autodoc to works well.\nbuilding_doc = \"sphinx\" in sys.modules\n\n\ndef QT_VERSION_CHECK(major, minor=0, patch=0):\n    return (major << 16) | (minor << 8) | patch\n\n\nclass _QtVersionChecker(object):\n    __slots__ = (\"version\",)\n\n    def __init__(self, version):\n        self.version = version\n\n    def __eq__(self, other):\n        return self.version == QT_VERSION_CHECK(*other)\n\n    def __lt__(self, other):\n        return self.version < QT_VERSION_CHECK(*other)\n\n    def __gt__(self, other):\n        return self.version > QT_VERSION_CHECK(*other)\n\n    def __le__(self, other):\n        return self.version <= QT_VERSION_CHECK(*other)\n\n    def __ge__(self, other):\n        return self.version >= QT_VERSION_CHECK(*other)\n\n\nmin_qt_version = _QtVersionChecker(min(QT_VERSION, PYQT_VERSION))\nqt_version = _QtVersionChecker(QT_VERSION)\npyqt_version = _QtVersionChecker(PYQT_VERSION)\n\n\ndef chromium_version():\n    \"\"\"\n    Get the Chromium version for QtWebEngine.\n\n    This can also be checked by looking at this file with the right Qt tag:\n    https://github.com/qt/qtwebengine/blob/dev/tools/scripts/version_resolver.py#L41\n    \"\"\"\n    if QWebEngineProfile is None:\n        # This should never happen\n        return 'unavailable'\n    profile = QWebEngineProfile()\n    ua = profile.httpUserAgent()\n    match = re.search(r' Chrome/([^ ]*) ', ua)\n    if not match:\n        logging.error(\"Could not get Chromium version from: {}\".format(ua))\n        return 'unknown'\n    return match.group(1)\n\n\ndef webmacs_revision():\n    \"\"\"\n    Try to get webmacs git revision.\n\n    First try to read the \"revision\" file that should be created at\n    installation time - else fall back to executing the git command.\n    \"\"\"\n    path = os.path.dirname(sys.modules[\"webmacs\"].__file__)\n\n    revision_file = os.path.join(path, \"revision\")\n    if os.path.isfile(revision_file):\n        with open(revision_file) as f:\n            return f.read().strip()\n\n    # git directory should be in the parent directory\n    if not os.path.exists(os.path.join(os.path.dirname(path), \".git\")):\n        return None\n\n    p = subprocess.Popen(\n        [\"git\", \"rev-parse\", \"HEAD\"], cwd=path,\n        stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n    )\n    out, err = p.communicate()\n    if p.returncode == 0:\n        return out.strip().decode(\"utf-8\")\n"
  },
  {
    "path": "webmacs/visited_links.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport sqlite3\nfrom datetime import datetime\nfrom . import variables\n\n\nvisited_links_display_limit = variables.define_variable(\n    \"visited-links-display-limit\",\n    \"Limit the number of history elements displayed in the\"\n    \" visited-links-history command.\",\n    2000,\n    type=variables.Int(min=1)\n)\n\n\nclass VisitedLinks(object):\n    def __init__(self, dbbath):\n        self._conn = sqlite3.connect(dbbath)\n        self._conn.execute(\"\"\"\n        CREATE TABLE IF NOT EXISTS visitedlinks\n        (url TEXT PRIMARY KEY, title TEXT, lastseen DATE);\n        \"\"\")\n\n    def visit(self, url, title):\n        self._conn.execute(\"\"\"\n        INSERT OR REPLACE INTO visitedlinks (url, title, lastseen)\n        VALUES (?, ?, ?)\n        \"\"\", (url, title, datetime.now()))\n        self._conn.commit()\n\n    def visited_urls(self):\n        return [(row[0], row[1]) for row in self._conn.execute(\n            \"select url, title from visitedlinks order by lastseen DESC\"\n            \" LIMIT %d\" % visited_links_display_limit.value\n        )]\n\n    def remove(self, url):\n        self._conn.execute(\"\"\"\n        DELETE from visitedlinks WHERE url = ?\n        \"\"\", (url,))\n"
  },
  {
    "path": "webmacs/webbuffer.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport logging\nimport time\nimport json\n\nfrom PyQt6.QtCore import QUrl, pyqtSlot as Slot\nfrom PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineScript\nfrom PyQt6.QtWebChannel import QWebChannel\nfrom collections import namedtuple\n\nfrom . import hooks, variables, windows\nfrom . import BUFFERS, current_minibuffer, minibuffer_show_info, \\\n    current_buffer, call_later, current_window, recent_buffers\nfrom .content_handler import WebContentHandler\nfrom .application import app\nfrom .minibuffer.prompt import YesNoPrompt, AskPasswordPrompt\nfrom .password_manager import PasswordManagerNotReady\nfrom .keyboardhandler import LOCAL_KEYMAP_SETTER\nfrom .mode import get_mode, Mode, get_auto_modename_for_url\n\n\nclose_buffer_close_window = variables.define_variable(\n    \"close-buffer-close-window\",\n    \"Policy to close a window when the last available buffer is closed.\"\n    \" If never, closing a buffer will never close a window.\"\n    \" If all, closing a buffer can close a window, even the last one (\"\n    \" and so it will exit the application). Finally, all-but-last is like\"\n    \" all but the last window will never be closed.\",\n    \"never\",\n    type=variables.String(choices=(\"never\", \"all\", \"all-but-last\")),\n)\n\n\n# a tuple of QUrl, str to delay loading of a page.\nDelayedLoadingUrl = namedtuple(\"DelayedLoadingUrl\", (\"url\", \"title\"))\n\n\ndef close_buffer(wb):\n    view = wb.view()\n    if view:\n        # buffer is currently visible, search for a buffer that is not visible\n        # yet to put it in the view\n        invisibles = [b for b in recent_buffers() if not b.view()]\n        if not invisibles:\n            if len(view.main_window.webviews()) > 1:\n                # we can close the current view if it is not alone\n                view.main_window.close_view(view)\n            else:\n                close_window = close_buffer_close_window.value\n                if close_window == \"never\":\n                    # never close the buffer, nor the window\n                    return\n                elif len(windows()) == 1:\n                    # if only one window left and policy is all, quit the app\n                    if close_window == \"all\":\n                        app().quit()\n                    return\n                else:\n                    # close both the window and the buffer\n                    view.setBuffer(None)\n                    view.main_window.close()\n        else:\n            # associate the first buffer that does not have any view yet\n            view.setBuffer(invisibles[0])\n\n    internal_view = wb.internal_view()\n    if internal_view:\n        # remove the associated internal page view (might be causing a crash\n        # from when calling ~QWebEnginePage())\n        internal_view.deleteLater()\n\n    # clear the web channel. Might be causing a crash when calling\n    # ~QWebEnginePage()\n    wb.webChannel().deleteLater()\n    wb.setWebChannel(None)\n\n    BUFFERS.remove(wb)\n    wb.deleteLater()\n    hooks.webbuffer_closed(wb)\n    return True\n\n\nclass WebBuffer(QWebEnginePage):\n    \"\"\"\n    Represent some web page content.\n    \"\"\"\n\n    LOGGER = logging.getLogger(\"webcontent\")\n    JSMessageLevel = QWebEnginePage.JavaScriptConsoleMessageLevel\n    JSLEVEL2LOGGING = {\n        JSMessageLevel.InfoMessageLevel: logging.INFO,\n        JSMessageLevel.WarningMessageLevel: logging.WARNING,\n        JSMessageLevel.ErrorMessageLevel: logging.ERROR,\n    }\n\n    def __init__(self, url=None):\n        \"\"\"\n        Create a webbuffer.\n\n        :param url: the url to use for the buffer. Must be an instance of QUrl,\n            an str or None to not load any url.\n        \"\"\"\n        QWebEnginePage.__init__(self, app().profile.q_profile, None)\n        self.last_use = time.time()\n        cb = current_buffer()\n        if cb:\n            BUFFERS.insert(BUFFERS.index(cb) + 1, self)\n        else:\n            BUFFERS.append(self)\n        hooks.webbuffer_created(self)\n\n        self.fullScreenRequested.connect(self._on_full_screen_requested)\n        self.featurePermissionRequested.connect(self._on_feature_requested)\n        self._content_handler = WebContentHandler(self)\n        channel = QWebChannel(self)\n        channel.registerObject(\"contentHandler\", self._content_handler)\n\n        self.setWebChannel(channel,\n                           QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n        self.loadFinished.connect(self.finished)\n        self.authenticationRequired.connect(self.handle_authentication)\n        self.linkHovered.connect(self.on_url_hovered)\n        self.titleChanged.connect(self.__on_title_changed)\n        self.__delay_loading_url = None\n        self.__keymap_mode = Mode.KEYMAP_NORMAL\n        self.__mode = get_mode(\"standard-mode\")\n        self.__text_edit_mark = False\n        self._internal_view = None\n\n        if url:\n            if isinstance(url, DelayedLoadingUrl):\n                self.__delay_loading_url = url\n            else:\n                self.load(url)\n\n    def internal_view(self):\n        return self._internal_view\n\n    def view(self):\n        iv = self._internal_view\n        if iv and iv.isVisible():\n            return iv.view()\n\n    @property\n    def mode(self):\n        return self.__mode\n\n    @property\n    def text_edit_mark(self):\n        return self.__text_edit_mark\n\n    def set_text_edit_mark(self, on):\n        self.__text_edit_mark = on\n\n    def set_mode(self, modename):\n        if self.__mode.name == modename:\n            return\n        old_mode = self.__mode\n        self.__mode = get_mode(modename)\n        LOCAL_KEYMAP_SETTER.buffer_mode_changed(self, old_mode)\n\n    def load(self, url):\n        if not isinstance(url, QUrl):\n            url = QUrl.fromUserInput(url)\n        self.__delay_loading_url = None\n        return QWebEnginePage.load(self, url)\n\n    def delayed_loading_url(self):\n        return self.__delay_loading_url\n\n    def url(self):\n        if self.__delay_loading_url:\n            return self.__delay_loading_url.url\n        return QWebEnginePage.url(self)\n\n    def title(self):\n        if self.__delay_loading_url:\n            return self.__delay_loading_url.title\n        return QWebEnginePage.title(self)\n\n    @property\n    def content_handler(self):\n        return self._content_handler\n\n    def javaScriptConsoleMessage(self, level, message, lineno, source):\n        logger = self.LOGGER\n        # small speed improvement, avoid to log if unnecessary\n        if logger.level < logging.CRITICAL:\n            level = self.JSLEVEL2LOGGING.get(level, logging.ERROR)\n            logger.log(level, message, extra={\"url\": self.url().toString()})\n\n    def active_keymap(self):\n        return self.mode.keymap_for_mode(self.__keymap_mode)\n\n    @property\n    def keymap_mode(self):\n        return self.__keymap_mode\n\n    def set_keymap_mode(self, enabled):\n        self.__keymap_mode = enabled\n\n    def async_scroll_pos(self, func):\n        self.runJavaScript(\"[window.pageXOffset, window.pageYOffset]\", func)\n\n    def set_scroll_pos(self, x=0, y=0):\n        self.runJavaScript(\"window.scrollTo(%d, %d);\" % (x, y))\n\n    def scroll_by(self, x=0, y=0):\n        self.runJavaScript(\"window.scrollBy(%d, %d);\" % (x, y))\n\n    def start_select_browser_objects(self, selector, method=\"filter\",\n                                     method_options=None):\n        self.runJavaScript(\n            \"hints.selectBrowserObjects(%r, %r, %r);\"\n            % (selector, method, json.dumps(method_options)),\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    def stop_select_browser_objects(self):\n        self.runJavaScript(\n            \"hints.clearBrowserObjects();\",\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    def select_nex_browser_object(self, forward=True):\n        self.runJavaScript(\n            \"hints.activateNextHint(%s);\" % (\"false\" if forward else \"true\",),\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    def filter_browser_objects(self, text):\n        self.runJavaScript(\n            \"hints.filterSelection(%r);\" % text,\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    def focus_active_browser_object(self):\n        self.runJavaScript(\n            \"hints.followCurrentLink();\",\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    def select_visible_hint(self, hint_id):\n        self.runJavaScript(\n            \"hints.selectVisibleHint(%r);\" % hint_id,\n            QWebEngineScript.ScriptWorldId.ApplicationWorld)\n\n    @Slot(\"QWebEngineFullScreenRequest\")\n    def _on_full_screen_requested(self, request):\n        internal_view = self.internal_view()\n        if not internal_view:\n            return\n        if internal_view.request_fullscreen(request.toggleOn()):\n            request.accept()\n\n    @Slot(QUrl, QWebEnginePage.Feature)\n    def _on_feature_requested(self, url, feature):\n        permission_db = app().features()\n\n        permission = permission_db.get_permission(url.host(), feature)\n\n        if permission == QWebEnginePage.PermissionPolicy.PermissionUnknown:\n            prompt = YesNoPrompt(\"Allow enabling feature {} for {}?\"\n                                 .format(feature.name, url.toString()),\n                                 always=True,\n                                 never=True)\n            answer = current_minibuffer().do_prompt(prompt, flash=True)\n\n            if answer in (YesNoPrompt.YES, YesNoPrompt.ALWAYS):\n                permission = QWebEnginePage.PermissionPolicy.PermissionGrantedByUser\n            elif answer in (YesNoPrompt.NO, YesNoPrompt.NEVER):\n                permission = QWebEnginePage.PermissionPolicy.PermissionDeniedByUser\n            else:\n                permission = QWebEnginePage.PermissionPolicy.PermissionUnknown\n\n            if answer in (YesNoPrompt.ALWAYS, YesNoPrompt.NEVER):\n                permission_db.set_permission(url.host(), feature, permission)\n\n        self.setFeaturePermission(url, feature, permission)\n\n    def createWindow(self, type):\n        buffer = create_buffer()\n        view = self.view()\n        if view is None:\n            view = current_window().current_webview()\n\n        def open_in_view():\n            view.setBuffer(buffer)\n\n        call_later(open_in_view)\n        return buffer\n\n    def finished(self):\n        url = self.url()\n        if url.isValid() and not url.scheme() == \"webmacs\":\n            app().visitedlinks().visit(url.toString(), self.title())\n\n        self.set_mode(get_auto_modename_for_url(self.url().toString()))\n\n        hooks.webbuffer_load_finished(self)\n\n        # We lose the keyboard focus without that with Qt 5.11. Though it\n        # happens quite randomly, but a combination of follow, go back, google\n        # something and the issue happens. I was not seeing this with Qt5.9.\n        view = self.view()\n        if view and not LOCAL_KEYMAP_SETTER.enabled_minibuffer \\\n           and view.main_window.current_webview() == view:\n\n            view.internal_view().setFocus()\n\n    def handle_authentication(self, url, authenticator):\n        password_manager = app().profile.password_manager\n        try:\n            credential = password_manager.credential_for_url(url.toString())\n        except PasswordManagerNotReady:\n            credential = None\n\n        if credential:\n            authenticator.setUser(credential.username)\n            authenticator.setPassword(credential.password)\n            return\n\n        # ask authentication credentials\n        prompt = AskPasswordPrompt(self)\n        current_minibuffer().do_prompt(prompt, flash=True)\n\n        authenticator.setUser(prompt.username)\n        authenticator.setPassword(prompt.password)\n\n    def certificateError(self, error):\n        url = \"{}:{}\".format(error.url().host(), error.url().port(80))\n        db = app().ignored_certs()\n        if db.is_ignored(url):\n            return True\n\n        prompt = YesNoPrompt(\"[certificate error] {} - ignore ? \"\n                             .format(error.errorDescription()), always=True)\n        current_minibuffer().do_prompt(prompt, flash=True)\n\n        if prompt.value() == YesNoPrompt.ALWAYS:\n            db.ignore(url)\n        return prompt.value() in (YesNoPrompt.ALWAYS, YesNoPrompt.YES)\n\n    def javaScriptConfirm(self, url, msg):\n        return current_minibuffer().do_prompt(\n            YesNoPrompt(\"[js-confirm] {} \".format(msg)),\n            flash=True,\n        )\n\n    def javaScriptAlert(self, url, msg):\n        msg = \"[js-alert] {}\".format(msg)\n        minibuffer_show_info(msg)\n\n    def on_url_hovered(self, url):\n        minibuffer_show_info(url)\n\n    def main_window(self):\n        view = self.view()\n        if view:\n            return view.main_window\n\n    def _incr_zoom(self, forward):\n        # Zooming constants\n        ZOOM_MIN = 25\n        ZOOM_MAX = 500\n        ZOOM_INC = 25\n\n        zoom = self.zoomFactor()*100\n        # We need to round up because the zoom factor is stored as a float\n        self.set_zoom(round(min(ZOOM_MAX, max(ZOOM_MIN, zoom +\n                                              (ZOOM_INC if forward\n                                               else -ZOOM_INC)))))\n\n    def set_zoom(self, zoom_factor):\n\n        if zoom_factor is not None:\n            self.setZoomFactor(zoom_factor/100)\n            minibuffer_show_info(\"Zoom level: %d%%\" % (zoom_factor))\n\n    def zoom_in(self):\n        self._incr_zoom(True)\n\n    def zoom_out(self):\n        self._incr_zoom(False)\n\n    def zoom_normal(self):\n        self.set_zoom(100)\n\n    @Slot(str)\n    def __on_title_changed(self, title):\n        if self.view():\n            self.view().main_window.update_title(title)\n\n\n# alias to create a web buffer\ncreate_buffer = WebBuffer\n"
  },
  {
    "path": "webmacs/webview.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nimport time\n\nfrom PyQt6.QtWebEngineWidgets import QWebEngineView\nfrom PyQt6.QtWidgets import QFrame, QVBoxLayout, QWidget\nfrom PyQt6.QtCore import QEvent\n\nfrom .keyboardhandler import local_keymap, set_local_keymap, \\\n    LOCAL_KEYMAP_SETTER\nfrom . import windows, variables\n\n\ndef _update_stylesheets(var):\n    for w in windows():\n        for view in w.webviews():\n            view.setStyleSheet(var.value)\n\n\nwebview_stylesheet = variables.define_variable(\n    \"webview-stylesheet\",\n    \"stylesheet associated to the webviews.\",\n    \"\"\"\\\n[single=false][current=true] {\n    border-top: 1px solid black;\n    padding: 1px;\n    background-color: red;\n}\n[single=false][current=false] {\n    border-top: 1px solid white;\n    padding: 1px;\n}\\\n\"\"\",\n    callbacks=(_update_stylesheets,),\n    type=variables.String(),\n)\n\n\nclass WebView(QFrame):\n    def __init__(self, window):\n        QFrame.__init__(self)\n        self.main_window = window\n        layout = QVBoxLayout()\n        layout.setContentsMargins(0, 0, 0, 0)\n        layout.setSpacing(0)\n        self.setLayout(layout)\n        self.setStyleSheet(webview_stylesheet.value)\n\n    def _attach_view(self, view):\n        if self.layout().count() == 0:\n            self.layout().addWidget(view)\n\n    def _detach_view(self):\n        if self.layout().count() > 0:\n            it = self.layout().takeAt(0)\n            it.widget().setParent(None)\n\n    def setBuffer(self, buffer, update_last_use=True):\n        otherviews = [w for w in self.main_window.webviews()\n                      if w != self]\n        for v in otherviews:\n            # this prevent multi views from being scrolled to the\n            # right; to reproduce, C-x 3, C-x o, then C-x f and open\n            # something\n            iv = v.internal_view()\n            if iv:\n                iv.setFocus()\n\n        self._detach_view()\n\n        if buffer is None:\n            self.main_window.update_title()\n            return\n\n        if buffer._internal_view is None:\n            buffer._internal_view = InternalWebView(self)\n            buffer._internal_view.setPage(buffer)\n        else:\n            buffer._internal_view._view = self\n\n        self._attach_view(buffer._internal_view)\n\n        url = buffer.delayed_loading_url()\n        if url:\n            buffer.load(url.url)\n        self.main_window.update_title()\n        LOCAL_KEYMAP_SETTER.buffer_opened_in_view(buffer)\n        # mark the buffer to be the most recently opened\n        if update_last_use:\n            buffer.last_use = time.time()\n\n        if self.main_window.current_webview() == self:\n            # keyboard focus is lost without that.\n            buffer._internal_view.setFocus()\n            self.show_focused(True)\n\n    def buffer(self):\n        if self.internal_view():\n            return self.internal_view().page()\n\n    def show_focused(self, active):\n        self.setProperty(\"current\", active)\n        self.setProperty(\"single\",\n                         len(self.main_window.webviews()) == 1)\n        # force the style to be taken into account\n        self.setStyle(self.style())\n\n    def internal_view(self):\n        if self.layout().count() > 0:\n            return self.layout().itemAt(0).widget()\n\n\nclass InternalWebView(QWebEngineView):\n    \"\"\"Do not instantiate that class directly\"\"\"\n    def __init__(self, view):\n        QWebEngineView.__init__(self)\n        self._view = view\n        self._fullscreen_state = None\n\n    def view(self):\n        return self._view\n\n    def event(self, evt):\n        if evt.type() == QEvent.Type.ChildAdded:\n            obj = evt.child()\n            if isinstance(obj, QWidget):\n                obj.installEventFilter(self)\n        return QWebEngineView.event(self, evt)\n\n    def eventFilter(self, obj, evt):\n        view = self.view()\n\n        t = evt.type()\n        if t == QEvent.Type.MouseButtonPress:\n            if view != view.main_window.current_webview():\n                view.main_window.set_current_webview(view)\n        elif t == QEvent.Type.FocusIn:\n            if self.isEnabled():  # disabled when there is a full-screen window\n                LOCAL_KEYMAP_SETTER.view_focus_changed(view, True)\n        elif t == QEvent.Type.FocusOut:\n            if self.isEnabled():  # disabled when there is a full-screen window\n                LOCAL_KEYMAP_SETTER.view_focus_changed(view, False)\n        return False\n\n    def request_fullscreen(self, toggle_on):\n        if toggle_on:\n            if self._fullscreen_state:\n                return\n            self._fullscreen_state = FullScreenState(self)\n            return True\n        else:\n            if not self._fullscreen_state:\n                return\n            self._fullscreen_state.restore()\n            self._fullscreen_state = None\n            return True\n\n\nclass FullScreenState(object):\n    def __init__(self, internal_view):\n        self.view = internal_view.view()\n        self.internal_view = internal_view\n        self.keymap = local_keymap()\n\n        set_local_keymap(self.view.buffer().mode.fullscreen_keymap())\n        self.view._detach_view()\n        # show fullscreen on the right place.\n        screen = self.view.screen()\n        self.internal_view.showFullScreen()\n        self.internal_view.setGeometry(screen.geometry())\n        self.view.main_window.fullscreen_window = self\n\n    def restore(self):\n        set_local_keymap(self.keymap)\n        self.internal_view.showNormal()\n        self.view._attach_view(self.internal_view)\n        self.view.main_window.fullscreen_window = None\n"
  },
  {
    "path": "webmacs/window.py",
    "content": "# This file is part of webmacs.\n#\n# webmacs is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# webmacs is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with webmacs.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom PyQt6.QtWidgets import QWidget, QVBoxLayout, QToolBar\nfrom PyQt6.QtCore import Qt, QRect\n\nfrom .minibuffer import Minibuffer\nfrom .egrid import ViewGridLayout\nfrom . import WINDOWS_HANDLER\nfrom . import hooks, variables\n\n\nwindow_toolbar_on_startup = variables.define_variable(\n    \"window-toolbar-on-startup\",\n    \"If set to True, the main window(s) will have the navigation toolbar\"\n    \" visible on startup.\",\n    False,\n    type=variables.Bool(),\n)\n\n\ndef remove_layout_spaces(layout):\n    layout.setContentsMargins(0, 0, 0, 0)\n    layout.setSpacing(0)\n\n\nclass Window(QWidget):\n    def __init__(self):\n        QWidget.__init__(self)\n        self._layout = QVBoxLayout()\n        remove_layout_spaces(self._layout)\n        self.setLayout(self._layout)\n\n        self._central_widget = QWidget()\n        self._layout.addWidget(self._central_widget)\n        self._webviews_layout = ViewGridLayout(self)\n        remove_layout_spaces(self._webviews_layout)\n        self._central_widget.setLayout(self._webviews_layout)\n\n        self._minibuffer = Minibuffer(self)\n        self._layout.addWidget(self._minibuffer)\n\n        self.fullscreen_window = None\n        self.quit_if_last_closed = True\n\n        WINDOWS_HANDLER.register_window(self)\n\n        self._toolbar = None\n        if window_toolbar_on_startup.value:\n            self.toggle_toolbar()\n\n        # remove the toolbar update callback if it was set\n        self.destroyed.connect(lambda:\n                               hooks.webbuffer_current_changed\n                               .remove_if_exists(self._update_toolbar))\n\n    def _update_toolbar(self, buffer):\n        if buffer.view().main_window != self:\n            return\n\n        self._toolbar.clear()\n        self._toolbar.addAction(buffer.action(buffer.WebAction.Back))\n        self._toolbar.addAction(buffer.action(buffer.WebAction.Forward))\n        self._toolbar.addSeparator()\n        self._toolbar.addAction(buffer.action(buffer.WebAction.Stop))\n        self._toolbar.addAction(buffer.action(buffer.WebAction.Reload))\n\n    def toggle_toolbar(self):\n        if self._toolbar is None:\n            hooks.webbuffer_current_changed.add(self._update_toolbar)\n            self._toolbar = QToolBar()\n            self._layout.insertWidget(0, self._toolbar)\n            current_view = self.current_webview()\n            if current_view and current_view.buffer():\n                self._update_toolbar(current_view.buffer())\n        else:\n            hooks.webbuffer_current_changed.remove(self._update_toolbar)\n            self._layout.removeWidget(self._toolbar)\n            self._toolbar.deleteLater()\n            self._toolbar = None\n\n    def set_current_webview(self, webview):\n        self.current_webview().show_focused(False)\n        if len(self.webviews()) > 1:\n            webview.show_focused(True)\n        self._webviews_layout.set_current_view(webview)\n\n    def current_webview(self):\n        return self._webviews_layout.current_view()\n\n    def webviews(self):\n        return self._webviews_layout.views()\n\n    def create_webview_on_right(self):\n        return self._webviews_layout.split_view(ViewGridLayout.VERTICAL)\n\n    def create_webview_on_bottom(self):\n        return self._webviews_layout.split_view(ViewGridLayout.HORIZONTAL)\n\n    def _delete_webview(self, webview):\n        webview.setBuffer(None)\n        self._webviews_layout.removeWidget(webview)\n        webview.deleteLater()\n\n    def minibuffer(self):\n        return self._minibuffer\n\n    def other_view(self):\n        \"\"\"switch to the next view\"\"\"\n        views = self.webviews()\n        index = views.index(self.current_webview())\n        index = index + 1\n        if index >= len(views):\n            index = 0\n        self.set_current_webview(views[index])\n\n    def close_view(self, view):\n        \"\"\"close the given view\"\"\"\n        views = self.webviews()\n        if len(views) == 1:\n            return  # can't delete a single view\n\n        if view == self.current_webview():\n            self.other_view()\n\n        self._delete_webview(view)\n\n        # do not show the window focused if there is one left\n        if len(self.webviews()) == 1:\n            self.current_webview().show_focused(True)\n\n    def close_other_views(self):\n        \"\"\"close all views but the current one\"\"\"\n        view = self.current_webview()\n        # to remove more than one item correctly, the iteration must\n        # be done on a shallow copy of the list\n        for other in list(self.webviews()):\n            if view != other:\n                self._delete_webview(other)\n\n        # do not show the window focused if there is one left\n        if len(self.webviews()) == 1:\n            self.current_webview().show_focused(False)\n\n    def update_title(self, title=None):\n        if title is None:\n            mw = self.current_webview()\n            if mw and mw.buffer():\n                title = mw.buffer().title()\n        if title:\n            self.setWindowTitle(\"{} - Webmacs\".format(title))\n        else:\n            self.setWindowTitle(\"Webmacs\")\n\n    def dump_state(self):\n        return {\n            \"geometry\": self.geometry().getRect(),\n            \"window-state\": self.windowState().value,\n            \"view-layout\": self._webviews_layout.dump_state(),\n        }\n\n    def restore_state(self, data, version):\n        self.setGeometry(QRect(*data[\"geometry\"]))\n        for e in Qt.WindowState:\n            if e.value == data[\"window-state\"]:\n                self.setWindowState(e)\n                break\n        self._webviews_layout.restore_state(data[\"view-layout\"])\n"
  }
]