zory hace 3 semanas
padre
commit
fcd3e205c4
Se han modificado 100 ficheros con 7377 adiciones y 0 borrados
  1. 8 0
      .editorconfig
  2. 21 0
      .eslintrc.js
  3. 13 0
      .gitignore
  4. 6 0
      .prettierrc.js
  5. 674 0
      LICENSE
  6. 21 0
      PATENTS
  7. 24 0
      cla.md
  8. 3 0
      dev-app-update.yml
  9. 51 0
      electron-builder.json
  10. 109 0
      package.json
  11. 90 0
      scripts/ci-build.js
  12. 14 0
      scripts/utils.js
  13. 11 0
      src/common/renderer-config.ts
  14. 9 0
      src/common/rpc/extensions.ts
  15. 14 0
      src/common/rpc/network.ts
  16. 4 0
      src/common/webui.ts
  17. 31 0
      src/constants/design.ts
  18. 23 0
      src/constants/files.ts
  19. 3 0
      src/constants/index.ts
  20. 10 0
      src/constants/settings.ts
  21. 8 0
      src/constants/tabs.ts
  22. 3 0
      src/constants/web-contents.ts
  23. 3 0
      src/index.d.ts
  24. 13 0
      src/interfaces/bookmark.ts
  25. 11 0
      src/interfaces/bounds.ts
  26. 8 0
      src/interfaces/download-item.ts
  27. 14 0
      src/interfaces/extensions.ts
  28. 5 0
      src/interfaces/favicon.ts
  29. 24 0
      src/interfaces/form-fill.ts
  30. 12 0
      src/interfaces/history-item.ts
  31. 7 0
      src/interfaces/history-section.ts
  32. 13 0
      src/interfaces/index.ts
  33. 13 0
      src/interfaces/news-item.ts
  34. 33 0
      src/interfaces/settings.ts
  35. 11 0
      src/interfaces/startup-tab.ts
  36. 19 0
      src/interfaces/storage.ts
  37. 10 0
      src/interfaces/suggestion.ts
  38. 13 0
      src/interfaces/tabs.ts
  39. 50 0
      src/interfaces/theme.ts
  40. 4 0
      src/interfaces/urls.ts
  41. 96 0
      src/interfaces/weather.ts
  42. 117 0
      src/main/application.ts
  43. 49 0
      src/main/dialogs/add-bookmark.ts
  44. 49 0
      src/main/dialogs/auth.ts
  45. 26 0
      src/main/dialogs/credentials.ts
  46. 193 0
      src/main/dialogs/dialog.ts
  47. 46 0
      src/main/dialogs/downloads.ts
  48. 51 0
      src/main/dialogs/extension-popup.ts
  49. 38 0
      src/main/dialogs/find.ts
  50. 45 0
      src/main/dialogs/form-fill.ts
  51. 24 0
      src/main/dialogs/menu.ts
  52. 55 0
      src/main/dialogs/permissions.ts
  53. 51 0
      src/main/dialogs/preview.ts
  54. 81 0
      src/main/dialogs/search.ts
  55. 24 0
      src/main/dialogs/tabgroup.ts
  56. 28 0
      src/main/dialogs/zoom.ts
  57. 17 0
      src/main/extension-service-handler.ts
  58. 69 0
      src/main/index.ts
  59. 131 0
      src/main/menus/bookmarks.ts
  60. 43 0
      src/main/menus/common-actions.ts
  61. 380 0
      src/main/menus/main.ts
  62. 237 0
      src/main/menus/view.ts
  63. 50 0
      src/main/models/protocol.ts
  64. 209 0
      src/main/models/settings.ts
  65. 20 0
      src/main/network/network-service-handler.ts
  66. 42 0
      src/main/network/request.ts
  67. 137 0
      src/main/services/adblock.ts
  68. 32 0
      src/main/services/auto-updater.ts
  69. 331 0
      src/main/services/dialogs-service.ts
  70. 3 0
      src/main/services/index.ts
  71. 275 0
      src/main/services/messaging.ts
  72. 17 0
      src/main/services/proxy.ts
  73. 508 0
      src/main/services/storage.ts
  74. 379 0
      src/main/sessions-service.ts
  75. 48 0
      src/main/user-agent.ts
  76. 48 0
      src/main/utils/form-fill.ts
  77. 1 0
      src/main/utils/index.ts
  78. 265 0
      src/main/view-manager.ts
  79. 451 0
      src/main/view.ts
  80. 73 0
      src/main/windows-service.ts
  81. 231 0
      src/main/windows/app.ts
  82. 1 0
      src/main/windows/index.ts
  83. 53 0
      src/models/database.ts
  84. 118 0
      src/models/dialog-store.ts
  85. 85 0
      src/preloads/chrome-webstore.ts
  86. 5 0
      src/preloads/constants/form-fill.ts
  87. 1 0
      src/preloads/constants/index.ts
  88. 1 0
      src/preloads/extensions-preload.ts
  89. 50 0
      src/preloads/models/auto-complete.ts
  90. 68 0
      src/preloads/models/database.ts
  91. 164 0
      src/preloads/models/form.ts
  92. 1 0
      src/preloads/models/index.ts
  93. 57 0
      src/preloads/models/ipc-event.ts
  94. 28 0
      src/preloads/popup-preload.ts
  95. 34 0
      src/preloads/utils/autofill.ts
  96. 10 0
      src/preloads/utils/dom.ts
  97. 1 0
      src/preloads/utils/index.ts
  98. 228 0
      src/preloads/view-preload.ts
  99. 32 0
      src/renderer/components/Button/index.tsx
  100. 57 0
      src/renderer/components/Button/styles.ts

+ 8 - 0
.editorconfig

@@ -0,0 +1,8 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+charset = utf-8
+trim_trailing_whitespace = false
+insert_final_newline = false

+ 21 - 0
.eslintrc.js

@@ -0,0 +1,21 @@
+module.exports = {
+  parser: '@typescript-eslint/parser',
+  extends: [
+    'plugin:react/recommended',
+    'plugin:@typescript-eslint/recommended',
+    'prettier/@typescript-eslint',
+    'plugin:prettier/recommended',
+    'prettier/react',
+  ],
+  parserOptions: {
+    ecmaVersion: 2018,
+    sourceType: 'module',
+  },
+  rules: {
+    '@typescript-eslint/explicit-function-return-type': 'off',
+    '@typescript-eslint/interface-name-prefix': 'off',
+    '@typescript-eslint/no-var-requires': 'off',
+    '@typescript-eslint/no-namespace': 'off',
+    '@typescript-eslint/explicit-module-boundary-types': 'off',
+  },
+};

+ 13 - 0
.gitignore

@@ -0,0 +1,13 @@
+node_modules
+*.log
+*.log*
+build
+dist
+.DS_Store
+.fusebox
+filters
+package-lock.json
+temp-electron-builder.json
+temp-package.json
+chunks-entries-map.json
+.idea

+ 6 - 0
.prettierrc.js

@@ -0,0 +1,6 @@
+module.exports = {
+  semi: true,
+  trailingComma: 'all',
+  singleQuote: true,
+  tabWidth: 2,
+};

+ 674 - 0
LICENSE

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    Wexond
+    Copyright (C) 2019  Eryk Rakowski (sentialx@gmail.com)
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    Wexond  Copyright (C) 2019  Eryk Rakowski (sentialx@gmail.com)
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 21 - 0
PATENTS

@@ -0,0 +1,21 @@
+Additional Grant of Patent
+
+A perpetual, non-exclusive, irrevocable license, under any necessary claims, to
+make, have made, use, import and otherwise transfer the Wexond software, is
+hereby granted to each recipient ("you") of the Wexond software distributed by
+Eryk Rakowski.
+
+The license granted hereunder will terminate, automatically and without notice,
+if you (or any of your subsidiaries, corporate affiliates or agents) initiate
+directly or indirectly, or take a direct financial interest in.
+
+(1) This software may not be sold to a third party nor redistributed or
+    otherwise conveyed in the original form.
+
+(2) No recipient or contributor is allowed to ask and receive any donations for
+    his copy of Wexond software.
+
+(3) A written permission from the main maintainer of Wexond software (Eryk
+    Rakowski) is necessary if a recipient or contributor decides to sell or
+    publish the software on official stores or intents to realize any economic
+    gains.

+ 24 - 0
cla.md

@@ -0,0 +1,24 @@
+Individual Contributor License Agreement
+
+You accept and agree to the following terms and conditions for Your past, present and future Contributions submitted to Eryk Rakowski (the “General Developer”) for inclusion in the following software code project Wexond (the “Code Project”). In return, the General Developer shall reference you as a contributor to the open source code version of the Code Project that is currently distributed under the GNU General Public License (GPLv3).
+
+Except for the license granted herein to the General Developer, You reserve all right, title, and interest in and to Your Contributions.
+
+1.	Definitions.
+
+"You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with the General Developer. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"Contribution" shall mean any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the General Developer for inclusion in, or documentation of, the Code Project. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the General Developer or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the General Developer for the purpose of discussing and improving the Code Project, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
+
+2.	Grant of License. Subject to the terms and conditions of this Agreement, You hereby grant to the General Developer a perpetual, transferable, worldwide, non-exclusive, no-charge, royalty-free, irrevocable license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works under any open source software license (as defined by the Open Source Initiative (OSI)) that General Developer chooses from time to time and under proprietary commercial licenses, pursuant to which the General Developer may charge license fees and receive other compensation, the terms of which proprietary commercial licenses will be determined by the General Developer in its absolute discretion. The license granted in this Section includes a license to all copyright, patent, trademark, trade secret and any other intellectual property right that You may possess in the Contribution. For clarity, this license grant includes any Contribution that you have made in the past to the General Developer for the Code Project, unless at the time you execute this license agreement you expressly and in writing exclude any such prior Contributions.
+
+3.	You warrant and represent that each of Your Contributions is Your original creation.  You warrant and represent that you are legally entitled to grant the above license. If your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer or that your employer has waived such rights for your Contributions to the General Developer.
+
+4.	You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, and except for the warranties set forth in Section ‎3, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+5.	Should You wish to submit work that is not Your original creation, You may submit it to the General Developer separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]".
+
+6.	You agree to notify the General Developer of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect.
+
+
+Please sign: __________________________________ Date: ________________

+ 3 - 0
dev-app-update.yml

@@ -0,0 +1,3 @@
+owner: wexond
+repo: desktop
+provider: github

+ 51 - 0
electron-builder.json

@@ -0,0 +1,51 @@
+{
+  "appId": "org.bluevchat.browser",
+  "productName": "BluevChat",
+  "nsis": {
+    "include": "static/installer.nsh"
+  },
+  "generateUpdatesFilesForAllChannels": true,
+  "asar": true,
+  "directories": {
+    "output": "dist",
+    "buildResources": "static/icons"
+  },
+  "files": ["build/**/*", "package.json", "static/**/*"],
+  "publish": "github",
+  "linux": {
+    "category": "Network",
+    "target": [
+      {
+        "target": "AppImage",
+        "arch": ["x64"]
+      },
+      {
+        "target": "deb",
+        "arch": ["x64"]
+      }
+    ]
+  },
+  "win": {
+    "target": [
+      {
+        "target": "nsis-web",
+        "arch": ["x64", "ia32"]
+      },
+      {
+        "target": "zip",
+        "arch": ["x64", "ia32"]
+      }
+    ]
+  },
+  "mac": {
+    "category": "public.app-category.navigation"
+  },
+  "fileAssociations": [
+    {
+      "name": "Document",
+      "description": "BluevChat",
+      "role": "Viewer",
+      "ext": "html"
+    }
+  ]
+}

+ 109 - 0
package.json

@@ -0,0 +1,109 @@
+{
+  "name": "BluevChat",
+  "version": "1.0.1",
+  "sideEffects": false,
+  "description": "蓝微旗下适用巨量引擎VPN的浏览器",
+  "keywords": [
+    "web-browser",
+    "material",
+    "electron",
+    "react",
+    "mobx",
+    "styled-components"
+  ],
+  "homepage": "https://www.bluevchat.com",
+  "main": "build/main.bundle.js",
+  "author": "Zory Lee<lee@ooow.vip>",
+  "repository": {
+    "type": "git",
+    "url": "git+https://gits.yunenv.cn/bluevchat/browser.git"
+  },
+  "bugs": {
+    "url": "https://gits.yunenv.cn/bluevchat/browser/issues"
+  },
+  "scripts": {
+    "dev-renderer": "cross-env DEV=1 webpack serve --config webpack.config.renderer.js",
+    "dev-webpack": "cross-env DEV=1 webpack",
+    "build-renderer": "webpack --config webpack.config.renderer.js",
+    "dev": "cross-env START=1 npm run watch",
+    "build": "rimraf build && concurrently \"npm run build-renderer\" \"webpack\"",
+    "ci-build": "node scripts/ci-build.js",
+    "start": "electron . > output.log 2>&1",
+    "watch": "concurrently \"npm run dev-renderer\" \"npm run dev-webpack\"",
+    "win": "npm run build && electron-builder -w",
+    "darwin": "npm run build && electron-builder -m",
+    "linux": "npm run build && electron-builder -l",
+    "lint": "eslint \"src/**/*.ts*\" \"src/**/*.tsx*\"",
+    "lint-fix": "npm run lint -- --fix",
+    "rebuild": "electron-builder install-app-deps"
+  },
+  "devDependencies": {
+    "@babel/core": "^7.12.16",
+    "@cliqz/adblocker-electron": "1.20.1",
+    "@pmmmwh/react-refresh-webpack-plugin": "^0.4.3",
+    "@types/animejs": "^3.1.2",
+    "@types/chrome": "0.0.130",
+    "@types/crypto-js": "^4.0.1",
+    "@types/jszip": "^3.4.1",
+    "@types/nedb": "1.8.11",
+    "@types/node": "14.14.28",
+    "@types/node-fetch": "^2.5.8",
+    "@types/react": "17.0.2",
+    "@types/react-dom": "17.0.1",
+    "@types/rimraf": "^3.0.0",
+    "@types/styled-components": "5.1.7",
+    "@typescript-eslint/eslint-plugin": "^4.15.1",
+    "@typescript-eslint/parser": "^4.15.1",
+    "@wexond/rpc-core": "^1.0.3",
+    "@wexond/rpc-electron": "^1.0.3",
+    "animejs": "^3.2.1",
+    "awesome-node-loader": "^1.1.1",
+    "babel-loader": "^8.2.2",
+    "concurrently": "^5.3.0",
+    "copy-webpack-plugin": "^7.0.0",
+    "cross-env": "7.0.3",
+    "electron": "11.2.3",
+    "electron-builder": "22.9.1",
+    "electron-extensions": "^7.0.0-beta.3",
+    "electron-updater": "4.3.5",
+    "eslint": "^7.20.0",
+    "eslint-config-prettier": "^7.2.0",
+    "eslint-plugin-prettier": "^3.3.1",
+    "eslint-plugin-react": "^7.22.0",
+    "file-loader": "^6.2.0",
+    "file-type": "16.2.0",
+    "fork-ts-checker-webpack-plugin": "^6.1.0",
+    "html-webpack-plugin": "^5.1.0",
+    "icojs": "^0.16.0",
+    "jszip": "^3.6.0",
+    "mobx": "6.1.7",
+    "mobx-react-lite": "3.2.0",
+    "nedb": "1.8.0",
+    "node-bookmarks-parser": "^2.0.0",
+    "node-fetch": "^2.6.1",
+    "prettier": "2.2.1",
+    "pretty-bytes": "5.5.0",
+    "react": "17.0.1",
+    "react-dom": "17.0.1",
+    "react-refresh": "^0.9.0",
+    "react-windows-controls": "1.1.1",
+    "rimraf": "^3.0.2",
+    "source-map-support": "^0.5.19",
+    "styled-components": "^5.2.1",
+    "terser": "^5.6.0",
+    "terser-webpack-plugin": "^5.1.1",
+    "ts-loader": "^8.0.17",
+    "tsconfig-paths-webpack-plugin": "^3.3.0",
+    "typescript": "^4.1.5",
+    "typescript-plugin-styled-components": "^1.4.4",
+    "webpack": "5.22.0",
+    "webpack-bundle-analyzer": "^4.4.0",
+    "webpack-cli": "4.5.0",
+    "webpack-dev-server": "^3.11.2",
+    "webpack-merge": "^5.7.3"
+  },
+  "dependencies": {
+    "global-agent": "^3.0.0",
+    "global-tunnel-ng": "^2.7.1"
+  }
+}

+ 90 - 0
scripts/ci-build.js

@@ -0,0 +1,90 @@
+const package = require('../package.json');
+const electronBuilder = require('../electron-builder.json');
+const { promises } = require('fs');
+const { resolve } = require('path');
+const { run } = require('./utils');
+
+const isNightly = package.version.indexOf('nightly') !== -1;
+
+const getPlatform = () => {
+  if (process.platform === 'win32') return 'windows';
+  else if (process.platform === 'darwin') return 'mac';
+  return process.platform;
+};
+
+const getEnv = (name) => process.env[name.toUpperCase()] || null;
+
+const setEnv = (name, value) => {
+  if (value) {
+    process.env[name.toUpperCase()] = value.toString();
+  }
+};
+
+const getInput = (name) => {
+  return getEnv(`INPUT_${name}`);
+};
+
+(async () => {
+  try {
+    if (isNightly) {
+      await promises.copyFile(
+        resolve(__dirname, '../package.json'),
+        resolve(__dirname, '../temp-package.json'),
+      );
+      await promises.copyFile(
+        resolve(__dirname, '../electron-builder.json'),
+        resolve(__dirname, '../temp-electron-builder.json'),
+      );
+      const newPkg = {
+        ...package,
+        name: 'wexond-nightly',
+        repository: {
+          type: 'git',
+          url: 'git+https://github.com/wexond/desktop-nightly.git',
+        },
+      };
+      await promises.writeFile(
+        resolve(__dirname, '../package.json'),
+        JSON.stringify(newPkg),
+      );
+
+      const newEBConfig = {
+        ...electronBuilder,
+        appId: 'org.wexond.wexond-nightly',
+        productName: 'Wexond Nightly',
+        directories: {
+          output: 'dist',
+          buildResources: 'static/nightly-icons',
+        },
+      };
+
+      await promises.writeFile(
+        resolve(__dirname, '../electron-builder.json'),
+        JSON.stringify(newEBConfig),
+      );
+    }
+
+    const release =
+      (getEnv('release') === 'true' || getEnv('release') === true) &&
+      getEnv('GH_TOKEN');
+    const platform = getPlatform();
+
+    if (platform === 'mac') {
+      setEnv('CSC_LINK', getEnv('mac_certs'));
+      setEnv('CSC_KEY_PASSWORD', getEnv('mac_certs_password'));
+    } else if (platform === 'windows') {
+      setEnv('CSC_LINK', getEnv('windows_certs'));
+      setEnv('CSC_KEY_PASSWORD', getEnv('windows_certs_password'));
+    }
+
+    run('yarn run build');
+    run(
+      `npx --no-install electron-builder --${platform} ${
+        release ? '-p always' : ''
+      }`,
+    );
+  } catch (e) {
+    console.error(e);
+    process.exit(1);
+  }
+})();

+ 14 - 0
scripts/utils.js

@@ -0,0 +1,14 @@
+const { execSync } = require('child_process');
+const { resolve } = require('path');
+
+const run = cmd => {
+  execSync(cmd, {
+    encoding: 'utf8',
+    cwd: resolve(__dirname, '..'),
+    stdio: 'inherit',
+  });
+};
+
+module.exports = {
+  run,
+};

+ 11 - 0
src/common/renderer-config.ts

@@ -0,0 +1,11 @@
+import { configure } from 'mobx';
+import { setIpcRenderer } from '@wexond/rpc-electron';
+import { ipcRenderer } from 'electron';
+
+export const configureUI = () => {
+  configure({ enforceActions: 'never' });
+};
+
+export const configureRenderer = () => {
+  setIpcRenderer(ipcRenderer);
+};

+ 9 - 0
src/common/rpc/extensions.ts

@@ -0,0 +1,9 @@
+import { RendererToMainChannel } from '@wexond/rpc-electron';
+
+export interface ExtensionMainService {
+  uninstall(id: string): void;
+}
+
+export const extensionMainChannel = new RendererToMainChannel<ExtensionMainService>(
+  'ExtensionMainService',
+);

+ 14 - 0
src/common/rpc/network.ts

@@ -0,0 +1,14 @@
+import { RendererToMainChannel } from '@wexond/rpc-electron';
+
+export interface ResponseDetails {
+  statusCode: number;
+  data: string;
+}
+
+export interface NetworkService {
+  request(url: string): Promise<ResponseDetails>;
+}
+
+export const networkMainChannel = new RendererToMainChannel<NetworkService>(
+  'NetworkService',
+);

+ 4 - 0
src/common/webui.ts

@@ -0,0 +1,4 @@
+import { WEBUI_BASE_URL, WEBUI_URL_SUFFIX } from '~/constants/files';
+
+export const getWebUIURL = (hostname: string) =>
+  `${WEBUI_BASE_URL}${hostname}${WEBUI_URL_SUFFIX}`;

+ 31 - 0
src/constants/design.ts

@@ -0,0 +1,31 @@
+export const DEFAULT_TAB_MARGIN_TOP = 4;
+export const COMPACT_TAB_MARGIN_TOP = 3;
+
+export const DEFAULT_TAB_HEIGHT = 32;
+export const COMPACT_TAB_HEIGHT = 32;
+
+// Toolbar
+export const TOOLBAR_HEIGHT = 42;
+
+export const TOOLBAR_BUTTON_WIDTH = 36;
+export const TOOLBAR_BUTTON_HEIGHT = 32;
+
+export const ADD_TAB_BUTTON_WIDTH = 28;
+export const ADD_TAB_BUTTON_HEIGHT = 28;
+
+export const DEFAULT_TITLEBAR_HEIGHT =
+  DEFAULT_TAB_MARGIN_TOP + DEFAULT_TAB_HEIGHT;
+export const COMPACT_TITLEBAR_HEIGHT =
+  2 * COMPACT_TAB_MARGIN_TOP + COMPACT_TAB_HEIGHT;
+
+export const VIEW_Y_OFFSET = TOOLBAR_HEIGHT + DEFAULT_TITLEBAR_HEIGHT;
+
+// Widths
+export const WINDOWS_BUTTON_WIDTH = 45;
+export const MENU_WIDTH = 330;
+
+// Dialogs
+export const DIALOG_MIN_HEIGHT = 130;
+export const DIALOG_MARGIN = 16;
+export const DIALOG_TOP = 34;
+export const DIALOG_MARGIN_TOP = 3;

+ 23 - 0
src/constants/files.ts

@@ -0,0 +1,23 @@
+import { DEFAULT_SETTINGS } from './settings';
+
+export const DIRECTORIES = ['adblock', 'extensions', 'storage'];
+
+export const WEBUI_PROTOCOL = 'bluevchat';
+
+export const ERROR_PROTOCOL = 'wexond-error';
+
+export const NETWORK_ERROR_HOST = 'network-error';
+
+export const WEBUI_BASE_URL =
+  process.env.NODE_ENV === 'development'
+    ? 'http://localhost:4444/'
+    : `${WEBUI_PROTOCOL}://`;
+
+export const WEBUI_URL_SUFFIX = WEBUI_BASE_URL.startsWith('http')
+  ? '.html'
+  : '';
+
+export const FILES = {
+  'settings.json': DEFAULT_SETTINGS,
+  'window-data.json': {},
+};

+ 3 - 0
src/constants/index.ts

@@ -0,0 +1,3 @@
+export * from './settings';
+
+export const EXTENSIONS_PROTOCOL = 'chrome-extension';

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 10 - 0
src/constants/settings.ts


+ 8 - 0
src/constants/tabs.ts

@@ -0,0 +1,8 @@
+import { getWebUIURL } from '~/common/webui';
+
+export const NEWTAB_URL = getWebUIURL('newtab');
+
+export const defaultTabOptions: chrome.tabs.CreateProperties = {
+  url: NEWTAB_URL,
+  active: true,
+};

+ 3 - 0
src/constants/web-contents.ts

@@ -0,0 +1,3 @@
+export const ZOOM_FACTOR_INCREMENT = 0.2;
+export const ZOOM_FACTOR_MAX = 5;
+export const ZOOM_FACTOR_MIN = 0.2;

+ 3 - 0
src/index.d.ts

@@ -0,0 +1,3 @@
+declare module '*.svg';
+declare module '*.png';
+declare module '*.woff2';

+ 13 - 0
src/interfaces/bookmark.ts

@@ -0,0 +1,13 @@
+export interface IBookmark {
+  _id?: string;
+  title?: string;
+  url?: string;
+  favicon?: string;
+  hovered?: boolean;
+  isFolder?: boolean;
+  parent?: string;
+  order?: number;
+  expanded?: boolean;
+  static?: 'mobile' | 'main' | 'other' | 'pinned';
+  children?: string[];
+}

+ 11 - 0
src/interfaces/bounds.ts

@@ -0,0 +1,11 @@
+export interface IRectangle {
+  x?: number;
+  y?: number;
+  height?: number;
+  width?: number;
+}
+
+export interface IPoint {
+  x?: number;
+  y?: number;
+}

+ 8 - 0
src/interfaces/download-item.ts

@@ -0,0 +1,8 @@
+export interface IDownloadItem {
+  fileName?: string;
+  receivedBytes?: number;
+  totalBytes?: number;
+  savePath?: string;
+  id?: string;
+  completed?: boolean;
+}

+ 14 - 0
src/interfaces/extensions.ts

@@ -0,0 +1,14 @@
+export type BrowserActionChangeType =
+  | 'setPopup'
+  | 'setBadgeText'
+  | 'setTitle'
+  | 'setIcon'
+  | 'setBadgeBackgroundColor';
+
+export const BROWSER_ACTION_METHODS: BrowserActionChangeType[] = [
+  'setPopup',
+  'setBadgeText',
+  'setTitle',
+  'setIcon',
+  'setBadgeBackgroundColor',
+];

+ 5 - 0
src/interfaces/favicon.ts

@@ -0,0 +1,5 @@
+export interface IFavicon {
+  url?: string;
+  data?: string;
+  _id?: string;
+}

+ 24 - 0
src/interfaces/form-fill.ts

@@ -0,0 +1,24 @@
+export interface IFormFillData {
+  _id?: string;
+  type?: 'password' | 'address';
+  url?: string;
+  favicon?: string;
+  fields?: {
+    username?: string;
+    passLength?: number;
+    password?: string;
+    name?: string;
+    address?: string;
+    postCode?: string;
+    city?: string;
+    phone?: string;
+    email?: string;
+    country?: string;
+  };
+}
+
+export interface IFormFillMenuItem {
+  _id?: string;
+  text?: string;
+  subtext?: string;
+}

+ 12 - 0
src/interfaces/history-item.ts

@@ -0,0 +1,12 @@
+export interface IHistoryItem {
+  _id?: string;
+  title?: string;
+  url?: string;
+  date?: number;
+  favicon?: string;
+  hovered?: boolean;
+}
+
+export interface IVisitedItem extends IHistoryItem {
+  times: number;
+}

+ 7 - 0
src/interfaces/history-section.ts

@@ -0,0 +1,7 @@
+import { IHistoryItem } from './history-item';
+
+export interface IHistorySection {
+  label?: string;
+  items?: IHistoryItem[];
+  date?: Date;
+}

+ 13 - 0
src/interfaces/index.ts

@@ -0,0 +1,13 @@
+export * from './bookmark';
+export * from './download-item';
+export * from './favicon';
+export * from './history-item';
+export * from './history-section';
+export * from './settings';
+export * from './suggestion';
+export * from './theme';
+export * from './weather';
+export * from './form-fill';
+export * from './storage';
+export * from './bounds';
+export * from './extensions';

+ 13 - 0
src/interfaces/news-item.ts

@@ -0,0 +1,13 @@
+export interface INewsItem {
+  source: {
+    id: string;
+    name: string;
+  };
+  author: string;
+  title: string;
+  description: string;
+  url: string;
+  urlToImage: string;
+  publishedAt: string;
+  content: string;
+}

+ 33 - 0
src/interfaces/settings.ts

@@ -0,0 +1,33 @@
+export interface ISearchEngine {
+  name?: string;
+  url?: string;
+  keywordsUrl?: string;
+  keyword?: string;
+  icon?: string;
+}
+
+export interface IStartupBehavior {
+  type: 'continue' | 'urls' | 'empty';
+}
+
+export type TopBarVariant = 'default' | 'compact';
+
+export interface ISettings {
+  theme: string;
+  themeAuto: boolean;
+  shield: boolean;
+  multrin: boolean;
+  animations: boolean;
+  bookmarksBar: boolean;
+  suggestions: boolean;
+  searchEngine: number;
+  searchEngines: ISearchEngine[];
+  startupBehavior: IStartupBehavior;
+  warnOnQuit: boolean;
+  version: number;
+  darkContents: boolean;
+  downloadsDialog: boolean;
+  downloadsPath: string;
+  doNotTrack: boolean;
+  topBarVariant: TopBarVariant;
+}

+ 11 - 0
src/interfaces/startup-tab.ts

@@ -0,0 +1,11 @@
+export interface IStartupTab {
+  id?: number;
+  windowId?: number;
+  groupId?: number;
+  title?: string;
+  url?: string;
+  favicon?: string;
+  order?: number;
+  pinned?: boolean;
+  isUserDefined?: boolean;
+}

+ 19 - 0
src/interfaces/storage.ts

@@ -0,0 +1,19 @@
+export interface IOperation {
+  scope: string;
+}
+
+export interface IFindOperation extends IOperation {
+  query: any;
+}
+
+export interface IInsertOperation extends IOperation {
+  item: any;
+}
+
+export interface IRemoveOperation extends IFindOperation {
+  multi?: boolean;
+}
+
+export interface IUpdateOperation extends IFindOperation, IRemoveOperation {
+  value: any;
+}

+ 10 - 0
src/interfaces/suggestion.ts

@@ -0,0 +1,10 @@
+export interface ISuggestion {
+  primaryText?: string;
+  secondaryText?: string;
+  id?: number;
+  favicon?: string;
+  canSuggest?: boolean;
+  isSearch?: boolean;
+  hovered?: boolean;
+  url?: string;
+}

+ 13 - 0
src/interfaces/tabs.ts

@@ -0,0 +1,13 @@
+export type TabEvent =
+  | 'load-commit'
+  | 'url-updated'
+  | 'title-updated'
+  | 'favicon-updated'
+  | 'did-navigate'
+  | 'loading'
+  | 'pinned'
+  | 'credentials'
+  | 'blocked-ad'
+  | 'zoom-updated'
+  | 'media-playing'
+  | 'media-paused';

+ 50 - 0
src/interfaces/theme.ts

@@ -0,0 +1,50 @@
+export interface ITheme {
+  'titlebar.backgroundColor': string;
+
+  'addressbar.backgroundColor': string;
+  'addressbar.textColor': string;
+
+  'toolbar.backgroundColor': string;
+  'toolbar.bottomLine.backgroundColor': string;
+  'toolbar.lightForeground': boolean;
+  'toolbar.separator.color': string;
+
+  'tab.textColor': string;
+  'tab.selected.textColor': string;
+
+  'control.backgroundColor': string;
+  'control.hover.backgroundColor': string;
+  'control.valueColor': string;
+  'control.lightIcon': boolean;
+  'switch.backgroundColor': string;
+
+  'dialog.separator.color': string;
+  'dialog.backgroundColor': string;
+  'dialog.textColor': string;
+  'dialog.lightForeground': boolean;
+
+  'searchBox.backgroundColor': string;
+  'searchBox.lightForeground': boolean;
+
+  'pages.backgroundColor': string;
+  'pages.lightForeground': boolean;
+  'pages.textColor': string;
+  'pages.navigationDrawer1.backgroundColor': string;
+  'pages.navigationDrawer2.backgroundColor': string;
+
+  'dropdown.backgroundColor': string;
+  'dropdown.backgroundColor.translucent': string;
+  'dropdown.separator.color': string;
+
+  backgroundColor: string;
+  accentColor: string;
+
+  animations?: boolean;
+
+  titlebarHeight?: number;
+  tabHeight?: number;
+  tabMarginTop?: number;
+  isCompact?: boolean;
+
+  dark?: boolean;
+}

+ 4 - 0
src/interfaces/urls.ts

@@ -0,0 +1,4 @@
+export interface IURLSegment {
+  value: string;
+  grayOut: boolean;
+}

+ 96 - 0
src/interfaces/weather.ts

@@ -0,0 +1,96 @@
+export interface IForecastRequest {
+  city: string;
+  lang: forecastLangCode;
+  units: 'metric' | 'imperial';
+}
+
+export interface IForecastItem {
+  date?: Date;
+  dayName?: string;
+  dayTemp?: number;
+  nightTemp?: number;
+  description?: string;
+  weather?: IWeatherCondition;
+}
+
+export interface IForecast {
+  city?: string;
+  today?: IForecastItem;
+  week?: IForecastItem[];
+}
+
+export type IWeatherCondition =
+  | 'clear'
+  | 'fewClouds'
+  | 'rain'
+  | 'showers'
+  | 'snow'
+  | 'storm';
+
+/* tslint:disable */
+export interface IOpenWeatherItem {
+  clouds: {
+    all: number;
+  };
+  dt: number;
+  dt_txt: string;
+  main: {
+    grnd_level: number;
+    humidity: number;
+    pressure: number;
+    sea_level: number;
+    temp: number;
+    temp_kf: number;
+    temp_max: number;
+    temp_min: number;
+  };
+  sys: {
+    pod: 'd' | 'n';
+  };
+  weather: {
+    description: string;
+    icon: string;
+    id: number;
+    main: IWeatherCondition;
+  }[];
+  wind: {
+    deg: number;
+    speed: number;
+  };
+}
+/* tslint:enable */
+
+export type forecastLangCode =
+  | 'ar'
+  | 'bg'
+  | 'ca'
+  | 'cz'
+  | 'de'
+  | 'el'
+  | 'en'
+  | 'fa'
+  | 'fi'
+  | 'fr'
+  | 'gl'
+  | 'hr'
+  | 'hu'
+  | 'it'
+  | 'ja'
+  | 'kr'
+  | 'la'
+  | 'lt'
+  | 'mk'
+  | 'nl'
+  | 'pl'
+  | 'pt'
+  | 'ro'
+  | 'ru'
+  | 'se'
+  | 'sk'
+  | 'sl'
+  | 'es'
+  | 'tr'
+  | 'ua'
+  | 'vi'
+  | 'zh_cn'
+  | 'zh_tw';

+ 117 - 0
src/main/application.ts

@@ -0,0 +1,117 @@
+import { app, ipcMain, Menu } from 'electron';
+import { isAbsolute, extname } from 'path';
+import { existsSync } from 'fs';
+import { SessionsService } from './sessions-service';
+import { checkFiles } from '~/utils/files';
+import { Settings } from './models/settings';
+import { isURL, prefixHttp } from '~/utils';
+import { WindowsService } from './windows-service';
+import { StorageService } from './services/storage';
+import { getMainMenu } from './menus/main';
+import { runAutoUpdaterService,proxyService } from './services';
+import { DialogsService } from './services/dialogs-service';
+import { requestAuth } from './dialogs/auth';
+import { NetworkServiceHandler } from './network/network-service-handler';
+import { ExtensionServiceHandler } from './extension-service-handler';
+
+export class Application {
+  public static instance = new Application();
+
+  public sessions: SessionsService;
+
+  public settings = new Settings();
+
+  public storage = new StorageService();
+
+  public windows = new WindowsService();
+
+  public dialogs = new DialogsService();
+
+  public start() {
+    const gotTheLock = app.requestSingleInstanceLock();
+
+    if (!gotTheLock) {
+      app.quit();
+      return;
+    } else {
+      app.on('second-instance', async (e, argv) => {
+        const path = argv[argv.length - 1];
+
+        if (isAbsolute(path) && existsSync(path)) {
+          if (process.env.NODE_ENV !== 'development') {
+            const path = argv[argv.length - 1];
+            const ext = extname(path);
+
+            if (ext === '.html') {
+              this.windows.current.win.focus();
+              this.windows.current.viewManager.create({
+                url: `file:///${path}`,
+                active: true,
+              });
+            }
+          }
+          return;
+        } else if (isURL(path)) {
+          this.windows.current.win.focus();
+          this.windows.current.viewManager.create({
+            url: prefixHttp(path),
+            active: true,
+          });
+          return;
+        }
+
+        this.windows.open();
+      });
+    }
+
+    app.on('login', async (e, webContents, request, authInfo, callback) => {
+      e.preventDefault();
+
+      const window = this.windows.findByBrowserView(webContents.id);
+      const credentials = await requestAuth(
+        window.win,
+        request.url,
+        webContents.id,
+      );
+
+      if (credentials) {
+        callback(credentials.username, credentials.password);
+      }
+    });
+
+    ipcMain.on('create-window', (e, incognito = false) => {
+      this.windows.open(incognito);
+    });
+
+    this.onReady();
+  }
+
+  private async onReady() {
+
+    await app.whenReady();
+    
+    proxyService();
+
+    new ExtensionServiceHandler();
+
+    NetworkServiceHandler.get();
+
+    checkFiles();
+
+    this.storage.run();
+    this.dialogs.run();
+
+    this.windows.open();
+
+    this.sessions = new SessionsService();
+
+    Menu.setApplicationMenu(getMainMenu());
+    runAutoUpdaterService();
+
+    app.on('activate', () => {
+      if (this.windows.list.filter((x) => x !== null).length === 0) {
+        this.windows.open();
+      }
+    });
+  }
+}

+ 49 - 0
src/main/dialogs/add-bookmark.ts

@@ -0,0 +1,49 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+import { IBookmark } from '~/interfaces';
+
+export const showAddBookmarkDialog = (
+  browserWindow: BrowserWindow,
+  x: number,
+  y: number,
+  data?: {
+    url: string;
+    title: string;
+    bookmark?: IBookmark;
+    favicon?: string;
+  },
+) => {
+  if (!data) {
+    const {
+      url,
+      title,
+      bookmark,
+      favicon,
+    } = Application.instance.windows.current.viewManager.selected;
+    data = {
+      url,
+      title,
+      bookmark,
+      favicon,
+    };
+  }
+
+  const dialog = Application.instance.dialogs.show({
+    name: 'add-bookmark',
+    browserWindow,
+    getBounds: () => ({
+      width: 366,
+      height: 240,
+      x: x - 366 + DIALOG_MARGIN,
+      y: y - DIALOG_MARGIN_TOP,
+    }),
+    onWindowBoundsUpdate: () => dialog.hide(),
+  });
+
+  if (!dialog) return;
+
+  dialog.on('loaded', (e) => {
+    e.reply('data', data);
+  });
+};

+ 49 - 0
src/main/dialogs/auth.ts

@@ -0,0 +1,49 @@
+import { VIEW_Y_OFFSET } from '~/constants/design';
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+
+export const requestAuth = (
+  browserWindow: BrowserWindow,
+  url: string,
+  tabId: number,
+): Promise<{ username: string; password: string }> => {
+  return new Promise((resolve, reject) => {
+    const appWindow = Application.instance.windows.fromBrowserWindow(
+      browserWindow,
+    );
+
+    const tab = appWindow.viewManager.views.get(tabId);
+    tab.requestedAuth = { url };
+
+    const dialog = Application.instance.dialogs.show({
+      name: 'auth',
+      browserWindow,
+      getBounds: () => {
+        const { width } = browserWindow.getContentBounds();
+        return {
+          width: 400,
+          height: 500,
+          x: width / 2 - 400 / 2,
+          y: VIEW_Y_OFFSET,
+        };
+      },
+      tabAssociation: {
+        tabId,
+        getTabInfo: (tabId) => {
+          const tab = appWindow.viewManager.views.get(tabId);
+          return tab.requestedAuth;
+        },
+      },
+      onWindowBoundsUpdate: (disposition) => {
+        if (disposition === 'resize') dialog.rearrange();
+      },
+    });
+
+    if (!dialog) return;
+
+    dialog.on('result', (e, result) => {
+      resolve(result);
+      dialog.hide();
+    });
+  });
+};

+ 26 - 0
src/main/dialogs/credentials.ts

@@ -0,0 +1,26 @@
+import { VIEW_Y_OFFSET } from '~/constants/design';
+import { AppWindow } from '../windows';
+import { Dialog } from '.';
+
+const WIDTH = 350;
+const HEIGHT = 271;
+
+export class CredentialsDialog extends Dialog {
+  public constructor(appWindow: AppWindow) {
+    super(appWindow, {
+      name: 'credentials',
+      bounds: {
+        height: HEIGHT,
+        width: WIDTH,
+        y: VIEW_Y_OFFSET,
+      },
+    });
+  }
+
+  public rearrange() {
+    const { width } = this.appWindow.win.getContentBounds();
+    super.rearrange({
+      x: width - WIDTH,
+    });
+  }
+}

+ 193 - 0
src/main/dialogs/dialog.ts

@@ -0,0 +1,193 @@
+import { BrowserView, app, ipcMain, BrowserWindow } from 'electron';
+import { join } from 'path';
+import { roundifyRectangle } from '../services/dialogs-service';
+
+interface IOptions {
+  name: string;
+  devtools?: boolean;
+  bounds?: IRectangle;
+  hideTimeout?: number;
+  customHide?: boolean;
+  webPreferences?: Electron.WebPreferences;
+}
+
+interface IRectangle {
+  x?: number;
+  y?: number;
+  width?: number;
+  height?: number;
+}
+
+export class PersistentDialog {
+  public browserWindow: BrowserWindow;
+  public browserView: BrowserView;
+
+  public visible = false;
+
+  public bounds: IRectangle = {
+    x: 0,
+    y: 0,
+    width: 0,
+    height: 0,
+  };
+
+  public name: string;
+
+  private timeout: any;
+  private hideTimeout: number;
+
+  private loaded = false;
+  private showCallback: any = null;
+
+  public constructor({
+    bounds,
+    name,
+    devtools,
+    hideTimeout,
+    webPreferences,
+  }: IOptions) {
+    this.browserView = new BrowserView({
+      webPreferences: {
+        nodeIntegration: true,
+        contextIsolation: false,
+        enableRemoteModule: true,
+        ...webPreferences,
+      },
+    });
+
+    this.bounds = { ...this.bounds, ...bounds };
+    this.hideTimeout = hideTimeout;
+    this.name = name;
+
+    const { webContents } = this.browserView;
+
+    ipcMain.on(`hide-${webContents.id}`, () => {
+      this.hide(false, false);
+    });
+
+    webContents.once('dom-ready', () => {
+      this.loaded = true;
+
+      if (this.showCallback) {
+        this.showCallback();
+        this.showCallback = null;
+      }
+    });
+
+    if (process.env.NODE_ENV === 'development') {
+      this.webContents.loadURL(`http://localhost:4444/${this.name}.html`);
+    } else {
+      this.webContents.loadURL(
+        join('file://', app.getAppPath(), `build/${this.name}.html`),
+      );
+    }
+  }
+
+  public get webContents() {
+    return this.browserView.webContents;
+  }
+
+  public get id() {
+    return this.webContents.id;
+  }
+
+  public rearrange(rect: IRectangle = {}) {
+    this.bounds = roundifyRectangle({
+      height: rect.height || this.bounds.height || 0,
+      width: rect.width || this.bounds.width || 0,
+      x: rect.x || this.bounds.x || 0,
+      y: rect.y || this.bounds.y || 0,
+    });
+
+    if (this.visible) {
+      this.browserView.setBounds(this.bounds as any);
+    }
+  }
+
+  public show(browserWindow: BrowserWindow, focus = true, waitForLoad = true) {
+    return new Promise((resolve) => {
+      this.browserWindow = browserWindow;
+
+      clearTimeout(this.timeout);
+
+      browserWindow.webContents.send(
+        'dialog-visibility-change',
+        this.name,
+        true,
+      );
+
+      const callback = () => {
+        if (this.visible) {
+          if (focus) this.webContents.focus();
+          return;
+        }
+
+        this.visible = true;
+
+        browserWindow.addBrowserView(this.browserView);
+        this.rearrange();
+
+        if (focus) this.webContents.focus();
+
+        resolve();
+      };
+
+      if (!this.loaded && waitForLoad) {
+        this.showCallback = callback;
+        return;
+      }
+
+      callback();
+    });
+  }
+
+  public hideVisually() {
+    this.send('visible', false);
+  }
+
+  public send(channel: string, ...args: any[]) {
+    this.webContents.send(channel, ...args);
+  }
+
+  public hide(bringToTop = false, hideVisually = true) {
+    if (!this.browserWindow) return;
+
+    if (hideVisually) this.hideVisually();
+
+    if (!this.visible) return;
+
+    this.browserWindow.webContents.send(
+      'dialog-visibility-change',
+      this.name,
+      false,
+    );
+
+    if (bringToTop) {
+      this.bringToTop();
+    }
+
+    clearTimeout(this.timeout);
+
+    if (this.hideTimeout) {
+      this.timeout = setTimeout(() => {
+        this.browserWindow.removeBrowserView(this.browserView);
+      }, this.hideTimeout);
+    } else {
+      this.browserWindow.removeBrowserView(this.browserView);
+    }
+
+    this.visible = false;
+
+    // this.appWindow.fixDragging();
+  }
+
+  public bringToTop() {
+    this.browserWindow.removeBrowserView(this.browserView);
+    this.browserWindow.addBrowserView(this.browserView);
+  }
+
+  public destroy() {
+    this.browserView.destroy();
+    this.browserView = null;
+  }
+}

+ 46 - 0
src/main/dialogs/downloads.ts

@@ -0,0 +1,46 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import {
+  DIALOG_MARGIN_TOP,
+  DIALOG_MARGIN,
+  DIALOG_TOP,
+} from '~/constants/design';
+
+export const showDownloadsDialog = (
+  browserWindow: BrowserWindow,
+  x: number,
+  y: number,
+) => {
+  let height = 0;
+
+  const dialog = Application.instance.dialogs.show({
+    name: 'downloads-dialog',
+    browserWindow,
+    getBounds: () => {
+      const winBounds = browserWindow.getContentBounds();
+      const maxHeight = winBounds.height - DIALOG_TOP - 16;
+
+      height = Math.round(Math.min(winBounds.height, height + 28));
+
+      dialog.browserView.webContents.send(
+        `max-height`,
+        Math.min(maxHeight, height),
+      );
+
+      return {
+        x: x - 350 + DIALOG_MARGIN,
+        y: y - DIALOG_MARGIN_TOP,
+        width: 350,
+        height,
+      };
+    },
+    onWindowBoundsUpdate: () => dialog.hide(),
+  });
+
+  if (!dialog) return;
+
+  dialog.on('height', (e, h) => {
+    height = h;
+    dialog.rearrange();
+  });
+};

+ 51 - 0
src/main/dialogs/extension-popup.ts

@@ -0,0 +1,51 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+
+export const showExtensionDialog = (
+  browserWindow: BrowserWindow,
+  x: number,
+  y: number,
+  url: string,
+  inspect = false,
+) => {
+  if (!process.env.ENABLE_EXTENSIONS) return;
+
+  let height = 512;
+  let width = 512;
+
+  const dialog = Application.instance.dialogs.show({
+    name: 'extension-popup',
+    browserWindow,
+    getBounds: () => {
+      return {
+        x: x - width + DIALOG_MARGIN,
+        y: y - DIALOG_MARGIN_TOP,
+        height: Math.min(1024, height),
+        width: Math.min(1024, width),
+      };
+    },
+    onWindowBoundsUpdate: () => dialog.hide(),
+  });
+
+  if (!dialog) return;
+
+  dialog.on('bounds', (e, w, h) => {
+    width = w;
+    height = h;
+    dialog.rearrange();
+  });
+
+  dialog.browserView.webContents.on(
+    'will-attach-webview',
+    (e, webPreferences, params) => {
+      webPreferences.sandbox = true;
+      webPreferences.nodeIntegration = false;
+      webPreferences.contextIsolation = true;
+    },
+  );
+
+  dialog.on('loaded', (e) => {
+    e.reply('data', { url, inspect });
+  });
+};

+ 38 - 0
src/main/dialogs/find.ts

@@ -0,0 +1,38 @@
+import { VIEW_Y_OFFSET } from '~/constants/design';
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+
+export const showFindDialog = (browserWindow: BrowserWindow) => {
+  const appWindow = Application.instance.windows.fromBrowserWindow(
+    browserWindow,
+  );
+
+  const dialog = Application.instance.dialogs.show({
+    name: 'find',
+    browserWindow,
+    devtools: true,
+    getBounds: () => {
+      const { width } = browserWindow.getContentBounds();
+      return {
+        width: 416,
+        height: 70,
+        x: width - 416,
+        y: VIEW_Y_OFFSET,
+      };
+    },
+    tabAssociation: {
+      tabId: appWindow.viewManager.selectedId,
+      getTabInfo: (tabId) => {
+        const tab = appWindow.viewManager.views.get(tabId);
+        return tab.findInfo;
+      },
+      setTabInfo: (tabId, info) => {
+        const tab = appWindow.viewManager.views.get(tabId);
+        tab.findInfo = info;
+      },
+    },
+    onWindowBoundsUpdate: (disposition) => {
+      if (disposition === 'resize') dialog.rearrange();
+    },
+  });
+};

+ 45 - 0
src/main/dialogs/form-fill.ts

@@ -0,0 +1,45 @@
+import { VIEW_Y_OFFSET, DIALOG_MARGIN_TOP } from '~/constants/design';
+import { Dialog } from './dialog';
+import { AppWindow } from '../windows';
+
+const WIDTH = 208;
+const HEIGHT = 128;
+
+export class FormFillDialog extends Dialog {
+  public inputRect = {
+    width: 0,
+    height: 0,
+    x: 0,
+    y: 0,
+  };
+
+  public constructor(appWindow: AppWindow) {
+    super(appWindow, {
+      name: 'form-fill',
+      bounds: {
+        height: HEIGHT,
+        width: WIDTH,
+      },
+    });
+  }
+
+  public rearrange() {
+    super.rearrange({
+      x: this.inputRect.x - 8,
+      y:
+        this.inputRect.y +
+        this.inputRect.height +
+        VIEW_Y_OFFSET -
+        DIALOG_MARGIN_TOP +
+        2,
+    });
+  }
+
+  public resize(count: number, hasSubtext = false) {
+    const itemHeight = hasSubtext ? 56 : 32;
+    super.rearrange({
+      width: WIDTH,
+      height: count * itemHeight + DIALOG_MARGIN_TOP * 2 + 16,
+    });
+  }
+}

+ 24 - 0
src/main/dialogs/menu.ts

@@ -0,0 +1,24 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+
+export const showMenuDialog = (
+  browserWindow: BrowserWindow,
+  x: number,
+  y: number,
+) => {
+  const menuWidth = 330;
+  const dialog = Application.instance.dialogs.show({
+    name: 'menu',
+    browserWindow,
+    getBounds: () => ({
+      width: menuWidth,
+      height: 510,
+      x: x - menuWidth + DIALOG_MARGIN,
+      y: y - DIALOG_MARGIN_TOP,
+    }),
+    onWindowBoundsUpdate: () => {
+      dialog.hide();
+    },
+  });
+};

+ 55 - 0
src/main/dialogs/permissions.ts

@@ -0,0 +1,55 @@
+import { VIEW_Y_OFFSET } from '~/constants/design';
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+
+export const requestPermission = (
+  browserWindow: BrowserWindow,
+  name: string,
+  url: string,
+  details: any,
+  tabId: number,
+): Promise<boolean> => {
+  return new Promise((resolve, reject) => {
+    if (
+      name === 'unknown' ||
+      (name === 'media' && details.mediaTypes.length === 0) ||
+      name === 'midiSysex'
+    ) {
+      return reject('Unknown permission');
+    }
+
+    const appWindow = Application.instance.windows.fromBrowserWindow(
+      browserWindow,
+    );
+
+    appWindow.viewManager.selected.requestedPermission = { name, url, details };
+
+    // const dialog = Application.instance.dialogs.show({
+    //   name: 'permissions',
+    //   browserWindow,
+    //   getBounds: () => ({
+    //     width: 366,
+    //     height: 165,
+    //     x: 0,
+    //     y: VIEW_Y_OFFSET,
+    //   }),
+    //   tabAssociation: {
+    //     tabId,
+    //     getTabInfo: (tabId) => {
+    //       const tab = appWindow.viewManager.views.get(tabId);
+    //       return tab.requestedPermission;
+    //     },
+    //   },
+    //   onWindowBoundsUpdate: (disposition) => {
+    //     if (disposition === 'resize') dialog.rearrange();
+    //   },
+    // });
+
+    // if (!dialog) return;
+
+    // dialog.on('result', (e, result) => {
+    //   resolve(result);
+    //   dialog.hide();
+    // });
+  });
+};

+ 51 - 0
src/main/dialogs/preview.ts

@@ -0,0 +1,51 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+import { PersistentDialog } from './dialog';
+import { ERROR_PROTOCOL } from '~/constants/files';
+
+const HEIGHT = 256;
+
+export class PreviewDialog extends PersistentDialog {
+  public visible = false;
+  public tab: { id?: number; x?: number; y?: number } = {};
+
+  constructor() {
+    super({
+      name: 'preview',
+      bounds: {
+        height: HEIGHT,
+      },
+      hideTimeout: 150,
+    });
+  }
+
+  public rearrange() {
+    const { width } = this.browserWindow.getContentBounds();
+    super.rearrange({ width, y: this.tab.y });
+  }
+
+  public async show(browserWindow: BrowserWindow) {
+    super.show(browserWindow, false);
+
+    const {
+      id,
+      url,
+      title,
+      errorURL,
+    } = Application.instance.windows
+      .fromBrowserWindow(browserWindow)
+      .viewManager.views.get(this.tab.id);
+
+    this.send('visible', true, {
+      id,
+      url: url.startsWith(`${ERROR_PROTOCOL}://`) ? errorURL : url,
+      title,
+      x: this.tab.x - 8,
+    });
+  }
+
+  public hide(bringToTop = true) {
+    super.hide(bringToTop);
+  }
+}

+ 81 - 0
src/main/dialogs/search.ts

@@ -0,0 +1,81 @@
+import { ipcMain, BrowserWindow } from 'electron';
+import {
+  DIALOG_MIN_HEIGHT,
+  DIALOG_MARGIN_TOP,
+  DIALOG_MARGIN,
+} from '~/constants/design';
+import { PersistentDialog } from './dialog';
+import { Application } from '../application';
+
+const WIDTH = 800;
+const HEIGHT = 80;
+
+export class SearchDialog extends PersistentDialog {
+  private isPreviewVisible = false;
+
+  public data = {
+    text: '',
+    x: 0,
+    y: 0,
+    width: 200,
+  };
+
+  public constructor() {
+    super({
+      name: 'search',
+      bounds: {
+        width: WIDTH,
+        height: HEIGHT,
+        y: 48,
+      },
+
+      devtools: false,
+    });
+
+    ipcMain.on(`height-${this.id}`, (e, height) => {
+      super.rearrange({
+        height: this.isPreviewVisible
+          ? Math.max(DIALOG_MIN_HEIGHT, HEIGHT + height)
+          : HEIGHT + height,
+      });
+    });
+
+    ipcMain.on(`addressbar-update-input-${this.id}`, (e, data) => {
+      this.browserWindow.webContents.send('addressbar-update-input', data);
+    });
+  }
+
+  public rearrange() {
+    super.rearrange({
+      x: this.data.x - DIALOG_MARGIN,
+      y: this.data.y - DIALOG_MARGIN_TOP,
+      width: this.data.width + 2 * DIALOG_MARGIN,
+    });
+  }
+
+  private onResize = () => {
+    this.hide();
+  };
+
+  public async show(browserWindow: BrowserWindow) {
+    super.show(browserWindow, true, false);
+
+    browserWindow.once('resize', this.onResize);
+
+    this.send('visible', true, {
+      id: Application.instance.windows.current.viewManager.selectedId,
+      ...this.data,
+    });
+
+    ipcMain.once('get-search-tabs', (e, tabs) => {
+      this.send('search-tabs', tabs);
+    });
+
+    browserWindow.webContents.send('get-search-tabs');
+  }
+
+  public hide(bringToTop = false) {
+    super.hide(bringToTop);
+    this.browserWindow.removeListener('resize', this.onResize);
+  }
+}

+ 24 - 0
src/main/dialogs/tabgroup.ts

@@ -0,0 +1,24 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+
+export const showTabGroupDialog = (
+  browserWindow: BrowserWindow,
+  tabGroup: any,
+) => {
+  const dialog = Application.instance.dialogs.show({
+    name: 'tabgroup',
+    browserWindow,
+    getBounds: () => ({
+      width: 266,
+      height: 180,
+      x: tabGroup.x - DIALOG_MARGIN,
+      y: tabGroup.y - DIALOG_MARGIN_TOP,
+    }),
+    onWindowBoundsUpdate: () => dialog.hide(),
+  });
+
+  if (!dialog) return;
+
+  dialog.handle('tabgroup', () => tabGroup);
+};

+ 28 - 0
src/main/dialogs/zoom.ts

@@ -0,0 +1,28 @@
+import { BrowserWindow } from 'electron';
+import { Application } from '../application';
+import { DIALOG_MARGIN_TOP, DIALOG_MARGIN } from '~/constants/design';
+
+export const showZoomDialog = (
+  browserWindow: BrowserWindow,
+  x: number,
+  y: number,
+) => {
+  const tabId = Application.instance.windows.fromBrowserWindow(browserWindow)
+    .viewManager.selectedId;
+
+  const dialog = Application.instance.dialogs.show({
+    name: 'zoom',
+    browserWindow,
+    getBounds: () => ({
+      width: 280,
+      height: 100,
+      x: x - 280 + DIALOG_MARGIN,
+      y: y - DIALOG_MARGIN_TOP,
+    }),
+    onWindowBoundsUpdate: () => dialog.hide(),
+  });
+
+  if (!dialog) return;
+
+  dialog.handle('tab-id', () => tabId);
+};

+ 17 - 0
src/main/extension-service-handler.ts

@@ -0,0 +1,17 @@
+import { RpcMainEvent, RpcMainHandler } from '@wexond/rpc-electron';
+import {
+  extensionMainChannel,
+  ExtensionMainService,
+} from '~/common/rpc/extensions';
+import { Application } from './application';
+
+export class ExtensionServiceHandler
+  implements RpcMainHandler<ExtensionMainService> {
+  constructor() {
+    extensionMainChannel.getReceiver().handler = this;
+  }
+
+  uninstall(e: RpcMainEvent, id: string): void {
+    Application.instance.sessions.uninstallExtension(id);
+  }
+}

+ 69 - 0
src/main/index.ts

@@ -0,0 +1,69 @@
+import { ipcMain, app, webContents } from 'electron';
+import { setIpcMain } from '@wexond/rpc-electron';
+setIpcMain(ipcMain);
+
+if (process.env.NODE_ENV === 'development') {
+  require('source-map-support').install();
+}
+
+import { platform } from 'os';
+import { Application } from './application';
+
+export const isNightly = app.name === 'wexond-nightly';
+
+app.allowRendererProcessReuse = true;
+app.name = isNightly ? '蓝微浏览器 Nightly' : '蓝微浏览器';
+
+(process.env as any)['ELECTRON_DISABLE_SECURITY_WARNINGS'] = true;
+
+app.commandLine.appendSwitch('--enable-transparent-visuals');
+app.commandLine.appendSwitch(
+  'enable-features',
+  'CSSColorSchemeUARendering, ImpulseScrollAnimations, ParallelDownloading',
+);
+
+if (process.env.NODE_ENV === 'development') {
+  app.commandLine.appendSwitch('remote-debugging-port', '9222');
+}
+
+ipcMain.setMaxListeners(0);
+
+// app.setAsDefaultProtocolClient('http');
+// app.setAsDefaultProtocolClient('https');
+
+const application = Application.instance;
+application.start();
+
+process.on('uncaughtException', (error) => {
+  console.error(error);
+});
+
+app.on('window-all-closed', () => {
+  if (platform() !== 'darwin') {
+    app.quit();
+  }
+});
+
+ipcMain.on('get-webcontents-id', (e) => {
+  e.returnValue = e.sender.id;
+});
+
+ipcMain.on('get-window-id', (e) => {
+  e.returnValue = (e.sender as any).windowId;
+});
+
+ipcMain.handle(
+  `web-contents-call`,
+  async (e, { webContentsId, method, args = [] }) => {
+    const wc = webContents.fromId(webContentsId);
+    const result = (wc as any)[method](...args);
+
+    if (result) {
+      if (result instanceof Promise) {
+        return await result;
+      }
+
+      return result;
+    }
+  },
+);

+ 131 - 0
src/main/menus/bookmarks.ts

@@ -0,0 +1,131 @@
+import {
+  Menu,
+  nativeImage,
+  NativeImage,
+  MenuItemConstructorOptions,
+  app,
+} from 'electron';
+import { join } from 'path';
+import { IBookmark } from '~/interfaces';
+import { Application } from '../application';
+import { AppWindow } from '../windows/app';
+import { showAddBookmarkDialog } from '../dialogs/add-bookmark';
+
+function getPath(file: string) {
+  if (process.env.NODE_ENV === 'development') {
+    return join(
+      app.getAppPath(),
+      'src',
+      'renderer',
+      'resources',
+      'icons',
+      `${file}.png`,
+    );
+  } else {
+    const path = require(`~/renderer/resources/icons/${file}.png`);
+    return join(app.getAppPath(), `build`, path);
+  }
+}
+
+function getIcon(
+  favicon: string | undefined,
+  isFolder: boolean,
+): NativeImage | string {
+  if (favicon) {
+    let dataURL = Application.instance.storage.favicons.get(favicon);
+    if (dataURL) {
+      // some favicon data urls have a corrupted base 64 file type descriptor
+      // prefixed with data:png;base64, instead of data:image/png;base64,
+      // see: https://github.com/electron/electron/issues/23369
+      if (!dataURL.split(',')[0].includes('image')) {
+        const split = dataURL.split(':');
+        dataURL = split.join(':image/');
+      }
+
+      const image = nativeImage
+        .createFromDataURL(dataURL)
+        .resize({ width: 16, height: 16 });
+      return image;
+    }
+  }
+
+  if (Application.instance.settings.object.theme === 'wexond-dark') {
+    if (isFolder) {
+      return getPath('folder_light');
+    } else {
+      return getPath('page_light');
+    }
+  } else {
+    if (isFolder) {
+      return getPath('folder_dark');
+    } else {
+      return getPath('page_dark');
+    }
+  }
+}
+
+export function createDropdown(
+  appWindow: AppWindow,
+  parentID: string,
+  bookmarks: IBookmark[],
+): Electron.Menu {
+  const folderBookmarks = bookmarks.filter(
+    ({ static: staticName, parent }) => !staticName && parent === parentID,
+  );
+  const template = folderBookmarks.map<MenuItemConstructorOptions>(
+    ({ title, url, favicon, isFolder, _id }) => ({
+      click: url
+        ? () => {
+            appWindow.viewManager.create({ url, active: true });
+          }
+        : undefined,
+      label: title,
+      icon: getIcon(favicon, isFolder),
+      submenu: isFolder ? createDropdown(appWindow, _id, bookmarks) : undefined,
+      id: _id,
+    }),
+  );
+
+  return template.length > 0
+    ? Menu.buildFromTemplate(template)
+    : Menu.buildFromTemplate([{ label: '(empty)', enabled: false }]);
+}
+
+export function createMenu(appWindow: AppWindow, item: IBookmark) {
+  const { isFolder, url } = item;
+  const folderItems: MenuItemConstructorOptions[] = [
+    {
+      label: '新标签打开',
+      click: () => {
+        appWindow.viewManager.create({ url, active: true });
+      },
+    },
+    {
+      type: 'separator',
+    },
+  ];
+
+  const template: MenuItemConstructorOptions[] = [
+    ...(!isFolder ? folderItems : []),
+    {
+      label: '编辑',
+      click: () => {
+        const windowBounds = appWindow.win.getBounds();
+        showAddBookmarkDialog(appWindow.win, windowBounds.width - 20, 72, {
+          url: item.url,
+          title: item.title,
+          bookmark: item,
+          favicon: item.favicon,
+        });
+      },
+    },
+    {
+      label: '移除',
+      click: () => {
+        Application.instance.storage.removeBookmark(item._id);
+      },
+    },
+  ];
+
+  return Menu.buildFromTemplate(template);
+}

+ 43 - 0
src/main/menus/common-actions.ts

@@ -0,0 +1,43 @@
+import { extname } from 'path';
+import { dialog } from 'electron';
+import { Application } from '../application';
+
+export const saveAs = async () => {
+  const {
+    title,
+    webContents,
+  } = Application.instance.windows.current.viewManager.selected;
+
+  const { canceled, filePath } = await dialog.showSaveDialog({
+    defaultPath: title,
+    filters: [
+      { name: 'Webpage, Complete', extensions: ['html', 'htm'] },
+      { name: 'Webpage, HTML Only', extensions: ['htm', 'html'] },
+    ],
+  });
+
+  if (canceled) return;
+
+  const ext = extname(filePath);
+
+  webContents.savePage(filePath, ext === '.htm' ? 'HTMLOnly' : 'HTMLComplete');
+};
+
+export const viewSource = async () => {
+  const { viewManager } = Application.instance.windows.current;
+
+  viewManager.create(
+    {
+      url: `view-source:${viewManager.selected.url}`,
+      active: true,
+    },
+    true,
+  );
+};
+
+export const printPage = () => {
+  const {
+    webContents,
+  } = Application.instance.windows.current.viewManager.selected;
+  webContents.print();
+};

+ 380 - 0
src/main/menus/main.ts

@@ -0,0 +1,380 @@
+import { Menu, webContents, app, BrowserWindow, MenuItem } from 'electron';
+import { defaultTabOptions } from '~/constants/tabs';
+import { viewSource, saveAs, printPage } from './common-actions';
+import { WEBUI_BASE_URL, WEBUI_URL_SUFFIX } from '~/constants/files';
+import { AppWindow } from '../windows';
+import { Application } from '../application';
+import { showMenuDialog } from '../dialogs/menu';
+import { getWebUIURL } from '~/common/webui';
+
+const isMac = process.platform === 'darwin';
+
+const createMenuItem = (
+  shortcuts: string[],
+  action: (
+    window: AppWindow,
+    menuItem: MenuItem,
+    shortcutIndex: number,
+  ) => void,
+  label: string = null,
+) => {
+  const result: any = shortcuts.map((shortcut, key) => ({
+    accelerator: shortcut,
+    visible: label != null && key === 0,
+    label: label != null && key === 0 ? label : '',
+    click: (menuItem: MenuItem, browserWindow: BrowserWindow) =>
+      action(
+        Application.instance.windows.list.find(
+          (x) => x.win.id === browserWindow.id,
+        ),
+        menuItem,
+        key,
+      ),
+  }));
+
+  return result;
+};
+
+export const getMainMenu = () => {
+  const template: any = [
+    ...(isMac
+      ? [
+          {
+            label: app.name,
+            submenu: [
+              { role: 'about' },
+              { type: 'separator' },
+              { role: 'services' },
+              { type: 'separator' },
+              { role: 'hide' },
+              { role: 'hideothers' },
+              { role: 'unhide' },
+              { type: 'separator' },
+              { role: 'quit' },
+            ],
+          },
+        ]
+      : []),
+    {
+      label: 'File',
+      submenu: [
+        ...createMenuItem(
+          ['CmdOrCtrl+N'],
+          () => {
+            Application.instance.windows.open();
+          },
+          'New window',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+Shift+N'],
+          () => {
+            Application.instance.windows.open(true);
+          },
+          'New incognito window',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+T'],
+          (window) => {
+            window.viewManager.create(defaultTabOptions);
+          },
+          'New tab',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+Shift+T'],
+          (window) => {
+            window.send('revert-closed-tab');
+          },
+          'Revert closed tab',
+        ),
+        {
+          type: 'separator',
+        },
+        ...createMenuItem(
+          ['CmdOrCtrl+Shift+W'],
+          (window) => {
+            window.win.close();
+          },
+          'Close window',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+W', 'CmdOrCtrl+F4'],
+          (window) => {
+            window.send('remove-tab', window.viewManager.selectedId);
+          },
+          'Close tab',
+        ),
+        {
+          type: 'separator',
+        },
+        ...createMenuItem(
+          ['CmdOrCtrl+S'],
+          () => {
+            saveAs();
+          },
+          'Save webpage as...',
+        ),
+        {
+          type: 'separator',
+        },
+        ...createMenuItem(
+          ['CmdOrCtrl+P'],
+          () => {
+            printPage();
+          },
+          'Print',
+        ),
+
+        // Hidden items
+
+        // Focus address bar
+        ...createMenuItem(['Ctrl+Space', 'CmdOrCtrl+L', 'Alt+D', 'F6'], () => {
+          Application.instance.dialogs
+            .getPersistent('search')
+            .show(Application.instance.windows.current.win);
+        }),
+
+        // Toggle menu
+        ...createMenuItem(['Alt+F', 'Alt+E'], () => {
+          Application.instance.windows.current.send('show-menu-dialog');
+        }),
+      ],
+    },
+    {
+      label: 'Edit',
+      submenu: [
+        { role: 'undo' },
+        { role: 'redo' },
+        { type: 'separator' },
+        { role: 'cut' },
+        { role: 'copy' },
+        { role: 'paste' },
+        ...(isMac
+          ? [
+              { role: 'pasteAndMatchStyle' },
+              { role: 'delete' },
+              { role: 'selectAll' },
+              { type: 'separator' },
+              {
+                label: 'Speech',
+                submenu: [{ role: 'startspeaking' }, { role: 'stopspeaking' }],
+              },
+            ]
+          : [{ role: 'delete' }, { type: 'separator' }, { role: 'selectAll' }]),
+        { type: 'separator' },
+        ...createMenuItem(
+          ['CmdOrCtrl+F'],
+          () => {
+            Application.instance.windows.current.send('find');
+          },
+          'Find in page',
+        ),
+      ],
+    },
+    {
+      label: 'View',
+      submenu: [
+        ...createMenuItem(
+          ['CmdOrCtrl+R', 'F5'],
+          () => {
+            Application.instance.windows.current.viewManager.selected.webContents.reload();
+          },
+          'Reload',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+Shift+R', 'Shift+F5'],
+          () => {
+            Application.instance.windows.current.viewManager.selected.webContents.reloadIgnoringCache();
+          },
+          'Reload ignoring cache',
+        ),
+      ],
+    },
+    {
+      label: 'History',
+      submenu: [
+        // TODO: Homepage - Ctrl+Shift+H
+        ...createMenuItem(
+          isMac ? ['Cmd+[', 'Cmd+Left'] : ['Alt+Left'],
+          () => {
+            const {
+              selected,
+            } = Application.instance.windows.current.viewManager;
+            if (selected) {
+              selected.webContents.goBack();
+            }
+          },
+          'Go back',
+        ),
+        ...createMenuItem(
+          isMac ? ['Cmd+]', 'Cmd+Right'] : ['Alt+Right'],
+          () => {
+            const {
+              selected,
+            } = Application.instance.windows.current.viewManager;
+            if (selected) {
+              selected.webContents.goForward();
+            }
+          },
+          'Go forward',
+        ),
+        // { type: 'separator' }
+        // TODO: list last closed tabs
+        // { type: 'separator' }
+        // TODO: list last visited
+        { type: 'separator' },
+        ...createMenuItem(
+          isMac ? ['Cmd+Y'] : ['Ctrl+H'],
+          () => {
+            Application.instance.windows.current.viewManager.create({
+              url: getWebUIURL('history'),
+              active: true,
+            });
+          },
+          'Manage history',
+        ),
+      ],
+    },
+    {
+      label: 'Bookmarks',
+      submenu: [
+        ...createMenuItem(
+          isMac ? ['Cmd+Option+B'] : ['CmdOrCtrl+Shift+O'],
+          () => {
+            Application.instance.windows.current.viewManager.create({
+              url: getWebUIURL('bookmarks'),
+              active: true,
+            });
+          },
+          'Manage bookmarks',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+Shift+B'],
+          () => {
+            const { bookmarksBar } = Application.instance.settings.object;
+            Application.instance.settings.updateSettings({
+              bookmarksBar: !bookmarksBar,
+            });
+          },
+          'Toggle bookmarks bar',
+        ),
+        ...createMenuItem(
+          ['CmdOrCtrl+D'],
+          () => {
+            Application.instance.windows.current.webContents.send(
+              'show-add-bookmark-dialog',
+            );
+          },
+          'Add this website to bookmarks',
+        ),
+        // { type: 'separator' }
+        // TODO: list bookmarks
+      ],
+    },
+    {
+      label: 'Tools',
+      submenu: [
+        {
+          label: 'Developer',
+          submenu: [
+            ...createMenuItem(
+              ['CmdOrCtrl+U'],
+              () => {
+                viewSource();
+              },
+              'View source',
+            ),
+            ...createMenuItem(
+              ['CmdOrCtrl+Shift+I', 'CmdOrCtrl+Shift+J', 'F12'],
+              () => {
+                setTimeout(() => {
+                  Application.instance.windows.current.viewManager.selected.webContents.toggleDevTools();
+                });
+              },
+              'Developer tools...',
+            ),
+
+            // Developer tools (current webContents) (dev)
+            ...createMenuItem(['CmdOrCtrl+Shift+F12'], () => {
+              setTimeout(() => {
+                webContents
+                  .getFocusedWebContents()
+                  .openDevTools({ mode: 'detach' });
+              });
+            }),
+          ],
+        },
+      ],
+    },
+    {
+      label: 'Tab',
+      submenu: [
+        ...createMenuItem(
+          isMac ? ['Cmd+Option+Right'] : ['Ctrl+Tab', 'Ctrl+PageDown'],
+          () => {
+            Application.instance.windows.current.webContents.send(
+              'select-next-tab',
+            );
+          },
+          'Select next tab',
+        ),
+        ...createMenuItem(
+          isMac ? ['Cmd+Option+Left'] : ['Ctrl+Shift+Tab', 'Ctrl+PageUp'],
+          () => {
+            Application.instance.windows.current.webContents.send(
+              'select-previous-tab',
+            );
+          },
+          'Select previous tab',
+        ),
+      ],
+    },
+    {
+      label: 'Window',
+      submenu: [
+        { role: 'minimize' },
+        { role: 'togglefullscreen' },
+        { role: 'zoom' },
+        ...(isMac
+          ? [
+              { type: 'separator' },
+              { role: 'front' },
+              { type: 'separator' },
+              { role: 'window' },
+            ]
+          : [{ role: 'close', accelerator: '' }]),
+        { type: 'separator' },
+        {
+          label: 'Always on top',
+          type: 'checkbox',
+          checked: false,
+          click(menuItem: MenuItem, browserWindow: BrowserWindow) {
+            browserWindow.setAlwaysOnTop(!browserWindow.isAlwaysOnTop());
+            menuItem.checked = browserWindow.isAlwaysOnTop();
+          },
+        },
+      ],
+    },
+  ];
+
+  // Ctrl+1 - Ctrl+8
+  template[0].submenu = template[0].submenu.concat(
+    createMenuItem(
+      Array.from({ length: 8 }, (v, k) => k + 1).map((i) => `CmdOrCtrl+${i}`),
+      (window, menuItem, i) => {
+        Application.instance.windows.current.webContents.send(
+          'select-tab-index',
+          i,
+        );
+      },
+    ),
+  );
+
+  // Ctrl+9
+  template[0].submenu = template[0].submenu.concat(
+    createMenuItem(['CmdOrCtrl+9'], () => {
+      Application.instance.windows.current.webContents.send('select-last-tab');
+    }),
+  );
+
+  return Menu.buildFromTemplate(template);
+};

+ 237 - 0
src/main/menus/view.ts

@@ -0,0 +1,237 @@
+import { AppWindow } from '../windows';
+import {
+  clipboard,
+  nativeImage,
+  Menu,
+  session,
+  ipcMain,
+  BrowserView,
+} from 'electron';
+import { isURL, prefixHttp } from '~/utils';
+import { saveAs, viewSource, printPage } from './common-actions';
+
+export const getViewMenu = (
+  appWindow: AppWindow,
+  params: Electron.ContextMenuParams,
+  webContents: Electron.WebContents,
+) => {
+  let menuItems: Electron.MenuItemConstructorOptions[] = [];
+
+  if (params.linkURL !== '') {
+    menuItems = menuItems.concat([
+      {
+        label: 'Open link in new tab',
+        click: () => {
+          appWindow.viewManager.create(
+            {
+              url: params.linkURL,
+              active: false,
+            },
+            true,
+          );
+        },
+      },
+      {
+        type: 'separator',
+      },
+      {
+        label: 'Copy link address',
+        click: () => {
+          clipboard.clear();
+          clipboard.writeText(params.linkURL);
+        },
+      },
+      {
+        type: 'separator',
+      },
+    ]);
+  }
+
+  if (params.hasImageContents) {
+    menuItems = menuItems.concat([
+      {
+        label: 'Open image in new tab',
+        click: () => {
+          appWindow.viewManager.create(
+            {
+              url: params.srcURL,
+              active: false,
+            },
+            true,
+          );
+        },
+      },
+      {
+        label: 'Copy image',
+        click: () => webContents.copyImageAt(params.x, params.y),
+      },
+      {
+        label: 'Copy image address',
+        click: () => {
+          clipboard.clear();
+          clipboard.writeText(params.srcURL);
+        },
+      },
+      {
+        label: 'Save image as...',
+        click: () => {
+          appWindow.webContents.downloadURL(params.srcURL);
+        },
+      },
+      {
+        type: 'separator',
+      },
+    ]);
+  }
+
+  if (params.isEditable) {
+    menuItems = menuItems.concat([
+      {
+        role: 'undo',
+        accelerator: 'CmdOrCtrl+Z',
+      },
+      {
+        role: 'redo',
+        accelerator: 'CmdOrCtrl+Shift+Z',
+      },
+      {
+        type: 'separator',
+      },
+      {
+        role: 'cut',
+        accelerator: 'CmdOrCtrl+X',
+      },
+      {
+        role: 'copy',
+        accelerator: 'CmdOrCtrl+C',
+      },
+      {
+        role: 'pasteAndMatchStyle',
+        accelerator: 'CmdOrCtrl+V',
+        label: 'Paste',
+      },
+      {
+        role: 'paste',
+        accelerator: 'CmdOrCtrl+Shift+V',
+        label: 'Paste as plain text',
+      },
+      {
+        role: 'selectAll',
+        accelerator: 'CmdOrCtrl+A',
+      },
+      {
+        type: 'separator',
+      },
+    ]);
+  }
+
+  if (!params.isEditable && params.selectionText !== '') {
+    menuItems = menuItems.concat([
+      {
+        role: 'copy',
+        accelerator: 'CmdOrCtrl+C',
+      },
+      {
+        type: 'separator',
+      },
+    ]);
+  }
+
+  if (params.selectionText !== '') {
+    const trimmedText = params.selectionText.trim();
+
+    if (isURL(trimmedText)) {
+      menuItems = menuItems.concat([
+        {
+          label: 'Go to ' + trimmedText,
+          click: () => {
+            appWindow.viewManager.create(
+              {
+                url: prefixHttp(trimmedText),
+                active: true,
+              },
+              true,
+            );
+          },
+        },
+        {
+          type: 'separator',
+        },
+      ]);
+    }
+  }
+
+  if (
+    !params.hasImageContents &&
+    params.linkURL === '' &&
+    params.selectionText === '' &&
+    !params.isEditable
+  ) {
+    menuItems = menuItems.concat([
+      {
+        label: '后退',
+        accelerator: 'Alt+Left',
+        enabled: webContents.canGoBack(),
+        click: () => {
+          webContents.goBack();
+        },
+      },
+      {
+        label: '前进',
+        accelerator: 'Alt+Right',
+        enabled: webContents.canGoForward(),
+        click: () => {
+          webContents.goForward();
+        },
+      },
+      {
+        label: '重新加载',
+        accelerator: 'CmdOrCtrl+R',
+        click: () => {
+          webContents.reload();
+        },
+      },
+      {
+        type: 'separator',
+      },
+      {
+        label: '另存为...',
+        accelerator: 'CmdOrCtrl+S',
+        click: async () => {
+          saveAs();
+        },
+      },
+      {
+        label: '打印',
+        accelerator: 'CmdOrCtrl+P',
+        click: async () => {
+          printPage();
+        },
+      },
+      {
+        type: 'separator',
+      },
+      {
+        label: '查看网页源码',
+        accelerator: 'CmdOrCtrl+U',
+        click: () => {
+          viewSource();
+        },
+      },
+    ]);
+  }
+
+  menuItems.push({
+    label: '检查',
+    accelerator: 'CmdOrCtrl+Shift+I',
+    click: () => {
+      webContents.inspectElement(params.x, params.y);
+
+      if (webContents.isDevToolsOpened()) {
+        webContents.devToolsWebContents.focus();
+      }
+    },
+  });
+
+  return Menu.buildFromTemplate(menuItems);
+};

+ 50 - 0
src/main/models/protocol.ts

@@ -0,0 +1,50 @@
+import { protocol } from 'electron';
+import { join } from 'path';
+import { parse } from 'url';
+import { ERROR_PROTOCOL, WEBUI_PROTOCOL } from '~/constants/files';
+
+protocol.registerSchemesAsPrivileged([
+  {
+    scheme: 'bluevchat',
+    privileges: {
+      bypassCSP: true,
+      secure: true,
+      standard: true,
+      supportFetchAPI: true,
+      allowServiceWorkers: true,
+      corsEnabled: false,
+    },
+  },
+]);
+
+export const registerProtocol = (session: Electron.Session) => {
+  session.protocol.registerFileProtocol(
+    ERROR_PROTOCOL,
+    (request, callback: any) => {
+      const parsed = parse(request.url);
+
+      if (parsed.hostname === 'network-error') {
+        return callback({
+          path: join(__dirname, '../static/pages/', `network-error.html`),
+        });
+      }
+    },
+  );
+
+  if (process.env.NODE_ENV !== 'development') {
+    session.protocol.registerFileProtocol(
+      WEBUI_PROTOCOL,
+      (request, callback: any) => {
+        const parsed = parse(request.url);
+
+        if (parsed.path === '/') {
+          return callback({
+            path: join(__dirname, `${parsed.hostname}.html`),
+          });
+        }
+
+        callback({ path: join(__dirname, parsed.path) });
+      },
+    );
+  }
+};

+ 209 - 0
src/main/models/settings.ts

@@ -0,0 +1,209 @@
+import { ipcMain, nativeTheme, dialog } from 'electron';
+
+import { DEFAULT_SETTINGS, DEFAULT_SEARCH_ENGINES } from '~/constants';
+
+import { promises } from 'fs';
+
+import { getPath, makeId } from '~/utils';
+import { EventEmitter } from 'events';
+import { runAdblockService, stopAdblockService } from '../services/adblock';
+import { Application } from '../application';
+import { WEBUI_BASE_URL } from '~/constants/files';
+import { ISettings } from '~/interfaces';
+
+export class Settings extends EventEmitter {
+  public object = DEFAULT_SETTINGS;
+
+  private queue: string[] = [];
+
+  private loaded = false;
+
+  public constructor() {
+    super();
+
+    ipcMain.on(
+      'save-settings',
+      (e, { settings }: { settings: string; incognito: boolean }) => {
+        this.updateSettings(JSON.parse(settings));
+      },
+    );
+
+    ipcMain.on('get-settings-sync', async (e) => {
+      await this.onLoad();
+      this.update();
+      e.returnValue = this.object;
+    });
+
+    ipcMain.on('get-settings', async (e) => {
+      await this.onLoad();
+      this.update();
+      e.sender.send('update-settings', this.object);
+    });
+
+    ipcMain.on('downloads-path-change', async () => {
+      const { canceled, filePaths } = await dialog.showOpenDialog({
+        defaultPath: this.object.downloadsPath,
+        properties: ['openDirectory'],
+      });
+
+      if (canceled) return;
+
+      this.object.downloadsPath = filePaths[0];
+
+      this.addToQueue();
+    });
+
+    nativeTheme.on('updated', () => {
+      this.update();
+    });
+
+    this.load();
+  }
+
+  private onLoad = async (): Promise<void> => {
+    return new Promise((resolve) => {
+      if (!this.loaded) {
+        this.once('load', () => {
+          resolve();
+        });
+      } else {
+        resolve();
+      }
+    });
+  };
+
+  public update = () => {
+    let themeSource = 'system';
+
+    if (this.object.themeAuto) {
+      this.object.theme = nativeTheme.shouldUseDarkColors
+        ? 'wexond-dark'
+        : 'wexond-light';
+    } else {
+      themeSource = this.object.theme === 'wexond-dark' ? 'dark' : 'light';
+    }
+
+    if (themeSource !== nativeTheme.themeSource) {
+      nativeTheme.themeSource = themeSource as any;
+    }
+
+    Application.instance.dialogs.sendToAll('update-settings', this.object);
+
+    for (const window of Application.instance.windows.list) {
+      window.send('update-settings', this.object);
+
+      window.viewManager.views.forEach(async (v) => {
+        if (v.webContents.getURL().startsWith(WEBUI_BASE_URL)) {
+          v.webContents.send('update-settings', this.object);
+        }
+      });
+    }
+
+    const contexts = [
+      Application.instance.sessions.view,
+      Application.instance.sessions.viewIncognito,
+    ];
+
+    contexts.forEach((e) => {
+      if (this.object.shield) {
+        runAdblockService(e);
+      } else {
+        stopAdblockService(e);
+      }
+    });
+  };
+
+  private async load() {
+    try {
+      const file = await promises.readFile(getPath('settings.json'), 'utf8');
+      const json = JSON.parse(file);
+
+      if (typeof json.version === 'string') {
+        // Migrate from 3.1.0
+        Application.instance.storage.remove({
+          scope: 'startupTabs',
+          query: {},
+          multi: true,
+        });
+      }
+
+      if (typeof json.version === 'string' || json.version === 1) {
+        json.searchEngines = DEFAULT_SEARCH_ENGINES;
+      }
+
+      if (json.themeAuto === undefined) {
+        json.themeAuto = true;
+      }
+
+      if (json.overlayBookmarks !== undefined) {
+        delete json.overlayBookmarks;
+      }
+
+      if (json.darkTheme !== undefined) {
+        delete json.darkTheme;
+      }
+
+      this.object = {
+        ...this.object,
+        ...json,
+        version: DEFAULT_SETTINGS.version,
+      };
+
+      this.loaded = true;
+
+      this.addToQueue();
+      this.emit('load');
+    } catch (e) {
+      this.loaded = true;
+      this.emit('load');
+    }
+
+    this.update();
+  }
+
+  private async save() {
+    try {
+      await promises.writeFile(
+        getPath('settings.json'),
+        JSON.stringify({ ...this.object, version: DEFAULT_SETTINGS.version }),
+      );
+
+      if (this.queue.length >= 3) {
+        for (let i = this.queue.length - 1; i > 0; i--) {
+          this.removeAllListeners(this.queue[i]);
+          this.queue.splice(i, 1);
+        }
+      } else {
+        this.queue.splice(0, 1);
+      }
+
+      if (this.queue[0]) {
+        this.emit(this.queue[0]);
+      }
+    } catch (e) {
+      console.error(e);
+    }
+  }
+
+  public async addToQueue() {
+    const id = makeId(32);
+
+    this.queue.push(id);
+
+    this.update();
+
+    if (this.queue.length === 1) {
+      this.save();
+    } else {
+      this.once(id, () => {
+        this.save();
+      });
+    }
+  }
+
+  public updateSettings(settings: Partial<ISettings>) {
+    this.object = { ...this.object, ...settings };
+
+    this.addToQueue();
+  }
+}

+ 20 - 0
src/main/network/network-service-handler.ts

@@ -0,0 +1,20 @@
+import { RpcMainEvent, RpcMainHandler } from '@wexond/rpc-electron';
+import { networkMainChannel, NetworkService } from '~/common/rpc/network';
+import { requestURL } from './request';
+
+export class NetworkServiceHandler implements RpcMainHandler<NetworkService> {
+  private static instance?: NetworkServiceHandler;
+
+  public static get() {
+    if (!this.instance) this.instance = new NetworkServiceHandler();
+    return this.instance;
+  }
+
+  constructor() {
+    networkMainChannel.getReceiver().handler = this;
+  }
+
+  request(e: RpcMainEvent, url: string) {
+    return requestURL(url);
+  }
+}

+ 42 - 0
src/main/network/request.ts

@@ -0,0 +1,42 @@
+import * as http from 'http';
+import * as https from 'https';
+import { parse } from 'url';
+import { ResponseDetails } from '~/common/rpc/network';
+
+export const requestURL = (url: string): Promise<ResponseDetails> =>
+
+  new Promise((resolve, reject) => {
+    const options = parse(url);
+
+    let { request } = http;
+
+    if (options.protocol === 'https:') {
+      request = https.request;
+    }
+
+    const req = request(options, (res) => {
+      let data = '';
+      res.setEncoding('binary');
+
+      res.on('data', (chunk) => {
+        data += chunk;
+      });
+
+      res.on('end', () => {
+        resolve({
+          statusCode: res.statusCode,
+          data,
+        });
+      });
+
+      res.on('error', (e) => {
+        reject(e);
+      });
+    });
+
+    req.on('error', (e) => {
+      reject(e);
+    });
+
+    req.end();
+  });

+ 137 - 0
src/main/services/adblock.ts

@@ -0,0 +1,137 @@
+import { existsSync, promises as fs } from 'fs';
+import { resolve, join } from 'path';
+import fetch from 'node-fetch';
+
+import { ElectronBlocker, Request } from '@cliqz/adblocker-electron';
+import { getPath } from '~/utils';
+import { Application } from '../application';
+import { ipcMain } from 'electron';
+
+export let engine: ElectronBlocker;
+
+const PRELOAD_PATH = join(__dirname, './preload.js');
+
+const loadFilters = async () => {
+  const path = resolve(getPath('adblock/cache.dat'));
+
+  const downloadFilters = async () => {
+    // Load lists to perform ads and tracking blocking:
+    //
+    //  - https://easylist.to/easylist/easylist.txt
+    //  - https://pgl.yoyo.org/adservers/serverlist.php?hostformat=adblockplus&showintro=1&mimetype=plaintext
+    //  - https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/resource-abuse.txt
+    //  - https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/badware.txt
+    //  - https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/filters.txt
+    //  - https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/unbreak.txt
+    //
+    //  - https://easylist.to/easylist/easyprivacy.txt
+    //  - https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/privacy.txt
+    engine = await ElectronBlocker.fromPrebuiltAdsAndTracking(fetch);
+
+    try {
+      await fs.writeFile(path, engine.serialize());
+    } catch (err) {
+      if (err) return console.error(err);
+    }
+  };
+
+  if (existsSync(path)) {
+    try {
+      const buffer = await fs.readFile(resolve(path));
+
+      try {
+        engine = ElectronBlocker.deserialize(buffer);
+      } catch (e) {
+        return downloadFilters();
+      }
+    } catch (err) {
+      return console.error(err);
+    }
+  } else {
+    return downloadFilters();
+  }
+};
+
+const emitBlockedEvent = (request: Request) => {
+  const win = Application.instance.windows.findByBrowserView(request.tabId);
+  if (!win) return;
+  win.viewManager.views.get(request.tabId).emitEvent('blocked-ad');
+};
+
+let adblockRunning = false;
+let adblockInitialized = false;
+
+interface IAdblockInfo {
+  headersReceivedId?: number;
+  beforeRequestId?: number;
+}
+
+const sessionAdblockInfoMap: Map<Electron.Session, IAdblockInfo> = new Map();
+
+export const runAdblockService = async (ses: any) => {
+  if (!adblockInitialized) {
+    adblockInitialized = true;
+    await loadFilters();
+  }
+
+  if (adblockInitialized && !engine) {
+    return;
+  }
+
+  if (adblockRunning) return;
+
+  adblockRunning = true;
+
+  const info = sessionAdblockInfoMap.get(ses) || {};
+
+  if (!info.headersReceivedId) {
+    info.headersReceivedId = ses.webRequest.addListener(
+      'onHeadersReceived',
+      { urls: ['<all_urls>'] },
+      (engine as any).onHeadersReceived,
+      { order: 0 },
+    ).id;
+  }
+
+  if (!info.beforeRequestId) {
+    info.beforeRequestId = ses.webRequest.addListener(
+      'onBeforeRequest',
+      { urls: ['<all_urls>'] },
+      (engine as any).onBeforeRequest,
+      { order: 0 },
+    ).id;
+  }
+
+  sessionAdblockInfoMap.set(ses, info);
+
+  ipcMain.on('get-cosmetic-filters', (engine as any).onGetCosmeticFilters);
+  ipcMain.on(
+    'is-mutation-observer-enabled',
+    (engine as any).onIsMutationObserverEnabled,
+  );
+  ses.setPreloads(ses.getPreloads().concat([PRELOAD_PATH]));
+
+  engine.on('request-blocked', emitBlockedEvent);
+  engine.on('request-redirected', emitBlockedEvent);
+};
+
+export const stopAdblockService = (ses: any) => {
+  if (!ses.webRequest.removeListener) return;
+  if (!adblockRunning) return;
+
+  adblockRunning = false;
+
+  const info = sessionAdblockInfoMap.get(ses) || {};
+
+  if (info.beforeRequestId) {
+    ses.webRequest.removeListener('onBeforeRequest', info.beforeRequestId);
+    info.beforeRequestId = null;
+  }
+
+  if (info.headersReceivedId) {
+    ses.webRequest.removeListener('onHeadersReceived', info.headersReceivedId);
+    info.headersReceivedId = null;
+  }
+
+  ses.setPreloads(ses.getPreloads().filter((p: string) => p !== PRELOAD_PATH));
+};

+ 32 - 0
src/main/services/auto-updater.ts

@@ -0,0 +1,32 @@
+import { autoUpdater } from 'electron-updater';
+import { ipcMain } from 'electron';
+import { Application } from '../application';
+
+export const runAutoUpdaterService = () => {
+  let updateAvailable = false;
+
+  ipcMain.on('install-update', () => {
+    if (process.env.NODE_ENV !== 'development') {
+      autoUpdater.quitAndInstall(true, true);
+    }
+  });
+
+  ipcMain.handle('is-update-available', () => {
+    return updateAvailable;
+  });
+
+  ipcMain.on('update-check', () => {
+    autoUpdater.checkForUpdates();
+  });
+
+  autoUpdater.on('update-downloaded', () => {
+    updateAvailable = true;
+
+    for (const window of Application.instance.windows.list) {
+      window.send('update-available');
+      Application.instance.dialogs
+        .getDynamic('menu')
+        ?.browserView?.webContents?.send('update-available');
+    }
+  });
+};

+ 331 - 0
src/main/services/dialogs-service.ts

@@ -0,0 +1,331 @@
+import { BrowserView, app, ipcMain } from 'electron';
+import { join } from 'path';
+import { SearchDialog } from '../dialogs/search';
+import { PreviewDialog } from '../dialogs/preview';
+import { PersistentDialog } from '../dialogs/dialog';
+import { Application } from '../application';
+import { IRectangle } from '~/interfaces';
+
+interface IDialogTabAssociation {
+  tabId?: number;
+  getTabInfo?: (tabId: number) => any;
+  setTabInfo?: (tabId: number, ...args: any[]) => void;
+}
+
+type BoundsDisposition = 'move' | 'resize';
+
+interface IDialogShowOptions {
+  name: string;
+  browserWindow: Electron.BrowserWindow;
+  hideTimeout?: number;
+  devtools?: boolean;
+  tabAssociation?: IDialogTabAssociation;
+  onWindowBoundsUpdate?: (disposition: BoundsDisposition) => void;
+  onHide?: (dialog: IDialog) => void;
+  getBounds: () => IRectangle;
+}
+
+interface IDialog {
+  name: string;
+  browserView: BrowserView;
+  id: number;
+  tabIds: number[];
+  _sendTabInfo: (tabId: number) => void;
+  hide: (tabId?: number) => void;
+  handle: (name: string, cb: (...args: any[]) => any) => void;
+  on: (name: string, cb: (...args: any[]) => any) => void;
+  rearrange: (bounds?: IRectangle) => void;
+}
+
+export const roundifyRectangle = (rect: IRectangle): IRectangle => {
+  const newRect: any = { ...rect };
+  Object.keys(newRect).forEach((key) => {
+    if (!isNaN(newRect[key])) newRect[key] = Math.round(newRect[key]);
+  });
+  return newRect;
+};
+
+export class DialogsService {
+  public browserViews: BrowserView[] = [];
+  public browserViewDetails = new Map<number, boolean>();
+  public dialogs: IDialog[] = [];
+
+  public persistentDialogs: PersistentDialog[] = [];
+
+  public run() {
+    this.createBrowserView();
+
+    this.persistentDialogs.push(new SearchDialog());
+    this.persistentDialogs.push(new PreviewDialog());
+  }
+
+  private createBrowserView() {
+    const view = new BrowserView({
+      webPreferences: {
+        nodeIntegration: true,
+        contextIsolation: false,
+        enableRemoteModule: true,
+        webviewTag: true,
+      },
+    });
+
+    view.webContents.loadURL(`about:blank`);
+
+    this.browserViews.push(view);
+
+    this.browserViewDetails.set(view.webContents.id, false);
+
+    return view;
+  }
+
+  public show(options: IDialogShowOptions): IDialog {
+    const {
+      name,
+      browserWindow,
+      getBounds,
+      devtools,
+      onHide,
+      hideTimeout,
+      onWindowBoundsUpdate,
+      tabAssociation,
+    } = options;
+
+    const foundDialog = this.getDynamic(name);
+
+    let browserView = foundDialog
+      ? foundDialog.browserView
+      : this.browserViews.find(
+          (x) => !this.browserViewDetails.get(x.webContents.id),
+        );
+
+    if (!browserView) {
+      browserView = this.createBrowserView();
+    }
+
+    const appWindow = Application.instance.windows.fromBrowserWindow(
+      browserWindow,
+    );
+
+    if (foundDialog && tabAssociation) {
+      foundDialog.tabIds.push(tabAssociation.tabId);
+      foundDialog._sendTabInfo(tabAssociation.tabId);
+    }
+
+    browserWindow.webContents.send('dialog-visibility-change', name, true);
+
+    this.browserViewDetails.set(browserView.webContents.id, true);
+
+    if (foundDialog) {
+      browserWindow.addBrowserView(browserView);
+      foundDialog.rearrange();
+      return null;
+    }
+
+    browserWindow.addBrowserView(browserView);
+    browserView.setBounds({ x: 0, y: 0, width: 1, height: 1 });
+
+    if (devtools) {
+      browserView.webContents.openDevTools({ mode: 'detach' });
+    }
+
+    const tabsEvents: {
+      activate?: (id: number) => void;
+      remove?: (id: number) => void;
+    } = {};
+
+    const windowEvents: {
+      resize?: () => void;
+      move?: () => void;
+    } = {};
+
+    const channels: string[] = [];
+
+    const dialog: IDialog = {
+      browserView,
+      id: browserView.webContents.id,
+      name,
+      tabIds: [tabAssociation?.tabId],
+      _sendTabInfo: (tabId) => {
+        if (tabAssociation.getTabInfo) {
+          const data = tabAssociation.getTabInfo(tabId);
+          browserView.webContents.send('update-tab-info', tabId, data);
+        }
+      },
+      hide: (tabId) => {
+        const { selectedId } = appWindow.viewManager;
+
+        dialog.tabIds = dialog.tabIds.filter(
+          (x) => x !== (tabId || selectedId),
+        );
+
+        if (tabId && tabId !== selectedId) return;
+
+        browserWindow.webContents.send('dialog-visibility-change', name, false);
+
+        browserWindow.removeBrowserView(browserView);
+
+        if (tabAssociation && dialog.tabIds.length > 0) return;
+
+        ipcMain.removeAllListeners(`hide-${browserView.webContents.id}`);
+        channels.forEach((x) => {
+          ipcMain.removeHandler(x);
+          ipcMain.removeAllListeners(x);
+        });
+
+        this.dialogs = this.dialogs.filter((x) => x.id !== dialog.id);
+
+        this.browserViewDetails.set(browserView.webContents.id, false);
+
+        if (this.browserViews.length > 1) {
+          // TODO: garbage collect unused BrowserViews?
+          // this.browserViewDetails.delete(browserView.id);
+          // browserView.destroy();
+          // this.browserViews.splice(1, 1);
+        } else {
+          browserView.webContents.loadURL('about:blank');
+        }
+
+        if (tabAssociation) {
+          appWindow.viewManager.off('activated', tabsEvents.activate);
+          appWindow.viewManager.off('removed', tabsEvents.remove);
+        }
+
+        browserWindow.removeListener('resize', windowEvents.resize);
+        browserWindow.removeListener('move', windowEvents.move);
+
+        if (onHide) onHide(dialog);
+      },
+      handle: (name, cb) => {
+        const channel = `${name}-${browserView.webContents.id}`;
+        ipcMain.handle(channel, (...args) => cb(...args));
+        channels.push(channel);
+      },
+      on: (name, cb) => {
+        const channel = `${name}-${browserView.webContents.id}`;
+        ipcMain.on(channel, (...args) => cb(...args));
+        channels.push(channel);
+      },
+      rearrange: (rect) => {
+        rect = rect || {};
+        browserView.setBounds({
+          x: 0,
+          y: 0,
+          width: 0,
+          height: 0,
+          ...roundifyRectangle(getBounds()),
+          ...roundifyRectangle(rect),
+        });
+      },
+    };
+
+    tabsEvents.activate = (id) => {
+      const visible = dialog.tabIds.includes(id);
+      browserWindow.webContents.send('dialog-visibility-change', name, visible);
+
+      if (visible) {
+        dialog._sendTabInfo(id);
+        browserWindow.removeBrowserView(browserView);
+        browserWindow.addBrowserView(browserView);
+      } else {
+        browserWindow.removeBrowserView(browserView);
+      }
+    };
+
+    tabsEvents.remove = (id) => {
+      dialog.hide(id);
+    };
+
+    const emitWindowBoundsUpdate = (type: BoundsDisposition) => {
+      if (
+        tabAssociation &&
+        !dialog.tabIds.includes(appWindow.viewManager.selectedId)
+      ) {
+        onWindowBoundsUpdate(type);
+      }
+    };
+
+    windowEvents.move = () => {
+      emitWindowBoundsUpdate('move');
+    };
+
+    windowEvents.resize = () => {
+      emitWindowBoundsUpdate('resize');
+    };
+
+    if (tabAssociation) {
+      appWindow.viewManager.on('removed', tabsEvents.remove);
+      appWindow.viewManager.on('activated', tabsEvents.activate);
+    }
+
+    if (onWindowBoundsUpdate) {
+      browserWindow.on('resize', windowEvents.resize);
+      browserWindow.on('move', windowEvents.move);
+    }
+
+    browserView.webContents.once('dom-ready', () => {
+      dialog.rearrange();
+      browserView.webContents.focus();
+    });
+
+    if (process.env.NODE_ENV === 'development') {
+      browserView.webContents.loadURL(`http://localhost:4444/${name}.html`);
+    } else {
+      browserView.webContents.loadURL(
+        join('file://', app.getAppPath(), `build/${name}.html`),
+      );
+    }
+
+    ipcMain.on(`hide-${browserView.webContents.id}`, () => {
+      dialog.hide();
+    });
+
+    if (tabAssociation) {
+      dialog.on('loaded', () => {
+        dialog._sendTabInfo(tabAssociation.tabId);
+      });
+
+      if (tabAssociation.setTabInfo) {
+        dialog.on('update-tab-info', (e, tabId, ...args) => {
+          tabAssociation.setTabInfo(tabId, ...args);
+        });
+      }
+    }
+
+    this.dialogs.push(dialog);
+
+    return dialog;
+  }
+
+  public getBrowserViews = () => {
+    return this.browserViews.concat(
+      Array.from(this.persistentDialogs).map((x) => x.browserView),
+    );
+  };
+
+  public destroy = () => {
+    this.getBrowserViews().forEach((x) => (x.webContents as any).destroy());
+  };
+
+  public sendToAll = (channel: string, ...args: any[]) => {
+    this.getBrowserViews().forEach(
+      (x) =>
+        !x.webContents.isDestroyed() && x.webContents.send(channel, ...args),
+    );
+  };
+
+  public get(name: string) {
+    return this.getDynamic(name) || this.getPersistent(name);
+  }
+
+  public getDynamic(name: string) {
+    return this.dialogs.find((x) => x.name === name);
+  }
+
+  public getPersistent(name: string) {
+    return this.persistentDialogs.find((x) => x.name === name);
+  }
+
+  public isVisible = (name: string) => {
+    return this.getDynamic(name) || this.getPersistent(name)?.visible;
+  };
+}

+ 3 - 0
src/main/services/index.ts

@@ -0,0 +1,3 @@
+export * from './messaging';
+export * from './auto-updater';
+export * from './proxy';

+ 275 - 0
src/main/services/messaging.ts

@@ -0,0 +1,275 @@
+import { ipcMain } from 'electron';
+import { parse } from 'url';
+// import { getPassword, setPassword, deletePassword } from 'keytar';
+
+import { AppWindow } from '../windows';
+import { Application } from '../application';
+import { showMenuDialog } from '../dialogs/menu';
+import { PreviewDialog } from '../dialogs/preview';
+import { IFormFillData, IBookmark } from '~/interfaces';
+import { SearchDialog } from '../dialogs/search';
+
+import * as bookmarkMenu from '../menus/bookmarks';
+import { showFindDialog } from '../dialogs/find';
+import { getFormFillMenuItems } from '../utils';
+import { showAddBookmarkDialog } from '../dialogs/add-bookmark';
+import { showExtensionDialog } from '../dialogs/extension-popup';
+import { showDownloadsDialog } from '../dialogs/downloads';
+import { showZoomDialog } from '../dialogs/zoom';
+import { showTabGroupDialog } from '../dialogs/tabgroup';
+
+export const runMessagingService = (appWindow: AppWindow) => {
+  const { id } = appWindow;
+
+  ipcMain.on(`window-focus-${id}`, () => {
+    appWindow.win.focus();
+    appWindow.webContents.focus();
+  });
+
+  ipcMain.on(`window-toggle-maximize-${id}`, () => {
+    if (appWindow.win.isMaximized()) {
+      appWindow.win.unmaximize();
+    } else {
+      appWindow.win.maximize();
+    }
+  });
+
+  ipcMain.on(`window-minimize-${id}`, () => {
+    appWindow.win.minimize();
+  });
+
+  ipcMain.on(`window-close-${id}`, () => {
+    appWindow.win.close();
+  });
+
+  ipcMain.on(`window-fix-dragging-${id}`, () => {
+    appWindow.fixDragging();
+  });
+
+  ipcMain.on(`show-menu-dialog-${id}`, (e, x, y) => {
+    showMenuDialog(appWindow.win, x, y);
+  });
+
+  ipcMain.on(`search-show-${id}`, (e, data) => {
+    const dialog = Application.instance.dialogs.getPersistent(
+      'search',
+    ) as SearchDialog;
+    dialog.data = data;
+    dialog.show(appWindow.win);
+  });
+
+  ipcMain.handle(`is-dialog-visible-${id}`, (e, dialog) => {
+    return Application.instance.dialogs.isVisible(dialog);
+  });
+
+  ipcMain.on(`show-tab-preview-${id}`, (e, tab) => {
+    const dialog = Application.instance.dialogs.getPersistent(
+      'preview',
+    ) as PreviewDialog;
+    dialog.tab = tab;
+    dialog.show(appWindow.win);
+  });
+
+  ipcMain.on(`hide-tab-preview-${id}`, (e, tab) => {
+    const dialog = Application.instance.dialogs.getPersistent(
+      'preview',
+    ) as PreviewDialog;
+    dialog.hide();
+  });
+
+  ipcMain.on(`find-show-${id}`, () => {
+    showFindDialog(appWindow.win);
+  });
+
+  ipcMain.on(`find-in-page-${id}`, () => {
+    appWindow.send('find');
+  });
+
+  ipcMain.on(`show-add-bookmark-dialog-${id}`, (e, left, top) => {
+    showAddBookmarkDialog(appWindow.win, left, top);
+  });
+
+  if (process.env.ENABLE_EXTENSIONS) {
+    ipcMain.on(`show-extension-popup-${id}`, (e, left, top, url, inspect) => {
+      showExtensionDialog(appWindow.win, left, top, url, inspect);
+    });
+  }
+
+  ipcMain.on(`show-downloads-dialog-${id}`, (e, left, top) => {
+    showDownloadsDialog(appWindow.win, left, top);
+  });
+
+  ipcMain.on(`show-zoom-dialog-${id}`, (e, left, top) => {
+    showZoomDialog(appWindow.win, left, top);
+  });
+
+  ipcMain.on(`show-tabgroup-dialog-${id}`, (e, tabGroup) => {
+    showTabGroupDialog(appWindow.win, tabGroup);
+  });
+
+  ipcMain.on(`edit-tabgroup-${id}`, (e, tabGroup) => {
+    appWindow.send(`edit-tabgroup`, tabGroup);
+  });
+
+  ipcMain.on(`is-incognito-${id}`, (e) => {
+    e.returnValue = appWindow.incognito;
+  });
+
+  if (process.env.ENABLE_AUTOFILL) {
+    // TODO: autofill
+    // ipcMain.on(`form-fill-show-${id}`, async (e, rect, name, value) => {
+    //   const items = await getFormFillMenuItems(name, value);
+
+    //   if (items.length) {
+    //     appWindow.dialogs.formFillDialog.send(`formfill-get-items`, items);
+    //     appWindow.dialogs.formFillDialog.inputRect = rect;
+
+    //     appWindow.dialogs.formFillDialog.resize(
+    //       items.length,
+    //       items.find((r) => r.subtext) != null,
+    //     );
+    //     appWindow.dialogs.formFillDialog.rearrange();
+    //     appWindow.dialogs.formFillDialog.show(false);
+    //   } else {
+    //     appWindow.dialogs.formFillDialog.hide();
+    //   }
+    // });
+
+    // ipcMain.on(`form-fill-hide-${id}`, () => {
+    //   appWindow.dialogs.formFillDialog.hide();
+    // });
+
+    ipcMain.on(
+      `form-fill-update-${id}`,
+      async (e, _id: string, persistent = false) => {
+        const url = appWindow.viewManager.selected.url;
+        const { hostname } = parse(url);
+
+        const item =
+          _id &&
+          (await Application.instance.storage.findOne<IFormFillData>({
+            scope: 'formfill',
+            query: { _id },
+          }));
+
+        if (item && item.type === 'password') {
+          item.fields.password = await getPassword(
+            'wexond',
+            `${hostname}-${item.fields.username}`,
+          );
+        }
+
+        appWindow.viewManager.selected.send(
+          `form-fill-update-${id}`,
+          item,
+          persistent,
+        );
+      },
+    );
+
+    // ipcMain.on(`credentials-show-${id}`, (e, data) => {
+    //   appWindow.dialogs.credentialsDialog.send('credentials-update', data);
+    //   appWindow.dialogs.credentialsDialog.rearrange();
+    //   appWindow.dialogs.credentialsDialog.show();
+    // });
+
+    // ipcMain.on(`credentials-hide-${id}`, () => {
+    //   appWindow.dialogs.credentialsDialog.hide();
+    // });
+
+    ipcMain.on(`credentials-save-${id}`, async (e, data) => {
+      const { username, password, update, oldUsername } = data;
+      const view = appWindow.viewManager.selected;
+      const hostname = view.hostname;
+
+      if (!update) {
+        const item = await Application.instance.storage.insert<IFormFillData>({
+          scope: 'formfill',
+          item: {
+            type: 'password',
+            url: hostname,
+            favicon: appWindow.viewManager.selected.favicon,
+            fields: {
+              username,
+              passLength: password.length,
+            },
+          },
+        });
+
+        appWindow.viewManager.settingsView.webContents.send(
+          'credentials-insert',
+          item,
+        );
+      } else {
+        await Application.instance.storage.update({
+          scope: 'formfill',
+          query: {
+            type: 'password',
+            url: hostname,
+            'fields.username': oldUsername,
+            'fields.passLength': password.length,
+          },
+          value: {
+            'fields.username': username,
+          },
+        });
+
+        appWindow.viewManager.settingsView.webContents.send(
+          'credentials-update',
+          { ...data, hostname },
+        );
+      }
+
+      await setPassword('wexond', `${hostname}-${username}`, password);
+
+      appWindow.send(`has-credentials-${view.id}`, true);
+    });
+
+    ipcMain.on(`credentials-remove-${id}`, async (e, data: IFormFillData) => {
+      const { _id, fields } = data;
+      const view = appWindow.viewManager.selected;
+
+      await Application.instance.storage.remove({
+        scope: 'formfill',
+        query: {
+          _id,
+        },
+      });
+
+      await deletePassword('wexond', `${view.hostname}-${fields.username}`);
+
+      appWindow.viewManager.settingsView.webContents.send(
+        'credentials-remove',
+        _id,
+      );
+    });
+
+    ipcMain.on(
+      'credentials-get-password',
+      async (e, id: string, account: string) => {
+        const password = await getPassword('wexond', account);
+        e.sender.send(id, password);
+      },
+    );
+  }
+
+  ipcMain.handle(
+    `show-bookmarks-bar-dropdown-${id}`,
+    (
+      event,
+      folderId: string,
+      bookmarks: IBookmark[],
+      { x, y }: { x: number; y: number },
+    ) => {
+      bookmarkMenu
+        .createDropdown(appWindow, folderId, bookmarks)
+        .popup({ x: Math.floor(x), y: Math.floor(y), window: appWindow.win });
+    },
+  );
+  ipcMain.handle(
+    `show-bookmarks-bar-context-menu-${id}`,
+    (event, item: IBookmark) => {
+      bookmarkMenu.createMenu(appWindow, item).popup({ window: appWindow.win });
+    },
+  );
+};

+ 17 - 0
src/main/services/proxy.ts

@@ -0,0 +1,17 @@
+import { session } from 'electron';
+import { bootstrap,createGlobalProxyAgent  } from "global-agent"
+
+export const proxyService  = () => {
+
+  bootstrap();
+  const agent = createGlobalProxyAgent();
+  agent.HTTP_PROXY = 'http://183.6.80.243:10808';
+  agent.HTTPS_PROXY = 'https://183.6.80.243:10808';
+  agent.NO_PROXY = '';
+
+  // 启用详细日志
+  process.env.GLOBAL_AGENT_LOG_LEVEL = 'debug';
+
+  // 设置连接超时
+  process.env.GLOBAL_AGENT_SOCKET_CONNECTION_TIMEOUT = '30000';
+}

+ 508 - 0
src/main/services/storage.ts

@@ -0,0 +1,508 @@
+import { ipcMain, dialog } from 'electron';
+import * as Datastore from 'nedb';
+import { fromBuffer } from 'file-type';
+import * as icojs from 'icojs';
+
+import { getPath } from '~/utils';
+import {
+  IFindOperation,
+  IInsertOperation,
+  IRemoveOperation,
+  IUpdateOperation,
+  IHistoryItem,
+  IVisitedItem,
+  IFavicon,
+  IBookmark,
+} from '~/interfaces';
+import { countVisitedTimes } from '~/utils/history';
+import { promises } from 'fs';
+import { Application } from '../application';
+import { requestURL } from '../network/request';
+import * as parse from 'node-bookmarks-parser';
+
+interface Databases {
+  [key: string]: Datastore;
+}
+
+const convertIcoToPng = async (icoData: Buffer): Promise<ArrayBuffer> => {
+  return (await icojs.parse(icoData, 'image/png'))[0].buffer;
+};
+
+const encodeHref = (str: string) => {
+  return (str || '').replace(/"/g, '&quot;');
+};
+
+const encodeTitle = (str: string) => {
+  return (str || '')
+    .replace(/</g, '&lt;')
+    .replace(/>/g, '&gt;')
+    .replace(/"/g, '&quot;');
+};
+
+const indentLength = 4;
+const indentType = ' ';
+
+export class StorageService {
+  public databases: Databases = {
+    favicons: null,
+    bookmarks: null,
+    history: null,
+    formfill: null,
+    startupTabs: null,
+    permissions: null,
+  };
+
+  public history: IHistoryItem[] = [];
+
+  public bookmarks: IBookmark[] = [];
+
+  public historyVisited: IVisitedItem[] = [];
+
+  public favicons: Map<string, string> = new Map();
+
+  public constructor() {
+    ipcMain.handle('storage-get', async (e, data: IFindOperation) => {
+      return await this.find(data);
+    });
+
+    ipcMain.handle('storage-get-one', async (e, data: IFindOperation) => {
+      return await this.findOne(data);
+    });
+
+    ipcMain.handle('storage-insert', async (e, data: IInsertOperation) => {
+      return await this.insert(data);
+    });
+
+    ipcMain.handle('storage-remove', async (e, data: IRemoveOperation) => {
+      return await this.remove(data);
+    });
+
+    ipcMain.handle('storage-update', async (e, data: IUpdateOperation) => {
+      return await this.update(data);
+    });
+
+    ipcMain.handle('import-bookmarks', async () => {
+      const dialogRes = await dialog.showOpenDialog({
+        filters: [{ name: 'Bookmark file', extensions: ['html'] }],
+      });
+
+      try {
+        const file = await promises.readFile(dialogRes.filePaths[0], 'utf8');
+        return parse(file);
+      } catch (err) {
+        console.error(err);
+      }
+
+      return [];
+    });
+
+    ipcMain.handle('export-bookmarks', async () => {
+      await this.exportBookmarks();
+    });
+
+    ipcMain.handle('bookmarks-get', (e) => {
+      return this.bookmarks;
+    });
+
+    ipcMain.on('bookmarks-remove', (e, ids: string[]) => {
+      ids.forEach((x) => this.removeBookmark(x));
+      Application.instance.windows.list.forEach((x) => {
+        x.viewManager.selected.updateBookmark();
+      });
+    });
+
+    ipcMain.handle('bookmarks-add', async (e, item) => {
+      const b = await this.addBookmark(item);
+
+      Application.instance.windows.list.forEach((x) => {
+        x.viewManager.selected.updateBookmark();
+      });
+
+      return b;
+    });
+
+    ipcMain.handle('bookmarks-get-folders', async (e) => {
+      return this.bookmarks.filter((x) => x.isFolder);
+    });
+
+    ipcMain.on('bookmarks-update', async (e, id, change) => {
+      await this.updateBookmark(id, change);
+    });
+
+    ipcMain.handle('history-get', (e) => {
+      return this.history;
+    });
+
+    ipcMain.on('history-remove', (e, ids: string[]) => {
+      this.history = this.history.filter((x) => ids.indexOf(x._id) === -1);
+      ids.forEach((x) => this.remove({ scope: 'history', query: { _id: x } }));
+    });
+
+    ipcMain.handle('topsites-get', (e, count) => {
+      return this.historyVisited
+        .filter((x) => x.title && x.title !== '')
+        .slice(0, count);
+    });
+  }
+
+  public find<T>(data: IFindOperation): Promise<T[]> {
+    const { scope, query } = data;
+
+    return new Promise((resolve, reject) => {
+      this.databases[scope].find(query, (err: any, docs: any) => {
+        if (err) reject(err);
+        resolve(docs);
+      });
+    });
+  }
+
+  public findOne<T>(data: IFindOperation): Promise<T> {
+    const { scope, query } = data;
+
+    return new Promise((resolve, reject) => {
+      this.databases[scope].findOne(query, (err: any, doc: any) => {
+        if (err) reject(err);
+        resolve(doc);
+      });
+    });
+  }
+
+  public insert<T>(data: IInsertOperation): Promise<T> {
+    const { scope, item } = data;
+
+    return new Promise((resolve, reject) => {
+      this.databases[scope].insert(item, (err: any, doc: any) => {
+        if (err) reject(err);
+        resolve(doc);
+      });
+    });
+  }
+
+  public remove(data: IRemoveOperation): Promise<number> {
+    const { scope, query, multi } = data;
+
+    return new Promise((resolve, reject) => {
+      this.databases[scope].remove(
+        query,
+        { multi },
+        (err: any, removed: number) => {
+          if (err) reject(err);
+          resolve(removed);
+        },
+      );
+    });
+  }
+
+  public update(data: IUpdateOperation): Promise<number> {
+    const { scope, query, value, multi } = data;
+
+    return new Promise((resolve, reject) => {
+      this.databases[scope].update(
+        query,
+        { $set: value },
+        { multi },
+        (err: any, replaced: number) => {
+          if (err) reject(err);
+          resolve(replaced);
+        },
+      );
+    });
+  }
+
+  public async run() {
+    for (const key in this.databases) {
+      this.databases[key] = this.createDatabase(key.toLowerCase());
+    }
+    this.loadBookmarks();
+    await this.loadFavicons();
+    this.loadHistory();
+  }
+
+  private async loadFavicons() {
+    (await this.find<IFavicon>({ scope: 'favicons', query: {} })).forEach(
+      (favicon) => {
+        const { data } = favicon;
+
+        if (this.favicons.get(favicon.url) == null) {
+          this.favicons.set(favicon.url, data);
+        }
+      },
+    );
+  }
+
+  private async loadHistory() {
+    const items: IHistoryItem[] = await this.find({
+      scope: 'history',
+      query: {},
+    });
+
+    items.sort((a, b) => {
+      let aDate = a.date;
+      let bDate = b.date;
+
+      if (typeof aDate === 'string') {
+        aDate = new Date(a.date).getTime();
+        bDate = new Date(b.date).getTime();
+      }
+
+      return aDate - bDate;
+    });
+
+    this.history = items;
+
+    this.historyVisited = countVisitedTimes(items);
+
+    this.historyVisited = this.historyVisited.map((x) => ({
+      ...x,
+      favicon: this.favicons.get(x.favicon),
+    }));
+  }
+
+  private async loadBookmarks() {
+    const items = await this.find<IBookmark>({ scope: 'bookmarks', query: {} });
+
+    items.sort((a, b) => a.order - b.order);
+
+    let barFolder = items.find((x) => x.static === 'main');
+    let otherFolder = items.find((x) => x.static === 'other');
+    let mobileFolder = items.find((x) => x.static === 'mobile');
+
+    this.bookmarks = items;
+
+    if (!barFolder) {
+      barFolder = await this.addBookmark({
+        static: 'main',
+        isFolder: true,
+      });
+
+      for (const item of items) {
+        if (!item.static) {
+          await this.updateBookmark(item._id, { parent: barFolder._id });
+        }
+      }
+    }
+
+    if (!otherFolder) {
+      otherFolder = await this.addBookmark({
+        static: 'other',
+        isFolder: true,
+      });
+    }
+
+    if (!mobileFolder) {
+      mobileFolder = await this.addBookmark({
+        static: 'mobile',
+        isFolder: true,
+      });
+    }
+  }
+
+  public removeBookmark(id: string) {
+    const item = this.bookmarks.find((x) => x._id === id);
+
+    if (!item) return;
+
+    this.bookmarks = this.bookmarks.filter((x) => x._id !== id);
+    const parent = this.bookmarks.find((x) => x._id === item.parent);
+
+    parent.children = parent.children.filter((x) => x !== id);
+    this.updateBookmark(item.parent, { children: parent.children });
+
+    this.remove({ scope: 'bookmarks', query: { _id: id } });
+
+    if (item.isFolder) {
+      this.bookmarks = this.bookmarks.filter((x) => x.parent !== id);
+      const removed = this.bookmarks.filter((x) => x.parent === id);
+
+      this.remove({ scope: 'bookmarks', query: { parent: id }, multi: true });
+
+      for (const i of removed) {
+        if (i.isFolder) {
+          this.removeBookmark(i._id);
+        }
+      }
+    }
+    Application.instance.windows.broadcast('reload-bookmarks');
+  }
+
+  public async updateBookmark(id: string, change: IBookmark) {
+    const index = this.bookmarks.indexOf(
+      this.bookmarks.find((x) => x._id === id),
+    );
+    this.bookmarks[index] = { ...this.bookmarks[index], ...change };
+
+    await this.update({
+      scope: 'bookmarks',
+      query: { _id: id },
+      value: change,
+    });
+
+    if (change.parent) {
+      const parent = this.bookmarks.find((x) => x._id === change.parent);
+      if (!parent.children.includes(change._id))
+        await this.updateBookmark(parent._id, {
+          children: [...parent.children, change._id],
+        });
+    }
+
+    Application.instance.windows.broadcast('reload-bookmarks');
+  }
+
+  public async addBookmark(item: IBookmark): Promise<IBookmark> {
+    if (item.parent === undefined) {
+      item.parent = null;
+    }
+
+    if (item.parent === null && !item.static) {
+      throw new Error('Parent bookmark should be specified');
+    }
+
+    if (item.isFolder) {
+      item.children = item.children || [];
+    } else {
+    }
+
+    if (item.order === undefined) {
+      item.order = this.bookmarks.filter((x) => !Boolean(x.static)).length;
+    }
+
+    const doc = await this.insert<IBookmark>({ item, scope: 'bookmarks' });
+
+    if (item.parent) {
+      const parent = this.bookmarks.find((x) => x._id === item.parent);
+      await this.updateBookmark(parent._id, {
+        children: [...parent.children, doc._id],
+      });
+    }
+
+    this.bookmarks.push(doc);
+
+    Application.instance.windows.broadcast('reload-bookmarks');
+
+    return doc;
+  }
+
+  private createDatabase = (name: string) => {
+    return new Datastore({
+      filename: getPath(`storage/${name}.db`),
+      autoload: true,
+    });
+  };
+
+  public addFavicon = async (url: string): Promise<string> => {
+    if (!this.favicons.get(url)) {
+      const res = await requestURL(url);
+
+      if (res.statusCode === 404) {
+        throw new Error('404 favicon not found');
+      }
+
+      let data = Buffer.from(res.data, 'binary');
+
+      const type = await fromBuffer(data);
+
+      if (type && type.ext === 'ico') {
+        data = Buffer.from(new Uint8Array(await convertIcoToPng(data)));
+      }
+
+      const str = `data:${(await fromBuffer(data)).ext};base64,${data.toString(
+        'base64',
+      )}`;
+
+      this.insert({
+        scope: 'favicons',
+        item: {
+          url,
+          data: str,
+        },
+      });
+
+      this.favicons.set(url, str);
+
+      return str;
+    } else {
+      return this.favicons.get(url);
+    }
+  };
+
+  private createBookmarkArray = (
+    parentFolderId: string = null,
+    first = true,
+    depth = 1,
+  ): string[] => {
+    let payload: string[] = [];
+    let title;
+    const bookmarks = this.bookmarks.filter((x) => x.parent === parentFolderId);
+    const indentFirst = indentType.repeat(depth * indentLength);
+    const indentNext = !first
+      ? indentFirst
+      : indentType.repeat((depth + 1) * indentLength);
+
+    if (first) payload.push(`${indentFirst}<DL><p>`);
+
+    for (const bookmark of bookmarks) {
+      if (!bookmark.isFolder && bookmark.url) {
+        title = encodeTitle(bookmark.title);
+        const href = encodeHref(bookmark.url);
+        let icon = bookmark.favicon;
+
+        if (!icon.startsWith('data:')) {
+          icon = this.favicons.get(icon);
+        }
+
+        payload.push(
+          `${indentNext}<DT><A HREF="${href}" ICON="${icon}">${title}</A>`,
+        );
+      } else if (bookmark.isFolder) {
+        title = encodeTitle(bookmark.title);
+        payload.push(`${indentNext}<DT><H3>${title}</H3>`);
+        payload = payload.concat(
+          this.createBookmarkArray(bookmark._id, true, depth + 1),
+        );
+      }
+    }
+
+    if (first) payload.push(`${indentFirst}</DL><p>`);
+
+    return payload;
+  };
+
+  public exportBookmarks = async () => {
+    const { filePath, canceled } = await dialog.showSaveDialog({
+      filters: [{ name: 'Bookmark file', extensions: ['html'] }],
+    });
+
+    if (canceled) return;
+
+    const breakTag = process.platform === 'win32' ? '\r\n' : '\n';
+    const documentTitle = 'Bookmarks';
+
+    const bar = this.createBookmarkArray(
+      this.bookmarks.find((x) => x.static === 'main')._id,
+    );
+
+    const other = this.createBookmarkArray(
+      this.bookmarks.find((x) => x.static === 'other')._id,
+      false,
+    );
+
+    const html = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
+<!-- This is an automatically generated file.
+    It will be read and overwritten.
+    DO NOT EDIT! -->
+<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
+<TITLE>${documentTitle}</TITLE>
+<H1>${documentTitle}</H1>
+<DL><p>
+    <DT><H3 PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
+${bar.join(breakTag)}
+${other.join(breakTag)}
+</DL><p>`;
+
+    try {
+      await promises.writeFile(filePath, html, 'utf8');
+    } catch (err) {
+      console.error(err);
+    }
+  };
+}

+ 379 - 0
src/main/sessions-service.ts

@@ -0,0 +1,379 @@
+import { session, ipcMain, app } from 'electron';
+import { getPath, makeId } from '~/utils';
+import { promises, existsSync } from 'fs';
+import { resolve, basename, parse, extname } from 'path';
+import { Application } from './application';
+import { registerProtocol } from './models/protocol';
+import * as url from 'url';
+import { IDownloadItem, BrowserActionChangeType } from '~/interfaces';
+import { parseCrx } from '~/utils/crx';
+import { pathExists } from '~/utils/files';
+import { extractZip } from '~/utils/zip';
+import { extensions, _setFallbackSession } from 'electron-extensions';
+import { requestPermission } from './dialogs/permissions';
+import * as rimraf from 'rimraf';
+import { promisify } from 'util';
+
+const rf = promisify(rimraf);
+
+// TODO: sessions should be separate.  This structure actually doesn't make sense.
+export class SessionsService {
+  public view = session.fromPartition('persist:view');
+  public viewIncognito = session.fromPartition('view_incognito');
+
+  public incognitoExtensionsLoaded = false;
+  public extensionsLoaded = false;
+
+  public extensions: Electron.Extension[] = [];
+
+  public constructor() {
+    registerProtocol(this.view);
+    registerProtocol(this.viewIncognito);
+
+    this.clearCache('incognito');
+
+    if (process.env.ENABLE_EXTENSIONS) {
+      extensions.initializeSession(
+        this.view,
+        `${app.getAppPath()}/build/extensions-preload.bundle.js`,
+      );
+
+      ipcMain.on('load-extensions', () => {
+        this.loadExtensions();
+      });
+
+      ipcMain.handle('get-extensions', () => {
+        return this.extensions;
+      });
+    }
+
+    /*
+    // TODO:
+    ipcMain.handle(`inspect-extension`, (e, incognito, id) => {
+      const context = incognito ? this.extensionsIncognito : this.extensions;
+      context.extensions[id].backgroundPage.webContents.openDevTools();
+    });
+    */
+
+    this.view.setPermissionRequestHandler(
+      async (webContents, permission, callback, details) => {
+        const window = Application.instance.windows.findByBrowserView(
+          webContents.id,
+        );
+
+        if (webContents.id !== window.viewManager.selectedId) return;
+
+        if (permission === 'fullscreen') {
+          callback(true);
+        } else {
+          try {
+            const { hostname } = url.parse(details.requestingUrl);
+            const perm: any = await Application.instance.storage.findOne({
+              scope: 'permissions',
+              query: {
+                url: hostname,
+                permission,
+                mediaTypes: JSON.stringify(details.mediaTypes) || '',
+              },
+            });
+
+            if (!perm) {
+              const response = await requestPermission(
+                window.win,
+                permission,
+                webContents.getURL(),
+                details,
+                webContents.id,
+              );
+
+              callback(response);
+
+              await Application.instance.storage.insert({
+                scope: 'permissions',
+                item: {
+                  url: hostname,
+                  permission,
+                  type: response ? 1 : 2,
+                  mediaTypes: JSON.stringify(details.mediaTypes) || '',
+                },
+              });
+            } else {
+              callback(perm.type === 1);
+            }
+          } catch (e) {
+            callback(false);
+          }
+        }
+      },
+    );
+
+    const getDownloadItem = (
+      item: Electron.DownloadItem,
+      id: string,
+    ): IDownloadItem => ({
+      fileName: basename(item.savePath),
+      receivedBytes: item.getReceivedBytes(),
+      totalBytes: item.getTotalBytes(),
+      savePath: item.savePath,
+      id,
+    });
+
+    const downloadsDialog = () =>
+      Application.instance.dialogs.getDynamic('downloads-dialog')?.browserView
+        ?.webContents;
+
+    const downloads: IDownloadItem[] = [];
+
+    ipcMain.handle('get-downloads', () => {
+      return downloads;
+    });
+
+    // TODO(sentialx): clean up the download listeners
+    this.view.on('will-download', (event, item, webContents) => {
+      const fileName = item.getFilename();
+      const id = makeId(32);
+      const window = Application.instance.windows.findByBrowserView(
+        webContents.id,
+      );
+
+      if (!Application.instance.settings.object.downloadsDialog) {
+        const downloadsPath =
+          Application.instance.settings.object.downloadsPath;
+        let i = 1;
+        let savePath = resolve(downloadsPath, fileName);
+
+        while (existsSync(savePath)) {
+          const { name, ext } = parse(fileName);
+          savePath = resolve(downloadsPath, `${name} (${i})${ext}`);
+          i++;
+        }
+
+        item.savePath = savePath;
+      }
+
+      const downloadItem = getDownloadItem(item, id);
+      downloads.push(downloadItem);
+
+      downloadsDialog()?.send('download-started', downloadItem);
+      window.send('download-started', downloadItem);
+
+      item.on('updated', (event, state) => {
+        if (state === 'interrupted') {
+          console.log('Download is interrupted but can be resumed');
+        } else if (state === 'progressing') {
+          if (item.isPaused()) {
+            console.log('Download is paused');
+          }
+        }
+
+        const data = getDownloadItem(item, id);
+
+        downloadsDialog()?.send('download-progress', data);
+        window.send('download-progress', data);
+
+        Object.assign(downloadItem, data);
+      });
+      item.once('done', async (event, state) => {
+        if (state === 'completed') {
+          const dialog = downloadsDialog();
+          dialog?.send('download-completed', id);
+          window.send('download-completed', id, !!dialog);
+
+          downloadItem.completed = true;
+
+          if (process.env.ENABLE_EXTENSIONS && extname(fileName) === '.crx') {
+            const crxBuf = await promises.readFile(item.savePath);
+            const crxInfo = parseCrx(crxBuf);
+
+            if (!crxInfo.id) {
+              crxInfo.id = makeId(32);
+            }
+
+            const extensionsPath = getPath('extensions');
+            const path = resolve(extensionsPath, crxInfo.id);
+            const manifestPath = resolve(path, 'manifest.json');
+
+            if (await pathExists(path)) {
+              console.log('Extension is already installed');
+              return;
+            }
+
+            await extractZip(crxInfo.zip, path);
+
+            const extension = await this.view.loadExtension(path);
+
+            if (crxInfo.publicKey) {
+              const manifest = JSON.parse(
+                await promises.readFile(manifestPath, 'utf8'),
+              );
+
+              manifest.key = crxInfo.publicKey.toString('base64');
+
+              await promises.writeFile(
+                manifestPath,
+                JSON.stringify(manifest, null, 2),
+              );
+            }
+
+            window.send('load-browserAction', extension);
+          }
+        } else {
+          console.log(`Download failed: ${state}`);
+        }
+      });
+    });
+
+    // 设置代理
+    // const username = 'zzf1'
+    // const password = 'zzf1s'
+    // const proxyHost = '183.146.16.172'
+    // const proxyPort = '19080'
+    // const proxyRules = `socks5://${username}:${password}@${proxyHost}:${proxyPort}`
+
+    // session.defaultSession.setProxy({
+    //   proxyRules: proxyRules,
+    //   proxyBypassRules: '<local>'
+    // }).then(() => {
+    //   console.log('代理设置成功');
+    // }).catch(err => {
+    //   console.error('代理设置失败:', err);
+    // });
+
+    session.defaultSession.on('will-download', (event, item, webContents) => {
+      const id = makeId(32);
+      const window = Application.instance.windows.list.find(
+        (x) => x && x.webContents.id === webContents.id,
+      );
+
+      const downloadItem = getDownloadItem(item, id);
+      downloads.push(downloadItem);
+
+      downloadsDialog()?.send('download-started', downloadItem);
+      window.send('download-started', downloadItem);
+
+      item.on('updated', (event, state) => {
+        if (state === 'interrupted') {
+          console.log('Download is interrupted but can be resumed');
+        } else if (state === 'progressing') {
+          if (item.isPaused()) {
+            console.log('Download is paused');
+          }
+        }
+
+        const data = getDownloadItem(item, id);
+
+        Object.assign(downloadItem, data);
+
+        downloadsDialog()?.send('download-progress', data);
+        window.send('download-progress', data);
+      });
+      item.once('done', async (event, state) => {
+        const dialog = downloadsDialog();
+        if (state === 'completed') {
+          dialog?.send('download-completed', id);
+          window.send('download-completed', id, !!dialog);
+
+          downloadItem.completed = true;
+        } else {
+          console.log(`Download failed: ${state}`);
+        }
+      });
+    });
+
+    ipcMain.on('clear-browsing-data', () => {
+      this.clearCache('normal');
+      this.clearCache('incognito');
+    });
+  }
+
+  public clearCache(session: 'normal' | 'incognito') {
+    const ses = session === 'incognito' ? this.viewIncognito : this.view;
+
+    ses.clearCache().catch((err) => {
+      console.error(err);
+    });
+
+    ses.clearStorageData({
+      storages: [
+        'appcache',
+        'cookies',
+        'filesystem',
+        'indexdb',
+        'localstorage',
+        'shadercache',
+        'websql',
+        'serviceworkers',
+        'cachestorage',
+      ],
+    });
+  }
+
+  public unloadIncognitoExtensions() {
+    /*
+    TODO(sentialx): unload incognito extensions
+    this.incognitoExtensionsLoaded = false;
+    */
+  }
+
+  // Loading extensions in an off the record BrowserContext is not supported.
+  public async loadExtensions() {
+    if (!process.env.ENABLE_EXTENSIONS) return;
+
+    const context = this.view;
+
+    if (this.extensionsLoaded) return;
+
+    const extensionsPath = getPath('extensions');
+    const dirs = await promises.readdir(extensionsPath);
+
+    for (const dir of dirs) {
+      try {
+        const path = resolve(extensionsPath, dir);
+        const extension = await context.loadExtension(path);
+
+        this.extensions.push(extension);
+
+        for (const window of Application.instance.windows.list) {
+          window.send('load-browserAction', extension);
+        }
+      } catch (e) {
+        console.error(e);
+      }
+    }
+
+    /*if (session === 'incognito') {
+      this.incognitoExtensionsLoaded = true;
+    }*/
+
+    this.extensionsLoaded = true;
+  }
+
+  async uninstallExtension(id: string) {
+    if (!process.env.ENABLE_EXTENSIONS) return;
+
+    const extension = this.view.getExtension(id);
+    if (!extension) return;
+
+    await this.view.removeExtension(id);
+
+    await rf(extension.path);
+  }
+
+  public onCreateTab = async (details: chrome.tabs.CreateProperties) => {
+    const view = Application.instance.windows.list
+      .find((x) => x.win.id === details.windowId)
+      .viewManager.create(details, false, true);
+
+    return view.id;
+  };
+
+  public onBrowserActionUpdate = (
+    extensionId: string,
+    action: BrowserActionChangeType,
+    details: any,
+  ) => {
+    Application.instance.windows.list.forEach((w) => {
+      w.send('set-browserAction-info', extensionId, action, details);
+    });
+  };
+}

+ 48 - 0
src/main/user-agent.ts

@@ -0,0 +1,48 @@
+import { app } from 'electron';
+
+const REMOVE_CHROME_COMPONENT_PATTERNS = [
+  /^https:\/\/accounts\.google\.com(\/|$)/,
+];
+
+const CHROME_COMPONENT_PATTERN = / Chrome\\?.([^\s]+)/g;
+
+const COMPONENTS_TO_REMOVE = [
+  / Electron\\?.([^\s]+)/g,
+  ` ${app.name}/${app.getVersion()}`,
+];
+
+// TODO(sentialx): script to update stable Chrome version?
+const COMPONENTS_TO_REPLACE: [string | RegExp, string][] = [
+  [CHROME_COMPONENT_PATTERN, ' Chrome/87.0.4280.88'],
+];
+
+const urlMatchesPatterns = (url: string, patterns: RegExp[]) =>
+  patterns.some((pattern) => url.match(pattern));
+
+/**
+ * Checks if a given url is suitable for removal of Chrome
+ * component from the user agent string.
+ * @param url
+ */
+const shouldRemoveChromeString = (url: string) =>
+  urlMatchesPatterns(url, REMOVE_CHROME_COMPONENT_PATTERNS);
+
+export const getUserAgentForURL = (userAgent: string, url: string) => {
+  let componentsToRemove = [...COMPONENTS_TO_REMOVE];
+
+  // For accounts.google.com, we remove Chrome/*.* component
+  // from the user agent, to fix compatibility issues on Google Sign In.
+  // WATCH: https://developers.googleblog.com/2020/08/guidance-for-our-effort-to-block-less-secure-browser-and-apps.html
+  if (shouldRemoveChromeString(url)) {
+    componentsToRemove = [...componentsToRemove, CHROME_COMPONENT_PATTERN];
+  }
+
+  // Replace the components.
+  [
+    // Convert components to remove to pairs.
+    ...componentsToRemove.map((x): [string | RegExp, string] => [x, '']),
+    ...COMPONENTS_TO_REPLACE,
+  ].forEach((x) => (userAgent = userAgent.replace(x[0], x[1])));
+
+  return userAgent;
+};

+ 48 - 0
src/main/utils/form-fill.ts

@@ -0,0 +1,48 @@
+import { parse } from 'url';
+
+import { IFormFillData } from '~/interfaces';
+import { getFormFillValue, getFormFillSubValue } from '~/utils/form-fill';
+import { Application } from '../application';
+
+const getType = (name: string) => {
+  return name === 'username' || name === 'login' || name === 'password'
+    ? 'password'
+    : 'address';
+};
+
+export const getFormFillMenuItems = async (name: string, value: string) => {
+  const dataType = getType(name);
+  const { url } = Application.instance.windows.current.viewManager.selected;
+  const { hostname } = parse(url);
+
+  const items = await Application.instance.storage.find<IFormFillData>({
+    scope: 'formfill',
+    query: {
+      type: dataType,
+    },
+  });
+
+  return items
+    .map((item: IFormFillData) => {
+      const text = getFormFillValue(name, item, true);
+      const subtext = getFormFillSubValue(name, item);
+
+      if (dataType === 'password' && item.url !== hostname) {
+        return null;
+      }
+
+      if (
+        text &&
+        (name !== 'password' ? text.startsWith(value) : !value.length)
+      ) {
+        return {
+          _id: item._id,
+          text,
+          subtext,
+        };
+      }
+
+      return null;
+    })
+    .filter((r) => r);
+};

+ 1 - 0
src/main/utils/index.ts

@@ -0,0 +1 @@
+export * from './form-fill';

+ 265 - 0
src/main/view-manager.ts

@@ -0,0 +1,265 @@
+import { ipcMain } from 'electron';
+import { VIEW_Y_OFFSET } from '~/constants/design';
+import { View } from './view';
+import { AppWindow } from './windows';
+import { WEBUI_BASE_URL } from '~/constants/files';
+
+import {
+  ZOOM_FACTOR_MIN,
+  ZOOM_FACTOR_MAX,
+  ZOOM_FACTOR_INCREMENT,
+} from '~/constants/web-contents';
+import { extensions } from 'electron-extensions';
+import { EventEmitter } from 'events';
+import { Application } from './application';
+
+export class ViewManager extends EventEmitter {
+  public views = new Map<number, View>();
+  public selectedId = 0;
+  public _fullscreen = false;
+
+  public incognito: boolean;
+
+  private window: AppWindow;
+
+  public get fullscreen() {
+    return this._fullscreen;
+  }
+
+  public set fullscreen(val: boolean) {
+    this._fullscreen = val;
+    this.fixBounds();
+  }
+
+  public constructor(window: AppWindow, incognito: boolean) {
+    super();
+
+    this.window = window;
+    this.incognito = incognito;
+
+    const { id } = window.win;
+    ipcMain.handle(`view-create-${id}`, (e, details) => {
+      return this.create(details, false, false).id;
+    });
+
+    ipcMain.handle(`views-create-${id}`, (e, options) => {
+      return options.map((option: any) => {
+        return this.create(option, false, false).id;
+      });
+    });
+
+    ipcMain.on(`add-tab-${id}`, (e, details) => {
+      this.create(details);
+    });
+
+    ipcMain.on('Print', (e, details) => {
+      this.views.get(this.selectedId).webContents.print();
+    });
+
+    ipcMain.handle(`view-select-${id}`, (e, id: number, focus: boolean) => {
+      if (process.env.ENABLE_EXTENSIONS) {
+        extensions.tabs.activate(id, focus);
+      } else {
+        this.select(id, focus);
+      }
+    });
+
+    ipcMain.on(`view-destroy-${id}`, (e, id: number) => {
+      this.destroy(id);
+    });
+
+    ipcMain.on(`mute-view-${id}`, (e, tabId: number) => {
+      const view = this.views.get(tabId);
+      view.webContents.setAudioMuted(true);
+    });
+
+    ipcMain.on(`unmute-view-${id}`, (e, tabId: number) => {
+      const view = this.views.get(tabId);
+      view.webContents.setAudioMuted(false);
+    });
+
+    ipcMain.on(`browserview-clear-${id}`, () => {
+      this.clear();
+    });
+
+    ipcMain.on('change-zoom', (e, zoomDirection) => {
+      const newZoomFactor =
+        this.selected.webContents.zoomFactor +
+        (zoomDirection === 'in'
+          ? ZOOM_FACTOR_INCREMENT
+          : -ZOOM_FACTOR_INCREMENT);
+
+      if (
+        newZoomFactor <= ZOOM_FACTOR_MAX &&
+        newZoomFactor >= ZOOM_FACTOR_MIN
+      ) {
+        this.selected.webContents.zoomFactor = newZoomFactor;
+        this.selected.emitEvent(
+          'zoom-updated',
+          this.selected.webContents.zoomFactor,
+        );
+      } else {
+        e.preventDefault();
+      }
+      this.emitZoomUpdate();
+    });
+
+    ipcMain.on('reset-zoom', (e) => {
+      this.selected.webContents.zoomFactor = 1;
+      this.selected.emitEvent(
+        'zoom-updated',
+        this.selected.webContents.zoomFactor,
+      );
+      this.emitZoomUpdate();
+    });
+
+    this.setBoundsListener();
+  }
+
+  public get selected() {
+    return this.views.get(this.selectedId);
+  }
+
+  public get settingsView() {
+    return Object.values(this.views).find((r) =>
+      r.url.startsWith(`${WEBUI_BASE_URL}settings`),
+    );
+  }
+
+  public create(
+    details: chrome.tabs.CreateProperties,
+    isNext = false,
+    sendMessage = true,
+  ) {
+    const view = new View(this.window, details.url, this.incognito);
+
+    const { webContents } = view.browserView;
+    const { id } = view;
+
+    this.views.set(id, view);
+
+    if (process.env.ENABLE_EXTENSIONS) {
+      extensions.tabs.observe(webContents);
+    }
+
+    webContents.once('destroyed', () => {
+      this.views.delete(id);
+    });
+
+    if (sendMessage) {
+      this.window.send('create-tab', { ...details }, isNext, id);
+    }
+    return view;
+  }
+
+  public clear() {
+    this.window.win.setBrowserView(null);
+    Object.values(this.views).forEach((x) => x.destroy());
+  }
+
+  public select(id: number, focus = true) {
+    const { selected } = this;
+    const view = this.views.get(id);
+
+    if (!view) {
+      return;
+    }
+
+    this.selectedId = id;
+
+    if (selected) {
+      this.window.win.removeBrowserView(selected.browserView);
+    }
+
+    this.window.win.addBrowserView(view.browserView);
+
+    if (focus) {
+      // Also fixes switching tabs with Ctrl + Tab
+      view.webContents.focus();
+    } else {
+      this.window.webContents.focus();
+    }
+
+    this.window.updateTitle();
+    view.updateBookmark();
+
+    this.fixBounds();
+
+    view.updateNavigationState();
+
+    this.emit('activated', id);
+
+    // TODO: this.emitZoomUpdate(false);
+  }
+
+  public async fixBounds() {
+    const view = this.selected;
+
+    if (!view) return;
+
+    const { width, height } = this.window.win.getContentBounds();
+
+    const toolbarContentHeight = await this.window.win.webContents
+      .executeJavaScript(`
+      document.getElementById('app').offsetHeight
+    `);
+
+    const newBounds = {
+      x: 0,
+      y: this.fullscreen ? 0 : toolbarContentHeight,
+      width,
+      height: this.fullscreen ? height : height - toolbarContentHeight,
+    };
+
+    if (newBounds !== view.bounds) {
+      view.browserView.setBounds(newBounds);
+      view.bounds = newBounds;
+    }
+  }
+
+  private setBoundsListener() {
+    // resize the BrowserView's height when the toolbar height changes
+    // ex: when the bookmarks bar appears
+    this.window.webContents.executeJavaScript(`
+        const {ipcRenderer} = require('electron');
+        const resizeObserver = new ResizeObserver(([{ contentRect }]) => {
+          ipcRenderer.send('resize-height');
+        });
+        const app = document.getElementById('app');
+        resizeObserver.observe(app);
+      `);
+
+    this.window.webContents.on('ipc-message', (e, message) => {
+      if (message === 'resize-height') {
+        this.fixBounds();
+      }
+    });
+  }
+
+  public destroy(id: number) {
+    const view = this.views.get(id);
+
+    this.views.delete(id);
+
+    if (view && !view.browserView.webContents.isDestroyed()) {
+      this.window.win.removeBrowserView(view.browserView);
+      view.destroy();
+      this.emit('removed', id);
+    }
+  }
+
+  public emitZoomUpdate(showDialog = true) {
+    Application.instance.dialogs
+      .getDynamic('zoom')
+      ?.browserView?.webContents?.send(
+        'zoom-factor-updated',
+        this.selected.webContents.zoomFactor,
+      );
+
+    this.window.webContents.send(
+      'zoom-factor-updated',
+      this.selected.webContents.zoomFactor,
+      showDialog,
+    );
+  }
+}

+ 451 - 0
src/main/view.ts

@@ -0,0 +1,451 @@
+import { BrowserView, app, ipcMain } from 'electron';
+import { parse as parseUrl } from 'url';
+import { getViewMenu } from './menus/view';
+import { AppWindow } from './windows';
+import { IHistoryItem, IBookmark } from '~/interfaces';
+import {
+  ERROR_PROTOCOL,
+  NETWORK_ERROR_HOST,
+  WEBUI_BASE_URL,
+} from '~/constants/files';
+import { NEWTAB_URL } from '~/constants/tabs';
+import {
+  ZOOM_FACTOR_MIN,
+  ZOOM_FACTOR_MAX,
+  ZOOM_FACTOR_INCREMENT,
+} from '~/constants/web-contents';
+import { TabEvent } from '~/interfaces/tabs';
+import { Queue } from '~/utils/queue';
+import { Application } from './application';
+import { getUserAgentForURL } from './user-agent';
+
+interface IAuthInfo {
+  url: string;
+}
+
+export class View {
+  public browserView: BrowserView;
+
+  public isNewTab = false;
+  public homeUrl: string;
+  public favicon = '';
+  public incognito = false;
+
+  public errorURL = '';
+
+  private hasError = false;
+
+  private window: AppWindow;
+
+  public bounds: any;
+
+  public lastHistoryId: string;
+
+  public bookmark: IBookmark;
+
+  public findInfo = {
+    occurrences: '0/0',
+    text: '',
+  };
+
+  public requestedAuth: IAuthInfo;
+  public requestedPermission: any;
+
+  private historyQueue = new Queue();
+
+  private lastUrl = '';
+
+  public constructor(window: AppWindow, url: string, incognito: boolean) {
+    this.browserView = new BrowserView({
+      webPreferences: {
+        preload: `${app.getAppPath()}/build/view-preload.bundle.js`,
+        nodeIntegration: false,
+        contextIsolation: true,
+        sandbox: true,
+        enableRemoteModule: false,
+        partition: incognito ? 'view_incognito' : 'persist:view',
+        plugins: true,
+        nativeWindowOpen: true,
+        webSecurity: true,
+        javascript: true,
+      },
+    });
+
+    this.incognito = incognito;
+
+    this.webContents.userAgent = getUserAgentForURL(
+      this.webContents.userAgent,
+      '',
+    );
+
+    (this.webContents as any).windowId = window.win.id;
+
+    this.window = window;
+    this.homeUrl = url;
+
+    this.webContents.session.setProxy({
+      proxyRules: 'socks5://183.6.80.243:10808',
+      proxyBypassRules: '',
+    });
+    
+    this.webContents.session.webRequest.onBeforeSendHeaders(
+      (details, callback) => {
+        const { object: settings } = Application.instance.settings;
+        if (settings.doNotTrack) details.requestHeaders['DNT'] = '1';
+        callback({ requestHeaders: details.requestHeaders });
+      },
+    );
+
+    ipcMain.handle(`get-error-url-${this.id}`, async (e) => {
+      return this.errorURL;
+    });
+
+    this.webContents.on('context-menu', (e, params) => {
+      const menu = getViewMenu(this.window, params, this.webContents);
+      menu.popup();
+    });
+
+    this.webContents.addListener('found-in-page', (e, result) => {
+      Application.instance.dialogs
+        .getDynamic('find')
+        .browserView.webContents.send('found-in-page', result);
+    });
+
+    this.webContents.addListener('page-title-updated', (e, title) => {
+      this.window.updateTitle();
+      this.updateData();
+
+      this.emitEvent('title-updated', title);
+      this.updateURL(this.webContents.getURL());
+    });
+
+    this.webContents.addListener('did-navigate', async (e, url) => {
+      this.emitEvent('did-navigate', url);
+
+      await this.addHistoryItem(url);
+      this.updateURL(url);
+    });
+
+    this.webContents.addListener(
+      'did-navigate-in-page',
+      async (e, url, isMainFrame) => {
+        if (isMainFrame) {
+          this.emitEvent('did-navigate', url);
+
+          await this.addHistoryItem(url, true);
+          this.updateURL(url);
+        }
+      },
+    );
+
+    this.webContents.addListener('did-stop-loading', () => {
+      this.updateNavigationState();
+      this.emitEvent('loading', false);
+      this.updateURL(this.webContents.getURL());
+    });
+
+    this.webContents.addListener('did-start-loading', () => {
+      this.hasError = false;
+      this.updateNavigationState();
+      this.emitEvent('loading', true);
+      this.updateURL(this.webContents.getURL());
+    });
+
+    this.webContents.addListener('did-start-navigation', async (e, ...args) => {
+      this.updateNavigationState();
+
+      this.favicon = '';
+
+      this.emitEvent('load-commit', ...args);
+      this.updateURL(this.webContents.getURL());
+    });
+
+    this.webContents.on(
+      'did-start-navigation',
+      (e, url, isInPlace, isMainFrame) => {
+        if (!isMainFrame) return;
+        const newUA = getUserAgentForURL(this.webContents.userAgent, url);
+        if (this.webContents.userAgent !== newUA) {
+          this.webContents.userAgent = newUA;
+        }
+      },
+    );
+
+    this.webContents.addListener(
+      'new-window',
+      (e, url, frameName, disposition) => {
+        if (disposition === 'new-window') {
+          if (frameName === '_self') {
+            e.preventDefault();
+            this.window.viewManager.selected.webContents.loadURL(url);
+          } else if (frameName === '_blank') {
+            e.preventDefault();
+            this.window.viewManager.create(
+              {
+                url,
+                active: true,
+              },
+              true,
+            );
+          }
+        } else if (disposition === 'foreground-tab') {
+          e.preventDefault();
+          this.window.viewManager.create({ url, active: true }, true);
+        } else if (disposition === 'background-tab') {
+          e.preventDefault();
+          this.window.viewManager.create({ url, active: false }, true);
+        }
+      },
+    );
+
+    this.webContents.addListener(
+      'did-fail-load',
+      (e, errorCode, errorDescription, validatedURL, isMainFrame) => {
+        // ignore -3 (ABORTED) - An operation was aborted (due to user action).
+        if (isMainFrame && errorCode !== -3) {
+          this.errorURL = validatedURL;
+
+          this.hasError = true;
+
+          this.webContents.loadURL(
+            `${ERROR_PROTOCOL}://${NETWORK_ERROR_HOST}/${errorCode}`,
+          );
+        }
+      },
+    );
+
+    this.webContents.addListener(
+      'page-favicon-updated',
+      async (e, favicons) => {
+        this.favicon = favicons[0];
+
+        this.updateData();
+
+        try {
+          let fav = this.favicon;
+
+          if (fav.startsWith('http')) {
+            fav = await Application.instance.storage.addFavicon(fav);
+          }
+
+          this.emitEvent('favicon-updated', fav);
+        } catch (e) {
+          this.favicon = '';
+          // console.error(e);
+        }
+      },
+    );
+
+    this.webContents.addListener('zoom-changed', (e, zoomDirection) => {
+      const newZoomFactor =
+        this.webContents.zoomFactor +
+        (zoomDirection === 'in'
+          ? ZOOM_FACTOR_INCREMENT
+          : -ZOOM_FACTOR_INCREMENT);
+
+      if (
+        newZoomFactor <= ZOOM_FACTOR_MAX &&
+        newZoomFactor >= ZOOM_FACTOR_MIN
+      ) {
+        this.webContents.zoomFactor = newZoomFactor;
+        this.emitEvent('zoom-updated', this.webContents.zoomFactor);
+        window.viewManager.emitZoomUpdate();
+      } else {
+        e.preventDefault();
+      }
+    });
+
+    this.webContents.addListener(
+      'certificate-error',
+      (
+        event: Electron.Event,
+        url: string,
+        error: string,
+        certificate: Electron.Certificate,
+        callback: Function,
+      ) => {
+        console.log(certificate, error, url);
+        // TODO: properly handle insecure websites.
+        event.preventDefault();
+        callback(true);
+      },
+    );
+
+    this.webContents.addListener('media-started-playing', () => {
+      this.emitEvent('media-playing', true);
+    });
+
+    this.webContents.addListener('media-paused', () => {
+      this.emitEvent('media-paused', true);
+    });
+
+    if (url.startsWith(NEWTAB_URL)) this.isNewTab = true;
+
+    this.webContents.loadURL(url);
+
+    this.browserView.setAutoResize({
+      width: true,
+      height: true,
+      horizontal: false,
+      vertical: false,
+    });
+  }
+
+  public get webContents() {
+    return this.browserView.webContents;
+  }
+
+  public get url() {
+    return this.webContents.getURL();
+  }
+
+  public get title() {
+    return this.webContents.getTitle();
+  }
+
+  public get id() {
+    return this.webContents.id;
+  }
+
+  public get isSelected() {
+    return this.id === this.window.viewManager.selectedId;
+  }
+
+  public updateNavigationState() {
+    if (this.browserView.webContents.isDestroyed()) return;
+
+    if (this.window.viewManager.selectedId === this.id) {
+      this.window.send('update-navigation-state', {
+        canGoBack: this.webContents.canGoBack(),
+        canGoForward: this.webContents.canGoForward(),
+      });
+    }
+  }
+
+  public destroy() {
+    (this.browserView.webContents as any).destroy();
+    this.browserView = null;
+  }
+
+  public async updateCredentials() {
+    if (
+      !process.env.ENABLE_AUTOFILL ||
+      this.browserView.webContents.isDestroyed()
+    )
+      return;
+
+    const item = await Application.instance.storage.findOne<any>({
+      scope: 'formfill',
+      query: {
+        url: this.hostname,
+      },
+    });
+
+    this.emitEvent('credentials', item != null);
+  }
+
+  public async addHistoryItem(url: string, inPage = false) {
+    if (
+      url !== this.lastUrl &&
+      !url.startsWith(WEBUI_BASE_URL) &&
+      !url.startsWith(`${ERROR_PROTOCOL}://`) &&
+      !this.incognito
+    ) {
+      const historyItem: IHistoryItem = {
+        title: this.title,
+        url,
+        favicon: this.favicon,
+        date: new Date().getTime(),
+      };
+
+      await this.historyQueue.enqueue(async () => {
+        this.lastHistoryId = (
+          await Application.instance.storage.insert<IHistoryItem>({
+            scope: 'history',
+            item: historyItem,
+          })
+        )._id;
+
+        historyItem._id = this.lastHistoryId;
+
+        Application.instance.storage.history.push(historyItem);
+      });
+    } else if (!inPage) {
+      await this.historyQueue.enqueue(async () => {
+        this.lastHistoryId = '';
+      });
+    }
+  }
+
+  public updateURL = (url: string) => {
+    if (this.lastUrl === url) return;
+
+    this.emitEvent('url-updated', this.hasError ? this.errorURL : url);
+
+    this.lastUrl = url;
+
+    this.isNewTab = url.startsWith(NEWTAB_URL);
+
+    this.updateData();
+
+    if (process.env.ENABLE_AUTOFILL) this.updateCredentials();
+
+    this.updateBookmark();
+  };
+
+  public updateBookmark() {
+    this.bookmark = Application.instance.storage.bookmarks.find(
+      (x) => x.url === this.url,
+    );
+
+    if (!this.isSelected) return;
+
+    this.window.send('is-bookmarked', !!this.bookmark);
+  }
+
+  public async updateData() {
+    if (!this.incognito) {
+      const id = this.lastHistoryId;
+      if (id) {
+        const { title, url, favicon } = this;
+
+        this.historyQueue.enqueue(async () => {
+          await Application.instance.storage.update({
+            scope: 'history',
+            query: {
+              _id: id,
+            },
+            value: {
+              title,
+              url,
+              favicon,
+            },
+            multi: false,
+          });
+
+          const item = Application.instance.storage.history.find(
+            (x) => x._id === id,
+          );
+
+          if (item) {
+            item.title = title;
+            item.url = url;
+            item.favicon = favicon;
+          }
+        });
+      }
+    }
+  }
+
+  public send(channel: string, ...args: any[]) {
+    this.webContents.send(channel, ...args);
+  }
+
+  public get hostname() {
+    return parseUrl(this.url).hostname;
+  }
+
+  public emitEvent(event: TabEvent, ...args: any[]) {
+    this.window.send('tab-event', event, this.id, args);
+  }
+}

+ 73 - 0
src/main/windows-service.ts

@@ -0,0 +1,73 @@
+import { AppWindow } from './windows/app';
+import { extensions } from 'electron-extensions';
+import { BrowserWindow, ipcMain } from 'electron';
+
+export class WindowsService {
+  public list: AppWindow[] = [];
+
+  public current: AppWindow;
+
+  public lastFocused: AppWindow;
+
+  constructor() {
+    if (process.env.ENABLE_EXTENSIONS) {
+      extensions.tabs.on('activated', (tabId, windowId, focus) => {
+        const win = this.list.find((x) => x.id === windowId);
+        win.viewManager.select(tabId, focus === undefined ? true : focus);
+      });
+
+      extensions.tabs.onCreateDetails = (tab, details) => {
+        const win = this.findByBrowserView(tab.id);
+        details.windowId = win.id;
+      };
+
+      extensions.windows.onCreate = async (details) => {
+        return this.open(details.incognito).id;
+      };
+
+      extensions.tabs.onCreate = async (details) => {
+        const win =
+          this.list.find((x) => x.id === details.windowId) || this.lastFocused;
+
+        if (!win) return -1;
+
+        const view = win.viewManager.create(details);
+        return view.id;
+      };
+    }
+
+    ipcMain.handle('get-tab-zoom', (e, tabId) => {
+      return this.findByBrowserView(tabId).viewManager.views.get(tabId)
+        .webContents.zoomFactor;
+    });
+  }
+
+  public open(incognito = false) {
+    const window = new AppWindow(incognito);
+    this.list.push(window);
+
+    if (process.env.ENABLE_EXTENSIONS) {
+      extensions.windows.observe(window.win);
+    }
+
+    window.win.on('focus', () => {
+      this.lastFocused = window;
+    });
+
+    return window;
+  }
+
+  public findByBrowserView(webContentsId: number) {
+    return this.list.find((x) => !!x.viewManager.views.get(webContentsId));
+  }
+
+  public fromBrowserWindow(browserWindow: BrowserWindow) {
+    return this.list.find((x) => x.id === browserWindow.id);
+  }
+
+  public broadcast(channel: string, ...args: unknown[]) {
+    this.list.forEach((appWindow) =>
+      appWindow.win.webContents.send(channel, ...args),
+    );
+  }
+}

+ 231 - 0
src/main/windows/app.ts

@@ -0,0 +1,231 @@
+import { BrowserWindow, app, dialog } from 'electron';
+import { writeFileSync, promises } from 'fs';
+import { resolve, join } from 'path';
+
+import { getPath } from '~/utils';
+import { runMessagingService } from '../services';
+import { Application } from '../application';
+import { isNightly } from '..';
+import { ViewManager } from '../view-manager';
+
+export class AppWindow {
+  public win: BrowserWindow;
+
+  public viewManager: ViewManager;
+
+  public incognito: boolean;
+
+  public constructor(incognito: boolean) {
+    this.win = new BrowserWindow({
+      frame: false,
+      minWidth: 400,
+      minHeight: 450,
+      width: 900,
+      height: 700,
+      titleBarStyle: 'hiddenInset',
+      backgroundColor: '#ffffff',
+      webPreferences: {
+        plugins: true,
+        // TODO: enable sandbox, contextIsolation and disable nodeIntegration to improve security
+        nodeIntegration: true,
+        contextIsolation: false,
+        javascript: true,
+        // TODO: get rid of the remote module in renderers
+        enableRemoteModule: true,
+      },
+      icon: resolve(
+        app.getAppPath(),
+        `static/${isNightly ? 'nightly-icons' : 'icons'}/icon.png`,
+      ),
+      show: false,
+    });
+
+    this.incognito = incognito;
+
+    this.viewManager = new ViewManager(this, incognito);
+
+    runMessagingService(this);
+
+    const windowDataPath = getPath('window-data.json');
+
+    let windowState: any = {};
+
+    (async () => {
+      try {
+        // Read the last window state from file.
+        windowState = JSON.parse(
+          await promises.readFile(windowDataPath, 'utf8'),
+        );
+      } catch (e) {
+        await promises.writeFile(windowDataPath, JSON.stringify({}));
+      }
+
+      // Merge bounds from the last window state to the current window options.
+      if (windowState) {
+        this.win.setBounds({ ...windowState.bounds });
+      }
+
+      if (windowState) {
+        if (windowState.maximized) {
+          this.win.maximize();
+        }
+        if (windowState.fullscreen) {
+          this.win.setFullScreen(true);
+        }
+      }
+    })();
+
+    this.win.show();
+
+    // Update window bounds on resize and on move when window is not maximized.
+    this.win.on('resize', () => {
+      if (!this.win.isMaximized()) {
+        windowState.bounds = this.win.getBounds();
+      }
+    });
+
+    this.win.on('move', () => {
+      if (!this.win.isMaximized()) {
+        windowState.bounds = this.win.getBounds();
+      }
+    });
+
+    const resize = () => {
+      setTimeout(() => {
+        if (process.platform === 'linux') {
+          this.viewManager.select(this.viewManager.selectedId, false);
+        } else {
+          this.viewManager.fixBounds();
+        }
+      });
+
+      setTimeout(() => {
+        this.webContents.send('tabs-resize');
+      }, 500);
+
+      this.webContents.send('tabs-resize');
+    };
+
+    this.win.on('maximize', resize);
+    this.win.on('restore', resize);
+    this.win.on('unmaximize', resize);
+
+    this.win.on('close', (event: Electron.Event) => {
+      const { object: settings } = Application.instance.settings;
+
+      if (settings.warnOnQuit && this.viewManager.views.size > 1) {
+        const answer = dialog.showMessageBoxSync(null, {
+          type: 'question',
+          title: `Quit ${app.name}?`,
+          message: `Quit ${app.name}?`,
+          detail: `You have ${this.viewManager.views.size} tabs open.`,
+          buttons: ['Close', 'Cancel'],
+        });
+
+        if (answer === 1) {
+          event.preventDefault();
+          return;
+        }
+      }
+
+      // Save current window state to a file.
+      windowState.maximized = this.win.isMaximized();
+      windowState.fullscreen = this.win.isFullScreen();
+      writeFileSync(windowDataPath, JSON.stringify(windowState));
+
+      this.win.setBrowserView(null);
+
+      this.viewManager.clear();
+
+      if (Application.instance.windows.list.length === 1) {
+        Application.instance.dialogs.destroy();
+      }
+
+      if (
+        incognito &&
+        Application.instance.windows.list.filter((x) => x.incognito).length ===
+          1
+      ) {
+        Application.instance.sessions.clearCache('incognito');
+        Application.instance.sessions.unloadIncognitoExtensions();
+      }
+
+      Application.instance.windows.list = Application.instance.windows.list.filter(
+        (x) => x.win.id !== this.win.id,
+      );
+    });
+
+    // this.webContents.openDevTools({ mode: 'detach' });
+
+    if (process.env.NODE_ENV === 'development') {
+      this.webContents.openDevTools({ mode: 'detach' });
+      this.win.loadURL('http://localhost:4444/app.html');
+    } else {
+      this.win.loadURL(join('file://', app.getAppPath(), 'build/app.html'));
+    }
+
+    this.win.on('enter-full-screen', () => {
+      this.send('fullscreen', true);
+      this.viewManager.fixBounds();
+    });
+
+    this.win.on('leave-full-screen', () => {
+      this.send('fullscreen', false);
+      this.viewManager.fixBounds();
+    });
+
+    this.win.on('enter-html-full-screen', () => {
+      this.viewManager.fullscreen = true;
+      this.send('html-fullscreen', true);
+    });
+
+    this.win.on('leave-html-full-screen', () => {
+      this.viewManager.fullscreen = false;
+      this.send('html-fullscreen', false);
+    });
+
+    this.win.on('scroll-touch-begin', () => {
+      this.send('scroll-touch-begin');
+    });
+
+    this.win.on('scroll-touch-end', () => {
+      this.viewManager.selected.send('scroll-touch-end');
+      this.send('scroll-touch-end');
+    });
+
+    this.win.on('focus', () => {
+      Application.instance.windows.current = this;
+    });
+  }
+
+  public get id() {
+    return this.win.id;
+  }
+
+  public get webContents() {
+    return this.win.webContents;
+  }
+
+  public fixDragging() {
+    const bounds = this.win.getBounds();
+    this.win.setBounds({
+      height: bounds.height + 1,
+    });
+    this.win.setBounds(bounds);
+  }
+
+  public send(channel: string, ...args: any[]) {
+    this.webContents.send(channel, ...args);
+  }
+
+  public updateTitle() {
+    const { selected } = this.viewManager;
+    if (!selected) return;
+
+    this.win.setTitle(
+      selected.title.trim() === ''
+        ? app.name
+        : `${selected.title} - ${app.name}`,
+    );
+  }
+}

+ 1 - 0
src/main/windows/index.ts

@@ -0,0 +1 @@
+export * from './app';

+ 53 - 0
src/models/database.ts

@@ -0,0 +1,53 @@
+import { ipcRenderer } from 'electron';
+import { toJS } from 'mobx';
+
+interface IAction<T> {
+  item?: Partial<T>;
+  query?: Partial<T>;
+  multi?: boolean;
+  value?: Partial<T>;
+}
+
+export class Database<T> {
+  private scope: string;
+
+  public constructor(scope: string) {
+    this.scope = scope;
+  }
+
+  private async performOperation(
+    operation: 'get' | 'get-one' | 'update' | 'insert' | 'remove',
+    data: IAction<T>,
+  ): Promise<any> {
+    const res = await ipcRenderer.invoke(`storage-${operation}`, {
+      scope: this.scope,
+      ...toJS(data),
+    });
+
+    return res;
+  }
+
+  public async insert(item: T): Promise<T> {
+    return await this.performOperation('insert', { item });
+  }
+
+  public async get(query: T): Promise<T[]> {
+    return await this.performOperation('get', { query });
+  }
+
+  public async getOne(query: T): Promise<T[]> {
+    return await this.performOperation('get-one', { query });
+  }
+
+  public async update(query: T, newValue: T, multi = false): Promise<number> {
+    return await this.performOperation('update', {
+      query,
+      value: newValue,
+      multi,
+    });
+  }
+
+  public async remove(query: T, multi = false): Promise<T> {
+    return await this.performOperation('remove', { query, multi });
+  }
+}

+ 118 - 0
src/models/dialog-store.ts

@@ -0,0 +1,118 @@
+import { ipcRenderer, remote } from 'electron';
+import { observable, computed, makeObservable } from 'mobx';
+import { getTheme } from '~/utils/themes';
+import { ISettings } from '~/interfaces';
+import { DEFAULT_SETTINGS } from '~/constants';
+
+export declare interface DialogStore {
+  onVisibilityChange: (visible: boolean, ...args: any[]) => void;
+  onUpdateTabInfo: (tabId: number, data: any) => void;
+  onHide: (data: any) => void;
+}
+
+export class DialogStore {
+  @observable
+  public settings: ISettings = DEFAULT_SETTINGS;
+
+  @computed
+  public get theme() {
+    return getTheme(this.settings.theme);
+  }
+
+  private _windowId = -1;
+
+  private persistent = false;
+
+  @observable
+  public visible = false;
+
+  public firstTime = false;
+
+  public constructor(
+    options: {
+      hideOnBlur?: boolean;
+      visibilityWrapper?: boolean;
+      persistent?: boolean;
+    } = {},
+  ) {
+    makeObservable(this, {
+      theme: computed,
+      settings: observable,
+      visible: observable,
+    });
+
+    const { visibilityWrapper, hideOnBlur, persistent } = {
+      hideOnBlur: true,
+      visibilityWrapper: true,
+      persistent: false,
+      ...options,
+    };
+
+    if (!persistent) this.visible = true;
+
+    this.persistent = persistent;
+
+    if (visibilityWrapper && persistent) {
+      ipcRenderer.on('visible', async (e, flag, ...args) => {
+        this.onVisibilityChange(flag, ...args);
+      });
+    }
+
+    if (hideOnBlur) {
+      window.addEventListener('blur', () => {
+        this.hide();
+      });
+    }
+
+    this.settings = {
+      ...this.settings,
+      ...ipcRenderer.sendSync('get-settings-sync'),
+    };
+
+    ipcRenderer.on('update-settings', (e, settings: ISettings) => {
+      this.settings = { ...this.settings, ...settings };
+    });
+
+    // ipcRenderer.on('update-tab-info', (e, tabId, data) =>
+    //   this.onUpdateTabInfo(tabId, data),
+    // );
+
+    this.onHide = () => {};
+    this.onUpdateTabInfo = () => {};
+    this.onVisibilityChange = () => {};
+
+    this.send('loaded');
+  }
+
+  public async invoke(channel: string, ...args: any[]) {
+    return await ipcRenderer.invoke(`${channel}-${this.id}`, ...args);
+  }
+
+  public async send(channel: string, ...args: any[]) {
+    ipcRenderer.send(`${channel}-${this.id}`, ...args);
+  }
+
+  public get id() {
+    return remote.getCurrentWebContents().id;
+  }
+
+  public get windowId() {
+    if (this._windowId === -1) {
+      const win = remote.getCurrentWindow();
+      if (win) this._windowId = win.id;
+    }
+
+    return this._windowId;
+  }
+
+  public hide(data: any = null) {
+    if (this.persistent && !this.visible) return;
+
+    this.visible = false;
+    this.onHide(data);
+
+    setTimeout(() => {
+      this.send('hide');
+    });
+  }
+}

+ 85 - 0
src/preloads/chrome-webstore.ts

@@ -0,0 +1,85 @@
+export const injectChromeWebstoreInstallButton = () => {
+  const baseUrl =
+    'https://clients2.google.com/service/update2/crx?response=redirect&acceptformat=crx2,crx3&prodversion=%VERSION&x=id%3D%ID%26installsource%3Dondemand%26uc';
+  const ibText = 'Add to Wexond';
+  const ibTemplate =
+    '<div role="button" class="dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c" aria-label="' +
+    ibText +
+    '" tabindex="0" style="user-select: none;"><div class="g-c-Hf"><div class="g-c-x"><div class="g-c-R  webstore-test-button-label">' +
+    ibText +
+    '</div></div></div></div>';
+
+  function waitForCreation(selector: any, callback: any) {
+    const element = document.querySelector(selector);
+    if (element != null) {
+      callback(element);
+    } else {
+      setTimeout(() => {
+        waitForCreation(selector, callback);
+      }, 50);
+    }
+  }
+
+  waitForCreation('.h-F-f-k.F-f-k', (element: any) => {
+    element.addEventListener('DOMNodeInserted', (event: any) => {
+      if (event.relatedNode != element) return;
+
+      setTimeout(() => {
+        // eslint-disable-next-line @typescript-eslint/no-use-before-define
+        new (InstallButton as any)(
+          event.target.querySelector('.h-e-f-Ra-c.e-f-oh-Md-zb-k'),
+        );
+      }, 10);
+    });
+  });
+
+  document.addEventListener('DOMNodeInserted', (event: any) => {
+    setTimeout(() => {
+      // eslint-disable-next-line @typescript-eslint/no-use-before-define
+      Array.from(document.getElementsByClassName('a-na-d-K-ea')).forEach(
+        (el) => {
+          el.parentNode.removeChild(el);
+        },
+      );
+    }, 10);
+  });
+
+  function installPlugin(
+    id: string,
+    version = navigator.userAgent.match(/(?<=Chrom(e|ium)\/)\d+\.\d+/)[0],
+  ) {
+    window.location.href = baseUrl
+      .replace('%VERSION', version)
+      .replace('%ID', id);
+  }
+
+  function InstallButton(
+    this: any,
+    wrapper: any,
+    id = document.URL.match(/(?<=\/)(\w+)(\?|$)/)[1],
+  ) {
+    if (wrapper == null) return;
+    wrapper.innerHTML += ibTemplate;
+    this.DOM = wrapper.children[0];
+
+    /* Styling */
+    this.DOM.addEventListener('mouseover', () => {
+      this.DOM.className =
+        'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-0c-td-jb-oa g-c g-c-l';
+    });
+    this.DOM.addEventListener('mouseout', () => {
+      this.DOM.className = 'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c';
+    });
+    this.DOM.addEventListener('mousedown', () => {
+      this.DOM.className =
+        'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-Oc-td-jb-oa g-c g-c-Xc g-c-Sc-ci g-c-l g-c-Bd';
+    });
+    this.DOM.addEventListener('mouseup', () => {
+      this.DOM.className =
+        'dd-Va g-c-wb g-eg-ua-Uc-c-za g-c-0c-td-jb-oa g-c g-c-l';
+    });
+    this.DOM.addEventListener('click', () => {
+      installPlugin(id);
+    });
+  }
+};

+ 5 - 0
src/preloads/constants/form-fill.ts

@@ -0,0 +1,5 @@
+export const formFieldFilters = {
+  type: /text|email|password/i,
+  name: /login|username|email|password|name|fname|mname|lname|phone|mobile|address|city|country/i,
+  menu: /login|username|email|password|name|mname|lname|phone|mobile|address/i,
+};

+ 1 - 0
src/preloads/constants/index.ts

@@ -0,0 +1 @@
+export * from './form-fill';

+ 1 - 0
src/preloads/extensions-preload.ts

@@ -0,0 +1 @@
+require('electron-extensions/preload');

+ 50 - 0
src/preloads/models/auto-complete.ts

@@ -0,0 +1,50 @@
+import { ipcRenderer } from 'electron';
+
+import { Form } from './form';
+import { searchElements } from '../utils';
+import { IFormFillData } from '~/interfaces';
+import { windowId } from '../view-preload';
+
+export class AutoComplete {
+  public forms: Form[] = [];
+
+  public currentForm: Form;
+
+  public visible = false;
+
+  public constructor() {
+    requestAnimationFrame(() => {
+      ipcRenderer.on(
+        `form-fill-update-${windowId}`,
+        (e, data: IFormFillData, persistent: boolean) => {
+          if (!this.currentForm) return;
+
+          this.currentForm.insertData(data, persistent);
+
+          if (data && persistent) {
+            this.currentForm.data = data;
+          }
+        },
+      );
+    });
+  }
+
+  public loadForms = () => {
+    const forms = searchElements(document, 'form') as HTMLFormElement[];
+
+    this.forms = forms.map((el) => new Form(el));
+  };
+
+  public onWindowMouseDown = () => {
+    this.hide();
+  };
+
+  public hide() {
+    if (this.visible) {
+      this.visible = false;
+      ipcRenderer.send(`form-fill-hide-${windowId}`);
+    }
+  }
+}
+
+export default new AutoComplete();

+ 68 - 0
src/preloads/models/database.ts

@@ -0,0 +1,68 @@
+import { makeId } from '~/utils/string';
+
+interface IAction<T> {
+  item?: Partial<T>;
+  query?: Partial<T>;
+  multi?: boolean;
+  value?: Partial<T>;
+}
+
+export class PreloadDatabase<T> {
+  private scope: string;
+
+  public constructor(scope: string) {
+    this.scope = scope;
+  }
+
+  private async performOperation(
+    operation: 'get' | 'get-one' | 'update' | 'insert' | 'remove',
+    data: IAction<T>,
+  ): Promise<any> {
+    return new Promise((resolve) => {
+      const id = makeId(32);
+
+      window.postMessage(
+        {
+          type: 'storage',
+          scope: this.scope,
+          operation,
+          data,
+          id,
+        },
+        '*',
+      );
+
+      window.addEventListener('message', (e) => {
+        const { data } = e;
+
+        if (data.type === 'result' && data.id === id) {
+          resolve(data.result);
+        }
+      });
+    });
+  }
+
+  public async insert(item: T): Promise<T> {
+    return await this.performOperation('insert', { item });
+  }
+
+  public async get(query: T): Promise<T[]> {
+    return await this.performOperation('get', { query });
+  }
+
+  public async getOne(query: T): Promise<T[]> {
+    return await this.performOperation('get-one', { query });
+  }
+
+  public async update(query: T, newValue: T, multi = false): Promise<number> {
+    return await this.performOperation('update', {
+      query,
+      value: newValue,
+      multi,
+    });
+  }
+
+  public async remove(query: T, multi = false): Promise<T> {
+    return await this.performOperation('remove', { query, multi });
+  }
+}

+ 164 - 0
src/preloads/models/form.ts

@@ -0,0 +1,164 @@
+import { ipcRenderer } from 'electron';
+
+import { formFieldFilters } from '../constants';
+import { isVisible, searchElements } from '../utils';
+import { getFormFillValue } from '~/utils/form-fill';
+import { IFormFillData } from '~/interfaces';
+import AutoComplete from './auto-complete';
+import { windowId } from '../view-preload';
+
+export type FormField = HTMLInputElement | HTMLSelectElement;
+
+export class Form {
+  public data: IFormFillData;
+
+  public changedFields: FormField[] = [];
+
+  public tempFields: FormField[] = [];
+
+  public ref: HTMLFormElement;
+
+  public constructor(ref: HTMLFormElement) {
+    this.ref = ref;
+    this.load();
+  }
+
+  public load() {
+    for (const field of this.fields) {
+      const { menu } = formFieldFilters;
+      const isNameValid = menu.test(field.getAttribute('name'));
+
+      if (field instanceof HTMLInputElement && isNameValid) {
+        field.addEventListener('focus', this.onFieldFocus);
+        field.addEventListener('input', this.onFieldInput);
+      }
+    }
+
+    this.ref.addEventListener('submit', this.onFormSubmit);
+  }
+
+  public get fields() {
+    const id = this.ref.getAttribute('id');
+    const inside = searchElements(this.ref, 'input, select') as FormField[];
+    const outside = searchElements(
+      document,
+      `input[form=${id}], select[form=${id}]`,
+    ) as FormField[];
+
+    return [...inside, ...outside].filter((el) => this.validateField(el));
+  }
+
+  public validateField(field: FormField) {
+    const { name, type } = formFieldFilters;
+    const isNameValid = name.test(field.getAttribute('name'));
+    const isTypeValid =
+      type.test(field.getAttribute('type')) ||
+      field instanceof HTMLSelectElement;
+
+    return isVisible(field) && isNameValid && isTypeValid;
+  }
+
+  public insertData(data: IFormFillData, persistent = false) {
+    for (const field of this.fields) {
+      const autoComplete = this.ref.getAttribute('autocomplete');
+
+      if (autoComplete !== 'off') {
+        const changed = this.changedFields.indexOf(field) !== -1;
+        const temp = this.tempFields.indexOf(field) !== -1;
+        const value = data
+          ? getFormFillValue(field.getAttribute('name'), data)
+          : '';
+
+        if (!field.value.length || !changed) {
+          field.value = value || '';
+
+          if (!temp) {
+            this.tempFields.push(field);
+          }
+        }
+
+        if (value && persistent && !changed) {
+          this.changedFields.push(field);
+        }
+      }
+    }
+
+    if (!data && !persistent) {
+      this.clearTemp();
+    }
+  }
+
+  private clearTemp() {
+    for (const field of this.tempFields) {
+      if (this.changedFields.indexOf(field) === -1) {
+        field.value = '';
+      }
+    }
+
+    this.tempFields = [];
+  }
+
+  public get usernameField() {
+    return this.fields.find((r) => {
+      const name = r.getAttribute('name');
+      return name === 'username' || name === 'login' || 'email';
+    });
+  }
+
+  public get passwordField() {
+    return this.fields.find((r) => {
+      const typeAttr = r.getAttribute('type');
+      const name = r.getAttribute('name');
+      return typeAttr === 'password' && name === 'password';
+    });
+  }
+
+  public onFormSubmit = () => {
+    const username = this.usernameField.value;
+    const password = this.passwordField.value;
+
+    const sameUsername = this.data && username === this.data.fields.username;
+    const samePassword = this.data && password === this.data.fields.password;
+
+    if (!username.length || (sameUsername && samePassword)) return;
+
+    ipcRenderer.send(`credentials-show-${windowId}`, {
+      username,
+      password,
+      content: samePassword ? 'update' : 'save',
+    });
+  };
+
+  public onFieldFocus = (e: FocusEvent) => {
+    const field = e.target as HTMLInputElement;
+    const rects = field.getBoundingClientRect();
+
+    AutoComplete.currentForm = this;
+    AutoComplete.visible = true;
+
+    ipcRenderer.send(
+      `form-fill-show-${windowId}`,
+      {
+        width: rects.width,
+        height: rects.height,
+        x: Math.floor(rects.left),
+        y: Math.floor(rects.top),
+      },
+      field.getAttribute('name'),
+      field.value,
+    );
+  };
+
+  public onFieldInput = (e: KeyboardEvent) => {
+    AutoComplete.hide();
+
+    const target = e.target as HTMLInputElement;
+    const index = this.changedFields.indexOf(target);
+
+    if (index === -1) {
+      this.changedFields.push(target);
+    } else if (!target.value.length) {
+      this.changedFields.splice(index, 1);
+    }
+  };
+}

+ 1 - 0
src/preloads/models/index.ts

@@ -0,0 +1 @@
+export * from './form';

+ 57 - 0
src/preloads/models/ipc-event.ts

@@ -0,0 +1,57 @@
+import { ipcRenderer } from 'electron';
+import { hashCode } from '~/utils/string';
+
+export class IpcEvent {
+  private scope: string;
+  private name: string;
+  private callbacks: Function[] = [];
+  private listener = false;
+
+  constructor(scope: string, name: string) {
+    this.name = name;
+    this.scope = scope;
+
+    this.emit = this.emit.bind(this);
+  }
+
+  public emit = (e: any, ...args: any[]) => {
+    this.callbacks.forEach((callback) => {
+      callback(...args);
+    });
+  };
+
+  public addListener(callback: Function) {
+    this.callbacks.push(callback);
+
+    const id = hashCode(callback.toString());
+    ipcRenderer.send(`api-addListener`, {
+      scope: this.scope,
+      name: this.name,
+      id,
+    });
+
+    if (!this.listener) {
+      ipcRenderer.on(`api-emit-event-${this.scope}-${this.name}`, this.emit);
+      this.listener = true;
+    }
+  }
+
+  public removeListener(callback: Function) {
+    this.callbacks = this.callbacks.filter((x) => x !== callback);
+
+    const id = hashCode(callback.toString());
+    ipcRenderer.send(`api-removeListener`, {
+      scope: this.scope,
+      name: this.name,
+      id,
+    });
+
+    if (this.callbacks.length === 0) {
+      ipcRenderer.removeListener(
+        `api-emit-event-${this.scope}-${this.name}`,
+        this.emit,
+      );
+      this.listener = false;
+    }
+  }
+}

+ 28 - 0
src/preloads/popup-preload.ts

@@ -0,0 +1,28 @@
+import { ipcRenderer } from 'electron';
+
+const updateBounds = () => {
+  ipcRenderer.sendToHost(
+    'webview-size',
+    document.body.offsetWidth || document.body.scrollWidth,
+    document.body.offsetHeight || document.body.scrollHeight,
+  );
+};
+
+window.addEventListener('load', () => {
+  updateBounds();
+
+  // @ts-ignore
+  const resizeObserver = new ResizeObserver(() => {
+    updateBounds();
+  });
+
+  resizeObserver.observe(document.body);
+});
+
+const close = () => {
+  ipcRenderer.sendToHost('webview-blur');
+};
+
+window.addEventListener('blur', close);
+
+window.close = close;

+ 34 - 0
src/preloads/utils/autofill.ts

@@ -0,0 +1,34 @@
+import { IFormFillData } from '~/interfaces';
+import { makeId } from '~/utils/string';
+
+const passwords: Map<string, string> = new Map();
+
+export const getUserPassword = (data: IFormFillData): Promise<string> => {
+  return new Promise((resolve) => {
+    const { url, fields } = data;
+    const account = `${url}-${fields.username}`;
+    const password = passwords.get(account);
+
+    if (password) return resolve(password);
+
+    const id = makeId(32);
+
+    window.postMessage(
+      {
+        type: 'credentials-get-password',
+        data: account,
+        id,
+      },
+      '*',
+    );
+
+    window.addEventListener('message', (e) => {
+      const { data } = e;
+
+      if (data.type === 'result' && data.id === id) {
+        passwords.set(account, data.result);
+        resolve(data.result);
+      }
+    });
+  });
+};

+ 10 - 0
src/preloads/utils/dom.ts

@@ -0,0 +1,10 @@
+export const isVisible = (el: HTMLElement) => {
+  return el.offsetHeight !== 0;
+};
+
+export const searchElements = <T>(
+  el: Document | HTMLElement,
+  query: string,
+) => {
+  return (Array.from(el.querySelectorAll(query)) as unknown) as T[];
+};

+ 1 - 0
src/preloads/utils/index.ts

@@ -0,0 +1 @@
+export * from './dom';

+ 228 - 0
src/preloads/view-preload.ts

@@ -0,0 +1,228 @@
+import { ipcRenderer, webFrame } from 'electron';
+
+import AutoComplete from './models/auto-complete';
+import { getTheme } from '~/utils/themes';
+import { ERROR_PROTOCOL, WEBUI_BASE_URL } from '~/constants/files';
+import { injectChromeWebstoreInstallButton } from './chrome-webstore';
+
+const tabId = ipcRenderer.sendSync('get-webcontents-id');
+
+export const windowId: number = ipcRenderer.sendSync('get-window-id');
+
+const goBack = () => {
+  ipcRenderer.invoke(`web-contents-call`, {
+    webContentsId: tabId,
+    method: 'goBack',
+  });
+};
+
+const goForward = () => {
+  ipcRenderer.invoke(`web-contents-call`, {
+    webContentsId: tabId,
+    method: 'goForward',
+  });
+};
+
+window.addEventListener('mouseup', (e) => {
+  if (e.button === 3) {
+    e.preventDefault();
+    goBack();
+  } else if (e.button === 4) {
+    e.preventDefault();
+    goForward();
+  }
+});
+
+let beginningScrollLeft: number = null;
+let beginningScrollRight: number = null;
+let horizontalMouseMove = 0;
+let verticalMouseMove = 0;
+
+const resetCounters = () => {
+  beginningScrollLeft = null;
+  beginningScrollRight = null;
+  horizontalMouseMove = 0;
+  verticalMouseMove = 0;
+};
+
+function getScrollStartPoint(x: number, y: number) {
+  let left = 0;
+  let right = 0;
+
+  let n = document.elementFromPoint(x, y);
+
+  while (n) {
+    if (n.scrollLeft !== undefined) {
+      left = Math.max(left, n.scrollLeft);
+      right = Math.max(right, n.scrollWidth - n.clientWidth - n.scrollLeft);
+    }
+    n = n.parentElement;
+  }
+  return { left, right };
+}
+
+document.addEventListener('wheel', (e) => {
+  verticalMouseMove += e.deltaY;
+  horizontalMouseMove += e.deltaX;
+
+  if (beginningScrollLeft === null || beginningScrollRight === null) {
+    const result = getScrollStartPoint(e.deltaX, e.deltaY);
+    beginningScrollLeft = result.left;
+    beginningScrollRight = result.right;
+  }
+});
+
+ipcRenderer.on('scroll-touch-end', () => {
+  if (
+    horizontalMouseMove - beginningScrollRight > 150 &&
+    Math.abs(horizontalMouseMove / verticalMouseMove) > 2.5
+  ) {
+    if (beginningScrollRight < 10) {
+      goForward();
+    }
+  }
+
+  if (
+    horizontalMouseMove + beginningScrollLeft < -150 &&
+    Math.abs(horizontalMouseMove / verticalMouseMove) > 2.5
+  ) {
+    if (beginningScrollLeft < 10) {
+      goBack();
+    }
+  }
+
+  resetCounters();
+});
+
+if (process.env.ENABLE_AUTOFILL) {
+  window.addEventListener('load', AutoComplete.loadForms);
+  window.addEventListener('mousedown', AutoComplete.onWindowMouseDown);
+}
+
+const postMsg = (data: any, res: any) => {
+  window.postMessage(
+    {
+      id: data.id,
+      result: res,
+      type: 'result',
+    },
+    '*',
+  );
+};
+
+const hostname = window.location.href.substr(WEBUI_BASE_URL.length);
+
+if (
+  process.env.ENABLE_EXTENSIONS &&
+  window.location.host === 'chrome.google.com'
+) {
+  injectChromeWebstoreInstallButton();
+}
+
+const settings = ipcRenderer.sendSync('get-settings-sync');
+if (
+  window.location.href.startsWith(WEBUI_BASE_URL) ||
+  window.location.protocol === `${ERROR_PROTOCOL}:`
+) {
+  (async function () {
+    const w = await webFrame.executeJavaScript('window');
+    w.settings = settings;
+    w.require = (id: string) => {
+      if (id === 'electron') {
+        return { ipcRenderer };
+      }
+      return undefined;
+    };
+
+    if (window.location.pathname.startsWith('//network-error')) {
+      w.theme = getTheme(w.settings.theme);
+      w.errorURL = await ipcRenderer.invoke(`get-error-url-${tabId}`);
+    } else if (hostname.startsWith('history')) {
+      w.getHistory = async () => {
+        return await ipcRenderer.invoke(`history-get`);
+      };
+      w.removeHistory = (ids: string[]) => {
+        ipcRenderer.send(`history-remove`, ids);
+      };
+    } else if (hostname.startsWith('newtab')) {
+      w.getTopSites = async (count: number) => {
+        return await ipcRenderer.invoke(`topsites-get`, count);
+      };
+    }
+  })();
+} else {
+  (async function () {
+    if (settings.doNotTrack) {
+      const w = await webFrame.executeJavaScript('window');
+      Object.defineProperty(w.navigator, 'doNotTrack', { value: 1 });
+    }
+  })();
+}
+
+if (window.location.href.startsWith(WEBUI_BASE_URL)) {
+  window.addEventListener('DOMContentLoaded', () => {
+    if (hostname.startsWith('settings')) document.title = '设置';
+    else if (hostname.startsWith('history')) document.title = '历史记录';
+    else if (hostname.startsWith('bookmarks')) document.title = '管理书签';
+    else if (hostname.startsWith('extensions')) document.title = '扩展';
+    else if (hostname.startsWith('newtab')) {
+      document.title = '新建标签页';
+    }
+  });
+
+  window.addEventListener('message', async ({ data }) => {
+    if (data.type === 'storage') {
+      const res = await ipcRenderer.invoke(`storage-${data.operation}`, {
+        scope: data.scope,
+        ...data.data,
+      });
+
+      postMsg(data, res);
+    } else if (data.type === 'credentials-get-password') {
+      const res = await ipcRenderer.invoke(
+        'credentials-get-password',
+        data.data,
+      );
+      postMsg(data, res);
+    } else if (data.type === 'save-settings') {
+      ipcRenderer.send('save-settings', { settings: data.data });
+    }
+  });
+
+  ipcRenderer.on('update-settings', async (e, data) => {
+    const w = await webFrame.executeJavaScript('window');
+    if (w.updateSettings) {
+      w.updateSettings(data);
+    }
+  });
+
+  ipcRenderer.on('credentials-insert', (e, data) => {
+    window.postMessage(
+      {
+        type: 'credentials-insert',
+        data,
+      },
+      '*',
+    );
+  });
+
+  ipcRenderer.on('credentials-update', (e, data) => {
+    window.postMessage(
+      {
+        type: 'credentials-update',
+        data,
+      },
+      '*',
+    );
+  });
+
+  ipcRenderer.on('credentials-remove', (e, data) => {
+    window.postMessage(
+      {
+        type: 'credentials-remove',
+        data,
+      },
+      '*',
+    );
+  });
+}

+ 32 - 0
src/renderer/components/Button/index.tsx

@@ -0,0 +1,32 @@
+import * as React from 'react';
+
+import { StyledButton, StyledLabel } from './styles';
+
+interface Props {
+  background?: string;
+  foreground?: string;
+  type?: 'contained' | 'outlined';
+  children?: any;
+  onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
+  style?: any;
+}
+
+export const Button = ({
+  background,
+  foreground,
+  type,
+  onClick,
+  children,
+  style,
+}: Props) => (
+  <StyledButton
+    className="button"
+    background={background}
+    foreground={foreground}
+    type={type}
+    onClick={onClick}
+    style={style}
+  >
+    <StyledLabel>{children}</StyledLabel>
+  </StyledButton>
+);

+ 57 - 0
src/renderer/components/Button/styles.ts

@@ -0,0 +1,57 @@
+import styled, { css } from 'styled-components';
+
+interface StyledButtonProps {
+  background: string;
+  foreground: string;
+  type?: 'contained' | 'outlined';
+}
+
+export const StyledButton = styled.div`
+  min-width: 80px;
+  width: fit-content;
+  height: 32px;
+  padding: 0px 12px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  overflow: hidden;
+  border-radius: 4px;
+  position: relative;
+  cursor: pointer;
+
+  &::before {
+    content: '';
+    display: block;
+    width: 100%;
+    height: 100%;
+    z-index: 0;
+    opacity: 0;
+    position: absolute;
+    will-change: opacity;
+    transition: 0.2s opacity;
+  }
+
+  &:hover::before {
+    opacity: 0.12;
+  }
+
+  ${({ background, foreground, type }: StyledButtonProps) => css`
+    color: ${foreground || '#fff'};
+    border: ${type === 'outlined'
+      ? `1px solid ${background || '#2196F3'}`
+      : 'unset'};
+    background-color: ${type === 'outlined'
+      ? 'transparent'
+      : background || '#2196F3'};
+
+    &::before {
+      background-color: ${foreground || '#fff'};
+    }
+  `};
+`;
+
+export const StyledLabel = styled.div`
+  z-index: 1;
+  font-size: 12px;
+  pointer-events: none;
+`;

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio