## Contributor Code of Conduct
### Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
### Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our
mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political
attacks Public or private harassment Publishing others' private
- information, such as a physical or email address, without their
explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
### Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
### Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may
be reported to the community leaders responsible for enforcement at mail@0negal.com or @0neGal on Twitter.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
### Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
#### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
#### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
#### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
#### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
================================================
FILE: CONTRIBUTING.md
================================================
## Contributing
Generally speaking, as Viper is a FOSS (GPLv3) project any bug reports, pull requests, or other types of help, forks are appreciated, but preferably unless it's off-topic to the goals of Viper, it would be far more appreciated if you were to make a pull request, or similar, and get it upstream.
**HOWEVER:** Before opening issues and pull requests and similar, please do read our code of conduct, as to avoid issues.
### General contributions
If you're contributing, please follow code of conduct as mentioned above, along with that please do not change code style. Viper uses double quotes, 1 tab per indent, and semicolons at the end of function calls.
`//` for 1-2 lines of comments, max of 72 comment text width always, preferably if textwidth outside of comments also exceeds 72 characters if possible find a way to make it fit within 72 characters. Lower case comments are also generally preferred when using `//`
`/* */` is useful in some cases, refer to the code example below.
`() => {}` is also preferred over `function () {}` when possible.
Single use functions are also generally discouraged, if a function is used once there's no need to make it a function.
As shown below below:
```js
function foo(bar) {
/*
This is a very long comment, however, it does not exceed 72
characters, and instead wraps down so it fits nicely on a small
screen without having to mess with soft-wrapping or similar.
*/
console.log(bar);
// and this is a comment using "//",
// which is two lines long
}
// examples of () => {}
setInterval(() => {
foo("I RUN EVERY 1000MS");
}, 1000)
```
With the above information you should be able to comfortably make contributions without too much hassle...
### Localizing/Translating
Viper has a very simple i18n system, please read below for instructions.
#### Language file
The language file will be a file inside the `src/lang/` folder, name it according to the [ISO 3166-1 Alpha-2 standard](https://en.m.wikipedia.org/wiki/ISO_3166-1_alpha-2) in lowercase, meaning English = `en.json`, Spanish = `es.json`, French = `fr.json`, and so on.
Everything inside the file is pretty straight forward, the only special one is the `lang.title` string, please set this to ` - `, meaning for French it's, `French - Français`. This will be shown inside the language selection screen.
If you don't feel like editing a JSON file and copying keys back and forwards from other complete language files, then you're in luck, because `scripts/langs.js` help with this exact problem. Simply make sure a valid localization file already exists, meaning it could have just `{}` inside it. Then after that you can use the language script to manage it:
```sh
$ npm install
$ npm run langs:localize
```
You'll be prompted to select a language to edit, then if there are missing keys you'll be prompted for whether you just want to add those keys or if you want to edit all keys. After that you'll get a list of all the keys available, you'll simply select any of them, then you'll be prompted for the value for the key, then hit Enter when you're done, and you'll be put right back to the list of keys as before. You'll then edit as needed, when you're done select `Save changes`, you're changes will then be written to the localization file and it'll automatically be formatted for you.
To sum it up:
1. Make sure a parseable JSON localization file exists in `src/lang/`
2. Run `npm run langs:localize` (after `npm install`)
3. Select your desired language
4. Select the key you want to add/change
5. Edit it as you wish
6. Save whenever your done
7. Commit your changes!
If you do happen to manually edit your localization files remember to run the following commands before committing and pushing changes:
```sh
$ npm install
$ npm langs:check # verifies the files are parseable and not missing keys
$ npm langs:format # formats and sorts the file for you
```
#### Maintainers file
If you're okay with being contacted in the future when new strings have to be localized please put your contact links inside this file, under your language. Preferably put the link to your GitHub profile as that is the easiest contact method for obvious reasons.
================================================
FILE: FAQ.md
================================================
## Frequently Asked Questions (FAQ)
### How do I install Viper?
As briefly covered in the README, you've multiple choices for installing Viper.
#### Windows
There's the installer, and the portable `.exe`, we recommend using the installer as it can auto update, there's a Download button on the README which downloads the newest version of the installer.
#### Linux
On the [releases page](https://github.com/0neGal/viper/releases/latest) there are various package distributions we release, feel free to pick any one of them, but as with Windows only one of them supports auto-installation, that one being the AppImage.
#### After Install
After you've gotten Viper installed you'll select your game path (this may or may not be done automatically, however if we can't find your game automatically we'll ask you to select it manually), then go onto the Northstar tab, click "Install", and now you can launch Northstar and have fun on the frontier.
If you keep getting errors about your game path being wrong follow the [instructions further below...](#this-folder-is-not-a-valid-game-path)
### How do I install mods?
We recommend using Thunderstore, which allows you to easily find mods and install them, to do so simply go into the Northstar tab, then go into the Mods section, and there'll be a button aptly named **"Find Mods"**, clicking it will open an easy to use UI that'll let you search for mods and install them.
### "This folder is not a valid game path."
When selecting a game path make sure it actually is *the game path*. Your game path is where the `Titanfall2.exe` is located, usually inside `C:\Program Files (x86)\Origin Games\Titanfall2`, however if you've installed the game somewhere else or you've installed the game through Steam it may be located somewhere else.
For Steam users, you can inside Steam right click on the game, click **Properties**, then in the window that opens **Local Files**, then **Browse**, the folder that it opens is the game path.
Ideally Viper should be able to find Titanfall automatically, however given we can't predict every installation of the game we can't always find the game.
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
================================================
FILE: PUBLISH.md
================================================
# Publishing a new release
1. Make sure your code works!
2. Update `package.json` version
3. Make sure `package.json`'s `repository.url` key references correct repository
4. Ensure application builds correctly with `npm run build:[windows/linux]`
5. Expose `GH_TOKEN` environment var with your Github token (`build/publish.sh` asks for it)
6. Build and publish with `npm run publish:[windows/linux]`
- Optionally just use `build/publish.sh`, however that only works on Linux/Systems with a `/bin/sh` file, it also checks whether all files have been localized, and that the version numbers have been updated
7. Edit the draft release message and publish the new release!
## CI release
If you don't want to build releases yourself, you can make GitHub build them for you!
1. Make sure your code works!
2. Update `package.json` version
3. Make sure `package.json`'s `repository.url` key references correct repository
4. Ensure application builds correctly with `npm run build:[windows/linux]`
5. Create a prerelease with newest version name
- Creating the prerelease will trigger CI, that will build all executables
- You can use build time to update release notes :)
6. When all binaries have been uploaded to the prerelease, you can publish it!
================================================
FILE: README.md
================================================
## What is Viper?
Viper is a launcher and updater for [Northstar](https://github.com/R2Northstar/Northstar), and not much more than that.
## Install
Downloads are available on the [releases page](https://github.com/0neGal/viper/releases/latest).
Please note that some versions will update themselves automatically when a new release is available (just like Origin or Steam) and some will NOT, so choose it accordingly. Only the AppImage, Flatpak and Windows Setup/Installer can auto-update.
**Windows:** [`Viper Setup [x.y.z].exe`](https://0negal.github.io/viper/index.html?win-setup) (auto-updates, and is recommended), [`Viper [x.y.z].exe`](https://0negal.github.io/viper/index.html?win-portable) (single executable, no fuss)
**Linux:** [`.AppImage`](https://0negal.github.io/viper/index.html?appimage) or [Flatpak](https://flathub.org/apps/details/com.github._0negal.Viper) (auto-updates), [AUR (unofficial)](https://aur.archlinux.org/packages/viper-bin), [`.deb`](https://0negal.github.io/viper/index.html?deb), [`.rpm`](https://0negal.github.io/viper/index.html?rpm), [`.tar.gz`](https://0negal.github.io/viper/index.html?linux)
## What can it do specifically?
Currently Viper is capable of:
* Updating/Installing Northstar
* Launching Vanilla and or Northstar
* Manage Mods
* Auto-Update itself
* Be pretty!
There are of course many other things that it can do, but summed up very simply, that is what Viper is capable of doing. With every update Viper gets more features and alike, often many optional features are also available in the settings menu.
## Configuration
All settings take place in the settings page, found in the top right corner of the app, where you can change all kinds of settings. You can also manually go in and edit your config file (`viper.json`), if you feel so inclined.
Your configuration file will be found in `%APPDATA%\viper.json` on Windows, and inside either `~/.config` or through your environment variables (`$XDG_CONFIG_HOME`) on Linux, the latter has priority.
## Support
To get support please [open a GitHub issue](https://github.com/0neGal/viper/issues/new/choose), and clearly describe the problem with as many details as possible.
### Frequently Asked Questions (FAQ)
Many of the questions and problems you may have might be able to be answered by reading the [FAQ page](FAQ.md). So before opening an issue or asking for support please read through it first!
## Sidenote
Given that we already have so many Northstar updaters and launchers I urge people to instead of creating new launchers unless there's a very specific reason, just make a pull request on one of the existing ones, otherwise we'll continue to have new ones.
Relevant xkcd:
Some of the existing launchers are listed below:
* Viper - A launcher, updater and mod manager with an easy to use GUI
* [FlightCore](https://github.com/R2NorthstarTools/FlightCore) - A more minimal GUI manager and updater, with similar features to Viper
* [ViperSH](https://github.com/0neGal/viper-sh) - A Bourne Shell, CLI only, Northstar updater and mod manager
* [VTOL](https://github.com/BigSpice/VTOL) - an updater and manager for mods, very feature rich
* [r2modman](https://github.com/ebkr/r2modmanPlus) - General purpose mod manager, which has support for Northstar
* [Papa](https://github.com/AnActualEmerald/papa) - a CLI only installer, updater, and mod manager
* [FIITE](https://github.com/EladNLG/FastestInstallerInTheEast) - a minimalistic CLI installer and updater.
## Development
If you wanna edit Viper's code, run it, and so on, you can simply do something along the lines of the below:
```sh
$ git clone https://github.com/0neGal/viper
$ cd viper
$ npm i
$ npm run start
```
This'll launch it with the Electron build installed by `npm`.
Additionally, if you're creating your own fork you easily publish builds and or make builds with either `npm run publish` or `npm run build` respectively, the prior requiring a `$GH_TOKEN` to be set, as it creates the release itself so it needs a token with access to your repo. So you'd do something along the lines of:
```sh
$ GH_TOKEN="" npm run publish
```
Keep in mind building all Linux builds may take a while on some systems, as packaging the `tar.gz` release can take a while on many CPUs, at least from my testing. All other builds should be done quickly. When using the `publish` command it also automatically uploads the needed files to deploy auto-updates, keep in mind you'd need to have the `repository` setting changed to your new fork's location, otherwise it'll fetch from the original.
## Credits
**Logo:** Imply#9781
**Viper Background:** [Uber Panzerhund](https://www.reddit.com/r/titanfall/comments/fwuh2x/take_to_the_skies)
**Titanfall+Northstar Logo:** [Aftonstjarma](https://www.steamgriddb.com/logo/47851)
================================================
FILE: docs/index.html
================================================
Viper
================================================
FILE: src/app/js/browser.js
================================================
const Fuse = require("fuse.js");
const { ipcRenderer, shell } = require("electron");
const lang = require("../../lang");
const popups = require("./popups");
const toasts = require("./toasts");
const request = require("./request");
var browser_fuse;
var packages = [];
var packagecount = 0;
var browser_el = document.getElementById("browser")
var browser = {
maxentries: 50,
mod_versions: {},
filters: {
getpkgs: () => {
let pkgs = [];
let other = [];
for (let i in packages) {
if (! browser.filters.isfiltered(packages[i].categories)) {
pkgs.push(packages[i]);
} else {
other.push(packages[i]);
}
}
return pkgs;
},
get: () => {
let filtered = [];
let unfiltered = [];
let checks = browser_el.querySelectorAll("#filters .check");
for (let i = 0; i < checks.length; i++) {
if (! checks[i].classList.contains("checked")) {
filtered.push(checks[i].getAttribute("value"));
} else {
unfiltered.push(checks[i].getAttribute("value"));
}
}
return {
filtered,
unfiltered
};
},
isfiltered: (categories) => {
let filtered = browser.filters.get().filtered;
let unfiltered = browser.filters.get().unfiltered;
let state = false;
let filters = [
"Mods", "Skins",
"Client-side", "Server-side",
];
let newcategories = [];
for (let i = 0; i < categories.length; i++) {
if (filters.includes(categories[i])) {
newcategories.push(categories[i]);
}
}; categories = newcategories;
if (categories.length == 0) {return true}
for (let i = 0; i < categories.length; i++) {
if (filtered.includes(categories[i])) {
state = true;
continue
} else if (unfiltered.includes(categories[i])) {
state = false;
continue
}
state = true;
}
return state;
},
toggle: (state) => {
if (state == false) {
filters.classList.remove("shown");
return
}
filters.classList.toggle("shown");
let filterRect = filter.getBoundingClientRect();
let spacing = parseInt(getComputedStyle(filters).getPropertyValue("--spacing"));
filters.style.top = filterRect.bottom - (spacing + (spacing * 1.3));
filters.style.right = filterRect.right - filterRect.left + filterRect.width - (spacing / 2);
},
},
toggle: (state) => {
browser_el.scrollTo(0, 0);
popups.set("#browser", state);
if (state) {
if (browserEntries.querySelectorAll(".el").length == 0) {
browser.loadfront();
}
} else if (state === false) {
browser.filters.toggle(false);
}
},
install: async (package_obj, clear_queue = false) => {
let can_connect = await request.check_with_toasts(
"Thunderstore", "https://thunderstore.io"
)
if (! can_connect) {
return;
}
return mods.install_from_url(
package_obj.download || package_obj.versions[0].download_url,
package_obj.dependencies || package_obj.versions[0].dependencies,
clear_queue,
package_obj.author || package_obj.owner,
package_obj.name || package_obj.pkg.name,
package_obj.version || package_obj.versions[0].version_number
)
},
add_pkg_properties: () => {
for (let i = 0; i < packages.length; i++) {
let properties = packages[i];
let normalized = mods.normalize(packages[i].name);
let has_update = false;
let local_name = false;
let local_version = false;
let remote_version = packages[i].versions[0].version_number;
remote_version = version.format(remote_version);
if (mods.list()) {
for (let ii = 0; ii < mods.list().all.length; ii++) {
let mod = mods.list().all[ii];
if (mods.normalize(mod.name) !== normalized && (
! mod.package ||
mod.package.author + "-" + mod.package.package_name !==
packages[i].full_name
)) {
continue;
}
local_name = mod.name;
local_version = version.format(mod.version);
if (version.is_newer(remote_version, local_version)) {
has_update = true;
}
}
}
let install = () => {
return browser.install({...properties});
}
packages[i].unix_created = new Date(packages[i].date_created).getTime();
packages[i].unix_updated = new Date(packages[i].date_updated).getTime();
packages[i].install = install;
packages[i].has_update = has_update;
packages[i].local_version = local_version;
packages[i].downloads = 0;
for (let version of packages[i].versions) {
packages[i].downloads += version.downloads || 0;
}
if (local_version) {
browser.mod_versions[normalized] = {
install: install,
has_update: has_update,
local_name: local_name,
local_version: local_version,
package: packages[i]
}
}
}
},
// sorts `pkgs` based on `property` in package object
sort: (pkgs, property) => {
// get property from sort selector, if not specified
if (! property) {
property = sort.querySelector("select").value;
// if we somehow still don't have a property, just return
if (! property) {
return pkgs;
}
}
// if `property` doesn't even exist, just return
if (typeof pkgs[0][property] == "undefined") {
return pkgs;
}
// sort in descending order
return pkgs.sort((a, b) => {
return b[property] - a[property];
})
},
loadfront: async () => {
browser.loading();
packagecount = 0;
if (packages.length < 1) {
let host = "northstar.thunderstore.io";
let path = "/api/v1/package/";
packages = [];
// attempt to get the list of packages from Thunderstore, if
// this has been done recently, it'll simply return a cached
// version of the request
try {
packages = JSON.parse(
await request(host, path, "thunderstore-packages")
)
}catch(err) {
console.error(err)
}
browser.add_pkg_properties();
browser_fuse = new Fuse(packages, {
keys: ["full_name"]
})
}
let pkgs = browser.sort(browser.filters.getpkgs());
for (let i in pkgs) {
if (packagecount >= browser.maxentries) {
browser.endoflist();
break
}
browser.mod_el_from_obj(pkgs[i]);
packagecount++;
}
},
loading: (string) => {
if (browser.filters.get().unfiltered.length == 0) {
string = lang("gui.browser.no_results");
}
if (string) {
browserEntries.innerHTML = `
${string}
`;
}
if (! browserEntries.querySelector(".loading")) {
browserEntries.innerHTML = `
${lang('gui.browser.loading')}
`;
}
},
endoflist: (is_end) => {
let pkgs = [];
let filtered = browser.filters.getpkgs();
for (let i = 0; i < filtered.length; i++) {
if (filtered[packagecount + i]) {
pkgs.push(filtered[packagecount + i]);
} else {
break
}
}
if (browserEntries.querySelector(".message")) {
browserEntries.querySelector(".message").remove();
}
if (pkgs.length == 0 || is_end) {
browser.msg(`${lang('gui.browser.endoflist')}`);
return
}
browser.msg(``);
loadmore.addEventListener("click", () => {
browser.loadpkgs(pkgs);
browser.endoflist(! pkgs.length);
})
},
search: (string) => {
browser.loading();
let res = browser_fuse.search(string);
if (res.length < 1) {
browser.loading(lang("gui.browser.no_results"));
return
}
packagecount = 0;
let count = 0;
for (let i = 0; i < res.length; i++) {
if (count >= browser.maxentries) {break}
if (browser.filters.isfiltered(res[i].item.categories)) {continue}
browser.mod_el_from_obj(res[i].item);
count++;
}
if (count < 1) {
browser.loading(lang("gui.browser.no_results"));
}
},
setbutton: (mod, string, icon) => {
mod = mods.normalize(mod);
if (browserEntries.querySelector(`#mod-${mod}`)) {
let elems = browserEntries.querySelectorAll(`.el#mod-${mod}`);
for (let i = 0; i < elems.length; i++) {
if (icon) {
string = `` +
`${string}`;
}
elems[i].querySelector(".text button").innerHTML = string;
}
} else {
let make = (str) => {
if (browserEntries.querySelector(`#mod-${str}`)) {
return browser.setbutton(str, string, icon);
} else {
return false;
}
}
setTimeout(() => {
for (let i = 0; i < mods.list().all.length; i++) {
let modname = mods.normalize(mods.list().all[i].name);
let modfolder = mods.normalize(mods.list().all[i].folder_name);
if (mod.includes(modname)) {
if (! make(modname)) {
if (mods.list().all[i].manifest_name) {
make(mods.normalize(mods.list().all[i].manifest_name));
}
}
}
else if (mod.includes(modfolder)) {make(modfolder);break}
}
}, 1501)
}
},
loadpkgs: (pkgs, clear) => {
if (clear) {packagecount = 0}
if (browserEntries.querySelector(".message")) {
browserEntries.querySelector(".message").remove();
}
let count = 0;
for (let i in pkgs) {
if (count >= browser.maxentries) {
if (pkgs[i] === undefined) {
browser.endoflist(true);
}
browser.endoflist();
break
}
try {
browser.mod_el_from_obj(pkgs[i]);
}catch(e) {}
count++;
packagecount++;
}
},
msg: (html) => {
let msg = document.createElement("div");
msg.classList.add("message");
msg.innerHTML = html;
browserEntries.appendChild(msg);
}
}
sort.querySelector("select").addEventListener("change", () => {
browser.loadfront();
})
setInterval(browser.add_pkg_properties, 1500);
if (navigator.onLine) {
browser.loadfront();
}
var view = document.querySelector(".popup#preview webview");
browser.preview = {
show: () => {
popups.show(preview, false);
},
hide: () => {
popups.hide(preview, false);
},
set: (url, autoshow) => {
if (autoshow != false) {browser.preview.show()}
view.src = url;
document.querySelector("#preview #external").setAttribute(
"onclick",
`require("electron").shell.openExternal("${url}")`
)
}
}
browser.mod_el_from_obj = (obj) => {
let pkg = {...obj, ...obj.versions[0]};
browser.mod_el({
pkg: pkg,
title: pkg.name,
image: pkg.icon,
author: pkg.owner,
url: pkg.package_url,
download: pkg.download_url,
version: pkg.version_number,
categories: pkg.categories,
description: pkg.description,
dependencies: pkg.dependencies,
})
}
browser.mod_el = (properties) => {
if (browser.filters.isfiltered(properties.categories)) {return}
properties = {
title: "No name",
version: "1.0.0",
image: "icons/no-image.png",
author: "Unnamed Pilot",
description: "No description",
...properties
}
if (properties.version[0] != "v") {
properties.version = "v" + properties.version;
}
if (browserEntries.querySelector(".loading")) {
browserEntries.innerHTML = "";
}
let installicon = "downloads";
let installstr = lang("gui.browser.install");
let normalized_title = mods.normalize(properties.title)
let installcallback = () => {
browser.install(properties);
}
let nondefault_install = {
"vanillaplus": "https://github.com/NachosChipeados/NP.VanillaPlus/blob/main/README.md"
}
if (normalized_title in nondefault_install) {
installicon = "open";
installstr = lang("gui.browser.guide");
installcallback = () => {
shell.openExternal(nondefault_install[normalized_title])
}
}
else if (properties.pkg.local_version) {
installicon = "redo";
installstr = lang("gui.browser.reinstall");
if (properties.pkg.has_update) {
installicon = "downloads";
installstr = lang("gui.browser.update");
}
}
let entry = document.createElement("div");
entry.classList.add("el");
entry.id = `mod-${normalized_title}`;
entry.innerHTML = `
${properties.title}
${properties.description}
`
entry.querySelector("button.install").addEventListener("click", installcallback)
browserEntries.appendChild(entry);
}
browser.packages = async () => {
await browser.loadfront();
return packages;
}
let recent_toasts = {};
function add_recent_toast(name, timeout = 3000) {
if (recent_toasts[name]) {return}
recent_toasts[name] = true;
setTimeout(() => {
delete recent_toasts[name];
}, timeout)
}
ipcRenderer.on("removed-mod", (_, mod) => {
set_buttons(true);
browser.setbutton(mod.name, lang("gui.browser.install"), "downloads");
if (mod.manifest_name) {
browser.setbutton(mod.manifest_name, lang("gui.browser.install"), "downloads");
}
})
ipcRenderer.on("failed-mod", (_, modname) => {
if (recent_toasts["failed" + modname]) {return}
add_recent_toast("failed" + modname);
set_buttons(true);
toasts.show({
timeout: 10000,
scheme: "error",
title: lang("gui.toast.title.failed"),
description: lang("gui.toast.desc.failed")
})
})
ipcRenderer.on("legacy-duped-mod", (_, modname) => {
if (recent_toasts["duped" + modname]) {return}
add_recent_toast("duped" + modname);
set_buttons(true);
toasts.show({
timeout: 10000,
scheme: "warning",
title: lang("gui.toast.title.duped"),
description: modname + " " + lang("gui.toast.desc.duped")
})
})
ipcRenderer.on("no-internet", () => {
toasts.show({
timeout: 10000,
scheme: "error",
title: lang("gui.toast.title.no_internet"),
description: lang("gui.toast.desc.no_internet")
})
})
ipcRenderer.on("installed-mod", (_, mod) => {
if (recent_toasts["installed" + mod.name]) {return}
add_recent_toast("installed" + mod.name);
let name = mod.fancy_name || mod.name;
set_buttons(true);
browser.setbutton(name, lang("gui.browser.reinstall"), "redo");
if (mod.malformed) {
toasts.show({
timeout: 8000,
scheme: "warning",
title: lang("gui.toast.title.malformed"),
description: name + " " + lang("gui.toast.desc.malformed")
})
}
toasts.show({
scheme: "success",
title: lang("gui.toast.title.installed"),
description: name + " " + lang("gui.toast.desc.installed")
})
if (mods.install_queue.length != 0) {
mods.install_from_url(
"https://thunderstore.io/package/download/" + mods.install_queue[0].pkg,
false, false, mods.install_queue[0].author, mods.install_queue[0].package_name, mods.install_queue[0].version
)
mods.install_queue.shift();
}
})
let searchtimeout;
let searchstr = "";
let search = document.querySelector("#browser .search");
search.addEventListener("keyup", () => {
browser.filters.toggle(false);
clearTimeout(searchtimeout);
if (searchstr != search.value) {
if (search.value.replaceAll(" ", "") == "") {
searchstr = "";
browser.loadfront();
return
}
searchtimeout = setTimeout(() => {
browser.search(search.value);
searchstr = search.value;
}, 500)
}
})
let mouse_events = ["scroll", "mousedown", "touchdown"];
mouse_events.forEach((event) => {
document.body.addEventListener(event, () => {
let mouse_at = document.elementsFromPoint(mouseX, mouseY);
if (! mouse_at.includes(document.querySelector("#preview"))) {
browser.preview.hide();
}
if (! mouse_at.includes(document.querySelector("#filter"))
&& ! mouse_at.includes(document.querySelector(".overlay"))) {
browser.filters.toggle(false);
}
})
});
view.addEventListener("dom-ready", () => {
let css = [
fs.readFileSync(__dirname + "/../css/theming.css", "utf8"),
fs.readFileSync(__dirname + "/../css/webview.css", "utf8")
]
view.insertCSS(css.join(" "));
})
view.addEventListener("did-stop-loading", () => {
view.style.display = "flex";
setTimeout(() => {
view.classList.remove("loading");
}, 200)
})
view.addEventListener("did-start-loading", () => {
view.style.display = "none";
view.classList.add("loading");
})
let mouseY = 0;
let mouseX = 0;
browser_el.addEventListener("mousemove", (event) => {
mouseY = event.clientY;
mouseX = event.clientX;
})
let checks = document.querySelectorAll(".check");
for (let i = 0; i < checks.length; i++) {
checks[i].setAttribute("onclick",
"this.classList.toggle('checked');browser.loadfront();search.value = ''"
)
}
module.exports = browser;
================================================
FILE: src/app/js/dom_events.js
================================================
const popups = require("./popups");
const settings = require("./settings");
let drag_timer;
document.addEventListener("dragover", (e) => {
e.preventDefault();
e.stopPropagation();
dragUI.classList.add("shown");
clearTimeout(drag_timer);
drag_timer = setTimeout(() => {
dragUI.classList.remove("shown");
}, 5000)
})
document.addEventListener("mouseover", () => {
clearTimeout(drag_timer);
dragUI.classList.remove("shown");
})
document.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
dragUI.classList.remove("shown");
mods.install_from_path(e.dataTransfer.files[0].path);
})
document.body.addEventListener("click", (e) => {
if (e.target.tagName.toLowerCase() === "a"
&& e.target.protocol != "file:") {
e.preventDefault();
shell.openExternal(e.target.href);
}
})
================================================
FILE: src/app/js/events.js
================================================
const EventEmitter = require("events");
class Emitter extends EventEmitter {};
const events = new Emitter();
module.exports = events;
================================================
FILE: src/app/js/gamepad.js
================================================
const popups = require("./popups");
const settings = require("./settings");
const launcher = require("./launcher");
const navigate = require("./navigate");
window.addEventListener("gamepadconnected", (e) => {
console.log("Gamepad connected:", e.gamepad.id);
}, false)
window.addEventListener("gamepaddisconnected", (e) => {
console.log("Gamepad disconnected:", e.gamepad.id);
}, false)
// this contains the names/directions of axes and IDs that have
// previously been pressed, if it is found that these were recently
// pressed in the next iteration of the `setInterval()` below than the
// iteration is skipped
//
// the value of each item is equivalent to the amount of iterations to
// wait, so `up: 3` will cause it to wait 3 iterations, before `up` can
// be pressed again
let delay_press = {};
let held_buttons = {};
setInterval(() => {
let gamepads = navigator.getGamepads();
// this has a list of all the directions that the `.axes[]` are
// pointing in, letting us navigate in that direction
let directions = {}
// keeps track of which buttons `delay_press` that have already been
// lowered, that way we can lower the ones that haven't been lowered
// through a button press
let lowered_delay = [];
// is the select/accept button being held
let selecting = false;
for (let i in gamepads) {
if (! gamepads[i]) {continue}
// every other `.axes[]` element is a different coordinate, each
// analog stick has 2 elements in `.axes[]`, the first one is
// the x coordinate, second is the y coordinate
//
// so we use this to keep track of which coordinate we're
// currently on, and thereby the direction of the float inside
// `.axes[i]`
let coord = "x";
let deadzone = 0.5;
for (let ii = 0; ii < gamepads[i].axes.length; ii++) {
let value = gamepads[i].axes[ii];
// check if we're beyond the deadzone in both the negative
// and positive direction, and then using `coord` add a
// direction to `directions`
if (value < -deadzone) {
if (coord == "y") {
directions.up = true;
} else {
directions.left = true;
}
} else if (value > deadzone) {
if (coord == "y") {
directions.down = true;
} else {
directions.right = true;
}
}
// flip `coord`
if (coord == "x") {
coord = "y";
} else {
coord = "x";
}
}
// only support "standard" button layouts/mappings
//
// TODO: for anybody reading this in the future, the support
// for other mappings is something that's on the table,
// however, due to not having all the hardware in the world,
// this will have to be up to someone else
if (gamepads[i].mapping != "standard") {
continue;
}
for (let ii = 0; ii < gamepads[i].buttons.length; ii++) {
if (! gamepads[i].buttons[ii].pressed) {
held_buttons[ii] = false;
continue;
}
// a list of known combinations of buttons for the most
// common brands out there, more should possibly be added
let brands = {
"Xbox": {
accept: 0,
cancel: 1
},
"Nintendo": {
accept: 1,
cancel: 0
},
"PlayStation": {
accept: 0,
cancel: 1
}
}
// this is the most common setup, to my understanding, with
// the exception of third party Nintendo controller, may
// need to be adjusted in the future
let buttons = {
accept: 0,
cancel: 1
}
// set `cancel` and `accept` accordingly to the ID of the
// gamepad, if its a known brand
for (let brand in brands) {
// unknown brand
if (! gamepads[i].id.includes(brand)) {
continue;
}
// set buttons according to brand
buttons = brands[brand];
break;
}
// if the button that's being pressed is the "accept"
// button, then we set `selecting` to `true`, this is done
// before we check for the button delay so that holding the
// button keeps the selection in place, until the button is
// no longer pressed
if (ii == buttons.accept) {
selecting = true;
}
// if this button is still delayed, we lower the delay and
// then go to the next button
if (delay_press[ii]) {
delay_press[ii]--;
lowered_delay.push(ii);
continue;
}
// add delay to this button, so it doesn't get clicked
// immediately again after this
delay_press[ii] = 3;
if (held_buttons[ii]) {
continue;
}
held_buttons[ii] = true;
// interpret `ii` as a specific button/action, using the
// standard IDs: https://w3c.github.io/gamepad/#remapping
switch(ii) {
// settings popup (center cluster buttons)
case 8: settings.popup.toggle(); break;
case 9: settings.popup.toggle(); break;
// change active section (top bumpers)
case 4: launcher.relative_section("left"); break;
case 5: launcher.relative_section("right"); break;
// navigate selection (dpad)
case 12: navigate.move("up"); break;
case 13: navigate.move("down"); break;
case 14: navigate.move("left"); break;
case 15: navigate.move("right"); break;
// click selected element
case buttons.accept: navigate.select(); break;
// close last opened popup
case buttons.cancel: popups.hide_last(); break;
}
}
}
for (let i in directions) {
if (directions[i] === true) {
// if this direction is still delayed, we lower the delay,
// and then go to the next direction
if (delay_press[i]) {
delay_press[i]--;
lowered_delay.push(i);
continue;
}
// move in the direction
navigate.move(i);
// add delay to this direction, to prevent it from being
// triggered immediately again
delay_press[i] = 5;
}
}
// run through buttons that have or have had a delay
for (let i in delay_press) {
// if a button has a delay, and it hasn't already been lowered,
// then we lower it
if (delay_press[i] && ! lowered_delay.includes(i)) {
delay_press[i]--;
}
}
let selection_el = document.getElementById("selection");
// add `.selecting` to `#selection` depending on whether
// `selecting`, is set or not
if (selecting) {
selection_el.classList.add("controller-selecting");
} else {
selection_el.classList.remove("controller-selecting");
}
}, 50)
let can_keyboard_navigate = (e) => {
// quite empty right now, might add more in the future, these are
// just element selectors where movement with the keyboard is off
let ignore_on_focus = [
"input",
"select"
]
// check for whether the active element is one that matches
// something in `ignore_on_focus`
for (let i = 0; i < ignore_on_focus.length; i++) {
if (! document.activeElement.matches(ignore_on_focus)) {
// active element does not match to `ignore_on_focus[i]`
continue;
}
// if the key that's being pressed is "Escape" then we unfocus
// to the currently focused active element, this lets you go
// into an input, and then exit it as well
if (e.key == "Escape") {
document.activeElement.blur();
}
return false;
}
// check if there's already an active selection
if (document.querySelector(".active-selection")) {
// this is a list of keys where this keyboard event will be
// cancelled on, this prevents key events from being sent to
// element, but still lets you type
let cancel_keys = [
"Space", "Enter",
"ArrowUp", "ArrowDown",
"ArrowLeft", "ArrowRight"
]
// cancel this keyboard event if `e.key` is inside `cancel_keys`
if (cancel_keys.includes(e.code)) {
e.preventDefault();
}
}
return true;
}
window.addEventListener("keydown", (e) => {
// do nothing if we cant navigate
if (! can_keyboard_navigate(e)) {
return;
}
let select = () => {
// do nothing if this is a repeat key press
if (e.repeat) {return}
// select `.active-selection`
navigate.select();
// add `.keyboard-selecting` to `#selection`
document.getElementById("selection")
.classList.add("keyboard-selecting");
}
// perform the relevant action for the key that was pressed
switch(e.code) {
// select
case "Space": return select();
case "Enter": return select();
// close popup
case "Escape": return popups.hide_last();
// move selection
case "KeyK": case "ArrowUp": return navigate.move("up")
case "KeyJ": case "ArrowDown": return navigate.move("down")
case "KeyH": case "ArrowLeft": return navigate.move("left")
case "KeyL": case "ArrowRight": return navigate.move("right")
}
})
window.addEventListener("keyup", (e) => {
if (! can_keyboard_navigate(e)) {
return;
}
let selection_el = document.getElementById("selection");
// perform the relevant action for the key that was pressed
switch(e.code) {
// the second and third cases here are for SteamDeck bumper
// button support whilst inside the desktop layout
case "KeyQ":
case "ControlLeft": case "ControlRight":
launcher.relative_section("left"); break;
case "KeyE":
case "AltLeft": case "AltRight":
launcher.relative_section("right"); break;
case "Space": return selection_el
.classList.remove("keyboard-selecting");
case "Enter": return selection_el
.classList.remove("keyboard-selecting");
}
})
================================================
FILE: src/app/js/gamepath.js
================================================
const ipcRenderer = require("electron").ipcRenderer;
const lang = require("../../lang");
const process = require("./process");
const launcher = require("./launcher");
const settings = require("./settings");
// frontend part of settings a new game path
ipcRenderer.on("newpath", (_, newpath) => {
set_buttons(true);
settings.set({gamepath: newpath});
ipcRenderer.send("gui-getmods");
ipcRenderer.send("save-settings", settings.data());
})
// a previously valid gamepath no longer exists, and is therefore lost
ipcRenderer.on("gamepath-lost", () => {
launcher.change_page(0);
set_buttons(false, true);
alert(lang("gui.gamepath.lost"));
})
// error out when no game path is set
ipcRenderer.on("no-path-selected", () => {
alert(lang("gui.gamepath.must"));
process.exit();
})
// error out when game path is wrong
ipcRenderer.on("wrong-path", () => {
alert(lang("gui.gamepath.wrong"));
gamepath.set(false);
})
// reports to the main process about game path status.
module.exports = {
open: () => {
let gamepath = settings.data().gamepath;
if (gamepath) {
require("electron").shell.openPath(gamepath);
} else {
alert(lang("gui.settings.miscbuttons.open_gamepath_alert"));
}
},
set: (value) => {
ipcRenderer.send("setpath", value);
}
}
================================================
FILE: src/app/js/is_running.js
================================================
const lang = require("../../lang");
// is the game running?
let is_running = false;
// updates play buttons depending on whether the game is running
ipcRenderer.on("is-running", (event, running) => {
let set_playbtns = (text) => {
let playbtns = document.querySelectorAll(".playBtn");
for (let i = 0; i < playbtns.length; i++) {
playbtns[i].innerHTML = text;
}
}
if (running && is_running != running) {
set_buttons(false);
set_playbtns(lang("general.running"));
is_running = running;
// show force quit button in Titanfall tab
tfquit.style.display = "inline-block";
update.setAttribute("onclick", "kill('game')");
update.innerHTML = "(" + lang("ns.menu.force_quit") + ")";
return;
}
if (is_running != running) {
set_buttons(true);
set_playbtns(lang("gui.launch"));
is_running = running;
// hide force quit button in Titanfall tab
tfquit.style.display = "none";
update.setAttribute("onclick", "update.ns()");
update.innerHTML = "(" + lang("gui.update.check") + ")";
}
})
// return whether the game is running
module.exports = () => {
return is_running;
}
================================================
FILE: src/app/js/kill.js
================================================
const ipcRenderer = require("electron").ipcRenderer;
// attempts to kill something using the main process' `modules/kill.js`
// functions, it simply attempts to run `kill[function_name]()`, if it
// doesn't exist, nothing happens
module.exports = (function_name) => {
ipcRenderer.send("kill", function_name);
}
================================================
FILE: src/app/js/launch.js
================================================
const update = require("./update");
// tells the main process to launch `game_version`
module.exports = (game_version) => {
if (game_version == "vanilla") {
ipcRenderer.send("launch", game_version);
return;
}
if (update.ns.should_install) {
update.ns();
} else {
ipcRenderer.send("launch", game_version);
}
}
================================================
FILE: src/app/js/launcher.js
================================================
const popups = require("./popups");
const markdown = require("marked").parse;
let launcher = {};
var servercount;
var playercount;
var masterserver;
// changes the main page, this is the tabs in the sidebar
launcher.change_page = (page) => {
let btns = document.querySelectorAll(".gamesContainer button");
let pages = document.querySelectorAll(".mainContainer .contentContainer");
for (let i = 0; i < pages.length; i++) {
pages[i].classList.add("hidden");
}
for (let i = 0; i < btns.length; i++) {
btns[i].classList.add("inactive");
}
pages[page].classList.remove("hidden");
btns[page].classList.remove("inactive");
bgHolder.setAttribute("bg", page);
}; launcher.change_page(1)
launcher.format_release = (notes) => {
if (! notes) {return ""}
let content = "";
if (notes.length === 1) {
content = notes[0];
} else {
for (let release of notes) {
if (release.prerelease) {continue}
let new_content =
// release date
new Date(release.published_at).toLocaleString() +
"\n" +
// release name
`# ${release.name}` +
"\n\n" +
// actual release text/body
release.body +
"\n\n\n";
content +=
"
";
}
content = content.replaceAll(/\@(\S+)/g, `@$1`);
}
return markdown(content, {
breaks: true
});
}
// sets content of `div` to a single release block with centered text
// inside it, the text being `lang(lang_key)`
launcher.error = (div, lang_key) => {
div.innerHTML =
"
" +
"
" +
lang(lang_key) +
"
" +
"
";
}
// updates the Viper release notes
ipcRenderer.on("vp-notes", (event, response) => {
if (! response) {
return launcher.error(
vpReleaseNotes,
"request.no_vp_release_notes"
)
}
vpReleaseNotes.innerHTML = launcher.format_release(response);
});
// updates the Northstar release notes
ipcRenderer.on("ns-notes", (event, response) => {
if (! response) {
return launcher.error(
nsRelease,
"request.no_ns_release_notes"
)
}
nsRelease.innerHTML = launcher.format_release(response);
});
launcher.load_vp_notes = async () => {
ipcRenderer.send("get-vp-notes");
}; launcher.load_vp_notes();
launcher.load_ns_notes = async () => {
ipcRenderer.send("get-ns-notes");
}; launcher.load_ns_notes();
// TODO: We gotta make this more automatic instead of switch statements
// it's both not pretty, but adding more sections requires way too much
// effort, compared to how it should be.
launcher.show_vp = (section) => {
if (!["main", "release", "info", "credits"].includes(section)) throw new Error("unknown vp section");
vpMainBtn.removeAttribute("active");
vpReleaseBtn.removeAttribute("active");
vpInfoBtn.removeAttribute("active");
vpMain.classList.add("hidden");
vpReleaseNotes.classList.add("hidden");
vpInfo.classList.add("hidden");
switch(section) {
case "main":
vpMainBtn.setAttribute("active", "");
vpMain.classList.remove("hidden");
break;
case "release":
vpReleaseBtn.setAttribute("active", "");
vpReleaseNotes.classList.remove("hidden");
break;
case "info":
vpInfoBtn.setAttribute("active", "");
vpInfo.classList.remove("hidden");
break;
}
}
launcher.show_ns = (section) => {
if (! ["main", "release", "mods"].includes(section)) {
throw new Error("unknown ns section");
}
nsMainBtn.removeAttribute("active");
nsModsBtn.removeAttribute("active");
nsReleaseBtn.removeAttribute("active");
nsMain.classList.add("hidden");
nsMods.classList.add("hidden");
nsRelease.classList.add("hidden");
switch(section) {
case "main":
nsMainBtn.setAttribute("active", "");
nsMain.classList.remove("hidden");
break;
case "mods":
nsModsBtn.setAttribute("active", "");
nsMods.style.display = "block";
nsMods.classList.remove("hidden");
break;
case "release":
nsReleaseBtn.setAttribute("active", "");
nsRelease.classList.remove("hidden");
break;
}
}
// changes the active section on the currently active
// `.contentContainer` in the direction specified
//
// `direction` can be: left or right
launcher.relative_section = (direction) => {
// prevent switching section if a popup is open
if (popups.open_list().length) {
return;
}
// the `.contentMenu` in the currently active tab
let active_menu = document.querySelector(
".contentContainer:not(.hidden) .contentMenu"
)
// get the currently active section
let active_section = active_menu.querySelector("[active]");
// no need to do anything, if there's somehow no active section
if (! active_section) {return}
// these will be filled out
let prev_section, next_section;
// get list of all the sections
let sections = active_menu.querySelectorAll("li");
for (let i = 0; i < sections.length; i++) {
if (sections[i] != active_section) {
continue;
}
// make `next_section` be the next element in `sections`
next_section = sections[i + 1];
// if we're at the first iteration, use the last element in
// `sections` as the previous section, otherwise make it the
// element before this iteration
if (i == 0) {
prev_section = sections[sections.length - 1];
} else {
prev_section = sections[i - 1];
}
}
let new_section;
// if we're going left, and a previous section was found, click it
if (direction == "left" && prev_section) {
new_section = prev_section;
} else if (direction == "right") {
// click the next section, if one was found, otherwise just
// assume that the first section is the next section, as the
// active section is likely just the last section, so we wrap
// around instead
if (next_section) {
new_section = next_section;
} else if (sections[0]) {
new_section = sections[0];
}
}
if (new_section) {
new_section.click();
// if there's an active selection, we select the new section, as
// that selection may be in a section that's now hidden
if (document.querySelector(".active-selection")) {
navigate.selection(new_section);
}
}
}
launcher.check_servers = async () => {
serverstatus.classList.add("checking");
try {
let host = "northstar.tf";
let path = "/client/servers";
// ask the masterserver for the list of servers, if this has
// been done recently, it'll simply return the cached version
let servers = JSON.parse(
await request(host, path, "ns-servers", false)
)
masterserver = true;
playercount = 0;
servercount = servers.length;
for (let i = 0; i < servers.length; i++) {
playercount += servers[i].playerCount
}
}catch (err) {
playercount = 0;
servercount = 0;
masterserver = false;
}
serverstatus.classList.remove("checking");
if (servercount == 0 || ! servercount || ! playercount) {masterserver = false}
let playerstr = lang("gui.server.players");
if (playercount == 1) {
playerstr = lang("gui.server.player");
}
if (masterserver) {
serverstatus.classList.add("up");
serverstatus.classList.remove("down");
serverstatus.innerHTML = `${servercount} ${lang("gui.server.servers")} - ${playercount} ${playerstr}`;
} else {
serverstatus.classList.add("down");
serverstatus.classList.remove("up");
serverstatus.innerHTML = lang("gui.server.offline");
}
}; launcher.check_servers()
// refreshes every 5 minutes
setInterval(() => {
launcher.check_servers();
}, 300000)
module.exports = launcher;
================================================
FILE: src/app/js/localize.js
================================================
// localizes `string`, removing instances of `%%string%%` with
// `lang("string")` and so forth
function localize_string(string) {
let parts = string.split("%%");
// basic checks to make sure `string` has lang strings
if (parts.length == 0
|| string.trim() == "" || ! string.match("%%")) {
return string;
}
for (let i = 0; i < parts.length; i++) {
// simply checks to make sure it is actually a lang string.
if (parts[i][0] != " " &&
parts[i][parts[i].length - 1] != " ") {
// get string
let lang_str = lang(parts[i]);
// make sure we got a string back, and if not, do nothing
if (typeof lang_str !== "string") {
continue;
}
// replace this part with the lang string
parts[i] = lang_str;
}
}
// return finalized formatted string
return parts.join("");
}
// runs `localize_string()` on `el`'s attributes, text nodes and children
function localize_el(el) {
// we don't want to mess with script tags
if (el.tagName == "SCRIPT") {return}
let attributes = el.getAttributeNames();
// run through child nodes
for (let i = 0; i < el.childNodes.length; i++) {
// if the node isn't a text node, we do nothing
if (el.childNodes[i].nodeType != Node.TEXT_NODE) {
continue;
}
// the node is a text node, so we set its `.textContent` by
// running `format_string()` on it
el.childNodes[i].textContent =
localize_string(el.childNodes[i].textContent)
}
// run through attributes and run `format_string()` on their values
for (let i = 0; i < attributes.length; i++) {
let attr = el.getAttribute(attributes[i]);
el.setAttribute(attributes[i], localize_string(attr))
}
// run `replace_in_el()` on `el`'s children
for (let i = 0; i < el.children.length; i++) {
localize_el(el.children[i]);
}
}
// localizes lang strings on (almost) all the elements inside ``
module.exports = () => {
localize_el(document.body);
}
================================================
FILE: src/app/js/mods.js
================================================
const util = require('util');
const ipcRenderer = require("electron").ipcRenderer;
const lang = require("../../lang");
const version = require("./version");
const toasts = require("./toasts");
const set_buttons = require("./set_buttons");
let mods = {};
let mods_list = {
all: [],
enabled: [],
disabled: []
}
// returns the list of mods
mods.list = () => {
return mods_list;
}
mods.load = (mods_obj) => {
modcount.innerHTML = `${lang("gui.mods.count")} ${mods_obj.all.length}`;
let normalized_names = [];
let set_mod = (mod) => {
let name = mod.name;
if (mod.package) {
name = mod.package.package_name;
}
let normalized_name = "mod-list-" + mods.normalize(name);
normalized_names.push(normalized_name);
let el = document.getElementById(normalized_name);
if (el) {
if (mod.disabled) {
el.querySelector(".switch").classList.remove("on");
} else {
el.querySelector(".switch").classList.add("on");
}
return;
}
let div = document.createElement("div");
div.classList.add("el");
div.id = normalized_name;
let mod_details = {
name: mod.name,
version: mod.version,
description: mod.description
}
if (mod.package) {
mod_details = {
image: mod.package.icon,
name: mod.package.manifest.name,
version: mod.package.manifest.version_number,
description: mod.package.manifest.description
}
}
div.innerHTML += `
${mod_details.name}
${mod_details.description}
`;
if (mod_details.name.match(/^Northstar\..*/)) {
div.querySelector("img").src = "icons/northstar.png"
}
div.querySelector(".remove").onclick = () => {
if (! mod.package) {
return mods.remove(mod.name);
}
for (let i = 0; i < mod.packaged_mods.length; i++) {
mods.remove(mod.packaged_mods[i]);
}
}
if (mod.disabled) {
div.querySelector(".switch").classList.remove("on");
}
div.querySelector(".switch").addEventListener("click", () => {
if (! mod.package) {
return mods.toggle(mod.name);
}
for (let i = 0; i < mod.packaged_mods.length; i++) {
mods.toggle(mod.packaged_mods[i]);
}
})
div.querySelector(".image").style.display = "none";
modsdiv.append(div);
}
for (let i = 0; i < mods_obj.all.length; i++) {
set_mod(mods_obj.all[i]);
}
let mod_els = document.querySelectorAll("#modsdiv .el");
let mod_update_els = [];
for (let i = 0; i < mod_els.length; i++) {
let update_btn = mod_els[i].querySelector(".update");
if (update_btn && update_btn.style.display != "none") {
mod_update_els.push(mod_els[i].id);
} else {
break;
}
}
for (let i = 0; i < mod_els.length; i++) {
let mod = mod_els[i].id.replace(/^mod-list-/, "");
if (! normalized_names.includes(mod_els[i].id)) {
mod_els[i].remove();
return;
}
let image_container = mod_els[i].querySelector(".image");
let image_el = image_container.querySelector("img")
let image_blur_el = image_container.querySelector("img.blur")
if (browser.mod_versions[mod]) {
image_el.src = browser.mod_versions[mod].package.versions[0].icon;
}
if (image_el.getAttribute("src") &&
! image_container.parentElement.classList.contains("has-icon")) {
let image_src = image_el.getAttribute("src");
image_blur_el.src = image_src;
image_container.style.display = null;
image_container.parentElement.classList.add("has-icon");
}
if (browser.mod_versions[mod]
&& browser.mod_versions[mod].has_update) {
mod_els[i].querySelector(".update").style.display = null;
mod_els[i].querySelector(".update").setAttribute(
"onclick", `browser.mod_versions["${mod}"].install()`
)
if (mod_update_els.includes(mod_els[i].id)) {
continue;
}
let mod_el = mod_els[i].cloneNode(true);
// copy click event of the remove button to the new button
mod_el.querySelector(".remove").onclick =
mod_els[i].querySelector(".remove").onclick;
mod_el.classList.add("no-animation");
mod_el.querySelector(".switch").addEventListener("click", () => {
if (browser.mod_versions[mod].local_name) {
mods.toggle(browser.mod_versions[mod].local_name);
}
})
mod_els[i].remove();
modsdiv.querySelector(".line:has(.search)").after(mod_el);
} else {
mod_els[i].querySelector(".update").style.display = "none";
}
}
}
// attempts to filter `#modsdiv` with `query`
mods.search = (query) => {
// if no `query` is given, use the search input's value
if (! query) {
query = mods.search.el.value;
}
// normalizes `string`
let normalize = (string) => {
return string
.trim().toLowerCase()
.replaceAll(" ", "").replaceAll(".", "");
}
// normalize `query`
query = normalize(query);
// get all mod elements
let mod_els = document.querySelectorAll("#modsdiv .el");
// run through all the mod elements
for (let mod_el of mod_els) {
// get the normalized name of the mod
let name = normalize(mod_el.querySelector(".title").innerText);
// if the name has `query` in it, show it
if (name.match(query)) {
mod_el.style.display = null;
} else { // hide if it doesn't match
mod_el.style.display = "none";
}
}
}
mods.search.el = document.getElementById("mods-search");
mods.search.el.addEventListener("keyup", () => {mods.search()})
mods.remove = (mod) => {
if (mod.toLowerCase().match(/^northstar\./)) {
if (! confirm(lang("gui.mods.required_confirm"))) {
return;
}
} else if (mod == "allmods") {
if (! confirm(lang("gui.mods.remove_all_confirm"))) {
return;
}
}
ipcRenderer.send("remove-mod", mod);
}
mods.toggle = (mod) => {
// is this a core mod?
if (mod.toLowerCase().match(/^northstar\./)) {
// keep track of whether this mod is disabled
let is_disabled = false;
// run through disabled mods
for (let mod_obj of mods_list.disabled) {
// if `mod` is `mod_obj`, update `is_disabled`
if (mod_obj.name.toLowerCase() == mod.toLowerCase()) {
is_disabled = true;
break;
}
}
// show prompt if the mod is enabled
if (! is_disabled && ! confirm(lang("gui.mods.required_confirm"))) {
return;
}
} else if (mod == "allmods") {
if (! confirm(lang("gui.mods.toggle_all_confirm"))) {
return;
}
}
ipcRenderer.send("toggle-mod", mod);
}
mods.install_queue = [];
// tells the main process to install a mod through the file selector
mods.install_prompt = () => {
set_buttons(false);
ipcRenderer.send("install-mod");
}
// tells the main process to directly install a mod from this path
mods.install_from_path = (path) => {
set_buttons(false);
ipcRenderer.send("install-from-path", path);
}
// tells the main process to install a mod from a URL
mods.install_from_url = (url, dependencies, clearqueue, author, package_name, version) => {
if (clearqueue) {mods.install_queue = []};
let prettydepends = [];
if (dependencies) {
let newdepends = [];
for (let i = 0; i < dependencies.length; i++) {
let depend = dependencies[i].toLowerCase();
if (! depend.match(/northstar-northstar-.*/)) {
depend = dependencies[i].replaceAll("-", "/");
let pkg = depend.split("/");
if (! mods.is_installed(pkg[1])) {
newdepends.push({
pkg: depend,
author: pkg[0],
version: pkg[2],
package_name: pkg[1]
});
prettydepends.push(`${pkg[1]} v${pkg[2]} - ${lang("gui.browser.made_by")} ${pkg[0]}`);
}
}
}
dependencies = newdepends;
}
if (dependencies && dependencies.length != 0) {
let confirminstall = confirm(lang("gui.mods.confirm_dependencies") + prettydepends.join("\n"));
if (! confirminstall) {
return;
}
}
set_buttons(false);
ipcRenderer.send("install-from-url", url, author, package_name, version);
if (dependencies) {
mods.install_queue = dependencies;
}
}
mods.is_installed = (modname) => {
for (let i = 0; i < mods.list().all.length; i++) {
let mod = mods.list().all[i];
if (mod.manifest_name) {
if (mod.manifest_name.match(modname)) {
return true;
}
} else if (mod.name.match(modname)) {
return true;
}
}
return false;
}
mods.normalize = (items) => {
let main = (string) => {
return string.replaceAll(" ", "")
.replaceAll(".", "").replaceAll("-", "")
.replaceAll("_", "").toLowerCase();
}
if (typeof items == "string") {
return main(items);
} else {
let newArray = [];
for (let i = 0; i < items.length; i++) {
newArray.push(main(items[i]));
}
return newArray;
}
}
// updates the installed mods
ipcRenderer.on("mods", (event, mods_obj) => {
mods_list = mods_obj;
if (! mods_obj) {return}
mods.load(mods_obj);
})
ipcRenderer.on("protocol-install-mod", async (event, data) => {
const domain = data[0];
const author = data[1];
const package_name = data[2];
const version = data[3];
const packages = await browser.packages();
const package = packages.find((package) => { return package.owner == author && package.name == package_name; })
if (!package) {
alert(util.format(lang("gui.mods.cant_find_specific"), author, package_name));
return;
}
const package_obj = package.versions.find((package_version) => { return package_version.version_number == version; })
if (!package_obj) {
alert(util.format(lang("gui.mods.cant_find_version"), version, author, package_name))
return;
}
toasts.show({
timeout: 3000,
scheme: "info",
title: lang("gui.mods.installing"),
description: package_obj.full_name
})
mods.install_from_url(
package_obj.download_url,
package_obj.dependencies,
false,
author,
package_name,
version
);
})
module.exports = mods;
================================================
FILE: src/app/js/navigate.js
================================================
const events = require("./events");
const popups = require("./popups");
const settings = require("./settings");
let navigate = {
using: false
}
// sets `#selection` to the correct position, size and border radius,
// according to what is currently the `.active-selection`, if none is
// found, it'll instead be hidden
navigate.selection = (new_selection) => {
// if we're not allowed to unselect an element, then make sure that
// element is still unselected, and then clear
// `navigate.dont_unselect`
if (navigate.dont_unselect
&& navigate.dont_unselect != new_selection) {
navigate.dont_unselect.classList.add("active-selection");
navigate.dont_unselect = false;
return;
}
if (new_selection) {
let selected = document.querySelectorAll(".active-selection");
// make sure just `new_selection` has `.active-selection`
for (let i = 0; i < selected.length; i++) {
if (selected[i] != new_selection) {
selected[i].classList.remove("active-selection");
}
}
new_selection.classList.add("active-selection");
}
// shorthands
let selection_el = document.getElementById("selection");
let active_el = document.querySelector(".active-selection");
// make sure there's an `active_el`, and hide the `selection_el` if
// that isn't the case
if (! active_el) {
selection_el.style.opacity = "0.0";
return;
}
// this adds space between the `selection_el` and ``
let padding = 8;
// attempt to get the border radius of `active_el`
let radius = getComputedStyle(active_el).borderRadius;
// if there's no radius set, we default to the default of
// `selection_el` through using `null`
if (! radius || radius == "0px") {
radius = null;
}
// set visibility and radius
selection_el.style.opacity = "1.0";
selection_el.style.borderRadius = radius;
// get bounds for position and size calculations of `selection_el`
let active_bounds = active_el.getBoundingClientRect();
// set top and left side coordinate subtracting the padding
selection_el.style.top = active_bounds.top - padding + "px";
selection_el.style.left = active_bounds.left - padding + "px";
// set width of `selection_el` with the padding
selection_el.style.width =
active_bounds.width + (padding * 2) + "px";
// set height of `selection_el` with the padding
selection_el.style.height =
active_bounds.height + (padding * 2) + "px";
}
// data from the last iterations of the interval below
let last_sel = {
el: false,
bounds: false
}
// auto update `#selection` if `.active-selection` changes bounds, but
// not element by itself
setInterval(() => {
// get active selection
let selected = document.querySelector(".active-selection");
// if there's no active selection, reset `last_sel`
if (! selected) {
last_sel.el = false;
last_sel.bounds = false;
return;
}
// get stringified bounds
let bounds = JSON.stringify(selected.getBoundingClientRect());
// if `last_sel.el` is not `selected` the selected element was
// changed, so we just set `last_el` and nothing more
if (last_sel.el != selected) {
last_sel.el = selected;
last_sel.bounds = bounds;
return;
}
// if stringified bounds changed we update `#selection`
if (bounds != last_sel.bounds) {
navigate.selection();
last_sel.el = selected;
last_sel.bounds = bounds;
}
}, 50)
// these events cause the `#selection` element to reposition itself
window.addEventListener("resize", () => {navigate.selection()}, true);
window.addEventListener("scroll", () => {navigate.selection()}, true);
// listen for click events, and hide the `#selection` element, when
// emitting a mouse event we will want to hide, as it then isn't needed
window.addEventListener("click", (e) => {
// make sure its a trusted click event, and therefore actually a
// mouse, and not anything else
if (! e.isTrusted) {
return;
}
// we're no longer using navigation functions
navigate.using = false;
// get the `.active-selection`
let active_el = document.querySelector(".active-selection");
// if there's an `active_el` then we unselect it, and update the
// `#selection` element, hiding it
if (active_el) {
active_el.classList.remove("active-selection");
navigate.selection();
}
})
// returns a list of valid elements that should be possible to navigate
// to/select with the `#selection` element
//
// setting `div` makes it limit itself to elements inside that, without
// it, it'll use `document.body` or the active popup, if one is found
navigate.get_els = (div) => {
let els = [];
// is `div` not set, and is there a popup shown
if (! div && document.body.querySelector(".popup.shown")) {
// the spread operator is to convert from a `NodeList` to an
// `Array`, and then we need to reverse this to get the ones
// that are layered on top first.
let popups_list = [...popups.list()].reverse();
// run through the list of popups
for (let i = 0; i < popups_list.length; i++) {
// if this popup is shown, we make it the current `div`
if (popups_list[i].classList.contains("shown")) {
div = popups_list[i];
break;
}
}
// get buttons inside `#winbtns`
els = [...document.body.querySelectorAll("#winbtns [onclick]")];
} if (! div) { // default
div = document.body;
}
// this gets the list of all the elements we should be able to
// select inside `div`, on top of anything that's already in `els`
els = [...els, ...div.querySelectorAll([
"a",
"input",
"button",
"select",
"textarea",
"[onclick]",
".scroll-selection"
])]
// this'll contain a filtered list of `els`
let new_els = [];
// filter out elements we don't care about
filter: for (let i = 0; i < els.length; i++) {
// elements that match on `els.closest()` with any of these will
// be stripped away, as we dont want them
let ignore_closest = [
"#overlay",
".no-navigate",
"button.visual",
".scroll-selection",
".popup:not(.shown)"
]
// ignore, even if `.closest()` matches, if its just matching on
// itself instead of a different element
let ignore_closest_self = [
".scroll-selection"
]
// check if `els[i].closest()` matches on any of the elements
// inside of `ignore_closest`
for (let ii = 0; ii < ignore_closest.length; ii++) {
let closest = els[i].closest(ignore_closest[ii]);
// check if `.closest()` matches, but not on itself
if (closest) {
// ignore if `closest` is just `els[i]` and the selector
// is inside `ignore_closest_self`
if (closest == els[i] &&
ignore_closest_self.includes(ignore_closest[ii])) {
continue;
}
// it matches
continue filter;
}
}
// make sure `els[i]` is visible on screen
let visible = els[i].checkVisibility({
checkOpacity: true,
visibilityProperty: true,
checkVisibilityCSS: true,
contentVisibilityAuto: true
})
// filter out if not visible
if (! visible) {continue}
// add to filtered list
new_els.push(els[i])
}
// return the filtered list of elements
return new_els;
}
// attempts to select the currently default selection, if inside a popup
// we'll look for a `.default-selection`, if it doesn't exist we'll
// simply use the first selectable element in it
//
// if not inside a popup we'll just use the currently selected tab in
// the `.gamesContainer` sidebar
navigate.default_selection = () => {
// if we're not currently using any navigation functions, this
// function shouldn't do anything, as it'll cause a selection to be
// made, when it shouldn't be
if (! navigate.using) {
return;
}
// the spread operator is to convert from a `NodeList` to an
// `Array`, and then we need to reverse this to get the ones
// that are layered on top first.
let popups_list = [...popups.list()].reverse();
let active_popup;
// run through the list of popups
for (let i = 0; i < popups_list.length; i++) {
// if this popup is shown, set set `active_popup` to it
if (popups_list[i].classList.contains("shown")) {
active_popup = popups_list[i];
break;
}
}
// is there no active popup?
if (! active_popup) {
// select the currently selected page in `.gamesContainer`
document.querySelector(
".gamesContainer :not(.inactive)"
).classList.add("active-selection");
// update the `#selection` element
navigate.selection();
return;
}
// get the default element inside the active popup
let popup_default = active_popup.querySelector("default-selection");
// did we not find a default selection element?
if (! popup_default) {
// select the first selectable element in the popup
navigate.get_els(active_popup)[0].classList.add(
"active-selection"
)
// update the `#selection` element
navigate.selection();
return;
}
// select the default selection
popup_default.classList.add("active-selection");
// update the `#selection` element
navigate.selection();
}
// this navigates `#selection` in the direction of `direction`
// this can be: up, down, left and right
navigate.move = async (direction) => {
// make sure we note down that we're using navigation functions
navigate.using = true;
// get the `.active-selection` if there is one
let active = document.querySelector(".active-selection");
// if there is no active selection, then attempt to select the
// default selection
if (! active) {
navigate.default_selection()
active = document.querySelector(".active-selection");
// if there is somehow still no active selection we stop here
if (! active) {
return;
}
}
// is the active selection one that should be scrollable?
if (active.classList.contains("scroll-selection")) {
// scroll the respective `direction` if `active` has any more
// scroll left in that direction
// short hand to easily scroll in `direction` by `amount` with
// smooth scrolling enabled
let scroll = (direction, amount) => {
// update the `#selection` element
navigate.selection();
// scroll inside `` if the active selection is one
if (active.tagName == "WEBVIEW") {
active.executeJavaScript(`
document.scrollingElement.scrollBy({
behavior: "smooth",
${direction}: ${amount}
})
`)
return;
}
active.scrollBy({
behavior: "smooth",
[direction]: amount
})
}
// get values needed for determining if we should scroll the
// active selection, and by how much
let scroll_el = {
top: active.scrollTop,
left: active.scrollLeft,
width: active.scrollWidth,
height: active.scrollHeight,
bounds: {
width: active.clientWidth,
height: active.clientWidth
}
}
// get `scroll_el` from inside a `` if the active
// selection is one
if (active.tagName == "WEBVIEW") {
scroll_el = await active.executeJavaScript(`(() => {
return {
top: document.scrollingElement.scrollTop,
left: document.scrollingElement.scrollLeft,
width: document.scrollingElement.scrollWidth,
height: document.scrollingElement.scrollHeight,
bounds: {
width: document.scrollingElement.clientWidth,
height: document.scrollingElement.clientHeight
}
}
})()`)
}
// decrease to increase scroll length, and in reverse
let scroll_scale = 2;
if (direction == "up" && scroll_el.top > 0) {
return scroll("top", -scroll_el.bounds.height / scroll_scale);
}
if (direction == "down" &&
scroll_el.top <= scroll_el.height &&
scroll_el.height != scroll_el.bounds.height) {
return scroll("top", scroll_el.bounds.height / scroll_scale);
}
if (direction == "left" && scroll_el.left > 0) {
return scroll("left", -width / scroll_scale);
}
if (direction == "right" &&
scroll_el.left <= scroll_el.width &&
scroll_el.width != scroll_el.bounds.width) {
return scroll("left", scroll_el.bounds.width / scroll_scale);
}
}
// attempt to get the element in the `direction` requested
let move_to_el = navigate.get_relative_el(active, direction);
// if no element is found, do nothing
if (! move_to_el) {return}
// switch `.active-selection` from `active` to `move_to_el`
active.classList.remove("active-selection");
move_to_el.classList.add("active-selection");
// update the `#selection` element
navigate.selection();
// make sure the selecting classes are removed, and thereby the
// scale/pressed effect with it
document.getElementById("selection").classList.remove(
"keyboard-selecting",
"controller-selecting"
)
// stop here if `move_to_el` is a child to `document.body`
if (move_to_el.parentElement == document.body) {
return;
}
// this element will be scrolled in view later
let scroll_el = move_to_el;
// these elements cant be scrolled
let no_scroll_parents = [
".el .text",
".gamesContainer",
]
// run through unscrollable parent elements
for (let i = 0; i < no_scroll_parents.length; i++) {
// check if `move_to_el.closest()` matches on anything in
// `no_scroll_parents`
let no_scroll_parent = move_to_el.closest(
no_scroll_parents[i]
)
if (! no_scroll_parent) {
// it does not match
continue;
}
// it matches, so we make the new `scroll_el` the parent
scroll_el = no_scroll_parent;
}
// refuse to scroll to begin with, if any of these are a parent
let ignore_parents = [
".contentMenu",
".gamesContainer",
]
// check if `ignore_parents` match on `move_to_el`, and if so, stop
for (let i = 0; i < ignore_parents.length; i++) {
if (move_to_el.closest(ignore_parents[i])) {
return;
}
}
if (scroll_el.closest(".grid .el")) {
scroll_el = scroll_el.closest(".grid .el");
}
// scroll `scroll_el` smoothly into view, centered
scroll_el.scrollIntoView({
block: "center",
inline: "center",
behavior: "smooth",
})
}
// selects the currently selected element, by clicking or focusing it
navigate.select = () => {
// make sure we note down that we're using navigation functions
navigate.using = true;
// get the current selection
let active = document.querySelector(".active-selection");
// make sure there is a selection
if (! active) {return}
// slight delay to prevent some timing issues
setTimeout(() => {
// if `active` is a switch, use `settings.popup.switch()` on it,
// to be able to toggle it
if (active.closest(".switch")) {
active.closest(".switch").click();
settings.popup.switch(active.closest(".switch"));
return;
}
// correctly open a `