commit bf114513a592da8ca0c5c131e43164a7d5da21f71f2d473b7211646a52a36ddf Author: Linus Björnstam Date: Sat Nov 21 21:06:11 2026 +0100 bjomarks-android: the Android client of bjomarks Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..703539e --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.bjo/ +*.dll +*.exe +*.pdb +*.bjobuild +*.runtimeconfig.json +*.deps.json +# Native executables, and the output of bjo publish. +/src/main +/tests/app +/tests/screenshots +/publish/ +/publish-android/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d22367a --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Readme.org b/Readme.org new file mode 100644 index 0000000..4548533 --- /dev/null +++ b/Readme.org @@ -0,0 +1,101 @@ +#+TITLE: bjomarks-android + +Bookmarks on an Android phone. The bookmarks are a bjomarks vault in a +folder that a file syncer, such as Syncthing, shares with your other +devices. The folder holds only encrypted files. + +* Running it + +#+BEGIN_SRC sh +bjo run --android # build, install, start, and show the log +bjo publish --android # the APK +bjo run src/main.bjo # on the desktop, in a window +bjo run tests/app.bjo # the tests, with no window +#+END_SRC + +~bjo run --android~ needs ~ANDROID_HOME~ and ~JAVA_HOME~. See "Android" in +Bjolang's ~Docs/Projects.org~. + +The app id is ~org.bjoli.bjomarks~, the same as the Android build of +bjomarks-gui. The two replace each other on a device. + +* Using it + +1. At the first start, tap "Choose folder…" and choose the shared folder in + the system's picker. Then allow the app to use it. The app keeps the + access and opens the folder again at each start. +2. Type the password: + - When the folder has no vault, the app makes one. Type the password two + times. + - When the folder has the vault of your other devices, this device joins + it with their password. + - After that, the password opens the vault of this device. +3. The list shows the bookmarks, the newest first. + - Tap a bookmark for its menu: Open, Open in private window, Copy + address, Share, Edit, Remove. + - Open in private window opens the page in Firefox's private browsing, + or in Firefox Focus. Chrome does not let other apps open an incognito + tab: then the address is copied, to paste in one. + - Back clears the search, when one is typed; then it leaves the app. + - "Undo" brings back the bookmarks that were removed, the last first. +4. Several vaults: each shared folder is a vault of its own, named by its + folder. The password screen has a list of the folders added, with "Add + new…" at its end; the app opens the one used last at each start. + "Remove from list" takes the one chosen off the list, and deletes + nothing: adding its folder again opens it again. "Other bookmarks…", + under "More", saves the open vault and goes back to the password screen. + - Type in "Search" to find bookmarks. A word is looked for in the title, + the address and the tags, and may have a typo. ~t:rust~ is the tag + "rust", ~d:github.com~ the domain, ~a:2011:2012-06~ the days added, + ~"two words"~ exact text, and ~-~ before any of them excludes it. See + (bjomarks search). + - "New" adds a bookmark. "Fetch" beside the title gets the title of the + page. "Fetch" beside the archive link gets the latest copy of the page + in the Wayback Machine, if it has one. + - "More" has "Import a Firefox backup…", "Help", and the name of the + shared folder. +4. In a browser, share a page to "Bjomarks". The dialog of a new bookmark + opens with the address and the title of the page. When the vault is + locked, the dialog opens after the password. When a bookmark has that + address, the dialog of that bookmark opens. + +To import the bookmarks of Firefox, make a backup on a computer: in +Firefox's Library (Ctrl+Shift+O), choose Import and Backup, then Backup. +Put the JSON file on the phone, then choose it under "More". Each folder of +the backup becomes a tag. A bookmark whose address is here already is not +changed. + +A change is written to the folder at once, in the background. The app also +reads the changes of your other devices each minute, when it goes to the +background, and when it comes back. + +* Files + +- The shared folder: ~keys.bin~, and a file for each device in ~devices/~. + See bjomarks. +- This device's own files: a folder for each shared folder, in + ~bjomarks/vaults~ in the app's folder for data, so that two shared folders + are two vaults (see ~device-folder~ in bjomarks). The phone keeps the + password of each behind its unlock on its own. +- The settings: ~bjomarks/settings.json~ in the app's folder for + configuration. It holds the folders added, each with its name and + bookmark, and the one used last. + +* Modules + +- ~src/main.bjo~: the program. +- ~src/app.bjo~, (bjomarks-android app): the model, the update and the + views. +- ~src/settings.bjo~, (bjomarks-android settings): the settings file. + +The shared folder has no path on Android. The app gives bjomarks a storage +of functions (~function-storage~ in (bjomarks store)) that reads and writes +the folder through (bjogui storage). + +* Not yet + +- A way to start again on a device: forget this device's vault, and join + the vault in the shared folder. Now, a device whose own files are of + another vault asks for that vault's password. Clear the app's data to + start again. +- An icon, signing, and an AAB for a store. diff --git a/icon.png b/icon.png new file mode 100644 index 0000000..2e6458d Binary files /dev/null and b/icon.png differ diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..6aa8dab --- /dev/null +++ b/icon.svg @@ -0,0 +1,50 @@ + + bjomarks bear + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/manifest.bjodat b/manifest.bjodat new file mode 100644 index 0000000..2a1aa10 --- /dev/null +++ b/manifest.bjodat @@ -0,0 +1,20 @@ +(package + (name (bjomarks-android)) + (version "0.1.0") + (description "Bookmarks on an Android phone: a bjomarks vault in a folder that a file syncer shares, and the Share menu.") + (license "MPL-2.0") + + ;; The Android app: bjo run --android, bjo publish --android. + (android-id "org.bjoli.bjomarks") + (android-label "Bjomarks") + (android-aot #t) + ;; Fetching titles. + (android-permissions "INTERNET") + ;; "Bjomarks" in the Share menu of a browser. + (android-share-target #t) + ;; The bear. icon.svg is its source. + (android-icon "icon.png") + + (depends + (package (name (bjomarks)) (source (path (dir "../bjomarks")))) + (package (name (bjogui)) (source (path (dir "../bjogui")))))) diff --git a/packages.lock.json b/packages.lock.json new file mode 100644 index 0000000..8491fc0 --- /dev/null +++ b/packages.lock.json @@ -0,0 +1,239 @@ +{ + "version": 1, + "dependencies": { + "net11.0": { + "Avalonia": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "Vw+gNvv4RXK5hLeVI9PfalhxPai6hrQjIElfoCDQK1fXTpk+vRyfhuhprrh+EIeuJtoYCy+AsSrqR1wgU28zeQ==", + "dependencies": { + "Avalonia.BuildServices": "11.3.2", + "Avalonia.Remote.Protocol": "12.1.5", + "MicroCom.Runtime": "0.11.6" + } + }, + "Avalonia.Angle.Windows.Natives": { + "type": "Transitive", + "resolved": "2.1.27548.20260419", + "contentHash": "l17nI3XVDN3oMnpjf2pnmJg0YTwK4m6NLsn/itAjDMdObTFxN77D5F1M9sRMSfViSY3KKcse1ROczwgoWLJsnA==" + }, + "Avalonia.BuildServices": { + "type": "Transitive", + "resolved": "11.3.2", + "contentHash": "qHDToxto1e3hci5YqbG9n0Ty8mlp3zBUN5wT66wKqaDVzXyQ0do3EnRILd4Ke9jpvsktaPpgE0YjEk7hornryQ==" + }, + "Avalonia.Desktop": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "l1jo9qKJjJ68gcuUwHgNgpsHV6STcvqfYTFvFPprOf949gmE506X/d7Mox/y36tU2BSWBqLGZ1M3mh8Ggl2g/Q==", + "dependencies": { + "Avalonia": "12.1.5", + "Avalonia.HarfBuzz": "12.1.5", + "Avalonia.Native": "12.1.5", + "Avalonia.Skia": "12.1.5", + "Avalonia.Win32": "12.1.5", + "Avalonia.X11": "12.1.5" + } + }, + "Avalonia.Fonts.Inter": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "SeFNLktbuxrHxUzPjYubzWB1O9HVCNo3IezZZ9SgkFBAcKcSYrY2KcD8lfP7QWMGxPUvqdLyn0TmioR9d3nZUg==", + "dependencies": { + "Avalonia": "12.1.5" + } + }, + "Avalonia.FreeDesktop": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "XqLCj3V2PJsIaNANnFwolEv9Ng8LT7XM//dG39wPv/oeVTijjLNbayWAkeQlpKxi6RtAkjfnXjK+xK/S1caQLA==", + "dependencies": { + "Avalonia": "12.1.5", + "Tmds.DBus.Protocol": "0.94.1" + } + }, + "Avalonia.FreeDesktop.AtSpi": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "MTqCBRv1+nkUHPUeMtbh4/dA3AaCEA6LpIT+ZtCnWO4QSxEQFIdlyMZa/d4y6qBBIcxw2DhdY3+JzdhCn6DpUg==", + "dependencies": { + "Avalonia": "12.1.5" + } + }, + "Avalonia.HarfBuzz": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "3kspGPaRVrCzgMi4Rv4N33VNbQNN4wcY4NoCufYxKF/kvYqPbrAnGD2Mjm6Kmc3IA3QrLbj5UJpg8WDTAd4cPw==", + "dependencies": { + "Avalonia": "12.1.5", + "HarfBuzzSharp": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3" + } + }, + "Avalonia.Headless": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "0s3+IiZ/lP7A2R80OOFc3YiSK3qnWOLO9KVsMBGjLX/kg4JSsU2YJiAMNTZIihDmIOYV0VHECJCzsSNKCTMXww==", + "dependencies": { + "Avalonia": "12.1.5", + "Avalonia.Fonts.Inter": "12.1.5", + "Avalonia.HarfBuzz": "12.1.5" + } + }, + "Avalonia.Native": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "LsC92ialAyccwXiqSjSHVlYGbASfB8XHbGT0XB3zqERF7PM7M3KjSnMgGc1HkzvwtGX+GgTYap6PV8N9H6un8Q==", + "dependencies": { + "Avalonia": "12.1.5" + } + }, + "Avalonia.Remote.Protocol": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "yNSke7MNKxJrgcTOQJk70QhPU568dxwRMeQCSmq9N7IGbpPS4zpbr4o6e8rLF/8UfASBQN/yuTgqUfa2nwf6Iw==" + }, + "Avalonia.Skia": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "irfPBtb4UoAT0qfRviYsALBwo0JwXnziRNOTQLzzAQt3eoNPyKFLBsgyj5hE4+6vgunQ7hltEHlvTHPkCoreIg==", + "dependencies": { + "Avalonia": "12.1.5", + "HarfBuzzSharp": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.Linux": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.WebAssembly": "8.3.1.3", + "SkiaSharp": "3.119.4", + "SkiaSharp.NativeAssets.Linux": "3.119.4", + "SkiaSharp.NativeAssets.WebAssembly": "3.119.4" + } + }, + "Avalonia.Themes.Fluent": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "FGjtJEpeVIbth+u4r507c9nbm1NQWLTvT3RC4e/yqDceRC4crAl37zVUloElA6rexDz69y0WvDfMLGX+t12yBQ==", + "dependencies": { + "Avalonia": "12.1.5" + } + }, + "Avalonia.Win32": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "QHfRLCyvVzj74AMCohS5a08Jz5f7VAeRgZ0SJsDTSfqxRzdbw9DXpKsncu21YmEvRWxMPkwyoB9cx9dvS1Bwmg==", + "dependencies": { + "Avalonia": "12.1.5", + "Avalonia.Angle.Windows.Natives": "2.1.27548.20260419" + } + }, + "Avalonia.X11": { + "type": "Transitive", + "resolved": "12.1.5", + "contentHash": "5EK2QrM9I3Lm3Aq/ZSpJjg1ZzBXl7YE9PxaB/mLxF9ysZz8qgFaJ5Zj+A9NdtAszupA+81Z3B9EmZP++2Xs4Ug==", + "dependencies": { + "Avalonia": "12.1.5", + "Avalonia.FreeDesktop": "12.1.5", + "Avalonia.FreeDesktop.AtSpi": "12.1.5", + "Avalonia.Skia": "12.1.5" + } + }, + "HarfBuzzSharp": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "NGZ2+ZVNPM+NdHB/asW0/ykWngyHWwcqjrbN2nDeH1B/aptPGlCUl8wkQ2cSJxw5fdWgdmIPmNuTPWpLwNVXWg==", + "dependencies": { + "HarfBuzzSharp.NativeAssets.Win32": "8.3.1.3", + "HarfBuzzSharp.NativeAssets.macOS": "8.3.1.3" + } + }, + "HarfBuzzSharp.NativeAssets.Linux": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "RI6A1LgmooU30+4QIyFt5rmBCzP0VzTR+587IJSGvYIsHHWlahFufihYxtraLfsIhW7I8dn6+xX+DZGygOPKWQ==" + }, + "HarfBuzzSharp.NativeAssets.macOS": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "KPTq0xnslkI6nAo0jh3ptcQPJvZZr7MWYXa2jUe4SnHc9q+JlHElmNXp0sfFoiTgoCX7WOYpYsurypuH9Gehxw==" + }, + "HarfBuzzSharp.NativeAssets.WebAssembly": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "w2QfdNm9Uz/sUa0B5D+OnVQhyq3G/fBq6ibQMdWBlQqqwh0g0/5j3RFvYqZAmRZ5+RzvjVe8o8SFFnWYUSkuxA==" + }, + "HarfBuzzSharp.NativeAssets.Win32": { + "type": "Transitive", + "resolved": "8.3.1.3", + "contentHash": "bx8CE8Js+XGX8PUxAHCBDEORt5aaBYtMN4Hr9QFs57Xithh6yjUyYqksizH6eRDhJkwsGI+SXWmPmMm8lZC9Pw==" + }, + "libsodium": { + "type": "Transitive", + "resolved": "1.0.20.2", + "contentHash": "FButtPK6HZvOewaE20F1HXNJn4qOoGAf7FEDm0VbWJ+xBX9pN9+2nkQQnfaLz+Ae5KuEzRoe1GHO00UpabgNxA==" + }, + "LibSodium.Net": { + "type": "Transitive", + "resolved": "0.16.0-alpha", + "contentHash": "uNW5uuT2QEu5zUSDAbNyXM/RPZjnLjMEp88uYMCkH2yr9+jX7LpZsV9JZimdIABKiHivfGqSJAXmj3Bd2tmJUQ==", + "dependencies": { + "libsodium": "1.0.20.1" + } + }, + "MicroCom.Runtime": { + "type": "Transitive", + "resolved": "0.11.6", + "contentHash": "NdNWGDiZ6eS/Mf/9+QHR91cj1K7Hy+PX9yrHI/zM7xFYuj9IWT2uxtB6sCHjrnxAeLV9fut1R6zHDUGKX6f9lQ==" + }, + "SkiaSharp": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } + }, + "SkiaSharp.NativeAssets.Linux": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "UAyVzbqNfZsZbKbzj68zXLyUyF/SbTKmzTfOO6qDu++dtIUMMTzPBe8oOuzU/DiewpfKoUUlOSsJmqWc6blxBw==" + }, + "SkiaSharp.NativeAssets.macOS": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "fgBOWEqbY012x7gMfJU4ezgz6dfhJb30Z6YdW35h85Zoe39+a8YNbAAwL29ihPfWoppg5AjvyKNzD1oCvlqWwA==" + }, + "SkiaSharp.NativeAssets.WebAssembly": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "S1HOxtBbD4bYDtA2e9WH5TX+lxqRrTPvKjrjttRhxnHNNu7YY8VFo/LeCP7tNqoTA6PV+8vsvNbmRUEC2ip8RQ==" + }, + "SkiaSharp.NativeAssets.Win32": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "XOpbx/4CReO2wYsq2s6rbvdauc6dntG4Zv499sHGTJ87bwZaFXszFkwql3+FIZMc8kUPeaj3Mx2ezIJmo8a1Kg==" + }, + "Tmds.DBus.Protocol": { + "type": "Transitive", + "resolved": "0.94.1", + "contentHash": "11YMr7FnAbL83bQmVxlhbIKHvSLxjO81D12Ej0QMSGXMDTxNA9MTOa4MQxx43nv5el/efuPHwzyrj6a5ha2gug==" + }, + "bjopackage.bjogui": { + "type": "Project", + "dependencies": { + "Avalonia": "[12.1.5, )", + "Avalonia.Desktop": "[12.1.5, )", + "Avalonia.Headless": "[12.1.5, )", + "Avalonia.Skia": "[12.1.5, )", + "Avalonia.Themes.Fluent": "[12.1.5, )" + } + }, + "bjopackage.bjosodium": { + "type": "Project", + "dependencies": { + "LibSodium.Net": "[0.16.0-alpha, 0.16.0-alpha]", + "libsodium": "[1.0.20.2, 1.0.21)" + } + } + } + } +} \ No newline at end of file diff --git a/src/app.bjo b/src/app.bjo new file mode 100644 index 0000000..af286e1 --- /dev/null +++ b/src/app.bjo @@ -0,0 +1,1166 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks-android/src/app.bjo — the module (bjomarks-android app): the +;; phone app's model, its update and its views. +;; +;; - The shared folder comes from the system's folder picker. It has no +;; path: the vault reads and writes it through (bjogui storage). Its +;; bookmark is saved, so that the next start opens it again. +;; - Then the vault is opened, joined or made, with a password. Argon2id and +;; the first sync run in the background. +;; - The phone can keep the password behind its unlock: a fingerprint, a +;; face, or the screen lock. The password screen then asks for the unlock +;; at once. See "The phone's unlock". +;; - Then the screen is a search box, New and More over the bookmarks. A tap +;; or a long press, on a bookmark opens its menu: Open, Open in private +;; window, Copy address, Share, Edit, Remove. Share sends the title, the +;; address and the tags, each on a line. Undo brings back what was removed. More has Import +;; and Help. Back clears the search, when there is one; then it leaves the +;; app. +;; - The dialog of a bookmark is that of bjomarks-gui: see (bjomarks draft). +;; It fetches the title and the archive link. +;; - Import reads a Firefox bookmark backup that the user chose in the +;; system's file picker. +;; - A text shared to the app, such as a page shared from a browser, opens +;; the dialog of a new bookmark with its address and title. A share that +;; comes while the vault is locked waits for it. A shared address that a +;; bookmark has opens that bookmark's dialog. +;; - A page that two devices bookmarked before they synced becomes one +;; bookmark, after the sync: see (bjomarks duplicates). When the two have +;; different titles, the app asks which to keep. +;; - A change is synced in the background: this device's file is written, +;; and the other devices' files are merged. Changes made while a sync runs +;; are merged with its result, and written by the next. A sync also runs +;; each minute, when the app goes to the background, and when it comes +;; back. +;; +;; Each storage operation runs in `blocking`: on Android it waits for +;; Avalonia's storage, which may need the UI thread. + +(export + Start Phase Model Msg + initial-model gui-update view windows subscriptions back-message + storage-of shared-url visible-bookmarks share-text-of password-secret) + +(import (std prelude)) +(import (std uuid)) +(import (bjogui view)) +;; bjogui's `Live` is a control; this module's is a bookmark's entry. +(import (except (bjogui app) Live)) +(import (bjogui dialogs)) +(import (bjogui storage)) +(import (bjogui platform)) +(import (bjomarks bookmark)) +(import (bjomarks store)) +(import (bjomarks title)) +(import (bjomarks wayback)) +(import (bjomarks import)) +(import (bjomarks draft)) +(import (bjomarks search)) +(import (bjomarks duplicates)) +(import (std datetime)) +(import (bjomarks-android settings)) + +(import/class + (Exception (: System.Exception))) + +;; --------------------------------------------------------------------------- +;; The model +;; --------------------------------------------------------------------------- + +;; What the password screen does: open this device's vault, join the one in +;; the shared folder, or make a new one there. +(type (: Start (Union OpenExisting JoinShared CreateNew))) + +;; - `NoFolder`: no shared folder is chosen, or the saved one did not open. +;; - `Checking`: the folder is opened, and its files looked at. +(type (: Phase (Union NoFolder Checking Locked Unlocking Open))) + +;; - `local` is this device's own folder for the shared folder, and +;; `settings` the folder of the settings. `root` is the folder of those +;; folders: each shared folder has its own (see `device-folder`). +;; - `vaults` is the shared folders that the user added, and `current` the +;; bookmark of the one in use. `leaving` is true while the vault is saved +;; before the app goes back to the choice of a folder. +;; - `mark` is the saved bookmark of the shared folder, while the app opens +;; it at the start. +;; - `selected` is the bookmark chosen in the list, or -1. A tap opens the +;; menu and chooses none, so it stays -1 on a phone. +;; - `removed` is the entries of the bookmarks removed, the last first, as +;; they were before: what Undo brings back. +;; - `more` and `help` are true while those layers show. +;; - `saving` is true while a sync runs in the background. `failed` is true +;; when the last one raised. +;; - `shared` is a share, its subject and its text, that waits for the vault. +;; - `fetches` counts the fetches of titles and archive links: each has its +;; number, so that a result is known to be the draft's latest. +;; - `wayback` is the address of the Wayback Machine's availability API. +;; - `duplicates` is the pages bookmarked more than once with different +;; titles, for the user to choose one. `later` is the addresses of those +;; that the user closed the question of: they are asked again when the app +;; starts again. +;; - The phone's unlock: `device` is true when the phone can keep the +;; password behind it, and `kept` when it does. `keep` is the choice on +;; the password screen to keep it. `asking` is true while the phone asks +;; for the unlock. `from-device` is true while the password that the phone +;; gave is tried. +(type (: Model (Record (: local string) + (: root string) + (: settings string) + (: storage (Option Storage)) + (: mark (Option string)) + (: vaults (Vec VaultEntry)) + (: current (Option string)) + (: leaving bool) + (: folder-label string) + (: start Start) + (: phase Phase) + (: password string) + (: again string) + (: problem string) + (: vault (Option Vault)) + (: query string) + (: selected int) + (: removed (List Entry)) + (: draft (Option Draft)) + (: more bool) + (: help bool) + (: fetches int) + (: wayback string) + (: saving bool) + (: failed bool) + (: status string) + (: note string) + (: shared (Option (Tuple string string))) + (: duplicates (Vec Duplicate)) + (: later (Vec string)) + (: device bool) + (: kept bool) + (: keep bool) + (: asking bool) + (: from-device bool)))) + +(type (: Msg (Union + ;; "Choose folder": the picker, and the folder chosen. + ChooseFolder + ;; A folder of those added, by its place, or "Add new…" after + ;; them; removing the one chosen from the list; and going back + ;; to the choice from the open vault. + (: ChooseVault int) + ForgetVault + SwitchVault + (: FolderPicked (Option Folder)) + ;; The saved folder, opened again at the start. + (: FolderReopened (Option Folder)) + ;; The folder's files were looked at: whether its bookmark is + ;; to be saved, the bookmark, and what the password screen + ;; does. + (: FolderReady bool (Result Exception (Tuple (Option string) string Start))) + (: MarkSaved (Result Exception bool)) + (: Password string) + (: Again string) + Unlock + (: Unlocked (Result Exception (Result string (Tuple Vault SyncReport)))) + (: Search string) + ;; The bookmark at this index of those shown was chosen in the + ;; list, such as with a keyboard: nothing more. + (: Tapped int) + ;; Open, and Open in private window, from the menu. + (: OpenBookmark Uuid) + (: OpenPrivately Uuid) + (: OpenedPrivately string bool) + New + (: Edit Uuid) + (: ShareOut Uuid) + (: CopyAddress Uuid) + ;; Back, with a search typed. + ClearSearch + (: Remove Uuid) + Undo + (: Opened string bool) + (: SharedOut bool) + ;; The "More" layer, and the help. + ShowMore + HideMore + ShowHelp + HideHelp + ;; "Import": the picker; the file chosen, if one was; and the + ;; file read, with its name. + ImportAsked + (: ImportChosen (Option StoredFile)) + (: BackupRead string (Result Exception (Result string FirefoxBackup))) + (: DraftUrl string) + (: DraftTitle string) + (: DraftTags string) + (: DraftArchive string) + DraftFetchTitle + (: DraftTitleFetched int (Result Exception (Result string string))) + DraftFetchArchive + (: DraftArchiveFetched int (Result Exception (Result string string))) + SaveDraft + CancelDraft + (: Synced (Result Exception (Tuple Vault SyncReport))) + SyncTick + ;; The app came back (#t) or went to the background (#f). + (: Active bool) + ;; A text shared to the app: its subject and its text. + (: SharedIn string string) + ;; The title chosen for a page bookmarked twice, and closing + ;; the question. + (: ChooseTitle string string) + (: Later string) + ;; The phone's unlock: whether the phone can keep the password + ;; and whether it does; the choice to keep it; asking for the + ;; unlock, and its result; the password kept; and forgetting it. + (: DeviceChecked (Result Exception (Tuple bool bool))) + (: KeepWithDevice bool) + AskDevice + (: DeviceAnswered SecretResult) + (: DeviceKept bool) + ForgetDevice + DeviceForgot))) + +;; The first model. +;; - `local` is the folder of this device's own folders, one for each shared +;; folder, and `settings` the folder of the settings. +;; - `mark` is the saved bookmark of the shared folder: the app opens it. +;; With none, the app asks for a folder. +;; - `#:storage` is a storage to use at once, in place of a folder: for +;; tests. The password screen is then for `#:start`. +;; - `#:wayback` is the address of the Wayback Machine's availability API. +;; - `#:vaults` is the shared folders that the user added. +(: (-> string string (Option string) (#:storage (Option Storage)) (#:start Start) (#:wayback string) + (#:vaults (Vec VaultEntry)) + Model)) +(defun (initial-model local settings mark #:storage None #:start CreateNew #:wayback wayback-api #:vaults []) + (def phase (cond ((some? storage) Locked) ((some? mark) Checking) (else NoFolder))) + (Model (local local) (root local) (settings settings) (storage storage) (mark mark) + (vaults vaults) (current mark) (leaving #f) + (folder-label (match storage ((Some s) (storage-label s)) (None ""))) + (start start) (phase phase) (password "") (again "") (problem "") + (vault None) (query "") (selected -1) (removed '()) (draft None) (more #f) (help #f) + (fetches 0) (wayback wayback) (saving #f) (failed #f) (status "") (note "") (shared None) + (duplicates []) (later []) + (device #f) (kept #f) (keep #f) (asking #f) (from-device #f))) + +;; --------------------------------------------------------------------------- +;; The shared folder +;; --------------------------------------------------------------------------- + +;; The storage of a folder of (bjogui storage). +(: (-> Folder Storage)) +(defun (storage-of f) + (function-storage (folder-name f) + (fun (name) (folder-read f name)) + (fun (name bytes) (folder-write f name bytes)) + (fun (dir) (folder-list f dir)))) + +;; What the password screen does, by the files that are there: this +;; device's `device.json`, and the shared `keys.bin`. Reads the storage. +(: (-> Storage string Start)) +(defun (start-for storage local) + (cond + ((file-exists? (path-combine local "device.json")) OpenExisting) + ((some? (storage-read storage "keys.bin")) JoinShared) + (else CreateNew))) + +(: (-> Exception string)) +(defun (message-of e) (.-Message e)) + +;; The name of the password that the phone keeps, behind its unlock. +(: string) +(def password-secret "bjomarks-password") + +;; The name of the password of the vault of `m`'s shared folder: each has +;; its own. +(: (-> Model string)) +(defun (secret-of m) + (if (= (.local m) (.root m)) + password-secret + (str password-secret "-" (option-ref-or (path-filename (.local m)) "")))) + +;; Asks the phone whether it can keep the password, and whether it does. +(: (-> Model (Event Msg))) +(defun (check-device m) + (def secret (secret-of m)) + (wrap (blocking (fun () (Tuple (device-secrets?) (device-secret? secret)))) DeviceChecked)) + +;; Uses the folder `f`, and looks at its files in the background. With +;; `save?`, its bookmark is made there too, and saved when it is there. +(: (-> Model Folder bool (Tuple Model (List (Event Msg))))) +(defun (use-folder m f save?) + (def storage (storage-of f)) + (def root (.root m)) + (next (record-set m (storage (Some storage)) (folder-label (folder-name f)) (mark None) + (phase Checking) (problem "") (password "") (again "")) + (wrap (blocking (fun () + (def local (device-folder root (folder-id f) storage)) + (Tuple (if save? (folder-bookmark f) None) local (start-for storage local)))) + (fun (r) (FolderReady save? r))))) + +(: (-> Model bool (Result Exception (Tuple (Option string) string Start)) (Tuple Model (List (Event Msg))))) +(defun (folder-ready m save? r) + (match r + ((Ok (Tuple mark local start)) + (def ready (record-set m (phase Locked) (local local) (start start) (kept #f))) + (def check (check-device ready)) + (def name (short-name (.folder-label m))) + (match (Tuple save? mark (.current m)) + ((Tuple #t (Some s) _) + (def added (record-set ready (current (Some s)) (vaults (with-vault (.vaults m) name s)))) + (next added (save-vaults added) check)) + ((Tuple #t None _) + (next (record-set ready (problem "This folder cannot be kept: it is asked for again at the next start.")) + check)) + ;; A folder of the list, opened again: its name, as the folder has it + ;; now. + ((Tuple #f _ (Some s)) + (def named (record-set ready (vaults (with-vault (.vaults m) name s)))) + (if (= (.vaults named) (.vaults m)) (next named check) (next named (save-vaults named) check))) + (_ (next ready check)))) + ((Err e) + (next (record-set m (phase NoFolder) (storage None) + (problem (str "The folder could not be read: " (message-of e)))))))) + +(: (-> Model (Result Exception bool) (Tuple Model (List (Event Msg))))) +(defun (mark-saved m r) + (match r + ((Ok _) (next m)) + ((Err e) (next (record-set m (problem (str "The folder is used now, but could not be saved for the next time: " + (message-of e)))))))) + +;; --------------------------------------------------------------------------- +;; The list of shared folders +;; --------------------------------------------------------------------------- + +;; The name of a folder to show: the last part of what the system calls it, +;; such as "Bookmarks" for "primary:Documents/Bookmarks". +(: (-> string string)) +(defun (short-name label) + (def parts (vec-filter (fun (p) (not (string-empty? (string-trim p)))) + (vec-fold (fun (p acc) (vec-append acc (string-split p "/"))) [] (string-split label ":")))) + (if (vec-empty? parts) label (vec-ref parts (- (vec-length parts) 1)))) + +;; `vaults` with the folder `mark` named `name`: added at the end when it is +;; not there. +(: (-> (Vec VaultEntry) string string (Vec VaultEntry))) +(defun (with-vault vaults name mark) + (if (vec-empty? (vec-filter (fun (e) (= (vault-entry-mark e) mark)) vaults)) + (vec-add vaults (VaultEntry (name name) (mark mark))) + (vec-map (fun (e) (if (= (vault-entry-mark e) mark) (VaultEntry (name name) (mark mark)) e)) vaults))) + +;; Saves the list, and the folder in use, in the background. +(: (-> Model (Event Msg))) +(defun (save-vaults m) + (def settings (.settings m)) + (def vaults (.vaults m)) + (def current (.current m)) + (wrap (blocking (fun () (save-vaults! settings vaults current) #t)) MarkSaved)) + +;; Where the folder in use is in the list, or -1. +(: (-> Model int)) +(defun (current-index m) + (match (.current m) + ((Some mark) + (let go ((i 0)) + (cond ((= i (vec-length (.vaults m))) -1) + ((= (vault-entry-mark (vec-ref (.vaults m) i)) mark) i) + (else (go (+ i 1)))))) + (None -1))) + +;; The folder at `i` of the list, or the picker for a new one after them. +(: (-> Model int (Tuple Model (List (Event Msg))))) +(defun (choose-vault m i) + (cond + ((not (or (= (.phase m) NoFolder) (= (.phase m) Locked))) (next m)) + ((>= i (vec-length (.vaults m))) + (next m (pick-folder FolderPicked #:title "The shared folder for the bookmarks"))) + ((< i 0) (next m)) + ((= i (current-index m)) (next m)) + (else + (def mark (vault-entry-mark (vec-ref (.vaults m) i))) + (def chosen (record-set m (phase Checking) (mark (Some mark)) (current (Some mark)) (storage None) + (problem "") (password "") (again "") (keep #f) (kept #f))) + (next chosen (save-vaults chosen))))) + +;; The folder in use, out of the list. Its files stay where they are, in +;; the shared folder and on this device: adding it again opens it again. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (forget-vault m) + (match (.current m) + ((Some mark) #:when (or (= (.phase m) NoFolder) (= (.phase m) Locked)) + (def left (record-set m (vaults (vec-filter (fun (e) (not (= (vault-entry-mark e) mark))) (.vaults m))) + (current None) (storage None) (phase NoFolder) (password "") (again "") + (problem ""))) + (next left (save-vaults left))) + (_ (next m)))) + +;; Back to the choice of a folder, from the open vault: it is synced first, +;; and closed when all of it is written. See `synced`. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (switch-vault m) + (if (= (.phase m) Open) + (let ((leaving (record-set m (more #f) (leaving #t)))) + (if (.saving m) + (next leaving) + (match (.vault m) + ((Some v) + (next (record-set leaving (saving #t) (status "Saving…")) + (wrap (blocking (fun () (vault-sync v))) Synced))) + (None (next leaving))))) + (next m))) + +;; The vault closed, and the password screen of its folder. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (closed m) + (match (.vault m) ((Some v) (vault-close v)) (None unit)) + (def locked (record-set m (vault None) (phase Locked) (start OpenExisting) (leaving #f) (query "") (selected -1) + (removed '()) (draft None) (duplicates []) (status "") (note "") (password "") + (again "") (keep #f) (kept #f))) + (next locked (check-device locked))) + +;; --------------------------------------------------------------------------- +;; The vault +;; --------------------------------------------------------------------------- + +;; The bookmarks that the search shows, in the order of (bjomarks search). +(: (-> Model (Vec Bookmark))) +(defun (visible-bookmarks m) + (match (.vault m) + ((Some v) (search-bookmarks v (.query m))) + (None []))) + +(: (-> StoreError string)) +(defun (describe e) + (match e + (WrongPassword "The password is wrong.") + ((NoVault why) why) + ((VaultExists why) why) + ((OtherVault why) why) + ((BadFile why) why))) + +;; Opens, joins or makes the vault, and syncs it. Runs in the background: +;; Argon2id takes a core for a while, and the storage may wait for the UI +;; thread. +(: (-> Storage string string Start (Result string (Tuple Vault SyncReport)))) +(defun (open-or-make storage local password start) + (match start + (OpenExisting + (match (open-vault storage local password) + ((Ok v) (Ok (vault-sync v))) + ((Err e) (Err (describe e))))) + (JoinShared + (match (join-vault storage local password) + ((Ok r) (Ok r)) + ((Err e) (Err (describe e))))) + (CreateNew + (match (create-vault storage local password) + ((Ok v) (Ok (vault-sync v))) + ((Err e) (Err (describe e))))))) + +;; Why the password screen cannot go on yet, or "". +(: (-> Model string)) +(defun (unlock-problem m) + (cond + ((string-empty? (.password m)) "Type the password.") + ((and (= (.start m) CreateNew) (not (= (.password m) (.again m)))) + "The two passwords are not the same.") + (else ""))) + +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (unlock m) + (def problem (unlock-problem m)) + (match (Tuple (.phase m) (.storage m)) + ((Tuple Locked (Some storage)) + (cond + ((not (string-empty? problem)) (next (record-set m (problem problem)))) + (else + (def local (.local m)) + (def password (.password m)) + (def start (.start m)) + (next (record-set m (phase Unlocking) (problem "")) + (wrap (blocking (fun () (open-or-make storage local password start))) Unlocked))))) + (_ (next m)))) + +(: (-> SyncReport string)) +(defun (report-status r) + (match (vec-length (.problems r)) + (0 "Saved.") + (1 (str "Saved. " (vec-ref (.problems r) 0))) + (n (str "Saved. " (int->string n) " problems; the first: " (vec-ref (.problems r) 0))))) + +(: (-> Model (Result Exception (Result string (Tuple Vault SyncReport))) (Tuple Model (List (Event Msg))))) +(defun (unlocked m r) + (match r + ((Ok (Ok (Tuple v report))) + ;; The password typed is kept behind the phone's unlock, when that was + ;; chosen. It needs no unlock. + (def keeping (if (and (.keep m) (.device m) (not (.from-device m))) + (list (keep-device-secret (secret-of m) (.password m) DeviceKept)) + '())) + (def (Tuple joined asked) (vault-join-duplicates v)) + (def opened (record-set m (phase Open) (vault (Some joined)) (duplicates asked) + (password "") (again "") (keep #f) (from-device #f) + (status (if (vec-empty? (.problems report)) "" (report-status report))))) + (def shown (match (.shared m) + ((Some (Tuple subject text)) (draft-of-share (record-set opened (shared None)) subject text)) + (None opened))) + (def (Tuple after events) (if (vault-dirty? joined) (start-sync shown) (next shown))) + (Tuple after (list-append events keeping))) + ;; The password that the phone kept is not the vault's: it is forgotten. + ((Ok (Err why)) #:when (.from-device m) + (next (record-set m (phase Locked) (password "") (from-device #f) (kept #f) + (problem (str "The password that the phone kept did not open the bookmarks: " why + " Type the password."))) + (forget-device-secret (secret-of m) DeviceForgot))) + ((Ok (Err why)) (next (record-set m (phase Locked) (from-device #f) (problem why)))) + ((Err e) (next (record-set m (phase Locked) (from-device #f) (password (if (.from-device m) "" (.password m))) + (problem (message-of e))))))) + +;; --------------------------------------------------------------------------- +;; The phone's unlock +;; --------------------------------------------------------------------------- + +;; The phone asks for its unlock, and gives the password that it keeps. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (ask-device m) + (if (and (= (.phase m) Locked) (.kept m) (not (.asking m))) + (next (record-set m (asking #t) (problem "")) + (unlock-device-secret (secret-of m) "Unlock the bookmarks" DeviceAnswered)) + (next m))) + +;; What the phone said: a password kept is the vault's only on this device, +;; so it is asked for only to open this device's vault. +(: (-> Model (Result Exception (Tuple bool bool)) (Tuple Model (List (Event Msg))))) +(defun (device-checked m r) + (match r + ((Ok (Tuple device kept)) + (def checked (record-set m (device device) (kept (and device kept)))) + (if (and (.kept checked) (= (.start checked) OpenExisting)) + (ask-device checked) + (next checked))) + ((Err _) (next m)))) + +(: (-> Model SecretResult (Tuple Model (List (Event Msg))))) +(defun (device-answered m answer) + (def done (record-set m (asking #f))) + (match answer + ((SecretOk password) (unlock (record-set done (password password) (from-device #t)))) + (SecretCancelled (next done)) + (SecretGone + (next (record-set done (kept #f) + (problem (str "The phone's unlock does not open the bookmarks any more: its fingerprints " + "or its screen lock changed. Type the password."))))) + ((SecretFailed why) (next (record-set done (problem (str "The phone could not unlock: " why))))))) + +;; Starts a sync in the background, unless one runs: then the vault's +;; changes are written by the next, when that one is done. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (start-sync m) + (match (Tuple (.vault m) (.saving m)) + ((Tuple (Some v) #f) + (next (record-set m (saving #t) (status "Saving…")) + (wrap (blocking (fun () (vault-sync v))) Synced))) + (_ (next m)))) + +(: (-> Model Vault (Tuple Model (List (Event Msg))))) +(defun (changed m v) + (start-sync (record-set m (vault (Some v))))) + +(: (-> Model (Result Exception (Tuple Vault SyncReport)) (Tuple Model (List (Event Msg))))) +(defun (synced m r) + (match (Tuple r (.vault m)) + ((Tuple (Ok (Tuple done report)) (Some current)) + (def (Tuple merged asked) (vault-join-duplicates (vault-merge current done))) + (def m2 (record-set m (vault (Some merged)) (duplicates asked) (saving #f) (failed #f) + (status (report-status report)))) + (cond ((vault-dirty? merged) (start-sync m2)) + ((.leaving m2) (closed m2)) + (else (next m2)))) + ((Tuple (Err e) _) + (next (record-set m (saving #f) (failed #t) (leaving #f) + (status (str "Could not save, so the bookmarks stay open: " (message-of e)))))) + (_ (next (record-set m (saving #f)))))) + +(: (-> Model Uuid (Option Bookmark))) +(defun (find-bookmark m id) + (match (.vault m) + ((Some v) (vault-find v id)) + (None None))) + +;; What the note and the list call a bookmark: its title, or its address. +(: (-> Bookmark string)) +(defun (name-of b) (option-ref-or (.title b) (.url b))) + +;; The title chosen for the page `url`: its bookmarks become one. +(: (-> Model string string (Tuple Model (List (Event Msg))))) +(defun (choose-title m url title) + (match (.vault m) + ((Some v) + (changed (record-set m (duplicates (vec-filter (fun (d) (not (= (duplicate-url d) url))) (.duplicates m))) + (note (str "Kept " title "."))) + (vault-choose-title v url (Some title)))) + (None (next m)))) + +;; --------------------------------------------------------------------------- +;; Opening, sharing and removing +;; --------------------------------------------------------------------------- + +;; Open: the system opens the bookmark's address, in the browser. +(: (-> Model Uuid (Tuple Model (List (Event Msg))))) +(defun (open-bookmark m id) + (match (find-bookmark m id) + ((Some b) + (def url (.url b)) + (next (record-set m (note (str "Opening " url "…"))) (open-uri url (fun (done) (Opened url done))))) + (None (next m)))) + +;; Open in private window: in Firefox's private browsing, or Firefox Focus. +;; With neither, the address is copied, to paste in a private tab. +(: (-> Model Uuid (Tuple Model (List (Event Msg))))) +(defun (open-privately m id) + (match (find-bookmark m id) + ((Some b) + (def url (.url b)) + (next (record-set m (note (str "Opening " url " in a private window…"))) + (open-private url (fun (done) (OpenedPrivately url done))))) + (None (next m)))) + +(: (-> Model string bool (Tuple Model (List (Event Msg))))) +(defun (opened-privately m url done) + (if done + (next (record-set m (note ""))) + (next (record-set m (note (str "No browser here opens a private window from another app; Firefox does. " + "The address is copied: paste it in a private tab."))) + (copy-text url)))) + +(: (-> Model Uuid (Tuple Model (List (Event Msg))))) +(defun (share-out m id) + (match (find-bookmark m id) + ((Some b) (next m (share-text (share-text-of b) SharedOut))) + (None (next m)))) + +;; What Share sends: the title, the address, and "Tags: " and the tags, each +;; on a line. A bookmark without a title or tags has no line for them. +(: (-> Bookmark string)) +(defun (share-text-of b) + (def title (match (.title b) ((Some t) (list t)) (None '()))) + (def tags (if (vec-empty? (.tags b)) '() (list (str "Tags: " (string-join (.tags b) " "))))) + (string-join (list->vec (list-append title (cons (.url b) tags))) "\n")) + +;; Removes the bookmark, and keeps its entry, so that Undo brings it back. +(: (-> Model Uuid (Tuple Model (List (Event Msg))))) +(defun (remove-bookmark m id) + (def entry (match (.vault m) + ((Some v) (map-try-ref (vault-entries v) (uuid->string id))) + (None None))) + (match (Tuple (.vault m) (find-bookmark m id) entry) + ((Tuple (Some v) (Some b) (Some before)) + (changed (record-set m (removed (cons before (.removed m))) (note (str "Removed " (name-of b) "."))) + (vault-delete v id))) + (_ (next m)))) + +;; Brings back the bookmark removed last, as it was. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (undo m) + (match (Tuple (.removed m) (.vault m)) + ((Tuple (List e rest ...) (Some v)) + (def name (match (.state e) ((Live b) (name-of b)) ((Deleted _) "it"))) + (changed (record-set m (removed rest) (note (str "Brought back " name "."))) + (vault-restore v e))) + (_ (next m)))) + +;; --------------------------------------------------------------------------- +;; Importing +;; --------------------------------------------------------------------------- + +;; "Import": asks for Firefox's JSON backup. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (ask-import m) + (next (record-set m (more #f)) + (pick-file ImportChosen #:title "A Firefox bookmark backup" + #:filters (list (Tuple "Firefox bookmark backups" '("*.json")) (Tuple "All files" '("*")))))) + +;; The file chosen: it is read in the background. +(: (-> Model (Option StoredFile) (Tuple Model (List (Event Msg))))) +(defun (import-chosen m chosen) + (match chosen + ((Some f) + (def name (stored-file-name f)) + (next (record-set m (note (str "Reading " name "…"))) + (wrap (blocking (fun () (read-firefox-backup (bytes->string (stored-file-bytes f))))) + (fun (r) (BackupRead name r))))) + (None (next m)))) + +;; The backup was read: the bookmarks that the vault does not have are put +;; in it, and synced as any change is. +(: (-> Model string (Result Exception (Result string FirefoxBackup)) (Tuple Model (List (Event Msg))))) +(defun (backup-read m name r) + (match (Tuple r (.vault m)) + ((Tuple (Ok (Ok backup)) (Some v)) + (def (Tuple v2 report) (vault-import v (.bookmarks backup))) + (def noted (record-set m (note (import-summary name backup report)))) + (if (> (.added report) 0) (changed noted v2) (next noted))) + ((Tuple (Ok (Err why)) _) (next (record-set m (note (str "Could not import " name ": " why))))) + ((Tuple (Err e) _) (next (record-set m (note (str "Could not import " name ": " (message-of e)))))) + (_ (next m)))) + +;; --------------------------------------------------------------------------- +;; The dialog of a bookmark +;; --------------------------------------------------------------------------- + +(: (-> Model (-> Draft Draft) (Tuple Model (List (Event Msg))))) +(defun (edit-draft m f) + (match (.draft m) + ((Some d) (next (record-set m (draft (Some (f d)))))) + (None (next m)))) + +;; The first address in a shared text: a word that starts with "http://" or +;; "https://". A browser shares the page's address, and some put words +;; before it. +(: (-> string (Option string))) +(defun (shared-url text) + (def words (string-split (string-replace (string-replace (string-replace text "\n" " ") "\r" " ") "\t" " ") " ")) + (def found (vec-filter (fun (w) (or (string-starts-with? w "http://") (string-starts-with? w "https://"))) words)) + (if (vec-empty? found) None (Some (vec-ref found 0)))) + +;; The dialog for a shared text: of a new bookmark with its address and, as +;; its title, the subject. An address that a bookmark has loads that +;; bookmark, as typing it does. +(: (-> Model string string Model)) +(defun (draft-of-share m subject text) + (def url (option-ref-or (shared-url text) (string-trim text))) + (def typed (record-set empty-draft (title (string-trim subject)))) + (match (.vault m) + ((Some v) (record-set m (more #f) (help #f) (draft (Some (with-address v typed url))))) + (None m))) + +;; A text was shared to the app. It waits while the vault is locked. +(: (-> Model string string (Tuple Model (List (Event Msg))))) +(defun (shared-in m subject text) + (if (= (.phase m) Open) + (next (draft-of-share m subject text)) + (next (record-set m (shared (Some (Tuple subject text))))))) + +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (save-draft m) + (match (Tuple (.vault m) (.draft m)) + ((Tuple (Some v) (Some d)) + (match (apply-draft v d) + ((Err why) (next (record-set m (draft (Some (record-set d (problem why))))))) + ((Ok (Tuple v2 b)) + (changed (record-set m (draft None) (note (str "Saved " (name-of b) "."))) v2)))) + (_ (next (record-set m (draft None)))))) + +;; "Fetch" beside the title: fetches the title of the page at the draft's +;; address, in the background. Nothing while a fetch runs. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (fetch-draft-title m) + (def n (+ (.fetches m) 1)) + (match (.draft m) + ((Some d) + (match (start-title-fetch d n) + (None (next m)) + ((Some (Err d2)) (next (record-set m (draft (Some d2))))) + ((Some (Ok (Tuple d2 url))) + (next (record-set m (fetches n) (draft (Some d2))) + (wrap (spawn-evt (fetch-title url)) (fun (r) (DraftTitleFetched n r))))))) + (None (next m)))) + +;; "Fetch" beside the archive link: asks the Wayback Machine for the latest +;; snapshot of the page, in the background. Nothing while a lookup runs. +(: (-> Model (Tuple Model (List (Event Msg))))) +(defun (fetch-draft-archive m) + (def n (+ (.fetches m) 1)) + (match (.draft m) + ((Some d) + (match (start-archive-fetch d n) + (None (next m)) + ((Some (Err d2)) (next (record-set m (draft (Some d2))))) + ((Some (Ok (Tuple d2 url))) + (next (record-set m (fetches n) (draft (Some d2))) + (wrap (spawn-evt (fetch-archive url #:api (.wayback m))) + (fun (r) (DraftArchiveFetched n r))))))) + (None (next m)))) + +;; --------------------------------------------------------------------------- +;; The update +;; --------------------------------------------------------------------------- + +(: gui-update (-> Msg Model (Tuple Model (List (Event Msg))))) +(defun (gui-update msg m) + (match msg + (ChooseFolder + (if (or (= (.phase m) NoFolder) (= (.phase m) Locked)) + (next m (pick-folder FolderPicked #:title "The shared folder for the bookmarks")) + (next m))) + ((ChooseVault i) (choose-vault m i)) + (ForgetVault (forget-vault m)) + (SwitchVault (switch-vault m)) + ((FolderPicked (Some f)) (use-folder m f #t)) + ((FolderPicked None) (next m)) + ((FolderReopened (Some f)) (use-folder m f #f)) + ((FolderReopened None) + (next (record-set m (phase NoFolder) (mark None) + (problem "The saved folder could not be opened. Choose it again.")))) + ((FolderReady save? r) (folder-ready m save? r)) + ((MarkSaved r) (mark-saved m r)) + ((Password s) (next (record-set m (password s) (problem "")))) + ((Again s) (next (record-set m (again s) (problem "")))) + (Unlock (unlock m)) + ((Unlocked r) (unlocked m r)) + ((Search q) (next (record-set m (query q) (selected -1)))) + ((Tapped i) (next (record-set m (selected i)))) + ((OpenBookmark id) (open-bookmark m id)) + ((OpenPrivately id) (open-privately m id)) + ((OpenedPrivately url done) (opened-privately m url done)) + (New (next (record-set m (draft (Some empty-draft))))) + ((Edit id) + (match (find-bookmark m id) + ((Some b) (next (record-set m (draft (Some (draft-of b)))))) + (None (next m)))) + ((ShareOut id) (share-out m id)) + ((CopyAddress id) + (match (find-bookmark m id) + ((Some b) (next (record-set m (note (str "Copied " (.url b) "."))) (copy-text (.url b)))) + (None (next m)))) + (ClearSearch (next (record-set m (query "") (selected -1)))) + ((Remove id) (remove-bookmark m id)) + (Undo (undo m)) + ((Opened url done) + (next (record-set m (selected -1) (note (if done "" (str "Could not open " url)))))) + ((SharedOut done) (next (if done m (record-set m (note "This device cannot share."))))) + (ShowMore (next (record-set m (more #t)))) + (HideMore (next (record-set m (more #f)))) + (ShowHelp (next (record-set m (more #f) (help #t)))) + (HideHelp (next (record-set m (help #f)))) + (ImportAsked (ask-import m)) + ((ImportChosen chosen) (import-chosen m chosen)) + ((BackupRead name r) (backup-read m name r)) + ;; Typing in a field drops the fetch for it that runs: what it returns + ;; would be of the address before, or would replace what was typed. + ((DraftUrl s) (match (.vault m) + ((Some v) (edit-draft m (fun (d) (with-address v d s)))) + (None (next m)))) + ((DraftTitle s) (edit-draft m (fun (d) (record-set d (title s) (fetching None))))) + ((DraftTags s) (edit-draft m (fun (d) (record-set d (tags s))))) + ((DraftArchive s) (edit-draft m (fun (d) (record-set d (archive s) (problem "") (archiving None))))) + (DraftFetchTitle (fetch-draft-title m)) + ((DraftTitleFetched n r) (edit-draft m (fun (d) (with-title-fetched d n r)))) + (DraftFetchArchive (fetch-draft-archive m)) + ((DraftArchiveFetched n r) (edit-draft m (fun (d) (with-archive-fetched d n r)))) + (SaveDraft (save-draft m)) + (CancelDraft (next (record-set m (draft None)))) + ((Synced r) (synced m r)) + (SyncTick (start-sync m)) + ;; Both ways: the changes of this device are written before Android may + ;; end the process, and those of the others are read when it comes back. + ((Active _) (start-sync m)) + ((SharedIn subject text) (shared-in m subject text)) + ((ChooseTitle url title) (choose-title m url title)) + ((Later url) (next (record-set m (later (vec-add (.later m) url))))) + ((DeviceChecked r) (device-checked m r)) + ((KeepWithDevice b) (next (record-set m (keep b)))) + (AskDevice (ask-device m)) + ((DeviceAnswered answer) (device-answered m answer)) + ((DeviceKept b) + (next (record-set m (kept b) + (note (if b + "The fingerprint or the screen lock opens the bookmarks from now on." + "The phone could not keep the password."))))) + (ForgetDevice (next (record-set m (more #f)) (forget-device-secret (secret-of m) DeviceForgot))) + (DeviceForgot (next (record-set m (kept #f)))))) + +;; --------------------------------------------------------------------------- +;; The views +;; --------------------------------------------------------------------------- + +(: string) +(def grey "#808080") + +(: string) +(def red "#c0392b") + +(: (-> Model (View Msg))) +(defun (view m) + (match (.phase m) + (NoFolder (folder-view m)) + (Checking (column #:spacing 12.0 #:margin 24.0 + (text "Bjomarks" #:size 22.0) + (text "Opening the folder…"))) + (Open (main-view m)) + (_ (lock-view m)))) + +;; The shared folders added, to choose one, with "Add new…" after them; and +;; "Remove from list" for the one chosen. +(: (-> Model bool (View Msg))) +(defun (vault-picker m enabled) + (def names (vec-map (fun (e) (if (string-empty? (vault-entry-name e)) "Bookmarks" (vault-entry-name e))) + (.vaults m))) + (column #:spacing 8.0 + ;; In a row, so that it is at the left, as the buttons are. + (row (keyed "vaults" (dropdown (vec-add names "Add new…") (current-index m) ChooseVault + #:enabled enabled #:width 260.0))) + (if (and (some? (.current m)) (> (vec-length (.vaults m)) 1)) + (button "Remove from list" ForgetVault #:enabled enabled #:width 180.0) + (text "")))) + +(: (-> Model (View Msg))) +(defun (folder-view m) + (column #:spacing 12.0 #:margin 24.0 + (text "Bjomarks" #:size 22.0) + (if (vec-empty? (.vaults m)) + (column #:spacing 12.0 + (text (str "Choose the folder for your bookmarks: a folder that a file syncer, such as " + "Syncthing, shares with your other devices. It holds only encrypted files.") + #:wrap #t) + (button "Choose folder…" ChooseFolder #:width 180.0)) + (column #:spacing 12.0 + (text "Choose the bookmarks to open, or add a folder." #:wrap #t) + (vault-picker m #t))) + (paint (text (.problem m) #:wrap #t) #:colour red))) + +(: (-> Model (View Msg))) +(defun (lock-view m) + (def what (match (.start m) + (OpenExisting "Open the bookmarks of this device.") + (JoinShared "Join the bookmarks in the shared folder, with their password.") + (CreateNew "Make new bookmarks in the shared folder. Choose a password."))) + (def label (match (.start m) (OpenExisting "Open") (JoinShared "Join") (CreateNew "Create"))) + (def busy (or (= (.phase m) Unlocking) (.asking m))) + (def with-device (and (.kept m) (= (.start m) OpenExisting))) + (scroll + (column #:spacing 12.0 #:margin 24.0 + (text "Bjomarks" #:size 22.0) + (text what #:wrap #t) + (if (some? (.shared m)) + (text "The page that was shared is added when the bookmarks are open." #:wrap #t) + (text "")) + (vault-picker m (not busy)) + (keyed "password" (text-input (.password m) Password #:password #t #:placeholder "Password")) + (if (= (.start m) CreateNew) + (keyed "again" (text-input (.again m) Again #:password #t #:placeholder "Password again")) + (text "")) + (if (and (.device m) (not (.kept m))) + (keyed "keep" (checkbox "Next time, open with the fingerprint or the screen lock" + (.keep m) KeepWithDevice)) + (text "")) + (paint (text (.problem m) #:wrap #t) #:colour red) + (row #:spacing 12.0 + (button label Unlock #:enabled (not busy) #:width 120.0) + (text (if (= (.phase m) Unlocking) "Opening…" ""))) + (if with-device + (button "Use the fingerprint or the screen lock" AskDevice #:enabled (not busy) #:width 300.0) + (text ""))))) + +;; The day a bookmark was added, as 2026-11-19, in the phone's time zone. +(: (-> Bookmark string)) +(defun (day-of b) (written (->date (instant->moment (.added b) (clock-timezone))))) + +;; The second line of a bookmark: the day it was added, its address, when +;; the first line is its title, and its tags. +(: (-> Bookmark string)) +(defun (details b) + (def parts (vec-filter (fun (s) (not (string-empty? s))) + [(day-of b) + (match (.title b) ((Some _) (.url b)) (None "")) + (string-join (.tags b) " ")])) + (string-join parts " · ")) + +(: string) +(def divider "#33808080") + +(: (-> Bookmark (View Msg))) +(defun (item-view b) + (def id (.id b)) + (keyed (uuid->string id) + (with-context-menu + ;; One line each, so that each item is as tall as the others: the + ;; list then keeps its place when an item above goes. + ;; The line under it is halfway to the next: the item's padding + ;; is below it, and the next one's above that. + (column #:spacing 3.0 + (text (name-of b) #:size 16.0 #:trim #t) + (paint (text (details b) #:size 12.0 #:trim #t) #:colour grey) + (canvas 0.0 6.0) + (canvas 0.0 1.0 #:background divider)) + #:tap #t + (menu-item "Open" (OpenBookmark id)) + (menu-item "Open in private window" (OpenPrivately id)) + (menu-item "Copy address" (CopyAddress id)) + (menu-item "Share" (ShareOut id)) + (menu-item "Edit" (Edit id)) + (menu-item "Remove" (Remove id))))) + +(: (-> Model (View Msg))) +(defun (main-view m) + (def shown (visible-bookmarks m)) + (def empty-text (cond + ((not (vec-empty? shown)) "") + ((string-empty? (string-trim (.query m))) + "No bookmarks yet. Tap New, or share a page from the browser to Bjomarks.") + (else (str "No bookmark matches \"" (.query m) "\".")))) + (def problem (query-problem (parse-query (.query m)))) + (def line (string-join (vec-filter (fun (s) (not (string-empty? s))) [problem (.note m) (.status m)]) " ")) + (dock + (at-top (grid #:columns "*,Auto,Auto" #:spacing 8.0 #:margin 8.0 + (at 0 0 (keyed "search" (text-input (.query m) Search #:placeholder "Search t: d: a:"))) + (at 0 1 (button "New" New #:width 70.0)) + (at 0 2 (button "More" ShowMore #:width 70.0)))) + (at-bottom (grid #:columns "*,Auto" #:spacing 8.0 #:margin 8.0 + (at 0 0 (paint (text line #:size 12.0 #:wrap #t) #:colour grey)) + (at 0 1 (if (empty? (.removed m)) (text "") (button "Undo" Undo #:width 80.0))))) + (if (vec-empty? shown) + (column (text empty-text #:margin 16.0 #:wrap #t)) + (keyed "list" (paint (list-box (vec-map item-view shown) (.selected m) Tapped) #:background "Transparent"))))) + +;; A field with a button beside it. +(: (-> (View Msg) (View Msg) (View Msg))) +(defun (with-button field b) + (grid #:columns "*,Auto" #:spacing 8.0 + (at 0 0 field) + (at 0 1 b))) + +(: (-> Draft (View Msg))) +(defun (draft-view d) + (def fetching (some? (.fetching d))) + (def archiving (some? (.archiving d))) + (scroll + (column #:spacing 8.0 #:margin 16.0 + (text "Address") + (keyed "draft-url" (text-input (.url d) DraftUrl #:placeholder "https://")) + (text "Title") + (with-button (keyed "draft-title" (text-input (.title d) DraftTitle)) + (button (if fetching "Fetching…" "Fetch") DraftFetchTitle + #:enabled (not fetching) #:width 100.0)) + (text "Tags") + (keyed "draft-tags" (text-input (.tags d) DraftTags #:placeholder "rust web")) + (text "Archive link") + (with-button (keyed "draft-archive" (text-input (.archive d) DraftArchive + #:placeholder "https://web.archive.org/…")) + (button (if archiving "Fetching…" "Fetch") DraftFetchArchive + #:enabled (not archiving) #:width 100.0)) + (paint (text (.problem d) #:wrap #t) #:colour red) + (row #:spacing 12.0 + (button "Save" SaveDraft #:width 100.0) + (button "Cancel" CancelDraft #:width 100.0))))) + +;; The "More" layer: what does not fit beside the search. +(: (-> Model (View Msg))) +(defun (more-view m) + (column #:spacing 12.0 #:margin 16.0 + (button "Import a Firefox backup…" ImportAsked #:width 260.0) + (button "Help" ShowHelp #:width 260.0) + (button "Other bookmarks…" SwitchVault #:enabled (not (.leaving m)) #:width 260.0) + (if (.kept m) + (button "Stop opening with the fingerprint" ForgetDevice #:width 260.0) + (text "")) + (paint (text (str "Folder: " (.folder-label m)) #:wrap #t) #:colour grey))) + +;; The help: how to use the app on a phone. +(: (-> (View Msg))) +(defun (help-view) + (def paragraph #(text & #:wrap #t)) + (scroll + (column #:spacing 12.0 #:margin 16.0 + (text "Bjomarks" #:size 16.0) + (paragraph (str "Tap a bookmark for its menu: Open, Open in private window, Copy address, Share, " + "Edit, Remove. Back clears the search.")) + (paragraph (str "Open in private window opens the page in Firefox's private browsing, or in Firefox " + "Focus. Other browsers, such as Chrome, do not let an app open a private tab: then " + "the address is copied, to paste in one. The menu stays open " + "until you choose in it, tap outside it, or press Back. Undo brings back what was " + "removed.")) + (paragraph (str "In a browser, share a page to Bjomarks. The dialog of a new bookmark opens with the " + "address and the title of the page.")) + (paragraph (str "Share sends the title, the address and the tags of a bookmark, each on a " + "line.")) + (text "Opening" #:size 16.0) + (paragraph (str "Under the password, choose to open the bookmarks with the fingerprint or the " + "screen lock the next time. The phone then keeps the password, and gives it after " + "its unlock. More has a button to stop it. When a fingerprint is added to the " + "phone, or its screen lock is changed, type the password again.")) + (text "Searching" #:size 16.0) + (paragraph (str "Each word must be in the title, the address or a tag of a bookmark: a whole word, " + "the start of one, or a part of one. A word of 4 letters or more may have a typo, " + "and one of 8 or more two. Capitals and accents do not matter, but å, ä, ö, æ and ø " + "are letters of their own.")) + (paragraph "t:rust has the tag rust, the whole tag. tag:rust is the same.") + (paragraph (str "d:github has github in its domain. d:github.com is at github.com, or under it, " + "such as gist.github.com.")) + (paragraph (str "a:2012 was added in 2012; a:2012-06 and a:2012-06-15 in that month and on that " + "day. a:2011:2012-06 was added from 1 January 2011 to 30 June 2012. a:2011: has " + "no end, and a::2012 no start.")) + (paragraph (str "\"two words\" has exactly that text. A - before a word or a term: the bookmark " + "must not have it. Example: rust -t:docs d:github.com a:2024:")) + (paragraph (str "The best matches come first: a whole word before a part of one, and the title " + "before the tags and the address. Without words, the newest come first.")) + (text "The dialog" #:size 16.0) + (paragraph (str "Fetch beside the title gets the title of the page at the address. An address that " + "a bookmark has already loads that bookmark, so that no address is there twice.")) + (paragraph (str "Fetch beside the archive link gets the address of the latest copy of the page in " + "the Wayback Machine of the Internet Archive (web.archive.org), if it has one. The " + "Internet Archive sees the address that is looked up.")) + (text "Importing" #:size 16.0) + (paragraph (str "Import reads the bookmark backup of Firefox, a JSON file. On a computer, in " + "Firefox's Library (Ctrl+Shift+O), choose Import and Backup, then Backup. Put the " + "file on the phone, for example in the shared folder. Each folder becomes a tag. " + "The bookmarks that are here already are not changed.")) + (text "Syncing" #:size 16.0) + (paragraph (str "Each change is written to the shared folder in the background. The changes of " + "the other devices are read each minute, and when the app comes back.")) + (paragraph (str "A page that two devices bookmarked before they synced becomes one bookmark, with " + "the tags of both. When the two have different titles, the app asks which to keep."))))) + +;; The layers over the list. Back closes the top one. +;; - The dialog of a bookmark is on top: a share opens it over the others. +(: windows (-> Model (List (WindowView Msg)))) +(defun (windows m) + (def more (if (.more m) (list (window "more" "More" HideMore (more-view m) #:modal #t)) '())) + (def help (if (.help m) (list (window "help" "Help" HideHelp (help-view) #:modal #t)) '())) + (def draft (match (.draft m) + ((Some d) + (list (window "draft" (match (.editing d) ((Some _) "Edit bookmark") (None "New bookmark")) + CancelDraft (draft-view d) #:modal #t))) + (None '()))) + (list-append (duplicate-windows m) (list-append more (list-append help draft)))) + +;; The question for the first page bookmarked twice: which title to keep. +(: (-> Model (List (WindowView Msg)))) +(defun (duplicate-windows m) + (def asked (vec-filter (fun (d) (not (vec-contains? (.later m) (duplicate-url d)))) (.duplicates m))) + (if (vec-empty? asked) + '() + (let ((d (vec-ref asked 0))) + (def url (duplicate-url d)) + (list (window "duplicate" "Bookmarked twice" (Later url) + (scroll + (column #:spacing 12.0 #:margin 16.0 + (text "This page is bookmarked twice, with different titles. Keep which?" #:wrap #t) + (paint (text url #:size 12.0 #:wrap #t) #:colour grey) + (vec-fold (fun (t acc) (column #:spacing 8.0 acc (button t (ChooseTitle url t)))) + (column) (duplicate-titles d)) + (paint (text "The bookmark that stays has the tags of both." #:size 12.0 #:wrap #t) #:colour grey))) + #:modal #t))))) + +;; Back, when no layer is open: it clears the search, when one is typed in +;; the list. Otherwise the app does not take it, and Android leaves the app. +(: back-message (-> Model (Option Msg))) +(defun (back-message m) + (if (and (= (.phase m) Open) (not (string-empty? (.query m)))) (Some ClearSearch) None)) + +;; - Shared text and the app's activity, in each phase: a share that comes +;; before the vault is open waits for it. +;; - The saved folder is opened once at the start. +;; - A sync each minute while the vault is open, for the changes of the +;; other devices. +(: subscriptions (-> Model (List (Sub Msg)))) +(defun (subscriptions m) + (def always (list (on-shared-text SharedIn) (on-activity Active))) + (match (Tuple (.phase m) (.mark m)) + ((Tuple Checking (Some mark)) + (cons (task (str "reopen " mark) (open-folder-bookmark mark FolderReopened)) always)) + ((Tuple Open _) (cons (every (seconds 60) SyncTick) always)) + (_ always))) diff --git a/src/main.bjo b/src/main.bjo new file mode 100644 index 0000000..b5cd38e --- /dev/null +++ b/src/main.bjo @@ -0,0 +1,30 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; (bjomarks-android) — bookmarks on an Android phone. +;; +;; bjo run --android +;; +;; - The shared folder is chosen with the system's folder picker, and opened +;; again at each start: see (bjomarks-android settings). +;; - This device's own folder is "bjomarks" in the app's folder for data. +;; - See (bjomarks-android app) for the screens. +;; +;; It runs on the desktop too, in a window, for trying it out: the picker is +;; then the desktop's. + +(import (std prelude)) +(import (std os)) +(import (bjogui app)) +(import (bjomarks-android app)) +(import (bjomarks-android settings)) + +(: (-> (Vec string) int)) +(defun (main args) + (def settings (settings-folder)) + (def local (path-combine (data-directory) "bjomarks")) + (run-app (initial-model local settings (read-folder-mark settings) #:vaults (read-vaults settings)) gui-update view + #:windows windows #:subscriptions subscriptions #:on-back back-message + #:title "Bjomarks" #:width 420.0 #:height 760.0) + 0) diff --git a/src/settings.bjo b/src/settings.bjo new file mode 100644 index 0000000..a9085a4 --- /dev/null +++ b/src/settings.bjo @@ -0,0 +1,120 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks-android/src/settings.bjo — the module (bjomarks-android +;; settings): what the app keeps between runs, in settings.json in a folder +;; of its own. +;; +;; {"folder": "", +;; "vaults": [{"name": "Bookmarks", "folder": ""}, ...]} +;; +;; - The folder is "bjomarks" in the app's folder for configuration. +;; - "folder" is the bookmark of the shared folder used last, from bjogui's +;; `folder-bookmark`. It opens the folder again, and on Android it keeps +;; the app's access to it. +;; - "vaults" is the shared folders that the user added, each with the name +;; of its folder, in the order they were added. Settings of an earlier +;; version, with "folder" only, have that one. +;; - The fields that this version does not know are kept when it writes. +;; - The file is written whole and then renamed over the old one, so that it +;; is never half written. + +(export settings-folder read-folder-mark save-folder-mark! + VaultEntry vault-entry-name vault-entry-mark read-vaults save-vaults!) + +(import (std prelude)) +(import (std os)) +(import (text json)) + +(: string) +(def file-name "settings.json") + +;; The folder of the settings: "bjomarks" in the app's folder for +;; configuration. +(: (-> string)) +(defun (settings-folder) (path-combine (config-directory) "bjomarks")) + +;; The fields of the settings in `folder`, in their order. None when there +;; is no settings file, or it is not a JSON object. +(: (-> string (Option (IArray (Tuple string Json))))) +(defun (read-fields folder) + (def file (path-combine folder file-name)) + (if (not (file-exists? file)) + None + (match (parse-json (file-read-text file) #:objects 'fields) + ((Ok (JsonFields fields)) (Some fields)) + (_ None)))) + +;; The bookmark of the shared folder saved in the settings in `folder`. None +;; when none is saved, or the file cannot be read as settings. +(: (-> string (Option string))) +(defun (read-folder-mark folder) + (match (read-fields folder) + ((Some fields) + (match (json-object-ref (JsonFields fields) "folder") + ((Some (JsonStr s)) (if (string-empty? (string-trim s)) None (Some s))) + (_ None))) + (None None))) + +;; Saves `mark` as the bookmark of the shared folder in the settings in +;; `folder`, and keeps their other fields. Makes `folder` when it is not +;; there. Raises what the file system raises. +(: (-> string string void)) +(defun (save-folder-mark! folder mark) + (save-fields! folder [(Tuple "folder" (JsonStr mark))])) + +;; A shared folder that the user added: the name to show, and its bookmark. +(type (: VaultEntry (Record (: name string) (: mark string)))) + +(: (-> VaultEntry string)) +(defun (vault-entry-name e) (.name e)) + +(: (-> VaultEntry string)) +(defun (vault-entry-mark e) (.mark e)) + +;; The shared folders saved in the settings in `folder`, in their order. +;; Settings with a "folder" and no "vaults" have that one, with no name yet. +(: (-> string (Vec VaultEntry))) +(defun (read-vaults folder) + (match (read-fields folder) + ((Some fields) + (match (json-object-ref (JsonFields fields) "vaults") + ((Some (JsonArr items)) + (vec-fold (fun (j acc) + (match (Tuple (json-object-ref j "name") (json-object-ref j "folder")) + ((Tuple (Some (JsonStr name)) (Some (JsonStr mark))) + (if (string-empty? mark) acc (vec-add acc (VaultEntry (name name) (mark mark))))) + (_ acc))) + [] (iarray->vec items))) + (_ (match (read-folder-mark folder) + ((Some mark) [(VaultEntry (name "") (mark mark))]) + (None []))))) + (None []))) + +;; Saves `vaults` in the settings in `folder`, and `last` as the one used +;; last, or none, and keeps their other fields. +(: (-> string (Vec VaultEntry) (Option string) void)) +(defun (save-vaults! folder vaults last) + (def items (vec-map (fun (e) (JsonFields (vec->iarray [(Tuple "name" (JsonStr (.name e))) + (Tuple "folder" (JsonStr (.mark e)))]))) + vaults)) + (def list-field (Tuple "vaults" (JsonArr (vec->iarray items)))) + ;; "" is no folder: `read-folder-mark` reads it as none. + (save-fields! folder [(Tuple "folder" (JsonStr (option-ref-or last ""))) list-field])) + +;; Saves `fields` in the settings in `folder`, in place of those of their +;; names, and keeps the others. Makes `folder` when it is not there. Raises +;; what the file system raises. +(: (-> string (Vec (Tuple string Json)) void)) +(defun (save-fields! folder fields) + (def names (vec-map fst fields)) + (def others (match (read-fields folder) + ((Some old) (vec-filter (fun (f) (not (vec-contains? names (fst f)))) (iarray->vec old))) + (None []))) + (def text (json->string (JsonFields (vec->iarray (vec-append others fields))))) + (directory-create folder) + (def file (path-combine folder file-name)) + (def partial (str file ".new")) + (file-write-text partial text) + (file-move partial file #:mode MoveReplace)) diff --git a/tests/app.bjo b/tests/app.bjo new file mode 100644 index 0000000..c4503f4 --- /dev/null +++ b/tests/app.bjo @@ -0,0 +1,414 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. + +;; bjomarks-android/tests/app.bjo — the phone app without a phone. +;; +;; bjo run tests/app.bjo +;; +;; - The shared folder is a storage of functions over a map in memory. +;; - The test is the host: it posts shared texts, as the Android app's C# +;; does, and keeps the password as the phone's unlock does. No window is +;; opened. + +(import (std prelude)) +(import (std simpletest)) +(import (std os)) +(import (std uuid)) +(import (bjogui view)) +(import (except (bjogui app) Live)) +(import (bjogui platform)) +(import (bjomarks bookmark)) +(import (bjomarks store)) +(import (bjomarks import)) +(import (bjomarks draft)) +(import (bjomarks duplicates)) +(import (bjomarks-android app)) +(import (bjomarks-android settings)) + +(import/class + (ClrString (: System.String))) + +(import/extern + (host-post (: Bjolang.Runtime.Host.Post (-> string string void))) + (host-offer (: Bjolang.Runtime.Host.SetHandler (-> string (-> ClrString bool) void))) + (sleep-ms (: System.Threading.Thread.Sleep (-> int void) #:blocking))) + +(: (-> (Box (Map string (Array byte))) Storage)) +(defun (memory-storage files) + (: (-> string (Option (Array byte)))) + (defun (read name) (map-try-ref (box-ref files) name)) + (: (-> string (Array byte) void)) + (defun (write name bytes) (box-set! files (map-set (box-ref files) name bytes))) + (: (-> string (Vec string))) + (defun (list-names dir) + (def prefix (str dir "/")) + (vec-map (fun (k) (string-drop k (string-count prefix))) + (vec-filter (fun (k) (string-starts-with? k prefix)) (->vec (map-keys (box-ref files)))))) + (function-storage "memory" read write list-names)) + +;; The phone's unlock, as the test plays it: what it keeps, its name, a +;; newline and the secret. +(: (Box string)) +(def phone-kept (make-box "")) + +(: phone-can (-> ClrString bool) #:sync) +(defun (phone-can s) #t) + +(: phone-has (-> ClrString bool) #:sync) +(defun (phone-has name) (not (string-empty? (box-ref phone-kept)))) + +(: phone-keep (-> ClrString bool) #:sync) +(defun (phone-keep s) (box-set! phone-kept (.ToString s)) #t) + +(: phone-forget (-> ClrString bool) #:sync) +(defun (phone-forget name) (box-set! phone-kept "") #t) + +(: (-> Model (Vec string))) +(defun (urls m) + (match (.vault m) + ((Some v) (vec-sort (vec-map (fun (b) (.url b)) (vault-bookmarks v)))) + (None []))) + +(: (-> Model (Option Draft))) +(defun (draft-in m) (.draft m)) + +;; A Firefox backup with two bookmarks in a folder "Reading", and one that +;; the vault has already. +(: string) +(def backup-json + """ + {"guid":"root________","title":"","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":1,"typeCode":2,"type":"text/x-moz-place-container","root":"placesRoot","children":[ + {"guid":"menu________","title":"menu","index":0,"dateAdded":1500000000000000,"lastModified":1500000000000000, + "id":2,"typeCode":2,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[ + {"guid":"folderA00001","title":"Reading","index":0,"dateAdded":1700000000000000,"lastModified":1700000000000000, + "id":7,"typeCode":2,"type":"text/x-moz-place-container","children":[ + {"guid":"bookmark0001","title":"The Book","index":0,"dateAdded":1700000100000000,"lastModified":1700000100000000, + "id":8,"typeCode":1,"type":"text/x-moz-place","uri":"https://doc.rust-lang.org/book/"}, + {"guid":"bookmark0002","title":"Old","index":1,"dateAdded":1700000100000000,"lastModified":1700000100000000, + "id":9,"typeCode":1,"type":"text/x-moz-place","uri":"https://example.org/b"}]}]}]} + """) + +(defun (main) + ;; shared-url, without an app. + (expect "an address after words" (shared-url "A page\nhttps://example.org/a b") (Some "https://example.org/a")) + (expect "http too" (shared-url "see http://example.org") (Some "http://example.org")) + (expect "no address" (shared-url "just words") None) + + (def root (make-temp-directory #:prefix "bjomarks-android-test-")) + (def files (make-box (: (map-empty) (Map string (Array byte))))) + (def storage (memory-storage files)) + + ;; Shared before the vault is open: it waits for it. + (start-headless!) + (host-post "share-text" "A page\nhttps://example.org/a") + (def app (start-app (initial-model (path-combine root "one") (path-combine root "settings") None + #:storage (Some storage) #:start CreateNew + ;; No server listens there: a lookup fails at once. + #:wayback "http://127.0.0.1:9/wayback") + gui-update view (fun (c) unit) + #:windows windows #:subscriptions subscriptions)) + + ;; Runs what the fibers posted until `done?` holds, for 30 seconds at most: + ;; Argon2id is slow. + (: (-> (-> Model bool) bool)) + (defun (wait-for done?) + (let go ((tries 0)) + (app-run-pending! app) + (cond ((done? (app-model app)) #t) + ((> tries 3000) #f) + (else (sleep-ms 10) (go (+ tries 1)))))) + + (defun (send msg) + (app-dispatch! app msg) + (app-run-pending! app)) + + (expect "the share waits" + (wait-for (fun (m) (some? (.shared m)))) #t) + (expect "a storage given is locked at once" (= (.phase (app-model app)) Locked) #t) + (expect "the label of the storage" (.folder-label (app-model app)) "memory") + + ;; The phone can keep the password, and the user chooses it. + (host-offer "device-secret-available" phone-can) + (host-offer "device-secret-stored" phone-has) + (host-offer "device-secret-keep" phone-keep) + (host-offer "device-secret-unlock" phone-has) + (host-offer "device-secret-forget" phone-forget) + (send (DeviceChecked (Ok (Tuple #t #f)))) + (expect "the phone can keep it" (Tuple (.device (app-model app)) (.kept (app-model app))) (Tuple #t #f)) + (send (KeepWithDevice #t)) + + (send Unlock) + (expect "no password" (.problem (app-model app)) "Type the password.") + (send (Password "hunter2")) + (send (Again "hunter3")) + (send Unlock) + (expect "two passwords" (.problem (app-model app)) "The two passwords are not the same.") + (send (Again "hunter2")) + (send Unlock) + (expect "unlocking" (= (.phase (app-model app)) Unlocking) #t) + (expect "the vault is made" (wait-for (fun (m) (= (.phase m) Open))) #t) + (expect "keys.bin is in the folder" (some? (map-try-ref (box-ref files) "keys.bin")) #t) + (expect "the phone keeps the password" (wait-for (fun (m) (.kept m))) #t) + (expect "under its name" (box-ref phone-kept) (str password-secret "\nhunter2")) + + ;; The share that waited is the dialog of a new bookmark. + (match (draft-in (app-model app)) + ((Some d) + (expect "the shared address" (.url d) "https://example.org/a") + (expect "the subject is the title" (.title d) "A page") + (expect "a new bookmark" (none? (.editing d)) #t)) + (None (expect "a dialog after the share" #f #t))) + (expect "the share is used" (none? (.shared (app-model app))) #t) + (send (DraftTags "web, test")) + (send SaveDraft) + (expect "saved" (urls (app-model app)) ["https://example.org/a"]) + (expect "what Share sends" + (share-text-of (vec-ref (visible-bookmarks (app-model app)) 0)) + "A page\nhttps://example.org/a\nTags: test web") + (expect "the dialog is closed" (none? (draft-in (app-model app))) #t) + (expect "the sync ends" (wait-for (fun (m) (not (.saving m)))) #t) + (expect "no sync failed" (.failed (app-model app)) #f) + (expect "the device's file is in the folder" + (vec-length (vec-filter (fun (k) (string-starts-with? k "devices/")) (->vec (map-keys (box-ref files))))) 1) + + ;; The same address again: the dialog of its bookmark. + (host-post "share-text" "Again\nhttps://example.org/a") + (expect "a share while open" + (wait-for (fun (m) (some? (draft-in m)))) #t) + (match (draft-in (app-model app)) + ((Some d) + (expect "the bookmark there" (some? (.editing d)) #t) + (expect "with a problem" (string-empty? (.problem d)) #f) + (expect "its tags, sorted" (.tags d) "test web")) + (None unit)) + (send CancelDraft) + + ;; A new bookmark that is not an address, and one with an address that a + ;; bookmark has: it loads that bookmark, and another address brings back + ;; what was typed. + (send New) + (send (DraftUrl "not an address")) + (send SaveDraft) + (expect "not an address" + (match (draft-in (app-model app)) ((Some d) (string-empty? (.problem d))) (None #t)) #f) + (send (DraftTitle "Bee")) + (send (DraftUrl "https://example.org/a")) + (expect "an address there already loads its bookmark" + (match (draft-in (app-model app)) ((Some d) (Tuple (.problem d) (.title d))) (None (Tuple "" ""))) + (Tuple address-here "A page")) + (send (DraftUrl "https://example.org/b")) + (expect "another address brings back what was typed" + (match (draft-in (app-model app)) ((Some d) (Tuple (none? (.editing d)) (.title d))) (None (Tuple #f ""))) + (Tuple #t "Bee")) + ;; The archive link: a lookup that fails says so; a link typed is kept. + (send DraftFetchArchive) + (expect "an archive lookup that fails" + (wait-for (fun (m) (match (draft-in m) + ((Some d) (string-starts-with? (.problem d) "No archive")) + (None #f)))) + #t) + (send (DraftArchive "https://web.archive.org/web/2026/https://example.org/b")) + (send SaveDraft) + (expect "two bookmarks" (urls (app-model app)) ["https://example.org/a" "https://example.org/b"]) + (expect "with the archive link" + (vec-map (fun (b) (.archive b)) + (vec-filter (fun (b) (= (.url b) "https://example.org/b")) + (match (.vault (app-model app)) ((Some v) (vault-bookmarks v)) (None [])))) + [(Some "https://web.archive.org/web/2026/https://example.org/b")]) + + ;; Searching. + (send (Search "tag:web")) + (expect "a search by tag" (vec-map (fun (b) (.url b)) (visible-bookmarks (app-model app))) + ["https://example.org/a"]) + (send (Search "bee")) + (expect "a search by title" (vec-map (fun (b) (.url b)) (visible-bookmarks (app-model app))) + ["https://example.org/b"]) + ;; Back clears the search, and with none it is not taken. + (expect "Back with a search" (some? (back-message (app-model app))) #t) + (send (match (back-message (app-model app)) ((Some msg) msg) (None (Search "not taken")))) + (expect "clears it" (.query (app-model app)) "") + (expect "and shows all" (vec-length (visible-bookmarks (app-model app))) 2) + (expect "Back without a search is not taken" (none? (back-message (app-model app))) #t) + + ;; Copy address: the note says what was copied. + (send (CopyAddress (.id (vec-ref (visible-bookmarks (app-model app)) 0)))) + (expect "Copy address" (string-starts-with? (.note (app-model app)) "Copied https://example.org/") #t) + + ;; Open in private window, with no host that can: the address is copied. + (def first-id (.id (vec-ref (visible-bookmarks (app-model app)) 0))) + (send (OpenPrivately first-id)) + (expect "no private window without a host" + (wait-for (fun (m) (string-contains? (.note m) "The address is copied"))) #t) + (send (OpenBookmark first-id)) + (expect "Open asks the system" (string-starts-with? (.note (app-model app)) "Opening https://example.org/") #t) + (expect "and without a window, it cannot" + (wait-for (fun (m) (string-starts-with? (.note m) "Could not open"))) #t) + + ;; Edit, remove and undo. + (def a-id (.id (vec-ref (vec-filter (fun (b) (= (.url b) "https://example.org/a")) + (visible-bookmarks (app-model app))) 0))) + (send (Edit a-id)) + (send (DraftTitle "Ay")) + (send (DraftTags "x")) + (send SaveDraft) + (def edited (vec-filter (fun (b) (= (.id b) a-id)) (visible-bookmarks (app-model app)))) + (expect "the title edited" (.title (vec-ref edited 0)) (Some "Ay")) + (expect "the tags edited" (.tags (vec-ref edited 0)) ["x"]) + (send (Remove a-id)) + (expect "removed" (urls (app-model app)) ["https://example.org/b"]) + (expect "the note" (.note (app-model app)) "Removed Ay.") + (send Undo) + (expect "brought back" (urls (app-model app)) ["https://example.org/a" "https://example.org/b"]) + (expect "nothing more to undo" (empty? (.removed (app-model app))) #t) + (expect "the syncs end" (wait-for (fun (m) (not (.saving m)))) #t) + + ;; More, Help, and an import: the file's text is read as the picker's + ;; file would be. + (send ShowMore) + (expect "the More layer" (app-windows app) (list "more")) + (send ShowHelp) + (expect "Help closes More" (Tuple (.more (app-model app)) (.help (app-model app))) (Tuple #f #t)) + (send HideHelp) + (expect "no layers" (app-windows app) (list)) + (send (BackupRead "bookmarks.json" (Ok (read-firefox-backup backup-json)))) + (expect "imported" (urls (app-model app)) + ["https://doc.rust-lang.org/book/" "https://example.org/a" "https://example.org/b"]) + (expect "the note of the import" (.note (app-model app)) + "Imported 1 bookmark from bookmarks.json. 1 was here already.") + (send (BackupRead "bad.json" (Ok (read-firefox-backup "not json")))) + (expect "a file that is not a backup" + (string-starts-with? (.note (app-model app)) "Could not import bad.json") #t) + (expect "the syncs end again" (wait-for (fun (m) (not (.saving m)))) #t) + ;; "Other bookmarks…": saved, closed, and back to the password screen. + (send ShowMore) + (send SwitchVault) + (expect "back to the password screen" + (wait-for (fun (m) (and (= (.phase m) Locked) (none? (.vault m))))) #t) + (expect "with nothing of the vault" + (Tuple (.query (app-model app)) (list-length (.removed (app-model app))) (.start (app-model app))) + (Tuple "" 0 OpenExisting)) + (app-stop! app) + + ;; This device again: the phone gives the password after its unlock. + (def again (start-app (initial-model (path-combine root "one") (path-combine root "settings") None + #:storage (Some storage) #:start OpenExisting) + gui-update view (fun (c) unit) + #:windows windows #:subscriptions subscriptions)) + (app-dispatch! again (DeviceChecked (Ok (Tuple #t #t)))) + (app-run-pending! again) + (expect "the phone asks at once" (.asking (app-model again)) #t) + (host-post "device-secret" "cancelled\n") + (let go ((tries 0)) + (app-run-pending! again) + (when (and (.asking (app-model again)) (< tries 300)) (sleep-ms 10) (go (+ tries 1)))) + (expect "cancelled: the password screen" (Tuple (.asking (app-model again)) (= (.phase (app-model again)) Locked)) + (Tuple #f #t)) + (app-dispatch! again AskDevice) + (host-post "device-secret" "ok\nhunter2") + (let go ((tries 0)) + (app-run-pending! again) + (unless (or (= (.phase (app-model again)) Open) (> tries 3000)) (sleep-ms 10) (go (+ tries 1)))) + (expect "the phone's password opens it" (= (.phase (app-model again)) Open) #t) + (app-stop! again) + + ;; A kept password that is wrong is forgotten. + (def wrong (start-app (initial-model (path-combine root "one") (path-combine root "settings") None + #:storage (Some storage) #:start OpenExisting) + gui-update view (fun (c) unit) + #:windows windows #:subscriptions subscriptions)) + (app-dispatch! wrong (DeviceChecked (Ok (Tuple #t #t)))) + (host-post "device-secret" "ok\nhunter3") + (let go ((tries 0)) + (app-run-pending! wrong) + (unless (or (string-empty? (box-ref phone-kept)) (> tries 3000)) (sleep-ms 10) (go (+ tries 1)))) + (expect "a wrong kept password is forgotten" + (Tuple (box-ref phone-kept) (.kept (app-model wrong)) (= (.phase (app-model wrong)) Locked)) + (Tuple "" #f #t)) + (app-stop! wrong) + + ;; Another device joins through the same folder, and sees both. + (def two (start-app (initial-model (path-combine root "two") (path-combine root "settings") None + #:storage (Some storage) #:start JoinShared) + gui-update view (fun (c) unit) + #:windows windows #:subscriptions subscriptions)) + (app-dispatch! two (Password "hunter2")) + (app-dispatch! two Unlock) + (let go ((tries 0)) + (app-run-pending! two) + (unless (or (= (.phase (app-model two)) Open) (> tries 3000)) + (sleep-ms 10) + (go (+ tries 1)))) + (expect "the other device opens" (= (.phase (app-model two)) Open) #t) + (expect "and has all" (urls (app-model two)) + ["https://doc.rust-lang.org/book/" "https://example.org/a" "https://example.org/b"]) + + ;; A third device, not yet synced, bookmarked example.org/a with a title + ;; of its own: after a sync, the app asks which title to keep. + (def three (match (join-vault storage (path-combine root "three") "hunter2") + ((Ok (Tuple v _)) v) + ((Err _) (panic! "the third device did not join")))) + (def three2 (match (vault-add three "https://example.org/a" #:title (Some "Another title") #:tags ["other"]) + ((Ok (Tuple v _)) v) + ((Err why) (panic! why)))) + (ignore (vault-sync three2)) + (defun (sync-two) + (app-dispatch! two SyncTick) + (let go ((tries 0)) + (app-run-pending! two) + (when (and (.saving (app-model two)) (< tries 3000)) (sleep-ms 10) (go (+ tries 1))))) + (sync-two) + (def asked (.duplicates (app-model two))) + (expect "a page bookmarked twice" (vec-length asked) 1) + (expect "its titles" (vec-length (duplicate-titles (vec-ref asked 0))) 2) + (expect "the question shows" (list-length (windows (app-model two))) 1) + (app-dispatch! two (ChooseTitle "https://example.org/a" "Another title")) + (sync-two) + (def kept (vec-filter (fun (b) (= (.url b) "https://example.org/a")) + (vault-bookmarks (option-ref-or (.vault (app-model two)) three2)))) + (expect "one bookmark of it" (vec-length kept) 1) + (expect "with the title chosen" (.title (vec-ref kept 0)) (Some "Another title")) + (expect "and the tags of both" (vec-contains? (.tags (vec-ref kept 0)) "other") #t) + (expect "no question" (Tuple (vec-length (.duplicates (app-model two))) (list-length (windows (app-model two)))) + (Tuple 0 0)) + (app-stop! two) + + ;; The settings keep the folder's bookmark, and other fields. + (def settings (path-combine root "settings")) + (expect "no settings yet" (read-folder-mark settings) None) + (save-folder-mark! settings "mark-1") + (save-folder-mark! settings "mark-2") + (expect "the last mark" (read-folder-mark settings) (Some "mark-2")) + + ;; The list of folders. Settings of an earlier version have their one + ;; folder, with no name yet. + (expect "the folder of an earlier version" (vec-map vault-entry-mark (read-vaults settings)) ["mark-2"]) + (def home (VaultEntry (name "Home") (mark "mark-a"))) + (def work (VaultEntry (name "Work") (mark "mark-b"))) + (save-vaults! settings [home work] (Some "mark-b")) + (expect "the list is kept" (vec-map vault-entry-name (read-vaults settings)) ["Home" "Work"]) + (expect "and the one used last" (read-folder-mark settings) (Some "mark-b")) + (save-vaults! settings [home] None) + (expect "none used last" (read-folder-mark settings) None) + (expect "a shorter list" (vec-map vault-entry-name (read-vaults settings)) ["Home"]) + + ;; Choosing among them. + (def listed (initial-model (path-combine root "four") settings (Some "mark-a") #:vaults [home work])) + (expect "the one used last opens at the start" (Tuple (.phase listed) (.current listed)) + (Tuple Checking (Some "mark-a"))) + (def locked (record-set listed (phase Locked))) + (def (Tuple chose _) (gui-update (ChooseVault 1) locked)) + (expect "another one is opened" (Tuple (.phase chose) (.mark chose) (.current chose)) + (Tuple Checking (Some "mark-b") (Some "mark-b"))) + (def (Tuple same _) (gui-update (ChooseVault 0) locked)) + (expect "the one in use again changes nothing" (.phase same) Locked) + (def (Tuple adding _) (gui-update (ChooseVault 2) locked)) + (expect "Add new asks for a folder, and keeps the one in use" + (Tuple (.phase adding) (.current adding)) (Tuple Locked (Some "mark-a"))) + (def (Tuple forgot _) (gui-update ForgetVault locked)) + (expect "Remove from list" (Tuple (vec-map vault-entry-name (.vaults forgot)) (.current forgot) (.phase forgot)) + (Tuple ["Work"] None NoFolder)) + + (directory-delete-tree root) + (println "bjomarks-android app ok"))