diff --git a/apps.json b/apps.json index 40e92d201..b6fd7b012 100644 --- a/apps.json +++ b/apps.json @@ -2,7 +2,7 @@ { "id": "fwupdate", "name": "Firmware Update", - "version": "0.02", + "version": "0.03", "description": "[BETA] Uploads new Espruino firmwares to Bangle.js 2. For now, please use the instructions under https://www.espruino.com/Bangle.js2#firmware-updates", "icon": "app.png", "type": "RAM", @@ -16,7 +16,7 @@ { "id": "boot", "name": "Bootloader", - "version": "0.39", + "version": "0.40", "description": "This is needed by Bangle.js to automatically load the clock, menu, widgets and settings", "icon": "bootloader.png", "type": "bootloader", @@ -77,7 +77,7 @@ { "id": "messages", "name": "Messages", - "version": "0.13", + "version": "0.17", "description": "App to display notifications from iOS and Gadgetbridge", "icon": "app.png", "type": "app", @@ -116,7 +116,7 @@ { "id": "ios", "name": "iOS Integration", - "version": "0.07", + "version": "0.08", "description": "Display notifications/music/etc from iOS devices", "icon": "app.png", "tags": "tool,system,ios,apple,messages,notifications", @@ -132,7 +132,7 @@ { "id": "health", "name": "Health Tracking", - "version": "0.08", + "version": "0.09", "description": "Logs health data and provides an app to view it (requires firmware 2v10.100 or later)", "icon": "app.png", "tags": "tool,system,health", @@ -167,7 +167,7 @@ { "id": "setting", "name": "Settings", - "version": "0.37", + "version": "0.40", "description": "A menu for setting up Bangle.js", "icon": "settings.png", "tags": "tool,system", @@ -554,7 +554,7 @@ { "id": "impwclock", "name": "Imprecise Word Clock", - "version": "0.03", + "version": "0.04", "description": "Imprecise word clock for vacations, weekends, and those who never need accurate time.", "icon": "clock-impword.png", "type": "clock", @@ -768,7 +768,7 @@ "id": "recorder", "name": "Recorder (BETA)", "shortName": "Recorder", - "version": "0.04", + "version": "0.05", "description": "Record GPS position, heart rate and more in the background, then download to your PC.", "icon": "app.png", "tags": "tool,outdoors,gps,widget", @@ -845,7 +845,7 @@ { "id": "weather", "name": "Weather", - "version": "0.13", + "version": "0.15", "description": "Show Gadgetbridge weather report", "icon": "icon.png", "screenshots": [{"url":"screenshot.png"}], @@ -936,7 +936,7 @@ "id": "widbatpc", "name": "Battery Level Widget (with percentage)", "shortName": "Battery Widget", - "version": "0.14", + "version": "0.16", "description": "Show the current battery level and charging status in the top right of the clock, with charge percentage", "icon": "widget.png", "type": "widget", @@ -971,7 +971,7 @@ { "id": "widbt", "name": "Bluetooth Widget", - "version": "0.07", + "version": "0.08", "description": "Show the current Bluetooth connection status in the top right of the clock", "icon": "widget.png", "type": "widget", @@ -1148,7 +1148,7 @@ { "id": "qrcode", "name": "Custom QR Code", - "version": "0.04", + "version": "0.05", "description": "Use this to upload a customised QR code to Bangle.js", "icon": "app.png", "tags": "qrcode", @@ -1324,7 +1324,7 @@ "icon": "gesture.png", "type": "app", "tags": "gesture,ai", - "supports": ["BANGLEJS"], + "supports": ["BANGLEJS", "BANGLEJS2"], "storage": [ {"name":"gesture.app.js","url":"gesture.js"}, {"name":".tfnames","url":"gesture-tfnames.js","evaluate":true}, @@ -1501,7 +1501,7 @@ { "id": "gpsinfo", "name": "GPS Info", - "version": "0.05", + "version": "0.08", "description": "An application that displays information about altitude, lat/lon, satellites and time", "icon": "gps-info.png", "type": "app", @@ -1590,7 +1590,7 @@ { "id": "widpedom", "name": "Pedometer widget", - "version": "0.20", + "version": "0.21", "description": "Daily pedometer widget", "icon": "widget.png", "type": "widget", @@ -1749,8 +1749,9 @@ "icon": "grocery.png", "type": "app", "tags": "tool,outdoors,shopping,list", - "supports": ["BANGLEJS"], + "supports": ["BANGLEJS", "BANGLEJS2"], "custom": "grocery.html", + "allow_emulator": true, "storage": [ {"name":"grocery.app.js","url":"app.js"}, {"name":"grocery.img","url":"grocery-icon.js","evaluate":true} @@ -2027,7 +2028,7 @@ "id": "chronowid", "name": "Chrono Widget", "shortName": "Chrono Widget", - "version": "0.04", + "version": "0.05", "description": "Chronometer (timer) which runs as widget.", "icon": "app.png", "tags": "tool,widget", @@ -2184,7 +2185,7 @@ "id": "calculator", "name": "Calculator", "shortName": "Calculator", - "version": "0.04", + "version": "0.05", "description": "Basic calculator reminiscent of MacOs's one. Handy for small calculus.", "icon": "calculator.png", "screenshots": [{"url":"screenshot_calculator.png"}], @@ -2429,7 +2430,7 @@ { "id": "calendar", "name": "Calendar", - "version": "0.03", + "version": "0.06", "description": "Simple calendar", "icon": "calendar.png", "screenshots": [{"url":"screenshot_calendar.png"}], @@ -2970,11 +2971,11 @@ { "id": "cprassist", "name": "CPR Assist", - "version": "0.01", + "version": "0.02", "description": "Provides assistance while performing a CPR", "icon": "cprassist-icon.png", "tags": "tool,firstaid", - "supports": ["BANGLEJS"], + "supports": ["BANGLEJS", "BANGLEJS2"], "readme": "README.md", "allow_emulator": true, "screenshots": [{"url":"bangle1-CPR-assist-screenshot.png"}], @@ -3532,7 +3533,7 @@ "id": "mclockplus", "name": "Morph Clock+", "shortName": "Morph Clock+", - "version": "0.02", + "version": "0.03", "description": "Morphing Clock with more readable seconds and date and additional stopwatch", "icon": "mclockplus.png", "type": "clock", @@ -3896,7 +3897,7 @@ "id": "qmsched", "name": "Quiet Mode Schedule and Widget", "shortName": "Quiet Mode", - "version": "0.05", + "version": "0.06", "description": "Automatically turn Quiet Mode on or off at set times, and change LCD options while Quiet Mode is active.", "icon": "app.png", "screenshots": [{"url":"screenshot_b1_main.png"},{"url":"screenshot_b1_edit.png"},{"url":"screenshot_b1_lcd.png"}, @@ -3986,11 +3987,12 @@ "icon": "app.png", "type": "clock", "tags": "clock", - "supports": ["BANGLEJS"], + "supports": ["BANGLEJS", "BANGLEJS2"], "readme": "README.md", "allow_emulator": true, "storage": [ - {"name":"doztime.app.js","url":"app.js"}, + {"name":"doztime.app.js","url":"app-bangle1.js","supports":["BANGLEJS"]}, + {"name":"doztime.app.js","url":"app-bangle2.js","supports":["BANGLEJS2"]}, {"name":"doztime.img","url":"app-icon.js","evaluate":true} ] }, @@ -4014,11 +4016,12 @@ { "id": "thermom", "name": "Thermometer", - "version": "0.04", - "description": "Displays the current temperature in degree Celsius, updated every 20 seconds", + "version": "0.05", + "description": "Displays the current temperature in degree Celsius/Fahrenheit (depending on locale), updates every 10 seconds with average of last 5 readings.", "icon": "app.png", "tags": "tool", "supports": ["BANGLEJS", "BANGLEJS2"], + "screenshots": [{"url":"screenshot.png"}], "allow_emulator": true, "storage": [ {"name":"thermom.app.js","url":"app.js"}, @@ -4063,7 +4066,7 @@ { "id": "hcclock", "name": "Hi-Contrast Clock", - "version": "0.02", + "version": "0.03", "description": "Hi-Contrast Clock : A simple yet very bold clock that aims to be readable in high luninosity environments. Uses big 10x5 pixel digits. Use BTN 1 to switch background and foreground colors.", "icon": "hcclock-icon.png", "type": "clock", @@ -4080,7 +4083,7 @@ "id": "thermomF", "name": "Fahrenheit Temp", "version": "0.01", - "description": "A modification of the Thermometer App to display temprature in Fahrenheit", + "description": "[NOT RECOMMENDED] A modification of the Thermometer App to display temprature in Fahrenheit. Please use the 'Thermometer App' and install 'Languages' to get the temperature in the correct format for your locale.", "icon": "thermf.png", "tags": "tool", "supports": ["BANGLEJS"], @@ -4209,13 +4212,13 @@ "id": "pastel", "name": "Pastel Clock", "shortName": "Pastel", - "version": "0.09", - "description": "A Configurable clock with custom fonts and background. Has a cyclic information line that includes, day, date, battery, sunrise and sunset times", + "version": "0.10", + "description": "A Configurable clock with custom fonts, background and weather display. Has a cyclic information line that includes, day, date, battery, sunrise and sunset times", "icon": "pastel.png", - "dependencies": {"mylocation":"app", "widpedom":"app"}, - "screenshots": [{"url":"screenshot_pastel.png"}], + "dependencies": {"mylocation":"app", "widpedom":"app","weather":"app"}, + "screenshots": [{"url":"screenshot_pastel.png"}, {"url":"weather_icons.png"}], "type": "clock", - "tags": "clock", + "tags": "clock, weather, tool", "supports": ["BANGLEJS","BANGLEJS2"], "readme": "README.md", "storage": [ @@ -4236,8 +4239,9 @@ { "id": "antonclk", "name": "Anton Clock", - "version": "0.03", - "description": "A simple clock using the bold Anton font.", + "version": "0.04", + "description": "A clock using the bold Anton font, optionally showing seconds and date in ISO-8601 format.", + "readme":"README.md", "icon": "app.png", "screenshots": [{"url":"screenshot.png"}], "type": "clock", @@ -4246,8 +4250,10 @@ "allow_emulator": true, "storage": [ {"name":"antonclk.app.js","url":"app.js"}, + {"name":"antonclk.settings.js","url":"settings.js"}, {"name":"antonclk.img","url":"app-icon.js","evaluate":true} - ] + ], + "data": [{"name":"antonclk.json"}] }, { "id": "waveclk", @@ -4381,7 +4387,7 @@ { "id": "gpstouch", "name": "GPS Touch", - "version": "0.01", + "version": "0.02", "description": "A touch based GPS watch, shows OS map reference", "icon": "gpstouch.png", "screenshots": [{"url":"screenshot4.png"},{"url":"screenshot2.png"},{"url":"screenshot3.png"},{"url":"screenshot1.png"}], @@ -4471,7 +4477,7 @@ "name": "A Battery Widget (with percentage)", "shortName":"A Battery Widget", "icon": "widget.png", - "version":"1.02", + "version":"1.03", "type": "widget", "supports": ["BANGLEJS", "BANGLEJS2"], "readme": "README.md", @@ -4486,7 +4492,7 @@ "name": "LCARS Clock", "shortName":"LCARS", "icon": "lcars.png", - "version":"0.06", + "version":"0.09", "readme": "README.md", "supports": ["BANGLEJS2"], "description": "Library Computer Access Retrieval System (LCARS) clock.", @@ -4495,7 +4501,8 @@ "screenshots": [{"url":"screenshot.png"}], "storage": [ {"name":"lcars.app.js","url":"lcars.app.js"}, - {"name":"lcars.img","url":"lcars.icon.js","evaluate":true} + {"name":"lcars.img","url":"lcars.icon.js","evaluate":true}, + {"name":"lcars.settings.js","url":"lcars.settings.js"} ] }, { "id": "binwatch", @@ -4619,7 +4626,7 @@ "shortName":"93 Dub", "icon": "93dub.png", "screenshots": [{"url":"screenshot.png"}], - "version":"0.05", + "version":"0.06", "description": "Fan recreation of orviwan's 91 Dub app for the Pebble smartwatch. Uses assets from his 91-Dub-v2.0 repo", "tags": "clock", "type": "clock", @@ -4650,7 +4657,7 @@ "id": "sensible", "name": "SensiBLE", "shortName": "SensiBLE", - "version": "0.04", + "version": "0.05", "description": "Collect, display and advertise real-time sensor data.", "icon": "sensible.png", "screenshots": [ @@ -4695,6 +4702,8 @@ "tags": "tool,timer", "readme":"README.md", "supports":["BANGLEJS2"], + "screenshots": [{"url":"screenshot1.png"},{"url":"screenshot2.png"},{"url":"screenshot3.png"}], + "allow_emulator": true, "storage": [ {"name":"a_speech_timer.app.js","url":"app.js"}, {"name":"a_speech_timer.img","url":"app-icon.js","evaluate":true} @@ -4706,7 +4715,7 @@ "icon": "mylocation.png", "type": "app", "screenshots": [{"url":"screenshot_1.png"}], - "version":"0.01", + "version":"0.02", "description": "Sets and stores the lat and long of your preferred City or it can be set from the GPS. mylocation.json can be used by other apps that need your main location lat and lon. See README", "readme": "README.md", "tags": "tool,utility", @@ -4723,7 +4732,7 @@ "id": "pebble", "name": "Pebble Clock", "shortName": "Pebble", - "version": "0.06", + "version": "0.07", "description": "A pebble style clock to keep the rebellion going", "dependencies": {"widpedom":"app"}, "readme": "README.md", @@ -4731,7 +4740,7 @@ "screenshots": [{"url":"pebble_screenshot.png"}], "type": "clock", "tags": "clock", - "supports": ["BANGLEJS2"], + "supports": ["BANGLEJS", "BANGLEJS2"], "storage": [ {"name":"pebble.app.js","url":"pebble.app.js"}, {"name":"pebble.settings.js","url":"pebble.settings.js"}, @@ -4765,7 +4774,7 @@ "screenshots": [{"url":"screenshot_widbata_1.png"}], "version":"0.01", "type": "widget", - "supports": ["BANGLEJS2"], + "supports": ["BANGLEJS", "BANGLEJS2"], "readme": "README.md", "description": "Shows the current battery level status in the top right using the clocks colour theme", "tags": "widget,battery", @@ -4776,7 +4785,7 @@ { "id": "weatherClock", "name": "Weather Clock", - "version": "0.04", + "version": "0.05", "description": "A clock which displays current weather conditions (requires Gadgetbridge and Weather apps).", "icon": "app.png", "screenshots": [{"url":"screens/screen1.png"}], @@ -4836,6 +4845,25 @@ {"name": "flow.img", "url": "app-icon.js","evaluate": true } ] }, + { "id": "tinydraw", + "name": "TinyDraw", + "shortName":"TinyDraw", + "version":"0.01", + "type": "app", + "description": "Draw stuff in your wrist", + "icon": "app.png", + "allow_emulator": true, + "tags": "tools, keyboard, text, scribble", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"tinydraw.app.js","url":"app.js"}, + {"name":"tinydraw.img","url":"app-icon.js","evaluate":true} + ], + "screenshots":[ + { "url":"screenshot.png" } + ] + }, { "id": "scribble", "name": "Scribble", "shortName":"Scribble", @@ -4859,7 +4887,7 @@ "id": "ptlaunch", "name": "Pattern Launcher", "shortName": "Pattern Launcher", - "version": "0.11", + "version": "0.13", "description": "Directly launch apps from the clock screen with custom patterns.", "icon": "app.png", "screenshots": [{"url":"manage_patterns_light.png"}], @@ -4873,11 +4901,25 @@ ], "data": [{"name":"ptlaunch.patterns.json"}] }, + { "id": "slimehunt", + "name": "Slime Hunt", + "shortName":"SlimeHunt", + "icon": "app.png", + "version":"0.02", + "description": "Fight against slimes in turn based combat, try to get the highscore!", + "tags": "rpg,slime", + "supports" : ["BANGLEJS"], + "readme": "README.md", + "storage": [ + {"name":"slimehunt.app.js","url":"app.js"}, + {"name":"slimehunt.img","url":"app-icon.js","evaluate":true} + ] + }, { "id": "rebble", "name": "Rebble Clock", "shortName": "Rebble", - "version": "0.03", + "version": "0.04", "description": "A Pebble style clock, with configurable background, three sidebars including steps, day, date, sunrise, sunset, long live the rebellion", "readme": "README.md", "icon": "rebble.png", @@ -4929,10 +4971,12 @@ "id":"awairmonitor", "name":"Awair Monitor", "icon": "app.png", + "screenshots": [{"url":"screenshot.png"}], "allow_emulator": true, - "version":"0.01", + "version":"0.03", "description": "Displays the level of CO2, VOC, PM 2.5, Humidity and Temperature, from your Awair device.", - "tags": "tool,health", + "type": "clock", + "tags": "clock,tool,health", "readme":"README.md", "supports":["BANGLEJS2"], "storage": [ @@ -4961,8 +5005,8 @@ }, { "id": "coretemp", - "name": "Core Temp Display", - "version": "0.01", + "name": "CoreTemp", + "version": "0.02", "description": "Display CoreTemp device sensor data", "icon": "coretemp.png", "type": "app", @@ -4970,17 +5014,21 @@ "readme": "README.md", "supports": ["BANGLEJS","BANGLEJS2"], "storage": [ - {"name":"coretemp.boot.js","url":"boot.js"}, + {"name":"coretemp.wid.js","url":"widget.js"}, {"name":"coretemp.app.js","url":"coretemp.js"}, - {"name":"coretemp.img","url":"coretemp-icon.js","evaluate":true} - ] + {"name":"coretemp.settings.js","url":"settings.js"}, + {"name":"coretemp.img","url":"coretemp-icon.js","evaluate":true}, + {"name":"coretemp.boot.js","url":"boot.js"} + ], + "data": [{"name":"coretemp.json","url":"app-settings.json"}], + "screenshots": [{"url":"screenshot.png"}] }, { "id": "showimg", "name": "simple image viewer", "shortName":"showImage", "version":"0.2", - "description": "Displays the image in \"showimage.user.img\". The file has to be uploaded via the espruino IDE. Returns to watch face after 60s or button push. I use it to display my vaccination certificate.", + "description": "Displays the image in \"showimg.user.img\". The file has to be uploaded via the espruino IDE. Returns to watch face after 60s or button push. I use it to display my vaccination certificate.", "icon": "app.png", "tags": "tool", "supports" : ["BANGLEJS2"], @@ -5006,25 +5054,399 @@ {"name":"lapcounter.img","url":"app-icon.js","evaluate":true} ] }, + { + "id": "pebbled", + "name": "Pebble Clock with distance", + "shortName": "Pebble + distance", + "version": "0.1", + "description": "Fork of Pebble Clock with distance in KM. Both step count and the distance are on the main screen. Default step length = 0.75m (can be changed in settings).", + "readme": "README.md", + "icon": "pebbled.png", + "screenshots": [{"url":"pebble_screenshot.png"}], + "type": "clock", + "tags": "clock,distance", + "supports": ["BANGLEJS2"], + "storage": [ + {"name":"pebbled.app.js","url":"pebbled.app.js"}, + {"name":"pebbled.settings.js","url":"pebbled.settings.js"}, + {"name":"pebbled.img","url":"pebbled.icon.js","evaluate":true} + ] + }, { "id": "circlesclock", - "name": "Circles clock", - "shortName":"Circles clock", - "version":"0.01", - "description": "A clock with circles for different data at the bottom in a probably familiar style", - "icon": "app.png", - "dependencies": {"widpedom":"app"}, - "type": "clock", - "tags": "clock", - "supports" : ["BANGLEJS2"], - "allow_emulator":true, - "readme": "README.md", - "storage": [ - {"name":"circlesclock.app.js","url":"app.js"}, - {"name":"circlesclock.img","url":"app-icon.js","evaluate":true}, - {"name":"circlesclock.settings.js","url":"settings.js"} - ], - "data": [ - {"name":"circlesclock.json"} - ] - } + "name": "Circles clock", + "shortName":"Circles clock", + "version":"0.03", + "description": "A clock with circles for different data at the bottom in a probably familiar style", + "icon": "app.png", + "screenshots": [{"url":"screenshot.png"}], + "dependencies": {"widpedom":"app"}, + "type": "clock", + "tags": "clock", + "supports" : ["BANGLEJS2"], + "allow_emulator":true, + "readme": "README.md", + "storage": [ + {"name":"circlesclock.app.js","url":"app.js"}, + {"name":"circlesclock.img","url":"app-icon.js","evaluate":true}, + {"name":"circlesclock.settings.js","url":"settings.js"} + ], + "data": [ + {"name":"circlesclock.json"} + ] + }, + { "id": "contourclock", + "name": "Contour Clock", + "shortName" : "Contour Clock", + "version":"0.01", + "icon": "app.png", + "description": "A Minimalist clockface with large Digits. Looks best with the dark theme", + "screenshots" : [{"url":"screenshot.png"}], + "tags": "clock", + "allow_emulator":true, + "supports" : ["BANGLEJS2"], + "type": "clock", + "storage": [ + {"name":"contourclock.app.js","url":"app.js"}, + {"name":"contourclock.img","url":"app-icon.js","evaluate":true} + ] + }, + { + "id": "ltherm", + "name": "Localized Thermometer", + "shortName": "Thermometer", + "version": "0.01", + "description": "Displays the current temperature in localized units.", + "icon": "thermf.png", + "tags": "tool", + "supports": ["BANGLEJS2"], + "allow_emulator": true, + "readme": "README.md", + "storage": [ + {"name":"ltherm.app.js","url":"app.js"}, + {"name":"ltherm.img","url":"icon.js","evaluate":true} + ] + }, + { + "id": "presentor", + "name": "Presentor", + "version": "3.0", + "description": "Use your Bangle to present!", + "icon": "app.png", + "type": "app", + "tags": "tool,bluetooth", + "interface": "interface.html", + "readme":"README.md", + "supports": ["BANGLEJS", "BANGLEJS2"], + "allow_emulator": true, + "storage": [ + {"name":"presentor.app.js","url":"app.js"}, + {"name":"presentor.img","url":"app-icon.js","evaluate":true}, + {"name":"presentor.json","url":"settings.json"} + ] + }, + { + "id": "slash", + "name": "Slash Watch", + "shortName":"Slash", + "icon": "slash.png", + "screenshots": [{"url":"screenshot.png"}], + "version":"0.01", + "description": "Slash Watch based on Pebble watch face by Nikki.", + "tags": "clock", + "type": "clock", + "supports":["BANGLEJS2"], + "readme": "README.md", + "allow_emulator": true, + "storage": [ + {"name":"slash.app.js","url":"app.js"}, + {"name":"slash.img","url":"app-icon.js","evaluate":true} + ] + }, + { + "id": "promenu", + "name": "Pro Menu", + "version": "0.02", + "description": "Replace the built in menu function. Supports Bangle.js 1 and Bangle.js 2.", + "icon": "icon.png", + "type": "boot", + "tags": "system", + "supports": ["BANGLEJS","BANGLEJS2"], + "screenshots": [{"url":"pro-menu-screenshot.png"}], + "storage": [ + {"name":"promenu.boot.js","url":"boot.js","supports": ["BANGLEJS"]}, + {"name":"promenu.boot.js","url":"bootb2.js","supports": ["BANGLEJS2"]}, + {"name":"promenu.img","url":"promenuIcon.js","evaluate":true} + ] + }, + { + "id": "touchtimer", + "name": "Touch Timer", + "shortName": "Touch Timer", + "version": "0.02", + "description": "Quickly and easily create a timer with touch-only input. The time can be easily set with a number pad.", + "icon": "app.png", + "tags": "tools", + "supports": ["BANGLEJS2"], + "readme": "README.md", + "screenshots": [{"url":"0_light_timer_edit.png"},{"url":"1_light_timer_ready.png"},{"url":"2_light_timer_running.png"},{"url":"3_light_timer_finished.png"}], + "storage": [ + { "name": "touchtimer.app.js", "url": "app.js" }, + { "name":"touchtimer.settings.js", "url":"settings.js"}, + { "name": "touchtimer.img", "url": "app-icon.js", "evaluate": true } + ], + "data": [{"name":"touchtimer.data.json"}] + }, + { + "id": "teatimer", + "name": "Tea Timer", + "version": "1.00", + "description": "A simple timer. You can easyly set up the time.", + "icon": "teatimer.png", + "type": "app", + "tags": "tool", + "supports": ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"teatimer.app.js","url":"app.js"}, + {"name":"teatimer.img","url":"app-icon.js","evaluate":true} + ], + "screenshots": [ + {"url":"TeatimerStart.jpg"}, + {"url":"TeatimerHelp.jpg"}, + {"url":"TeatimerRun.jpg"}, + {"url":"TeatimerUp.jpg"} + ] + }, + { + "id": "swp2clk", + "name": "Swipe back to the Clock", + "shortName": "Swipe to Clock", + "version": "0.01", + "description": "Let's you swipe from left to right on any app to return back to the clock face. Please configure in the settings app after installing to activate, since its disabled by default.", + "icon": "app.png", + "type": "boot", + "tags": "tools", + "supports": ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + { "name": "swp2clk.boot.js", "url": "boot.js" }, + {"name":"swp2clk.settings.js","url":"settings.js"} + ], + "data": [{"name":"swp2clk.data.json"}] + }, + { + "id":"colorwheel", + "name":"Color Wheel", + "tags":"app,tool", + "version":"0.01", + "description":"a tappable wheel of good-looking colors", + "readme":"README.md", + "supports":["BANGLEJS2"], + "allow_emulator":true, + "icon":"colorwheel.png", + "storage": [ + {"name":"colorwheel.app.js","url":"app.js"}, + {"name":"colorwheel.img","url":"app-icon.js","evaluate":true} + ] + }, + { "id": "minimal_clock", + "name": "Minimal Analog Clock", + "shortName":"Minimal Clock", + "version":"0.03", + "description": "a minimal analog clock - just with some hands and no clock face", + "icon": "app-icon.png", + "type": "clock", + "tags": "clock", + "supports" : ["BANGLEJS2"], + "allow_emulator": true, + "screenshots": [{"url":"app-screenshot.png"}], + "readme": "README.md", + "storage": [ + {"name":"minimal_clock.app.js","url":"app.js"}, + {"name":"minimal_clock.img","url":"app-icon.js","evaluate":true} + ] + }, + { "id": "simple_clock", + "name": "Simple Analog Clock", + "shortName":"Simple Clock", + "version":"0.02", + "description": "a simple, yet stylish, analog clock", + "icon": "app-icon.png", + "type": "clock", + "tags": "clock", + "supports" : ["BANGLEJS2"], + "allow_emulator": true, + "screenshots": [{"url":"app-screenshot.png"}], + "readme": "README.md", + "storage": [ + {"name":"simple_clock.app.js","url":"app.js"}, + {"name":"simple_clock.img","url":"app-icon.js","evaluate":true} + ] + }, + { "id": "colorful_clock", + "name": "Colorful Analog Clock", + "shortName":"Colorful Clock", + "version":"0.02", + "description": "a colorful analog clock", + "icon": "app-icon.png", + "type": "clock", + "tags": "clock", + "supports" : ["BANGLEJS2"], + "allow_emulator": true, + "screenshots": [{"url":"app-screenshot.png"}], + "readme": "README.md", + "storage": [ + {"name":"colorful_clock.app.js","url":"app.js"}, + {"name":"colorful_clock.img","url":"app-icon.js","evaluate":true} + ] + }, + { "id": "themesetter", + "name": "Theme Setter", + "shortName":"Theme Setter", + "version":"0.04", + "description": "a comfortable way to configure theme colors", + "icon": "app-icon.png", + "type": "app", + "tags": "tool", + "supports" : ["BANGLEJS2"], + "allow_emulator": true, + "screenshots": [{"url":"app-screenshot.png"}], + "readme": "README.md", + "storage": [ + {"name":"themesetter.app.js","url":"app.js"}, + {"name":"themesetter.img","url":"app-icon.js","evaluate":true} + ] + }, + { + "id": "widviztime", + "name": "Widget Autohide Widget", + "shortName": "Viz Time Widget", + "version": "0.01", + "description": "The widgets will be shown for four seconds after the device is unlocked.", + "icon": "eye.png", + "type": "widget", + "tags": "widget", + "readme":"README.md", + "supports": ["BANGLEJS","BANGLEJS2"], + "storage": [ + {"name":"widviztime.wid.js","url":"widget.js"} + ] + }, + { + "id": "supf", + "name": "Simple Clock with Date", + "shortName": "supf Clock", + "version": "0.01", + "description": "Simple Clock with seconds and date in custom language. Install 'Languages' to get localized names.", + "icon": "icon.png", + "screenshots": [{"url":"screenshot_supf.png"}], + "type": "clock", + "tags": "clock", + "supports": ["BANGLEJS2"], + "allow_emulator": true, + "readme": "README.md", + "storage": [ + {"name":"supf.app.js","url":"app.js"}, + {"name":"supf.img","url":"icon.js","evaluate":true} + ] + }, + { "id": "andark", + "name": "Analog Dark", + "shortName":"AnDark", + "version":"0.04", + "description": "analog clock face without disturbing widgets", + "icon": "andark_icon.png", + "type": "clock", + "tags": "clock", + "supports" : ["BANGLEJS2"], + "readme": "README.md", + "storage": [ + {"name":"andark.app.js","url":"app.js"}, + {"name":"andark.img","url":"app_icon.js","evaluate":true} + ] + }, + { + "id": "diract", + "name": "DirAct", + "shortName": "DirAct", + "version": "0.01", + "description": "Proximity interaction detection.", + "icon": "diract.png", + "type": "app", + "tags": "tool,sensors", + "supports" : [ "BANGLEJS2" ], + "allow_emulator": false, + "readme": "README.md", + "storage": [ + { "name": "diract.app.js", "url": "diract.js" }, + { "name": "diract.img", "url": "diract-icon.js", "evaluate": true } + ] + }, + { + "id": "sonicclk", + "name": "Sonic Clock", + "version": "1.01", + "description": "A classic sonic clock featuring run, stop and wait animations.", + "icon": "app.png", + "screenshots": [{"url":"screenshot.png"}], + "type": "clock", + "tags": "clock", + "supports": ["BANGLEJS2"], + "allow_emulator": true, + "readme": "README.md", + "storage": [ + {"name":"sonicclk.app.js","url":"app.js"}, + {"name":"sonicclk.img","url":"app-icon.js","evaluate":true} + ] + }, + { + "id": "touchmenu", + "name": "TouchMenu", + "version": "0.01", + "description": "Redesigned menu that uses the full touchscreen on the Bangle.js 2", + "screenshots": [{"url":"touchmenu.gif"}], + "icon": "touchmenu.png", + "type": "bootloader", + "tags": "tool", + "supports": ["BANGLEJS2"], + "storage": [ + {"name":"touchmenu.boot.js","url":"touchmenu.boot.js"} + ] + }, + { + "id": "puzzle15", + "name": "15 puzzle", + "version": "0.05", + "description": "A 15 puzzle game with drag gesture interface", + "readme":"README.md", + "icon": "puzzle15.app.png", + "screenshots": [{"url":"screenshot.png"}], + "type": "app", + "tags": "game", + "supports": ["BANGLEJS2"], + "allow_emulator": true, + "storage": [ + {"name":"puzzle15.app.js","url":"puzzle15.app.js"}, + {"name":"puzzle15.settings.js","url":"puzzle15.settings.js"}, + {"name":"puzzle15.img","url":"puzzle15.app-icon.js","evaluate":true} + ], + "data": [{"name":"puzzle15.json"}] + }, + { + "id": "flipper", + "name": "flipper", + "version": "0.01", + "description": "Switch between dark and light theme and vice versa, combine with pattern launcher and swipe to flip.", + "readme":"README.md", + "screenshots": [{"url":"flipper.png"}], + "icon": "flipper.png", + "type": "app", + "tags": "game", + "supports": ["BANGLEJS2"], + "allow_emulator": true, + "storage": [ + {"name":"flipper.app.js","url":"flipper.app.js"}, + {"name":"flipper.img","url":"flipper.icon.js","evaluate":true} + ] + } ] diff --git a/apps/93dub/ChangeLog b/apps/93dub/ChangeLog index c1b2588bb..1c18ca59b 100644 --- a/apps/93dub/ChangeLog +++ b/apps/93dub/ChangeLog @@ -3,3 +3,4 @@ 0.03: Code style cleanup 0.04: Set 00:00 to 12:00 for 12 hour time 0.05: Display time, even on Thursday +0.06: Fix light theme issue, where widgets would end up on a light strip diff --git a/apps/93dub/app.js b/apps/93dub/app.js index 1b0f69a94..f970eec5d 100644 --- a/apps/93dub/app.js +++ b/apps/93dub/app.js @@ -122,7 +122,13 @@ function draw(){ queueDraw(); } - +/** + * This watch is mostly dark, it does not make sense to respect the + * light theme as you end up with a white strip at the top for the + * widgets and black watch. So set the colours to the dark theme. + * + */ +g.setTheme({bg:"#000",fg:"#fff",dark:true}).clear(); draw(); //the following section is also from waveclk diff --git a/apps/andark/ChangeLog b/apps/andark/ChangeLog new file mode 100644 index 000000000..341868930 --- /dev/null +++ b/apps/andark/ChangeLog @@ -0,0 +1,4 @@ +0.01: Release +0.02: Rename app +0.03: Add type "clock" +0.04: changed update cylce, when locked diff --git a/apps/andark/README.md b/apps/andark/README.md new file mode 100644 index 000000000..3770c1017 --- /dev/null +++ b/apps/andark/README.md @@ -0,0 +1,10 @@ +# Analog Clock + +## Features + +* second hand +* date +* battery percantage +* no widgets + +![logo](andark_screen.png) diff --git a/apps/andark/andark_icon.png b/apps/andark/andark_icon.png new file mode 100644 index 000000000..cded02071 Binary files /dev/null and b/apps/andark/andark_icon.png differ diff --git a/apps/andark/andark_screen.png b/apps/andark/andark_screen.png new file mode 100644 index 000000000..2ac54c1cd Binary files /dev/null and b/apps/andark/andark_screen.png differ diff --git a/apps/andark/app.js b/apps/andark/app.js new file mode 100644 index 000000000..efa00ce6f --- /dev/null +++ b/apps/andark/app.js @@ -0,0 +1,125 @@ +const c={"x":g.getWidth()/2,"y":g.getHeight()/2}; +let zahlpos=[]; +let unlock = false; + +function zeiger(len,dia,tim){ + const x =c.x+ Math.cos(tim)*len/2, + y =c.y + Math.sin(tim)*len/2, + d={"d":3,"x":dia/2*Math.cos(tim+Math.PI/2),"y":dia/2*Math.sin(tim+Math.PI/2)}, + pol=[c.x-d.x,c.y-d.y,c.x+d.x,c.y+d.y,x+d.x,y+d.y,x-d.x,y-d.y]; + return pol; + +} + +function draw(){ + const d=new Date(); + let m=d.getMinutes(), h=d.getHours(), s=d.getSeconds(); + //draw black rectangle in the middle to clear screen from scale and hands + g.setColor(0,0,0); + g.fillRect(10,10,2*c.x-10,2*c.x-10); + g.setColor(1,1,1); + + if(h>12){ + h=h-12; + } + //calculates the position of the minute, second and hour hand + h=2*Math.PI/12*(h+m/60)-Math.PI/2; + //more accurate + //m=2*Math.PI/60*(m+s/60)-Math.PI/2; + m=2*Math.PI/60*(m)-Math.PI/2; + + s=2*Math.PI/60*s-Math.PI/2; + g.setFontAlign(0,0); + g.setFont("Vector",10); + let dateStr = " "+require("locale").date(d)+" "; + g.drawString(dateStr, c.x, c.y+20, true); + // g.drawString(d.getDate(),1.4*c.x,c.y,true); + g.drawString(Math.round(E.getBattery()/5)*5+"%",c.x,c.y+40,true); + drawlet(); + //g.setColor(1,0,0); + const hz = zeiger(100,5,h); + g.fillPoly(hz,true); + // g.setColor(1,1,1); + const minz = zeiger(150,5,m); + g.fillPoly(minz,true); + if (unlock){ + const sekz = zeiger(150,2,s); + g.fillPoly(sekz,true); + } + g.fillCircle(c.x,c.y,4); + + + +} +//draws the scale once the app is startet +function drawScale(){ + for(let i=-14;i<47;i++){ + const win=i*2*Math.PI/60; + let d=2; + if(i%5==0){d=5;} + g.fillPoly(zeiger(300,d,win),true); + g.setColor(0,0,0); + g.fillRect(10,10,2*c.x-10,2*c.x-10); + g.setColor(1,1,1); + } +} + +//draws the numbers on the screen + +function drawlet(){ + g.setFont("Vector",20); + for(let i = 0;i<12;i++){ + g.drawString(zahlpos[i][0],zahlpos[i][1],zahlpos[i][2]); + } +} +//calcultes the Position of the numbers when app starts and saves them in an array +function setlet(){ + let sk=1; + for(let i=-10;i<50;i+=5){ + let win=i*2*Math.PI/60; + let xsk =c.x+2+Math.cos(win)*(c.x-10), + ysk =c.y+2+Math.sin(win)*(c.x-10); + if(sk==3){xsk-=10;} + if(sk==6){ysk-=10;} + if(sk==9){xsk+=10;} + if(sk==12){ysk+=10;} + if(sk==10){xsk+=3;} + zahlpos.push([sk,xsk,ysk]); + sk+=1; + } +} +setlet(); +// Clear the screen once, at startup +g.setBgColor(0,0,0); +g.clear(); +drawScale(); +draw(); + +let secondInterval= setInterval(draw, 1000); +// Stop updates when LCD is off, restart when on + +Bangle.on('lcdPower',on=>{ + if (secondInterval) clearInterval(secondInterval); + secondInterval = undefined; + if (on) { + secondInterval = setInterval(draw, 1000); + draw(); // draw immediately + }else{ + } +}); +Bangle.on('lock',on=>{ + if (secondInterval) clearInterval(secondInterval); + secondInterval = undefined; + if (!on) { + secondInterval = setInterval(draw, 1000); + unlock = true; + draw(); // draw immediately + }else{ + secondInterval = setInterval(draw, 60000); + unlock = false; + draw(); + } + }); + +// Show launcher when middle button pressed +Bangle.setUI("clock"); diff --git a/apps/andark/app_icon.js b/apps/andark/app_icon.js new file mode 100644 index 000000000..b213fe5c8 --- /dev/null +++ b/apps/andark/app_icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwgIEBoUAiAKCgUCBQUEColEAYUQhAmKCwgeCAAcCgEDjwEBkEAg8TBocNgYFDh8GAYMDxkPjEA8EAwkHJgIcBAoPfAoYWCBYYFIgfvAoX4FYRJEAp9gAomYNAOAArPwAogAC4AFiRoIFJLgIFJuADCg//Q4U//4FDj4FEAAV4Aoi0CSxBsCA==")) \ No newline at end of file diff --git a/apps/antonclk/ChangeLog b/apps/antonclk/ChangeLog index f88276a90..668047d7a 100644 --- a/apps/antonclk/ChangeLog +++ b/apps/antonclk/ChangeLog @@ -1,3 +1,4 @@ 0.01: New App! 0.02: Load widgets after setUI so widclk knows when to hide 0.03: Clock now shows day of week under date. +0.04: Clock can optionally show seconds, date optionally in ISO-8601 format, weekdays and uppercase configurable, too. diff --git a/apps/antonclk/README.md b/apps/antonclk/README.md new file mode 100644 index 000000000..41d3e4559 --- /dev/null +++ b/apps/antonclk/README.md @@ -0,0 +1,77 @@ +# Anton Clock - Large font digital watch with seconds and date + +Anton clock uses the "Anton" bold font to show the time in a clear, easily readable manner. On the Bangle.js 2, the time can be read easily even if the screen is locked and unlit. + +## Features + +The basic time representation only shows hours and minutes of the current time. However, Anton clock can show additional information: + +* Seconds can be shown, either always or only if the screen is unlocked. +* To help easy recognition, the seconds can be coloured in blue on the Bangle.js 2. +* Date can be shown in three different formats: + * ISO-8601: 2021-12-19 + * short local format: 19/12/2021, 19.12.2021 + * long local format: DEC 19 2021 +* Weekday can be shown (on seconds screen only instead of year) + +## Usage + +Install Anton clock through the Bangle.js app loader. +Configure it through the default Bangle.js configuration mechanism +(Settings app, "Apps" menu, "Anton clock" submenu). +If you like it, make it your default watch face +(Settings app, "System" menu, "Clock" submenu, select "Anton clock"). + +## Configuration + +Anton clock is configured by the standard settings mechanism of Bangle.js's operating system: +Open the "Settings" app, then the "Apps" submenu and below it the "Anton clock" menu. +You configure Anton clock through several "on/off" switches in two menus. + +### The main menu + +The main menu contains several settings covering Anton clock in general. + +* **Seconds...** - Opens the submenu for configuring the presentation of the current time's seconds. +* **Date** - Format of the date representation. Possible values are + * **Long** - "Long" date format in the current locale. Usually with the month as name, not number. + * **Short** - "Short" date format in the current locale. Usually with the month as number. + * **ISO8601** - Show the date in ISO-8601 format (YYYY-MM-DD), irrespective of the current locale. +* **Show Weekday** - Weekday is shown in the time presentation without seconds. +Weekday name depends on the current locale. +If seconds are shown, the weekday is never shown as there is not enough space on the watch face. +* **Uppercase** - Weekday name and month name in the long format are converted to upper case letters. +This can improve readability. +* **Vector font** - Use the built-in vector font for dates and weekday. +This can improve readability. +Otherwise, a scaled version of the built-in 6x8 pixels font is used. + +### The "Seconds" submenu + +The "Seconds" submenu configures how (and if) seconds are shown on the "Anton" watch face. + +* **Show** - Configure when the seconds should be shown at all: + * **Never** - Seconds are never shown. +In this case, hour and minute are a bit more centered on the screen and the clock will always only update every minute. +This saves battery power. + * **Unlocked** - Seconds are shown if the display is unlocked. +On locked displays, only hour, minutes, date and optionally the weekday are shown. +_This option is highly recommended on the Bangle.js 2!_ + * **Always** - Seconds are _always_ shown, irrespective of the display's unlock state. +_Enabling this option increases power consumption as the watch face will update once per second instead of once per minute._ +* **With ":"** - If enabled, a colon ":" is prepended to the seconds. +This resembles the usual time representation "hh:mm:ss", even though the seconds are printed on a separate line. +* **Color** - If enabled, seconds are shown in blue instead of black. +If the date is shown on the seconds screen, it is colored read instead of black. +This make the visual orientation much easier on the watch face. +* **Date** - It is possible to show the date together with the seconds: + * **No** - Date is _not_ shown in the seconds screen. +In this case, the seconds are centered below hour and minute. + * **Year** - Date is shown with day, month, and year. If "Date" in the main settings is configured to _ISO8601_, this is used here, too. Otherwise, the short local format is used. + * **Weekday** - Date is shown with day, month, and weekday. + +The date is coloured in red if the "Coloured" option is chosen. + +## Compatibility + +Anton clock makes use of core Bangle.js 2 features (coloured display, display lock state). It also runs on the Bangle.js 1 but these features are not available there due to hardware restrictions. diff --git a/apps/antonclk/app.js b/apps/antonclk/app.js index 7912dfc0f..1f3e49792 100644 --- a/apps/antonclk/app.js +++ b/apps/antonclk/app.js @@ -1,61 +1,203 @@ +// Clock with large digits using the "Anton" bold font + +var SETTINGSFILE = "antonclk.json"; + Graphics.prototype.setFontAnton = function(scale) { -// Actual height 69 (68 - 0) - g.setFontCustom(atob("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAA/gAAAAAAAAAAP/gAAAAAAAAAH//gAAAAAAAAB///gAAAAAAAAf///gAAAAAAAP////gAAAAAAD/////gAAAAAA//////gAAAAAP//////gAAAAH///////gAAAB////////gAAAf////////gAAP/////////gAD//////////AA//////////gAA/////////4AAA////////+AAAA////////gAAAA///////wAAAAA//////8AAAAAA//////AAAAAAA/////gAAAAAAA////4AAAAAAAA///+AAAAAAAAA///gAAAAAAAAA//wAAAAAAAAAA/8AAAAAAAAAAA/AAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////AAAAAB///////8AAAAH////////AAAAf////////wAAA/////////4AAB/////////8AAD/////////+AAH//////////AAP//////////gAP//////////gAP//////////gAf//////////wAf//////////wAf//////////wAf//////////wA//8AAAAAB//4A//wAAAAAAf/4A//gAAAAAAP/4A//gAAAAAAP/4A//gAAAAAAP/4A//wAAAAAAf/4A///////////4Af//////////wAf//////////wAf//////////wAf//////////wAP//////////gAP//////////gAH//////////AAH//////////AAD/////////+AAB/////////8AAA/////////4AAAP////////gAAAD///////+AAAAAf//////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAAAAAAAAAP/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/AAAAAAAAAAA//AAAAAAAAAAA/+AAAAAAAAAAB/8AAAAAAAAAAD//////////gAH//////////gAP//////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/4AAAAB/gAAD//4AAAAf/gAAP//4AAAB//gAA///4AAAH//gAB///4AAAf//gAD///4AAA///gAH///4AAD///gAP///4AAH///gAP///4AAP///gAf///4AAf///gAf///4AB////gAf///4AD////gA////4AH////gA////4Af////gA////4A/////gA//wAAB/////gA//gAAH/////gA//gAAP/////gA//gAA///8//gA//gAD///w//gA//wA////g//gA////////A//gA///////8A//gA///////4A//gAf//////wA//gAf//////gA//gAf/////+AA//gAP/////8AA//gAP/////4AA//gAH/////gAA//gAD/////AAA//gAB////8AAA//gAA////wAAA//gAAP///AAAA//gAAD//8AAAA//gAAAP+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/+AAAAAD/wAAB//8AAAAP/wAAB///AAAA//wAAB///wAAB//wAAB///4AAD//wAAB///8AAH//wAAB///+AAP//wAAB///+AAP//wAAB////AAf//wAAB////AAf//wAAB////gAf//wAAB////gA///wAAB////gA///wAAB////gA///w//AAf//wA//4A//AAA//wA//gA//AAAf/wA//gB//gAAf/wA//gB//gAAf/wA//gD//wAA//wA//wH//8AB//wA///////////gA///////////gA///////////gA///////////gAf//////////AAf//////////AAP//////////AAP/////////+AAH/////////8AAH///+/////4AAD///+f////wAAA///8P////gAAAf//4H///+AAAAH//gB///wAAAAAP4AAH/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/wAAAAAAAAAA//wAAAAAAAAAP//wAAAAAAAAB///wAAAAAAAAf///wAAAAAAAH////wAAAAAAA/////wAAAAAAP/////wAAAAAB//////wAAAAAf//////wAAAAH///////wAAAA////////wAAAP////////wAAA///////H/wAAA//////wH/wAAA/////8AH/wAAA/////AAH/wAAA////gAAH/wAAA///4AAAH/wAAA//+AAAAH/wAAA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gAAAAAAAAH/4AAAAAAAAAAH/wAAAAAAAAAAH/wAAAAAAAAAAH/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB//8AAA/////+B///AAA/////+B///wAA/////+B///4AA/////+B///8AA/////+B///8AA/////+B///+AA/////+B////AA/////+B////AA/////+B////AA/////+B////gA/////+B////gA/////+B////gA/////+A////gA//gP/gAAB//wA//gf/AAAA//wA//gf/AAAAf/wA//g//AAAAf/wA//g//AAAA//wA//g//gAAA//wA//g//+AAP//wA//g////////gA//g////////gA//g////////gA//g////////gA//g////////AA//gf///////AA//gf//////+AA//gP//////+AA//gH//////8AA//gD//////4AA//gB//////wAA//gA//////AAAAAAAH////8AAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////gAAAAB///////+AAAAH////////gAAAf////////4AAB/////////8AAD/////////+AAH//////////AAH//////////gAP//////////gAP//////////gAf//////////wAf//////////wAf//////////wAf//////////wAf//////////4A//wAD/4AAf/4A//gAH/wAAP/4A//gAH/wAAP/4A//gAP/wAAP/4A//gAP/4AAf/4A//wAP/+AD//4A///wP//////4Af//4P//////wAf//4P//////wAf//4P//////wAf//4P//////wAP//4P//////gAP//4H//////gAH//4H//////AAH//4D/////+AAD//4D/////8AAB//4B/////4AAA//4A/////wAAAP/4AP////AAAAB/4AD///4AAAAAAAAAH/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//AAAAAAAAAAA//gAAAAAAAAAA//gAAAAAAAAAA//gAAAAAAADgA//gAAAAAAP/gA//gAAAAAH//gA//gAAAAB///gA//gAAAAP///gA//gAAAD////gA//gAAAf////gA//gAAB/////gA//gAAP/////gA//gAB//////gA//gAH//////gA//gA///////gA//gD///////gA//gf///////gA//h////////gA//n////////gA//////////gAA/////////AAAA////////wAAAA///////4AAAAA///////AAAAAA//////4AAAAAA//////AAAAAAA/////4AAAAAAA/////AAAAAAAA////8AAAAAAAA////gAAAAAAAA///+AAAAAAAAA///4AAAAAAAAA///AAAAAAAAAA//4AAAAAAAAAA/+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//gB///wAAAAP//4H///+AAAA///8P////gAAB///+f////4AAD///+/////8AAH/////////+AAH//////////AAP//////////gAP//////////gAf//////////gAf//////////wAf//////////wAf//////////wA///////////wA//4D//wAB//4A//wB//gAA//4A//gA//gAAf/4A//gA//AAAf/4A//gA//gAAf/4A//wB//gAA//4A///P//8AH//4Af//////////wAf//////////wAf//////////wAf//////////wAf//////////gAP//////////gAP//////////AAH//////////AAD/////////+AAD///+/////8AAB///8f////wAAAf//4P////AAAAH//wD///8AAAAA/+AAf//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//gAAAAAAAAB///+AA/+AAAAP////gA//wAAAf////wA//4AAB/////4A//8AAD/////8A//+AAD/////+A///AAH/////+A///AAP//////A///gAP//////A///gAf//////A///wAf//////A///wAf//////A///wAf//////A///wA///////AB//4A//4AD//AAP/4A//gAB//AAP/4A//gAA//AAP/4A//gAA/+AAP/4A//gAB/8AAP/4A//wAB/8AAf/4Af//////////wAf//////////wAf//////////wAf//////////wAf//////////wAP//////////gAP//////////gAH//////////AAH/////////+AAD/////////8AAB/////////4AAAf////////wAAAP////////AAAAB///////4AAAAAD/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/AAB/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="), 46, atob("EiAnGicnJycnJycnEw=="), 78+(scale<<8)+(1<<16)); + // Actual height 69 (68 - 0) + g.setFontCustom(atob("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAA/gAAAAAAAAAAP/gAAAAAAAAAH//gAAAAAAAAB///gAAAAAAAAf///gAAAAAAAP////gAAAAAAD/////gAAAAAA//////gAAAAAP//////gAAAAH///////gAAAB////////gAAAf////////gAAP/////////gAD//////////AA//////////gAA/////////4AAA////////+AAAA////////gAAAA///////wAAAAA//////8AAAAAA//////AAAAAAA/////gAAAAAAA////4AAAAAAAA///+AAAAAAAAA///gAAAAAAAAA//wAAAAAAAAAA/8AAAAAAAAAAA/AAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////AAAAAB///////8AAAAH////////AAAAf////////wAAA/////////4AAB/////////8AAD/////////+AAH//////////AAP//////////gAP//////////gAP//////////gAf//////////wAf//////////wAf//////////wAf//////////wA//8AAAAAB//4A//wAAAAAAf/4A//gAAAAAAP/4A//gAAAAAAP/4A//gAAAAAAP/4A//wAAAAAAf/4A///////////4Af//////////wAf//////////wAf//////////wAf//////////wAP//////////gAP//////////gAH//////////AAH//////////AAD/////////+AAB/////////8AAA/////////4AAAP////////gAAAD///////+AAAAAf//////4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAAAAAAAAAP/gAAAAAAAAAAf/gAAAAAAAAAAf/gAAAAAAAAAAf/AAAAAAAAAAA//AAAAAAAAAAA/+AAAAAAAAAAB/8AAAAAAAAAAD//////////gAH//////////gAP//////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/4AAAAB/gAAD//4AAAAf/gAAP//4AAAB//gAA///4AAAH//gAB///4AAAf//gAD///4AAA///gAH///4AAD///gAP///4AAH///gAP///4AAP///gAf///4AAf///gAf///4AB////gAf///4AD////gA////4AH////gA////4Af////gA////4A/////gA//wAAB/////gA//gAAH/////gA//gAAP/////gA//gAA///8//gA//gAD///w//gA//wA////g//gA////////A//gA///////8A//gA///////4A//gAf//////wA//gAf//////gA//gAf/////+AA//gAP/////8AA//gAP/////4AA//gAH/////gAA//gAD/////AAA//gAB////8AAA//gAA////wAAA//gAAP///AAAA//gAAD//8AAAA//gAAAP+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/+AAAAAD/wAAB//8AAAAP/wAAB///AAAA//wAAB///wAAB//wAAB///4AAD//wAAB///8AAH//wAAB///+AAP//wAAB///+AAP//wAAB////AAf//wAAB////AAf//wAAB////gAf//wAAB////gA///wAAB////gA///wAAB////gA///w//AAf//wA//4A//AAA//wA//gA//AAAf/wA//gB//gAAf/wA//gB//gAAf/wA//gD//wAA//wA//wH//8AB//wA///////////gA///////////gA///////////gA///////////gAf//////////AAf//////////AAP//////////AAP/////////+AAH/////////8AAH///+/////4AAD///+f////wAAA///8P////gAAAf//4H///+AAAAH//gB///wAAAAAP4AAH/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/wAAAAAAAAAA//wAAAAAAAAAP//wAAAAAAAAB///wAAAAAAAAf///wAAAAAAAH////wAAAAAAA/////wAAAAAAP/////wAAAAAB//////wAAAAAf//////wAAAAH///////wAAAA////////wAAAP////////wAAA///////H/wAAA//////wH/wAAA/////8AH/wAAA/////AAH/wAAA////gAAH/wAAA///4AAAH/wAAA//+AAAAH/wAAA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gA///////////gAAAAAAAAH/4AAAAAAAAAAH/wAAAAAAAAAAH/wAAAAAAAAAAH/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB//8AAA/////+B///AAA/////+B///wAA/////+B///4AA/////+B///8AA/////+B///8AA/////+B///+AA/////+B////AA/////+B////AA/////+B////AA/////+B////gA/////+B////gA/////+B////gA/////+A////gA//gP/gAAB//wA//gf/AAAA//wA//gf/AAAAf/wA//g//AAAAf/wA//g//AAAA//wA//g//gAAA//wA//g//+AAP//wA//g////////gA//g////////gA//g////////gA//g////////gA//g////////AA//gf///////AA//gf//////+AA//gP//////+AA//gH//////8AA//gD//////4AA//gB//////wAA//gA//////AAAAAAAH////8AAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////gAAAAB///////+AAAAH////////gAAAf////////4AAB/////////8AAD/////////+AAH//////////AAH//////////gAP//////////gAP//////////gAf//////////wAf//////////wAf//////////wAf//////////wAf//////////4A//wAD/4AAf/4A//gAH/wAAP/4A//gAH/wAAP/4A//gAP/wAAP/4A//gAP/4AAf/4A//wAP/+AD//4A///wP//////4Af//4P//////wAf//4P//////wAf//4P//////wAf//4P//////wAP//4P//////gAP//4H//////gAH//4H//////AAH//4D/////+AAD//4D/////8AAB//4B/////4AAA//4A/////wAAAP/4AP////AAAAB/4AD///4AAAAAAAAAH/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//AAAAAAAAAAA//gAAAAAAAAAA//gAAAAAAAAAA//gAAAAAAADgA//gAAAAAAP/gA//gAAAAAH//gA//gAAAAB///gA//gAAAAP///gA//gAAAD////gA//gAAAf////gA//gAAB/////gA//gAAP/////gA//gAB//////gA//gAH//////gA//gA///////gA//gD///////gA//gf///////gA//h////////gA//n////////gA//////////gAA/////////AAAA////////wAAAA///////4AAAAA///////AAAAAA//////4AAAAAA//////AAAAAAA/////4AAAAAAA/////AAAAAAAA////8AAAAAAAA////gAAAAAAAA///+AAAAAAAAA///4AAAAAAAAA///AAAAAAAAAA//4AAAAAAAAAA/+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//gB///wAAAAP//4H///+AAAA///8P////gAAB///+f////4AAD///+/////8AAH/////////+AAH//////////AAP//////////gAP//////////gAf//////////gAf//////////wAf//////////wAf//////////wA///////////wA//4D//wAB//4A//wB//gAA//4A//gA//gAAf/4A//gA//AAAf/4A//gA//gAAf/4A//wB//gAA//4A///P//8AH//4Af//////////wAf//////////wAf//////////wAf//////////wAf//////////gAP//////////gAP//////////AAH//////////AAD/////////+AAD///+/////8AAB///8f////wAAAf//4P////AAAAH//wD///8AAAAA/+AAf//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//gAAAAAAAAB///+AA/+AAAAP////gA//wAAAf////wA//4AAB/////4A//8AAD/////8A//+AAD/////+A///AAH/////+A///AAP//////A///gAP//////A///gAf//////A///wAf//////A///wAf//////A///wAf//////A///wA///////AB//4A//4AD//AAP/4A//gAB//AAP/4A//gAA//AAP/4A//gAA/+AAP/4A//gAB/8AAP/4A//wAB/8AAf/4Af//////////wAf//////////wAf//////////wAf//////////wAf//////////wAP//////////gAP//////////gAH//////////AAH/////////+AAD/////////8AAB/////////4AAAf////////wAAAP////////AAAAB///////4AAAAAD/////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/AAB/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAA//AAD/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="), 46, atob("EiAnGicnJycnJycnEw=="), 78 + (scale << 8) + (1 << 16)); +}; + +Graphics.prototype.setFontAntonSmall = function(scale) { + // Actual height 53 (52 - 0) + g.setFontCustom(atob("AAAAAAAAAAAAAAAAAAAAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAf8AAAAAAAAAAAAAAAAAAAAMAAAAAAAAD8AAAAAAAA/8AAAAAAAf/8AAAAAAH//8AAAAAB///8AAAAA////8AAAAP////8AAAD/////8AAB//////8AAf//////8AH///////4A///////+AA///////AAA//////wAAA/////8AAAA////+AAAAA////gAAAAA///4AAAAAA//8AAAAAAA//AAAAAAAA/wAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/////wAAA//////8AAB//////+AAH///////gAH///////gAP///////wAf///////4Af///////4A////////8A////////8A////////8A//AAAAD/8A/8AAAAA/8A/8AAAAA/8A/8AAAAA/8A/+AAAAB/8A////////8A////////8A////////8Af///////4Af///////4AP///////wAP///////wAH///////gAD///////AAA//////8AAAP/////wAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAA/4AAAAAAAA/4AAAAAAAB/wAAAAAAAB/wAAAAAAAD/wAAAAAAAD/gAAAAAAAH///////8AP///////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/4AAAP8AA//4AAA/8AB//4AAH/8AH//4AAP/8AP//4AA//8AP//4AB//8Af//4AD//8Af//4AP//8A///4Af//8A///4A///8A///4D///8A//AAH///8A/8AAP///8A/8AA//+/8A/8AD//8/8A/+Af//w/8A//////g/8A/////+A/8A/////8A/8Af////4A/8Af////wA/8AP////AA/8AP///+AA/8AH///8AA/8AD///wAA/8AA///AAA/8AAP/4AAA/8AAAAAAAAAAAAAAAAAAAAAAH4AAf/gAAA/4AAf/8AAD/4AAf//AAH/4AAf//gAP/4AAf//wAP/4AAf//wAf/4AAf//4Af/4AAf//4A//4AAf//8A//4AAf//8A//4AAP//8A//A/8AB/8A/8A/8AA/8A/8B/8AA/8A/8B/8AA/8A/+D//AB/8A////////8A////////8A////////8Af///////4Af///////4Af///////wAP///////gAH//9////gAD//4///+AAB//wf//4AAAP/AH//gAAAAAAAAAAAAAAAAAAAAAAAAAAAH/wAAAAAAB//wAAAAAAP//wAAAAAD///wAAAAA////wAAAAH////wAAAB/////wAAAf/////wAAD//////wAA///////wAA/////h/wAA////wB/wAA///8AB/wAA///AAB/wAA//gAAB/wAA////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8A////////8AAAAAAB/wAAAAAAAB/wAAAAAAAB/wAAAAAAAAAAAAAAAAAAAAAAAAAAAP/4AA////4P/+AA////4P//AA////4P//gA////4P//wA////4P//wA////4P//4A////4P//4A////4P//8A////4P//8A////4P//8A/8H/AAB/8A/8H+AAA/8A/8P+AAA/8A/8P+AAA/8A/8P/gAD/8A/8P/////8A/8P/////8A/8P/////8A/8P/////4A/8H/////4A/8H/////wA/8D/////wA/8B/////gA/8A////+AA/8AP///4AAAAAB///AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////wAAAf/////8AAB///////AAH///////gAP///////wAP///////wAf///////4Af///////4A////////8A////////8A////////8A/+AH/AB/8A/8AP+AA/8A/4Af+AA/8A/8Af+AA/8A/8Af/gH/8A//4f////8A//4f////8A//4f////8Af/4f////4Af/4f////4AP/4P////wAP/4P////gAH/4H////AAD/4D///+AAB/4B///4AAAP4AP//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/8AAAAAAAA/8AAAAAAAA/8AAAAAB8A/8AAAAB/8A/8AAAAf/8A/8AAAH//8A/8AAA///8A/8AAH///8A/8AA////8A/8AD////8A/8Af////8A/8B/////8A/8P/////8A/8//////8A////////AA///////AAA//////gAAA/////4AAAA/////AAAAA////4AAAAA////AAAAAA///8AAAAAA///gAAAAAA//+AAAAAAA//wAAAAAAA/+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/gD//gAAA//4P//8AAD//8f///AAH//+////gAH///////wAP///////4AP///////8Af///////8Af///////+Af///////+A////////+A//B//AB/+A/+A/+AA/+A/8Af+AA/+A/+Af+AA/+A//A//AB/+A////////+Af///////+Af///////+Af///////8Af///////8AP///////4AH///////4AH//+////wAD//+////AAA//4P//+AAAP/gH//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//gAfgAAA///8A/8AAB///+A//AAH////A//gAH////g//wAP////g//wAf////w//4Af////w//4A/////w//8A/////w//8A/////w//8A//gP/wA/8A/8AD/wA/8A/8AD/wAf8A/8AD/gA/8A/+AH/AB/8A////////8A////////8A////////8Af///////4Af///////4Af///////wAP///////wAH///////gAD//////+AAA//////4AAAP/////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAP+AA/4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="), 46, atob("DhgeFB4eHh4eHh4eDw=="), 60 + (scale << 8) + (1 << 16)); +}; + +// variables defined from settings +var secondsMode; +var secondsColoured; +var secondsWithColon; +var dateOnMain; +var dateOnSecs; +var weekDay; +var upperCase; +var vectorFont; + +// dynamic variables +var drawTimeout; +var queueMillis = 1000; +var secondsScreen = true; + +var isBangle1 = (g.getWidth() == 240); + +/* For development purposes +require('Storage').writeJSON(SETTINGSFILE, { + secondsMode: "Always", // "Never", "Unlocked", "Always" + secondsColoured: true, + secondsWithColon: true, + dateOnMain: "Long", // "Short", "Long", "ISO8601" + dateOnSecs: "Year", // "No", "Year", "Weekday", LEGACY: true/false + weekDay: true, + upperCase: true, + vectorFont: true, +}); +/* */ + +/* OR (also for development purposes) +require('Storage').erase(SETTINGSFILE); +/* */ + +// Helper method for loading the settings +function def(value, def) { + return (value !== undefined ? value : def); } -// timeout used to update every minute -var drawTimeout; +// Load settings +function loadSettings() { + var settings = require('Storage').readJSON(SETTINGSFILE, true) || {}; + secondsMode = def(settings.secondsMode, "Never"); + secondsColoured = def(settings.secondsColoured, true); + secondsWithColon = def(settings.secondsWithColon, true); + dateOnMain = def(settings.dateOnMain, "Long"); + dateOnSecs = def(settings.dateOnSecs, "Year"); + weekDay = def(settings.weekDay, true); + upperCase = def(settings.upperCase, true); + vectorFont = def(settings.vectorFont, false); -// schedule a draw for the next minute + // Legacy + if (dateOnSecs === true) + dateOnSecs = "Year"; + if (dateOnSecs === false) + dateOnSecs = "No"; +} + +// schedule a draw for the next second or minute function queueDraw() { if (drawTimeout) clearTimeout(drawTimeout); drawTimeout = setTimeout(function() { drawTimeout = undefined; draw(); - }, 60000 - (Date.now() % 60000)); + }, queueMillis - (Date.now() % queueMillis)); } - -function draw() { - var x = g.getWidth()/2; - var y = g.getHeight()/2; - g.reset(); - var date = new Date(); - var timeStr = require("locale").time(date,1); - var dateStr = require("locale").date(date).toUpperCase(); - var dowStr = require("locale").dow(date).toUpperCase(); - // draw time - g.setFontAlign(0,0).setFont("Anton"); - g.clearRect(0,y-40,g.getWidth(),y+35); // clear the background - g.drawString(timeStr,x,y); - // draw date - y += 40; - g.setFontAlign(0,0).setFont("6x8",2); - g.clearRect(0,y-8,g.getWidth(),y+8); // clear the background - g.drawString(dateStr,x,y); - //draw day of week - y += 16; - g.clearRect(0,y-8,g.getWidth(),y+8); // clear the background - g.drawString(dowStr,x,y); - // queue draw in one minute - queueDraw(); -} - -// Clear the screen once, at startup -g.clear(); -// draw immediately at first, queue update -draw(); -// Stop updates when LCD is off, restart when on -Bangle.on('lcdPower',on=>{ - if (on) { +function updateState() { + if (Bangle.isLCDOn()) { + if ((secondsMode === "Unlocked" && !Bangle.isLocked()) || secondsMode === "Always") { + secondsScreen = true; + queueMillis = 1000; + } else { + secondsScreen = false; + queueMillis = 60000; + } draw(); // draw immediately, queue redraw } else { // stop draw timer if (drawTimeout) clearTimeout(drawTimeout); drawTimeout = undefined; } +} + +function isoStr(date) { + return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).substr(-2) + "-" + ("0" + date.getDate()).substr(-2); +} + +function doColor() { + return !isBangle1 && !Bangle.isLocked() && secondsColoured; +} + +// Actually draw the watch face +function draw() { + var x = g.getWidth() / 2; + var y = g.getHeight() / 2 - (secondsMode !== "Never" ? 24 : (vectorFont ? 12 : 0)); + g.reset(); + /* This is to mark the widget areas during development. + g.setColor("#888") + .fillRect(0, 0, g.getWidth(), 23) + .fillRect(0, g.getHeight() - 23, g.getWidth(), g.getHeight()).reset(); + /* */ + g.clearRect(0, 24, g.getWidth(), g.getHeight() - 24); // clear whole background (w/o widgets) + var date = new Date(); // Actually the current date, this one is shown + var timeStr = require("locale").time(date, 1); // Hour and minute + g.setFontAlign(0, 0).setFont("Anton").drawString(timeStr, x, y); // draw time + if (secondsScreen) { + y += 65; + var secStr = (secondsWithColon ? ":" : "") + ("0" + date.getSeconds()).substr(-2); + if (doColor()) + g.setColor(0, 0, 1); + g.setFont("AntonSmall"); + if (dateOnSecs !== "No") { // A bit of a complex drawing with seconds on the right and date on the left + g.setFontAlign(1, 0).drawString(secStr, g.getWidth() - (isBangle1 ? 32 : 2), y); // seconds + y -= (vectorFont ? 15 : 13); + x = g.getWidth() / 4 + (isBangle1 ? 12 : 4) + (secondsWithColon ? 0 : g.stringWidth(":") / 2); + var dateStr2 = (dateOnMain === "ISO8601" ? isoStr(date) : require("locale").date(date, 1)); + var year; + var md; + var yearfirst; + if (dateStr2.match(/\d\d\d\d$/)) { // formatted date ends with year + year = (dateOnSecs === "Year" ? dateStr2.slice(-4) : require("locale").dow(date, 1)); + md = dateStr2.slice(0, -4); + if (!md.endsWith(".")) // keep separator before the year only if it is a dot (31.12. but 31/12) + md = md.slice(0, -1); + yearfirst = false; + } else { // formatted date begins with year + if (!dateStr2.match(/^\d\d\d\d/)) // if year position cannot be detected... + dateStr2 = isoStr(date); // ...use ISO date format instead + year = (dateOnSecs === "Year" ? dateStr2.slice(0, 4) : require("locale").dow(date, 1)); + md = dateStr2.slice(5); // never keep separator directly after year + yearfirst = true; + } + if (dateOnSecs === "Weekday" && upperCase) + year = year.toUpperCase(); + g.setFontAlign(0, 0); + if (vectorFont) + g.setFont("Vector", 24); + else + g.setFont("6x8", 2); + if (doColor()) + g.setColor(1, 0, 0); + g.drawString(md, x, (yearfirst ? y + (vectorFont ? 26 : 16) : y)); + g.drawString(year, x, (yearfirst ? y : y + (vectorFont ? 26 : 16))); + } else { + g.setFontAlign(0, 0).drawString(secStr, x, y); // Just the seconds centered + } + } else { // No seconds screen: Show date and optionally day of week + y += (vectorFont ? 50 : (secondsMode !== "Never") ? 52 : 40); + var dateStr = (dateOnMain === "ISO8601" ? isoStr(date) : require("locale").date(date, (dateOnMain === "Long" ? 0 : 1))); + if (upperCase) + dateStr = dateStr.toUpperCase(); + g.setFontAlign(0, 0); + if (vectorFont) + g.setFont("Vector", 24); + else + g.setFont("6x8", 2); + g.drawString(dateStr, x, y); + if (weekDay) { + var dowStr = require("locale").dow(date); + if (upperCase) + dowStr = dowStr.toUpperCase(); + g.drawString(dowStr, x, y + (vectorFont ? 26 : 16)); + } + } + + // queue next draw + queueDraw(); +} + +// Init the settings of the app +loadSettings(); +// Clear the screen once, at startup +g.clear(); +// Set dynamic state and perform initial drawing +updateState(); +// Register hooks for LCD on/off event and screen lock on/off event +Bangle.on('lcdPower', on => { + updateState(); +}); +Bangle.on('lock', on => { + updateState(); }); // Show launcher when middle button pressed Bangle.setUI("clock"); // Load widgets Bangle.loadWidgets(); Bangle.drawWidgets(); + +// end of file \ No newline at end of file diff --git a/apps/antonclk/app.png b/apps/antonclk/app.png index d96f17758..a38093c5f 100644 Binary files a/apps/antonclk/app.png and b/apps/antonclk/app.png differ diff --git a/apps/antonclk/screenshot.png b/apps/antonclk/screenshot.png index c66f8bdd8..e949b8a24 100644 Binary files a/apps/antonclk/screenshot.png and b/apps/antonclk/screenshot.png differ diff --git a/apps/antonclk/settings.js b/apps/antonclk/settings.js new file mode 100644 index 000000000..08fde512e --- /dev/null +++ b/apps/antonclk/settings.js @@ -0,0 +1,99 @@ +// Settings menu for the enhanced Anton clock + +(function(back) { + var FILE = "antonclk.json"; + // Load settings + var settings = Object.assign({ + secondsOnUnlock: false, + }, require('Storage').readJSON(FILE, true) || {}); + + function writeSettings() { + require('Storage').writeJSON(FILE, settings); + } + + // Helper method which uses int-based menu item for set of string values + function stringItems(startvalue, writer, values) { + return { + value: (startvalue === undefined ? 0 : values.indexOf(startvalue)), + format: v => values[v], + min: 0, + max: values.length - 1, + wrap: true, + step: 1, + onchange: v => { + writer(values[v]); + writeSettings(); + } + }; + } + + // Helper method which breaks string set settings down to local settings object + function stringInSettings(name, values) { + return stringItems(settings[name], v => settings[name] = v, values); + } + + var mainmenu = { + "": { + "title": "Anton clock" + }, + "< Back": () => back(), + "Seconds...": () => E.showMenu(secmenu), + "Date": stringInSettings("dateOnMain", ["Short", "Long", "ISO8601"]), + "Show Weekday": { + value: (settings.weekDay !== undefined ? settings.weekDay : true), + format: v => v ? "On" : "Off", + onchange: v => { + settings.weekDay = v; + writeSettings(); + } + }, + "Uppercase": { + value: (settings.upperCase !== undefined ? settings.upperCase : false), + format: v => v ? "On" : "Off", + onchange: v => { + settings.upperCase = v; + writeSettings(); + } + }, + "Vector font": { + value: (settings.vectorFont !== undefined ? settings.vectorFont : false), + format: v => v ? "On" : "Off", + onchange: v => { + settings.vectorFont = v; + writeSettings(); + } + }, + }; + + // Submenu + var secmenu = { + "": { + "title": "Show seconds..." + }, + "< Back": () => E.showMenu(mainmenu), + "Show": stringInSettings("secondsMode", ["Never", "Unlocked", "Always"]), + "With \":\"": { + value: (settings.secondsWithColon !== undefined ? settings.secondsWithColon : false), + format: v => v ? "On" : "Off", + onchange: v => { + settings.secondsWithColon = v; + writeSettings(); + } + }, + "Color": { + value: (settings.secondsColoured !== undefined ? settings.secondsColoured : false), + format: v => v ? "On" : "Off", + onchange: v => { + settings.secondsColoured = v; + writeSettings(); + } + }, + "Date": stringInSettings("dateOnSecs", ["No", "Year", "Weekday"]) + }; + + // Actually display the menu + E.showMenu(mainmenu); + +}); + +// end of file diff --git a/apps/authentiwatch/ChangeLog b/apps/authentiwatch/ChangeLog index e1b8ed5bc..7a902a731 100644 --- a/apps/authentiwatch/ChangeLog +++ b/apps/authentiwatch/ChangeLog @@ -1,4 +1,4 @@ -0.04: Fix tapping at very bottom of list, exit on inactivity -0.03: Add "Calculating" placeholder, update JSON save format -0.02: Fix JSON save format 0.01: First release +0.02: Fix JSON save format +0.03: Add "Calculating" placeholder, update JSON save format +0.04: Fix tapping at very bottom of list, exit on inactivity diff --git a/apps/awairmonitor/ChangeLog b/apps/awairmonitor/ChangeLog index 0cc9a42b0..71d6399c4 100644 --- a/apps/awairmonitor/ChangeLog +++ b/apps/awairmonitor/ChangeLog @@ -1 +1,3 @@ 0.01: Beta version for Bangle 2 paired with Chrome (2021/12/11) +0.02: The app is now a clock, the data is greyed after the connection is lost (2021/12/22) +0.03: Set the Awair's IP directly on the webpage (2021/12/27) diff --git a/apps/awairmonitor/README.md b/apps/awairmonitor/README.md index 69894fea2..f4c7c42c4 100644 --- a/apps/awairmonitor/README.md +++ b/apps/awairmonitor/README.md @@ -5,11 +5,10 @@ Displays the level of CO2, VOC, PM 2.5, Humidity and Temperature, from your Awai * What you need: * A BangleJS 2 * An Awair device [with local API enabled](https://support.getawair.com/hc/en-us/articles/360049221014-Awair-Local-API-Feature) - * The web app [awair_to_bangle.html](awair_to_bangle.html) that will retrive the data from your Awair device and sent it to your BangleJS 2 through Chrome's Bluetooth LE connection + * The web app [awair_to_bangle.html](awair_to_bangle.html) that will retrieve the data from your Awair device and sent it to your BangleJS 2 through Chrome's Bluetooth LE connection * How to get started - * Open awair_to_bangle.html with a text/code editor and input the IP address of your Awair on top (const awair_ip_1 = "192.168.xx.xx") * Launch the Awair Monitor app on your BangleJS - * Open awair_to_bangle.html on Chrome and click "Connect BangleJS" - it connects to your watch the same way as the Bangle app store + * Open awair_to_bangle.html on Chrome (desktop or Android), input the IP address of your Awair device, and click "Connect BangleJS" - it connects to your watch the same way as the Bangle app store * Once connected to the watch with the app running, the watch app is updated once per second ![](screenshot.png) diff --git a/apps/awairmonitor/app.js b/apps/awairmonitor/app.js index a5a1d1a72..9123a9c2c 100644 --- a/apps/awairmonitor/app.js +++ b/apps/awairmonitor/app.js @@ -30,6 +30,8 @@ var bt_temp_history = new Array(10).fill(0); var internal_last_update = -1; +var display_frozen = false; + function draw() { g.reset().clearRect(0,24,g.getWidth(),g.getHeight()); @@ -47,14 +49,8 @@ function draw() { g.drawString("Humi", 125, 100); g.drawString("Temp", 160, 100); - g.setFont("HaxorNarrow7x17"); - g.drawString(""+bt_current_co2, 18, 110); - g.drawString(""+bt_current_voc, 53, 110); - g.drawString(""+bt_current_pm25, 88, 110); - g.drawString(""+bt_current_humi, 123, 110); - g.drawString(""+bt_current_temp, 158, 110); - if (last_update != bt_last_update) { + display_frozen = false; last_update = bt_last_update; internal_last_update = last_update; if (last_update % 10 == 0) { @@ -65,16 +61,29 @@ function draw() { bt_temp_history.shift(); bt_temp_history.push(bt_current_temp); } } - + if (internal_last_update == -1) { g.drawString("Waiting for connection", 88, 164); - } else if (internal_last_update > last_update + 5) { + } else if ((internal_last_update > last_update + 5) && (internal_last_update < last_update + 60)) { g.drawString("Trying to reconnect since " + (internal_last_update - last_update), 88, 164); + } else if (internal_last_update > last_update + 5) { + display_frozen = true; + g.drawString("Waiting for connection", 88, 164); } + if (display_frozen) { g.setColor("#888"); } + + g.setFont("HaxorNarrow7x17"); + g.drawString(""+bt_current_co2, 18, 110); + g.drawString(""+bt_current_voc, 53, 110); + g.drawString(""+bt_current_pm25, 88, 110); + g.drawString(""+bt_current_humi, 123, 110); + g.drawString(""+bt_current_temp, 158, 110); for (i = 0; i < 10; i++) { - // max height = 32 + if (display_frozen) { g.setColor("#888"); } + + // max height = 32 g.drawLine(10+i*2, 150-(Math.min(Math.max(bt_co2_history[i],400), 1200)-400)/25, 10+i*2, 150); g.drawLine(45+i*2, 150-(Math.min(Math.max(bt_voc_history[i],0), 1440)-0)/45, 45+i*2, 150); g.drawLine(80+i*2, 150-(Math.min(Math.max(bt_pm25_history[i],0), 32)-0)/1, 80+i*2, 150); @@ -91,6 +100,7 @@ function draw() { } // init +Bangle.setUI("clock"); require("FontHaxorNarrow7x17").add(Graphics); g.clear(); Bangle.loadWidgets(); diff --git a/apps/awairmonitor/awair_to_bangle.html b/apps/awairmonitor/awair_to_bangle.html index 2926cca9e..69c52499f 100644 --- a/apps/awairmonitor/awair_to_bangle.html +++ b/apps/awairmonitor/awair_to_bangle.html @@ -7,15 +7,15 @@ // Don't forget to enable the Local API on your Awair before using this // https://support.getawair.com/hc/en-us/articles/360049221014-Awair-Local-API-Feature -const awair_ip_1 = "192.168.2.2"; // <- INPUT YOUR AWAIR IP ADDRESS HERE const awair_name_1 = "Awair"; var bt_connection; var is_connected = false; var reconnect_counter = 5; var reconnect_attempt_counter = 1; +var is_chart_started = false; -window.onload = function() { +function initChart() { var chart_co2; var chart_voc; var chart_pm; @@ -23,6 +23,8 @@ window.onload = function() { var chart_humidity; var dataPoints_1 = []; var posx = 0; + + var awair_ip_1 = document.getElementById('inputawairip').value; $.getJSON("http://"+awair_ip_1+"/air-data/latest", function(data) { $.each(data, function(key, value){ @@ -105,11 +107,12 @@ window.onload = function() { let current_humi = dataPoints_1['humid'][dataPoints_1['humid'].length-1].y; let current_temp = dataPoints_1['temp'][dataPoints_1['temp'].length-1].y; let last_update = dataPoints_1['temp'].length-1; - if (is_connected && bt_connection.isOpen) { + + if (is_connected && bt_connection && bt_connection.isOpen) { bt_connection.write('\x10bt_current_co2='+current_co2+';bt_current_voc='+current_voc+';bt_current_pm25='+current_pm25+';bt_current_humi='+current_humi+';bt_current_temp='+current_temp+';bt_last_update='+last_update+';\n'); console.log("Sent data through Bluetooth"); - } else if (is_connected && !bt_connection.isOpen) { + } else if (is_connected && bt_connection && !bt_connection.isOpen) { console.log("Disconnected - Next attempt to reconnect in " + reconnect_counter); reconnect_counter--; @@ -131,7 +134,6 @@ window.onload = function() { } } - setTimeout(function(){updateChart()}, 1000); }); } @@ -148,10 +150,16 @@ function connectBT() { bt_connection = c; is_connected = true; reconnect_attempt_counter = 1; + if (!is_chart_started) { + initChart(); + is_chart_started = true; + } }); } function disconnectBT() { + console.log("Disconnect Bluetooth button pressed. bt_connection value below.") + console.log(bt_connection); if (is_connected && bt_connection) { bt_connection.close(); is_connected = false; @@ -167,23 +175,21 @@ function disconnectBT() {

How to use -

+

Step 1: Enable the Local API on your Awair: https://support.getawair.com/hc/en-us/articles/360049221014-Awair-Local-API-Feature -

-Step 2: Modify this HTML file to input the IP address of your Awair on top (const awair_ip_1 = "192.168.xx.xx") -

-Step 3: Launch the Awair Monitor app on your BangleJS -

-Step 4: Click "Connect BangleJS" -

-Step 5: Optionally, open the web inspector's console (Right click > Inspector > Console) to read the bluetooth logs +

+Step 2: Launch the Awair Monitor app on your BangleJS +

+Step 3: Input your Awair IP address and click the Connect button: + + +

+Step 4: Optionally, open the web inspector's console (Right click > Inspector > Console) to read the Bluetooth logs +

+Step 5: Once you are done, click the Disconnect button to properly close the Blutooth connection +

-
- - -
-

@@ -192,4 +198,476 @@ Step 5: Optionally, open the web inspector's console (Right click > Inspector >
- +(buf)); + } + + function str2ab(str) { + var buf = new ArrayBuffer(str.length); + var bufView = new Uint8Array(buf); + for (var i=0, strLen=str.length; i Device UUIDs: ' + device.uuids.join('\n' + ' '.repeat(21))); + device.addEventListener('gattserverdisconnected', function() { + log(1, "Disconnected (gattserverdisconnected)"); + connection.close(); + }); + connection.device = device; + connection.reconnect(callback); + }).catch(function(error) { + log(1, 'ERROR: ' + error); + connection.close(); + }); + + connection.reconnect = function(callback) { + connection.device.gatt.connect().then(function(server) { + log(1, "Connected"); + btServer = server; + return server.getPrimaryService(NORDIC_SERVICE); + }).then(function(service) { + log(2, "Got service"); + btService = service; + return btService.getCharacteristic(NORDIC_RX); + }).then(function (characteristic) { + rxCharacteristic = characteristic; + log(2, "RX characteristic:"+JSON.stringify(rxCharacteristic)); + rxCharacteristic.addEventListener('characteristicvaluechanged', function(event) { + var dataview = event.target.value; + var data = ab2str(dataview.buffer); + if (data.length > chunkSize) { + log(2, "Received packet of length "+data.length+", increasing chunk size"); + chunkSize = data.length; + } + if (puck.flowControl) { + for (var i=0;i pause upload"); + flowControlXOFF = true; + } else if (ch==17) {// XON + log(2,"XON received => resume upload"); + flowControlXOFF = false; + } else + remove = false; + if (remove) { // remove character + data = data.substr(0,i-1)+data.substr(i+1); + i--; + } + } + } + log(3, "Received "+JSON.stringify(data)); + connection.emit('data', data); + }); + return rxCharacteristic.startNotifications(); + }).then(function() { + return btService.getCharacteristic(NORDIC_TX); + }).then(function (characteristic) { + txCharacteristic = characteristic; + log(2, "TX characteristic:"+JSON.stringify(txCharacteristic)); + }).then(function() { + connection.txInProgress = false; + connection.isOpen = true; + connection.isOpening = false; + isBusy = false; + queue = []; + callback(connection); + connection.emit('open'); + // if we had any writes queued, do them now + connection.write(); + }).catch(function(error) { + log(1, 'ERROR: ' + error); + connection.close(); + }); + }; + + return connection; + }; + + // ---------------------------------------------------------- + var connection; + /* convenience function... Write data, call the callback with data: + callbackNewline = false => if no new data received for ~0.2 sec + callbackNewline = true => after a newline */ + function write(data, callback, callbackNewline) { + if (!checkIfSupported()) return; + + let result; + /// If there wasn't a callback function, then promisify + if (typeof callback !== 'function') { + callbackNewline = callback; + + result = new Promise((resolve, reject) => callback = (value, err) => { + if (err) reject(err); + else resolve(value); + }); + } + + if (isBusy) { + log(3, "Busy - adding Puck.write to queue"); + queue.push({type:"write", data:data, callback:callback, callbackNewline:callbackNewline}); + return result; + } + + var cbTimeout; + function onWritten() { + if (callbackNewline) { + connection.cb = function(d) { + var newLineIdx = connection.received.indexOf("\n"); + if (newLineIdx>=0) { + var l = connection.received.substr(0,newLineIdx); + connection.received = connection.received.substr(newLineIdx+1); + connection.cb = undefined; + if (cbTimeout) clearTimeout(cbTimeout); + cbTimeout = undefined; + if (callback) + callback(l); + isBusy = false; + handleQueue(); + } + }; + } + // wait for any received data if we have a callback... + var maxTime = 300; // 30 sec - Max time we wait in total, even if getting data + var dataWaitTime = callbackNewline ? 100/*10 sec if waiting for newline*/ : 3/*300ms*/; + var maxDataTime = dataWaitTime; // max time we wait after having received data + cbTimeout = setTimeout(function timeout() { + cbTimeout = undefined; + if (maxTime) maxTime--; + if (maxDataTime) maxDataTime--; + if (connection.hadData) maxDataTime=dataWaitTime; + if (maxDataTime && maxTime) { + cbTimeout = setTimeout(timeout, 100); + } else { + connection.cb = undefined; + if (callback) + callback(connection.received); + isBusy = false; + handleQueue(); + connection.received = ""; + } + connection.hadData = false; + }, 100); + } + + if (connection && (connection.isOpen || connection.isOpening)) { + if (!connection.txInProgress) connection.received = ""; + isBusy = true; + connection.write(data, onWritten); + return result + } + + connection = connect(function(puck) { + if (!puck) { + connection = undefined; + if (callback) callback(null); + return; + } + connection.received = ""; + connection.on('data', function(d) { + connection.received += d; + connection.hadData = true; + if (connection.cb) connection.cb(d); + }); + connection.on('close', function(d) { + connection = undefined; + }); + isBusy = true; + connection.write(data, onWritten); + }); + + return result + } + + // ---------------------------------------------------------- + + var puck = { + /// Are we writing debug information? 0 is no, 1 is some, 2 is more, 3 is all. + debug : 1, + /// Should we use flow control? Default is true + flowControl : true, + /// Used internally to write log information - you can replace this with your own function + log : function(level, s) { if (level <= this.debug) console.log(" "+s)}, + /// Called with the current send progress or undefined when done - you can replace this with your own function + writeProgress : function (charsSent, charsTotal) { + //console.log(charsSent + "/" + charsTotal); + }, + /** Connect to a new device - this creates a separate + connection to the one `write` and `eval` use. */ + connect : connect, + /// Write to Puck.js and call back when the data is written. Creates a connection if it doesn't exist + write : write, + /// Evaluate an expression and call cb with the result. Creates a connection if it doesn't exist + eval : function(expr, cb) { + + const response = write('\x10Bluetooth.println(JSON.stringify(' + expr + '))\n', true) + .then(function (d) { + try { + return JSON.parse(d); + } catch (e) { + log(1, "Unable to decode " + JSON.stringify(d) + ", got " + e.toString()); + return Promise.reject(d); + } + }); + + + if (cb) { + return void response.then(cb, (err) => cb(null, err)); + } else { + return response; + } + + }, + /// Write the current time to the Puck + setTime : function(cb) { + var d = new Date(); + var cmd = 'setTime('+(d.getTime()/1000)+');'; + // in 1v93 we have timezones too + cmd += 'if (E.setTimeZone) E.setTimeZone('+d.getTimezoneOffset()/-60+');\n'; + write(cmd, cb); + }, + /// Did `write` and `eval` manage to create a connection? + isConnected : function() { + return connection!==undefined; + }, + /// get the connection used by `write` and `eval` + getConnection : function() { + return connection; + }, + /// Close the connection used by `write` and `eval` + close : function() { + if (connection) + connection.close(); + }, + /** Utility function to fade out everything on the webpage and display + a window saying 'Click to continue'. When clicked it'll disappear and + 'callback' will be called. This is useful because you can't initialise + Web Bluetooth unless you're doing so in response to a user input.*/ + modal : function(callback) { + var e = document.createElement('div'); + e.style = 'position:absolute;top:0px;left:0px;right:0px;bottom:0px;opacity:0.5;z-index:100;background:black;'; + e.innerHTML = '
Click to Continue...
'; + e.onclick = function(evt) { + callback(); + evt.preventDefault(); + document.body.removeChild(e); + }; + document.body.appendChild(e); + } + }; + return puck; +})); + + + + + + + +
+

Presentor

+
+
+
+
+
+
#
+
Subject
+
Time
+
Notes
+
+
Loading...
+
+
+
+
+ + +
+ + + + + + diff --git a/apps/presentor/settings.json b/apps/presentor/settings.json new file mode 100644 index 000000000..398bf1332 --- /dev/null +++ b/apps/presentor/settings.json @@ -0,0 +1 @@ +{"pparts":[{"subject":"#1","minutes":10,"seconds":0,"notes":"This is a note."},{"subject":"#2","minutes":2,"seconds":50,"notes":"Change in the app!"}],"sversion":2.2} \ No newline at end of file diff --git a/apps/promenu/ChangeLog b/apps/promenu/ChangeLog new file mode 100644 index 000000000..b7287cc80 --- /dev/null +++ b/apps/promenu/ChangeLog @@ -0,0 +1,2 @@ +0.01: New App! +0.02: Add Bangle.js 2 Support diff --git a/apps/promenu/README.md b/apps/promenu/README.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/apps/promenu/README.md @@ -0,0 +1 @@ + diff --git a/apps/promenu/boot.js b/apps/promenu/boot.js new file mode 100644 index 000000000..bd813a812 --- /dev/null +++ b/apps/promenu/boot.js @@ -0,0 +1,176 @@ +E.showMenu = function(items) { + function RectRnd(x1,y1,x2,y2,r) { + pp = []; + pp.push.apply(pp,g.quadraticBezier([x2-r,y1, x2,y1,x2,y1+r])); + pp.push.apply(pp,g.quadraticBezier([x2,y2-r,x2,y2,x2-r,y2])); + pp.push.apply(pp,g.quadraticBezier([x1+r,y2,x1,y2,x1,y2-r])); + pp.push.apply(pp,g.quadraticBezier([x1,y1+r,x1,y1,x1+r,y1])); + return pp; + } + function fillRectRnd(x1,y1,x2,y2,r,c) { + g.setColor(c); + g.fillPoly(RectRnd(x1,y1,x2,y2,r),1); + g.setColor(255,255,255); + } + function drawRectRnd(x1,y1,x2,y2,r,c) { + g.setColor(c); + g.drawPoly(RectRnd(x1,y1,x2,y2,r),1); + g.setColor(255,255,255); + } + g.reset().clearRect(Bangle.appRect); // clear if no menu supplied + Bangle.setLCDPower(1); // ensure screen is on + if (!items) { + Bangle.setUI(); + return; + } + var menuItems = Object.keys(items); + var options = items[""]; + if (options) menuItems.splice(menuItems.indexOf(""),1); + if (!(options instanceof Object)) options = {}; + options.fontHeight = options.fontHeight||35; + if (options.selected === undefined) + options.selected = 0; + if (!options.fontHeight) + options.fontHeight = 6; + var ar = Bangle.appRect; + var x = ar.x; + var x2 = ar.x2-11; // padding at side for up/down + var y = ar.y; + var y2 = ar.y2 - 20; // padding at end for arrow + if (options.title) + y += options.fontHeight+2; + var loc = require("locale"); + var l = { + lastIdx : 0, + draw : function(rowmin,rowmax) { + var rows = 0|Math.min((y2-y) / options.fontHeight,menuItems.length); + var idx = E.clip(options.selected-(rows>>1),0,menuItems.length-rows); + if (idx!=l.lastIdx) rowmin=undefined; // redraw all if we scrolled + l.lastIdx = idx; + var iy = y-5; + g.reset().setFont('6x8',2).setFontAlign(0,-1,0); + if (options.predraw) options.predraw(g); + if (rowmin===undefined && options.title) { + g.drawString(options.title,(x+x2)/2,y-options.fontHeight+5); + g.drawLine(x,y-7,x2,y-7); + } + if (rowmin!==undefined) { + if (idxrowmax) { + rows = 1+rowmax-rowmin; + } + } + while (rows--) { + var name = menuItems[idx]; + var item = items[name]; + var hl = (idx==options.selected && !l.selectEdit); + if(g.theme.dark){ + fillRectRnd(x+2,iy+1,x2,iy+options.fontHeight-3,7,hl ? g.theme.bgH : g.theme.bg+20); + }else{ + fillRectRnd(x+2,iy+1,x2,iy+options.fontHeight-3,7,hl ? g.theme.bgH : g.theme.bg-20); + } + g.setColor(hl ? g.theme.fgH : g.theme.fg); + g.setFontAlign(-1,-1); + if(loc.translate(name).length >= 11 && "object" == typeof item){ + var v = item.value; + if (item.format) v=item.format(v); + v = loc.translate(""+v); + g.drawString(loc.translate(name).substring(0, 15-v.length)+"...",x+8,iy+7); + }else{ + if(loc.translate(name).length >= 15){ + g.drawString(loc.translate(name).substring(0, 15)+"...",x+8,iy+7); + }else{ + g.drawString(loc.translate(name),x+8,iy+7); + } + } + if ("object" == typeof item) { + var xo = x2; + var v = item.value; + if (item.format) v=item.format(v); + v = loc.translate(""+v); + if (l.selectEdit && idx==options.selected) { + xo -= 24 + 1; + g.setColor(g.theme.fgH).drawImage("\x0c\x05\x81\x00 \x07\x00\xF9\xF0\x0E\x00@",xo,iy+(options.fontHeight-10)/2,{scale:2}); + } + g.setFontAlign(1,-1); + g.drawString(v,xo-4,iy+8.5); + } + g.setColor(g.theme.fg); + iy += options.fontHeight; + idx++; + } + g.setFontAlign(-1,-1); + var more = idxitem.max) item.value = item.wrap ? item.min : item.max; + if (item.onchange) item.onchange(item.value); + l.draw(options.selected,options.selected); + } else { + var lastSelected=options.selected; + options.selected = (dir+options.selected+menuItems.length)%menuItems.length; + l.draw(Math.min(lastSelected,options.selected), Math.max(lastSelected,options.selected)); + } + } + }; + l.draw(); + Bangle.setUI("updown",dir => { + if (dir) l.move(dir); + else l.select(); + }); + return l; +}; diff --git a/apps/promenu/bootb2.js b/apps/promenu/bootb2.js new file mode 100644 index 000000000..c84e0d894 --- /dev/null +++ b/apps/promenu/bootb2.js @@ -0,0 +1,142 @@ +E.showMenu = function(items) { + function RectRnd(x1,y1,x2,y2,r) { + pp = []; + pp.push.apply(pp,g.quadraticBezier([x2-r,y1, x2,y1,x2,y1+r])); + pp.push.apply(pp,g.quadraticBezier([x2,y2-r,x2,y2,x2-r,y2])); + pp.push.apply(pp,g.quadraticBezier([x1+r,y2,x1,y2,x1,y2-r])); + pp.push.apply(pp,g.quadraticBezier([x1,y1+r,x1,y1,x1+r,y1])); + return pp; + } + function fillRectRnd(x1,y1,x2,y2,r,c) { + g.setColor(c); + g.fillPoly(RectRnd(x1,y1,x2,y2,r),1); + g.setColor(255,255,255); + } + function drawRectRnd(x1,y1,x2,y2,r,c) { + g.setColor(c); + g.drawPoly(RectRnd(x1,y1,x2,y2,r),1); + g.setColor(255,255,255); + } + g.reset().clearRect(Bangle.appRect); // clear if no menu supplied + Bangle.setLCDPower(1); // ensure screen is on + if (!items) { + Bangle.setUI(); + return; + } + var menuItems = Object.keys(items); + var options = items[""]; + if (options) menuItems.splice(menuItems.indexOf(""),1); + if (!(options instanceof Object)) options = {}; + options.fontHeight = options.fontHeight||25; + if (options.selected === undefined) + options.selected = 0; + var ar = Bangle.appRect; + var x = ar.x; + var x2 = ar.x2; + var y = ar.y; + var y2 = ar.y2 - 12; // padding at end for arrow + if (options.title) + y += 22; + var loc = require("locale"); + var l = { + lastIdx : 0, + draw : function(rowmin,rowmax) { + var rows = 0|Math.min((y2-y) / options.fontHeight,menuItems.length); + var idx = E.clip(options.selected-( rows>>1),0,menuItems.length-rows); + if (idx!=l.lastIdx) rowmin=undefined; // redraw all if we scrolled + l.lastIdx = idx; + var iy = y; + g.reset().setFontAlign(0,-1,0).setFont('12x20'); + if (options.predraw) options.predraw(g); + if (rowmin===undefined && options.title) + g.drawString(options.title,(x+x2)/2,y-21).drawLine(x,y-2,x2,y-2). + setColor(g.theme.fg).setBgColor(g.theme.bg); + iy += 4; + if (rowmin!==undefined) { + if (idxrowmax) { + rows = 1+rowmax-rowmin; + } + } + while (rows--) { + var name = menuItems[idx]; + var item = items[name]; + var hl = (idx==options.selected && !l.selectEdit); + if(g.theme.dark){ + fillRectRnd(x,iy,x2,iy+options.fontHeight-3,7,hl ? g.theme.bgH : g.theme.bg+40); + }else{ + fillRectRnd(x,iy,x2,iy+options.fontHeight-3,7,hl ? g.theme.bgH : g.theme.bg-20); + } + g.setColor(hl ? g.theme.fgH : g.theme.fg); + g.setFontAlign(-1,-1); + var v = item.value; + v = loc.translate(""+v); + if(loc.translate(name).length >= 17-v.length && "object" == typeof item){ + if (item.format) v=item.format(v); + g.drawString(loc.translate(name).substring(0, 12-v.length)+"...",x+3.7,iy+2.7); + }else{ + if(loc.translate(name).length >= 15){ + g.drawString(loc.translate(name).substring(0, 15)+"...",x+3.7,iy+2.7); + }else{ + g.drawString(loc.translate(name),x+3.7,iy+2.7); + } + } + if ("object" == typeof item) { + var xo = x2; + var v = item.value; + if (item.format) v=item.format(v); + v = loc.translate(""+v); + if (l.selectEdit && idx==options.selected) { + xo -= 24 + 1; + g.setColor(g.theme.fgH).drawImage("\x0c\x05\x81\x00 \x07\x00\xF9\xF0\x0E\x00@",xo,iy+(options.fontHeight-10)/2,{scale:2}); + } + g.setFontAlign(1,-1); + g.drawString(v,xo-2,iy+1); + } + g.setColor(g.theme.fg); + iy += options.fontHeight; + idx++; + } + g.setFontAlign(-1,-1); + g.setColor((idxitem.max) item.value = item.wrap ? item.min : item.max; + if (item.onchange) item.onchange(item.value); + l.draw(options.selected,options.selected); + } else { + var lastSelected=options.selected; + options.selected = (dir+options.selected+menuItems.length)%menuItems.length; + l.draw(Math.min(lastSelected,options.selected), Math.max(lastSelected,options.selected)); + } + } + }; + l.draw(); + Bangle.setUI("updown",dir => { + if (dir) l.move(dir); + else l.select(); + }); + return l; +}; diff --git a/apps/promenu/icon.png b/apps/promenu/icon.png new file mode 100644 index 000000000..c6138b765 Binary files /dev/null and b/apps/promenu/icon.png differ diff --git a/apps/promenu/pro-menu-screenshot.png b/apps/promenu/pro-menu-screenshot.png new file mode 100644 index 000000000..2ae318eb8 Binary files /dev/null and b/apps/promenu/pro-menu-screenshot.png differ diff --git a/apps/promenu/promenuIcon.js b/apps/promenu/promenuIcon.js new file mode 100644 index 000000000..5c2dc6adc --- /dev/null +++ b/apps/promenu/promenuIcon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwyBC/AH4A/AH4A/AH4A/AH4A/AH4A/AH4A/AFE+rwBSAAU2j02js1/oBC7oBBlu9AIWdluclt8AIMlrgBCngBCjgBBjn7AIXbAIW7AIMUzYBFLv5ddMJ5d/LqJfeLv5fdLv5fQMJhd/LqQA/AH4A/AH4A/AH4A/AH4A/AAM+rwBSAAU2j02js1/oBC7oBBlu9AIWdluclt8AIMlrgBCngBCjgBBjn7AIXbAIW7AIMUzYBFLv5ddMJ5d/LqJfeLv5fdLv5fQMJhd/LqQA/AH4A/AH4A/AH4A/AH4A/AAM+rwBSAAU2j02js1/oBC7oBBlu9AIWdluclt8AIMlrgBCngBCjgBBjn7AIXbAIW7AIMUzYBFLv5ddMJ5d/LqJfeLv5fdLv5fQMJhd/LqQA/AH4A/AH4A/AH4A/AH4A/AH4A/AH4A/ADIA==")) diff --git a/apps/ptlaunch/ChangeLog b/apps/ptlaunch/ChangeLog index 23031cff3..68b7d3e1c 100644 --- a/apps/ptlaunch/ChangeLog +++ b/apps/ptlaunch/ChangeLog @@ -2,4 +2,6 @@ 0.02: Turn on lcd when launching an app if the lock screen was disabled in the settings 0.03: Make tap to confirm new pattern more reliable. Also allow for easier creation of single circle patterns. 0.10: Improve the management of existing patterns: Draw the linked pattern on the left hand side of the app name within a scroller, similar to the default launcher. Slighlty clean up the code to make it less horrible. -0.11: Respect theme colors. Fix: Do not pollute global space with internal variables ans functions in boot.js \ No newline at end of file +0.11: Respect theme colors. Fix: Do not pollute global space with internal variables ans functions in boot.js +0.12: Improve pattern detection code readability by PaddeK http://forum.espruino.com/profiles/117930/ +0.13: Improve pattern rendering by HughB http://forum.espruino.com/profiles/167235/ \ No newline at end of file diff --git a/apps/ptlaunch/README.md b/apps/ptlaunch/README.md index 7cc39e3d6..cf75315a9 100644 --- a/apps/ptlaunch/README.md +++ b/apps/ptlaunch/README.md @@ -29,32 +29,41 @@ Then launch the linked apps directly from the clock screen by simply drawing the ## Detailed Steps From the main menu you can: + - Add a new pattern and link it to an app (first entry) - - To create a new pattern first select "Add Pattern" - - Now draw any pattern you like, this will later launch the linked app from the clock screen - - You can also draw a single-circle pattern (meaning a single tap on one circle) instead of drawing a 'complex' pattern - - If you don't like the pattern, simply re-draw it. The previous pattern will be discarded. - - If you are happy with the pattern tap on screen or press the button to continue - - Now select the app you want to launch with the pattern. - - Note, you can bind multiple patterns to the same app. + - To create a new pattern first select "Add Pattern" + - Now draw any pattern you like, this will later launch the linked app from the clock screen + - You can also draw a single-circle pattern (meaning a single tap on one circle) instead of drawing a 'complex' pattern + - If you don't like the pattern, simply re-draw it. The previous pattern will be discarded. + - If you are happy with the pattern press the button to continue + - Now select the app you want to launch with the pattern. + - Note, you can bind multiple patterns to the same app. - Manage created patterns (second entry) - - To manage your patterns first select "Manage Patterns" - - You will now see a scrollabe list of patterns + linked apps - - If you want to deletion a pattern (and unlink the app) simply tap on it, and confirm the deletion + - To manage your patterns first select "Manage Patterns" + - You will now see a scrollabe list of patterns + linked apps + - If you want to deletion a pattern (and unlink the app) simply tap on it, and confirm the deletion - Disable the lock screen on the clock screen from the settings (third entry) - - To launch the app from the pattern on the clock screen the watch must be unlocked. - - If this annoys you, you can disable the lock on the clock screen from the setting here + - To launch the app from the pattern on the clock screen the watch must be unlocked. + - If this annoys you, you can disable the lock on the clock screen from the setting here ## FAQ -1) Nothing happens when I draw on the clock screen! +1. Nothing happens when I draw on the clock screen! Please double-check if you actually have a pattern linked to an app. -2) I have a pattern linked to an app and still nothing happens when I draw on the clock screen! +2. I have a pattern linked to an app and still nothing happens when I draw on the clock screen! Make sure the watch is unlocked before you start drawing. If this bothers you, you can permanently disable the watch-lock from within the Pattern Launcher app (via the Settings). -3) I have done all that and still nothing happens! +3. I have done all that and still nothing happens! Please note that drawing on the clock screen will not visually show the pattern you drew. It will start the app as soon as the pattern was recognized - this might take 1 or 2 seconds! If still nothing happens, that might be a bug, sorry! + +## Authors + +Initial creation: [crazysaem](https://github.com/crazysaem) + +Improve pattern detection code readability: [PaddeK](http://forum.espruino.com/profiles/117930/) + +Improve pattern rendering: [HughB](http://forum.espruino.com/profiles/167235/) diff --git a/apps/ptlaunch/add_pattern_dark.png b/apps/ptlaunch/add_pattern_dark.png index 04dfdecd6..4d5770835 100644 Binary files a/apps/ptlaunch/add_pattern_dark.png and b/apps/ptlaunch/add_pattern_dark.png differ diff --git a/apps/ptlaunch/add_pattern_light.png b/apps/ptlaunch/add_pattern_light.png index 47549b43e..998ec21a0 100644 Binary files a/apps/ptlaunch/add_pattern_light.png and b/apps/ptlaunch/add_pattern_light.png differ diff --git a/apps/ptlaunch/app.js b/apps/ptlaunch/app.js index 062cc3c62..5db3a335b 100644 --- a/apps/ptlaunch/app.js +++ b/apps/ptlaunch/app.js @@ -114,7 +114,6 @@ var showMainMenu = () => { E.showMenu(mainmenu); }; -var positions = []; var recognizeAndDrawPattern = () => { return new Promise((resolve) => { E.showMenu(); @@ -135,150 +134,55 @@ var recognizeAndDrawPattern = () => { resolve(pattern.join("")); }; setWatch(() => finishHandler(), BTN); - setTimeout(() => Bangle.on("tap", finishHandler), 250); + // setTimeout(() => Bangle.on("tap", finishHandler), 250); - positions = []; + var positions = []; + var getPattern = (positions) => { + var circles = [ + { x: 25, y: 25, i: 0 }, + { x: 87, y: 25, i: 1 }, + { x: 150, y: 25, i: 2 }, + { x: 25, y: 87, i: 3 }, + { x: 87, y: 87, i: 4 }, + { x: 150, y: 87, i: 5 }, + { x: 25, y: 150, i: 6 }, + { x: 87, y: 150, i: 7 }, + { x: 150, y: 150, i: 8 }, + ]; + return positions.reduce((pattern, p, i, arr) => { + var idx = circles.findIndex((c) => { + var dx = p.x > c.x ? p.x - c.x : c.x - p.x; + if (dx > CIRCLE_RADIUS) { + return false; + } + var dy = p.y > c.y ? p.y - c.y : c.y - p.y; + if (dy > CIRCLE_RADIUS) { + return false; + } + if (dx + dy <= CIRCLE_RADIUS) { + return true; + } + return dx * dx + dy * dy <= CIRCLE_RADIUS_2; + }); + if (idx >= 0) { + pattern += circles[idx].i; + circles.splice(idx, 1); + } + if (circles.length === 0) { + arr.splice(1); + } + return pattern; + }, ""); + }; var dragHandler = (position) => { - log(position); positions.push(position); - - debounce().then(() => { - if (isFinished) { - return; - } - - // This might actually be a 'tap' event. - // Use this check in addition to the actual tap handler to make it more reliable - if (pattern.length > 0 && positions.length === 2) { - if ( - positions[0].x === positions[1].x && - positions[0].y === positions[1].y - ) { - finishHandler(); - positions = []; - return; - } - } - - E.showMessage("Calculating..."); - var t0 = Date.now(); - - log(positions.length); - - var circlesClone = cloneCirclesArray(); - pattern = []; - - var step = Math.floor(positions.length / 100) + 1; - - var p, a, b, circle; - - for (var i = 0; i < positions.length; i += step) { - p = positions[i]; - - circle = circlesClone[0]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(0, 1); - } - } - - circle = circlesClone[1]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(1, 1); - } - } - - circle = circlesClone[2]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(2, 1); - } - } - - circle = circlesClone[3]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(3, 1); - } - } - - circle = circlesClone[4]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(4, 1); - } - } - - circle = circlesClone[5]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(5, 1); - } - } - - circle = circlesClone[6]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(6, 1); - } - } - circle = circlesClone[7]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(7, 1); - } - } - - circle = circlesClone[8]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circlesClone.splice(8, 1); - } - } - } - var tx = Date.now(); - log(tx - t0); - positions = []; - var t1 = Date.now(); - log(t1 - t0); - - log("pattern:"); - log(pattern); - - log("redrawing"); + if (position.b === 0 || positions.length >= 200) { + pattern = getPattern(positions).split(""); g.clear(); drawCirclesWithPattern(pattern); - }); + positions = []; + } }; - Bangle.on("drag", dragHandler); }); }; @@ -488,7 +392,8 @@ var drawCircle = (circle, drawBuffer, scale) => { log("drawing circle"); log({ x: x, y: y, r: r }); - drawBuffer.drawCircle(x, y, r); + drawBuffer.setColor(0); + drawBuffer.fillCircle(x, y, r); }; var cachedCirclesDrawings = {}; @@ -533,8 +438,11 @@ var drawCirclesWithPattern = (pattern, options) => { { msb: true } ); - CIRCLES.forEach((circle) => drawCircle(circle, drawBuffer, scale)); + drawBuffer.setColor(1); + drawBuffer.fillRect(0, 0, drawBuffer.getWidth(), drawBuffer.getHeight()); + CIRCLES.forEach((circle) => drawCircle(circle, drawBuffer, scale)); + drawBuffer.setColor(1); drawBuffer.setFontAlign(0, 0); drawBuffer.setFont("Vector", 40 * scale); pattern.forEach((circleIndex, patternIndex) => { @@ -545,12 +453,12 @@ var drawCirclesWithPattern = (pattern, options) => { circle.y * scale ); }); - image = { width: drawBuffer.getWidth(), height: drawBuffer.getHeight(), bpp: 1, buffer: drawBuffer.buffer, + palette: new Uint16Array([g.theme.fg, g.theme.bg], 0, 1), }; if (enableCaching) { @@ -563,16 +471,6 @@ var drawCirclesWithPattern = (pattern, options) => { g.drawImage(image, offset.x, offset.y); }; -var cloneCirclesArray = () => { - var circlesClone = Array(CIRCLES.length); - - for (var i = 0; i < CIRCLES.length; i++) { - circlesClone[i] = CIRCLES[i]; - } - - return circlesClone; -}; - ////// // misc lib functions ////// @@ -583,20 +481,6 @@ var log = (message) => { } }; -var debounceTimeoutId; -var debounce = (delay) => { - if (debounceTimeoutId) { - clearTimeout(debounceTimeoutId); - } - - return new Promise((resolve) => { - debounceTimeoutId = setTimeout(() => { - debounceTimeoutId = undefined; - resolve(); - }, delay || 500); - }); -}; - ////// // run main function ////// diff --git a/apps/ptlaunch/boot.js b/apps/ptlaunch/boot.js index 6fbd3ca41..19a8f16cb 100644 --- a/apps/ptlaunch/boot.js +++ b/apps/ptlaunch/boot.js @@ -5,131 +5,54 @@ console.log(JSON.stringify(message)); } }; - + var storedPatterns; + var CIRCLE_RADIUS = 25; + var CIRCLE_RADIUS_2 = Math.pow(CIRCLE_RADIUS, 2); var positions = []; + var getPattern = (positions) => { + var circles = [ + { x: 25, y: 25, i: 0 }, + { x: 87, y: 25, i: 1 }, + { x: 150, y: 25, i: 2 }, + { x: 25, y: 87, i: 3 }, + { x: 87, y: 87, i: 4 }, + { x: 150, y: 87, i: 5 }, + { x: 25, y: 150, i: 6 }, + { x: 87, y: 150, i: 7 }, + { x: 150, y: 150, i: 8 }, + ]; + return positions.reduce((pattern, p, i, arr) => { + var idx = circles.findIndex((c) => { + var dx = p.x > c.x ? p.x - c.x : c.x - p.x; + if (dx > CIRCLE_RADIUS) { + return false; + } + var dy = p.y > c.y ? p.y - c.y : c.y - p.y; + if (dy > CIRCLE_RADIUS) { + return false; + } + if (dx + dy <= CIRCLE_RADIUS) { + return true; + } + return dx * dx + dy * dy <= CIRCLE_RADIUS_2; + }); + if (idx >= 0) { + pattern += circles[idx].i; + circles.splice(idx, 1); + } + if (circles.length === 0) { + arr.splice(1); + } + return pattern; + }, ""); + }; var dragHandler = (position) => { positions.push(position); - - debounce().then(() => { - log(positions.length); - - var CIRCLE_RADIUS = 25; - var CIRCLE_RADIUS_2 = CIRCLE_RADIUS * CIRCLE_RADIUS; - - var circles = [ - { x: 25, y: 25, i: 0 }, - { x: 87, y: 25, i: 1 }, - { x: 150, y: 25, i: 2 }, - { x: 25, y: 87, i: 3 }, - { x: 87, y: 87, i: 4 }, - { x: 150, y: 87, i: 5 }, - { x: 25, y: 150, i: 6 }, - { x: 87, y: 150, i: 7 }, - { x: 150, y: 150, i: 8 }, - ]; - var pattern = []; - - var step = Math.floor(positions.length / 100) + 1; - - var p, a, b, circle; - - for (var i = 0; i < positions.length; i += step) { - p = positions[i]; - - circle = circles[0]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(0, 1); - } - } - - circle = circles[1]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(1, 1); - } - } - - circle = circles[2]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(2, 1); - } - } - - circle = circles[3]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(3, 1); - } - } - - circle = circles[4]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(4, 1); - } - } - - circle = circles[5]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(5, 1); - } - } - - circle = circles[6]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(6, 1); - } - } - circle = circles[7]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(7, 1); - } - } - - circle = circles[8]; - if (circle) { - a = p.x - circle.x; - b = p.y - circle.y; - if (CIRCLE_RADIUS_2 - (a * a + b * b) >= 0) { - pattern.push(circle.i); - circles.splice(8, 1); - } - } - } - positions = []; - - pattern = pattern.join(""); - + if (position.b === 0 || positions.length >= 200) { + var pattern = getPattern(positions); + log(pattern); + if (pattern) { if (storedPatterns[pattern]) { var app = storedPatterns[pattern].app; @@ -139,27 +62,15 @@ Bangle.setLCDPower(true); } } - + Bangle.removeListener("drag", dragHandler); load(app.src); } } } - }); - }; - - var debounceTimeoutId; - var debounce = (delay) => { - if (debounceTimeoutId) { - clearTimeout(debounceTimeoutId); + + positions = []; } - - return new Promise((resolve) => { - debounceTimeoutId = setTimeout(() => { - debounceTimeoutId = undefined; - resolve(); - }, delay || 500); - }); }; var sui = Bangle.setUI; diff --git a/apps/ptlaunch/manage_patterns_dark.png b/apps/ptlaunch/manage_patterns_dark.png index 698a19222..c502d23fe 100644 Binary files a/apps/ptlaunch/manage_patterns_dark.png and b/apps/ptlaunch/manage_patterns_dark.png differ diff --git a/apps/ptlaunch/manage_patterns_light.png b/apps/ptlaunch/manage_patterns_light.png index 5e4b27131..13470f450 100644 Binary files a/apps/ptlaunch/manage_patterns_light.png and b/apps/ptlaunch/manage_patterns_light.png differ diff --git a/apps/puzzle15/ChangeLog b/apps/puzzle15/ChangeLog new file mode 100644 index 000000000..0950b7ae0 --- /dev/null +++ b/apps/puzzle15/ChangeLog @@ -0,0 +1,5 @@ +0.01: Initial version, UI mechanics ready, no real game play so far +0.02: Lots of enhancements, menu system not yet functional, but packaging should be now... +0.03: Menu logic now generally functioning, splash screen added. The first really playable version! +0.04: Settings dialog, about screen +0.05: Central game end function diff --git a/apps/puzzle15/README.md b/apps/puzzle15/README.md new file mode 100644 index 000000000..16c0c4593 --- /dev/null +++ b/apps/puzzle15/README.md @@ -0,0 +1,57 @@ +# Puzzle15 - A 15-puzzle for the Bangle.js 2 + +This is a Bangle.js 2 adoption of the famous 15 puzzle. + +## The game + +A board of _n_ by _n_ fields is filled with _n^2-1_ numbered stones. So, one field, the "gap", is left free. + +Bring them in the correct order so that the gap is finally at the bottom right of the playing field. +The less moves you need, the better you are. + +If _n_ is 4, the number of stones is _16-1=15_. Hence the name of the game. + +## How to play + +If you start the game, it shows a splash screen and then generates a shuffled 4x4 board with a 15 puzzle. +Move the stones with drag gestures on the screen. +If you want to move the stone below the gap upward, drag from the bottom of the screen upward. +The drag gestures can be performed anywhere on the screen, there is no need to start or end them on the stone to be moved. + +If you managed to order the stones correctly, a success message appears. +You can continue with another game, go to the game's main menu, or quit the game entirely. + +There is a grey menu button right of the board containing the well-known three-bar menu symbol ("Hamburger menu"). +It opens the game's main menu directly from within the game. + +## The main menu + +Puzzle15 has a main menu which can be reached from the in-game menu button or the end-of-game message window. +It features the following options: + +* **Continue** - Continue the currently running game. _This option is only shown if the main menu is opened during an open game._ +* **Start 3x3**, **Start 4x4**, **Start 5x5** - Start a new game on a board with the respective dimension. Any currently open game is dropped. +* **About** Show a small "About" info box. +* **Exit** Exit Puzzle15 and return to the default watch face. + +## Game settings + +The game has some global settings which can be accessed on the usual way through the Bangle.js' app settings user interface. +Currently it has the following options: + +* **Splash** - Define whether the game should open with a splash screen. **long** shows the splash screen for five seconds, **short** shows it for two seconds. **off** starts the app _without_ a splash screen, it directly comes up with whatever the "Start with" option says. +* **Start with** - What should happen after the splash screen (or, if it is disabled, directly at app start): **3x3**, **4x4** and **5x5** start the game with a board of the respective dimension, **menu** shows the main menu which allows to select the board size. + +## Implementation notes + +The game engine always generates puzzles which can be solved. + +Solvability is detected by counting inversions, +i.e. pairs of stones where the stone at the earlier field (row-wise, left to right, top to bottom) has a number _greater than_ the stone on the later field, with all pairs of stones compared. +The algorithm is described at https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/ . + +## The splash screen + +The Splash screen shows a part of the illustration "The 14-15-puzzle in puzzleland" from Sam Loyd. Other than Puzzle15, it depicts a 15 puzzle with the stones "14" and "15" swapped. This puzzle is indeed *not* solvable. + +Have fun! diff --git a/apps/puzzle15/introscreen.png b/apps/puzzle15/introscreen.png new file mode 100644 index 000000000..766cd61fa Binary files /dev/null and b/apps/puzzle15/introscreen.png differ diff --git a/apps/puzzle15/puzzle15.app-icon.js b/apps/puzzle15/puzzle15.app-icon.js new file mode 100644 index 000000000..04fb4a665 --- /dev/null +++ b/apps/puzzle15/puzzle15.app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwgn/AC3+7oAD7e7AAW8BQndBQe79/9DomgHocH74KD/RJE34Xax4XDtvoC4fJ54XDluAC4f2z4XDzm/C4ett4XD34OBF4e/I4m+C4f8r4XChHuC5U98oXEF4cP7/AC5O9mYXC/2/F4cGtwvE/SsBC4Ws7gvD7YCBL4ULO4i/u1QAD7QED1e6AoetCAnf/YeE1wpD/lgBQcKIAgXG14LD/twC5kL3Z+BC4P+LgIXBg272wXD7wXEh7eCC4PWzIXChHtOoIXB/WX54XDh3KmAXC1oLBI4UD+AXC+/rdIIvD5wvD3O4C4cJ4AXC/dUI4kJhgMBC4Ov+AXDh9QC4X2/gvEhvvoAXC81dC4duR4f8wSncC6v8u4AD3ndAAXcy4KDtYKD7vf/oGE2wRDvPNBQfLFAnP/o2EVIIACg7yBAATZBAAe/C7P9g4XCx+wn/6C4Op//AC4MK+cI/+QC4X2/fPC4PM2HKh8H7vpewIXBhvThV5+AXC+/5C4UL2HHC4Pf/P/AIJHB6cAj2wC4X+3AXPhADBF4fX94XB1va1vOC4PXAIX6hfrxvb0CPD7p3C1e6hW2C4LOBAIIXB3eJ3YXEX78GM4IAC9QXG1QAD7QEDJYIFD14oE//7DwgME/twBQcPC70G6EG5dQ1/8VYPtC4ObgfM5IXHr/whvO4Gvy6LBtX9vfugnr3AXHkXggGOC4P97/43X9ukOgnv6BfIC4Oe2AXC6+nI4MOgfI9QXJhssF4f91AXCgnA9IXHr3u1HusGv3Ob//s/t693l3xHJX9v+3YAD7oAE5YKD34XFAC4=")) diff --git a/apps/puzzle15/puzzle15.app.js b/apps/puzzle15/puzzle15.app.js new file mode 100644 index 000000000..eec21933c --- /dev/null +++ b/apps/puzzle15/puzzle15.app.js @@ -0,0 +1,771 @@ +// A 15-puzzle game for the Bangle.js 2 clock +// (C) Dirk Hillbrecht 2022 +// Released unter the terms of the MIT license + +// The intro screen as large base-64-encoded binary data +const introscreen = E.toArrayBuffer(atob("sLABwAAAAA5QAAACAAAAHAAMEDgA/F/nvoAAAAA+3AAAAAAAAB4AQBIkAPwv//4AAAAAP/wQAAAAAAAAAA3wBAD8P//+AAAAAD7tGQAAAAAAAIADAAMF2C///wAAACA4oRmAHx/wQAAAAAABOfgP//8AAAAAAGEYgA+/AMAAQAAAAAP8B///AAAGAABxMKgD/AAABGAAAAAD/Af//wAAYQAr6TOoAfwAIAWTgAAAA/4D//8SAeCA9W0/mAH8ABAEBAAAAAP+A///YAMRh/5of/ADwMAYOAAAAAAD/gH/f4AMYd/3dv+AAwUABSAAAAAAA/8A/XIAMDrPn///gAMQAADAABgAAAH3APBAAMAdX3/fvjACEAQAAA/mAAAB/wcAAAcAz1/+3/34AgAAgADuF+AAAP8YAA8MEJ+Bt29/GAIAACAADAgwAAD/4AACMAyv/+f/6HwGAABAAE2IoAAAfgAAB8ADf/////mOADh5gABNCCAAAHwB/x4AAX//5/L9D4AAAAYBCQjgAA3QAgBgAAE//7P//jzAAADPAGkAoADggABwAwAC3//F9/5n4AAB/wFpACAHAADAAAEAA///c/v/4jABwf+A8Xwh+AD0BAAAAIfvPm/G/+IYA8P3wPh+P4AHAAAB+ACH//+Hy/9iCAfD/8CYX/QAL9AAAAcAme//z/PrR6gB4P/guPgAAODAGBwAAI8+7gf0P6/oAeD/4bjh//wxA4AAAw2f//8f+f+PiAHwf/+53AA/+AAAAA4Gv/P/9/A/nwgB8D6AuWD8EAAAYAD4A+7/8X/ADr8IAfAwgZlO/AAAHwAH4L2/////mDz9CAD6MB65YAAAAf+A/4D23/n/v4j4fcgA/wDguWAAAB8AD7ngg1////+EAD/Pg8AGDZlmgAP8e4zCX4aP///9AZA/D/4AAAGYf//////4ZwG2j/8H/gwLPggAAAAfWH/////8AQRCpr/+E/9IBT4IAA/hj1h///wFgIqBBO9//33/m6i8CAB8A//YH/gDMfGO/WH/0/5//4gEfAgP4Af+AB/gAHFEBoaTH+/+w/8fQDgI+aP//iifYABRCJ9a9w///+P+H/M4Gw8//34o3yBKkMUW0e3Pt//i6AHxeDg///gouP/poNPAnjzp/3v+2PgDfngz/v3rvjhO6bTTqDWsY//v/nz4LD/4N6bff3YYHu7UU6yZcm////5+3Kgf/CtMP/b+GJ7hr9O41tNB///+XNhAb/hv3kv/7hg7MQn3o+4N5Y9//gx8ME+59P47//gYK6Pnbvc5bu6///48MFl+d93/yv++GAVi+X51IyKqA//+eC4AzP0P3y4//hgb4/83QXYfjAP//1MYbwn9D/77/14YCnf/gIHLX96D//5WGA8Z7Bnf7b/8GgKG94GXuU9y4P/+DwwCeeafvfm93hubX8dvF3E6Ar/N/54OATj2Du/Pv/qY10/zTBB1h+CAff/8AwH4dmb6t7/2mN+IuRyI4CBngD///AMx6Xsnve+09pkNvgsQwAAWAHwo/+hBAeh5Czt5/HcZxSQ6AceCAAiAK/9ggQHBNBuZ5eQvGOducgFgA1BxADx5MIEX/Jo2p8YR/xjt4wINYAfYAf/K4TDAV8Ye48DLBDXY46ADQmBIe+HoSOMgwj5hFqH+CAB78O6AAX4gACAAgMPjYEK4f//7p/2f/NjOuAH8MAACACb5YmCCsDSPnbADz7w49+lI8BAAAf8aICRgAjACB/O4Ag1VcMuD/eAQD/oHISSsYEMzhg/qtABft//7LACAG/gwAMg2MGBCJ4cPD25gBN95Ovn5UA4DgHRncFAxQijj//5KA/jvcL6gAJBEAAf7fBB4MUI+fv/szeEAaqjO/gObYAAAAz57GDpAO5x19BIA/9uYw7gEyMQHwAD/mAg8KBjwv9Giv/vrvKQHBNAEsAUAP9kuP+gZAff+dcEX/ZljjebYDAAAAnf8Pj/YKsH/2E1HEAUQGTB21gwAAAGS5NYv0C6jP1mJY5MEqV0f9fcAfPoHM7qWL/EDg39PGcex7iu+4Bz7B/AD/63qRg/kwML/+DJR9PvOUTAK64RwYAcjek5f/4Yv/aT20L7v0m6gCNvNiYgDI15iE//jH/+2zij+9HsMY8qrA98f+CL9SiP/8//8/gkJ/Ht99M/OogD+MAOifQJj//nH//Y5KPw7//FLBZACAH+Arn8GV//////zMVT36V5sdAecAgCkHqP5H3///4v/+cbUdvIc7wADDAId4AegXuX///////iaVfkvNu/+wYA5Aj/AJl6j////v3/uyOW91wcvqImAZIcQeCBeg/////f/v8MqV/7gZ2cDwICMYAcgXpf////v+/JmJv5/7+B9A+HAiKYA5Bcb//////nxMOI8f92d+APDgZF34SbeU7///72/naafn22WAD/DwwCigR+kHlO///9/9fmWFt/+GMiT8uMARV/F5B/XP///5BTmsGTV/3EADfxlAMsfqjZ/XT///X/l/9FJs//CADDuQgEUnw08vnW/3/38tvx7G3v/BHeOfm4DNT4zpJ7uj///5NI//Cef/gvBlf5uBig8Og/aN////YVe9iWuvnwAD7g/JoxYeF0k/tf///s0U7c8ozbz4BwEHztJoPyrIdrZ//////qz5DpZvcDgBw/7MVHxc+mc+/8P/jL//+PV358GAACPtyKD4SYt/PZ+B////8/+dk/gDgB+G5tNA8fvir/HfNfAG4f/+9q8AAAAABgayg+E0Ot3/flDwADAP/4W/AHAAAAUfJoHizE7/xzww5AMPAAAXoQGADAAH9M/wZF2Sb/b4B3KAQPiLSOMAAAOAA4if/wmz3m+/eAOBwAA/aljmEAAAwAALNz/7Z8v/7/BIgbLwA3jBjNAIAHwAGnD39kTKe//3gBxeAAH0oreAP/+Pok7YH9HgCv7/+gABPAAADcxoADff4h3olwHy/Cvet+YAeAACgO/b+AR//g7geWjwP+/Kf/+IDgAeQXeEt3A+53AH4dKMDH//wnu/BIwDAYIbi/VQa/2bol+knwPg99r7/+MIAAAgDQ33L2P+/rLeyTfiaA/Cf/9kgAADYAIN+7f/ef+dj5pzj54Bynf8kiAABM8Dh+/r//+/anc0/A+7wH/9+On8AAHhgsf/1+CAD31mbA4bcDgI//DyQAAwAxrP/f4AgAKfzNlMNlkGib7gABdAYYBrD/3wLwAD//m3DGSPwYn/wA8BZgBg5S//i5AAAD/xR5x5uOHpP4AAQewAAPVn/nwAAAAP4o89mvDjSXsYAfH5AIB9///4Pwfx7+0debX4R09+pgeQHA8Bn/78f/nwAH/5DfLvzgfp3gAAkI0AJxL//+fjAAAP8k/ly4YOgF4no4Z3AAYH/xAL/gAAB7/DyJcGPz9cSA2XgaAPB+2AH/4AAAZ/+BonFj8B3AYAfAtiLg//A5QAQAAOQ/5WZg5qSVwYAAMAxK4P//jcAZyAGbD/sIQctMlYsAD9wclSf//gEAAB/B84H9UEPdm5cgAAAwOKMP//8eAGs/9i/gfaBnmziXYIABwXsRN7f//Cb+D/7fmB1wfzoqvktAAATGQD/3/vwdgAG918YP3h5+Q/0fmAAJMRZb///ZEQAAcT5xV/+A7MCdgIMAABBqt///+WEAADp+MNo/4XkCj4AMAAbILUf///vEhAgkvDH6D/vzA/mAgQIAPBrDpf/7D7+eSThxt4P/pgbnhkYCAQYDs//v/3/7P5Nw8+3g/+gPvgDhDABhgZP3//v3/j828efJsB/YDP8BjhAPM8Hf/9f/9/7eaDPPkwYH/g9BxIAQBAhA9Pa3/v/+3Fi/yz8Fgv+ASUAQYAJuOKH/9///+7yrj7p/MH//4/5CM8AwEw4S+7df/+uxx59ejvh2D//0YA+sAADhDq+d9v+b++M+zR3IfYf9ibgASEcAgCX1br+8i+fz+Nk7memA/J5IADiYYC2XwbbGK0/f/OHydxpz4DxiJgAAICAAY8e/3vd/mP8C5G4y93gP8hOAHhOeAA86rOvEfzQ/hMjudE4GAwlLwAgUcI4wtr77vf9uH+rR3OZI5YCMRvgAQAABDhR73nv8jwf7o5nnmfBx/yV+AIAAP+IY3/lX/ZvB90sxwzTkHiMZn4AAGQAxhXtX33E+8HoPI+ZhzwSAgXfwARwQPlaSv4dyfhg9w2cMw4+PjCYr+AEewAkhdlfvRP5qH/B+/YeODnIiHe4OAYAHCeld7/m88f/4ONkOHh2hjM//gAAAA4AK/n8TOLFp/gIzHjwsyYBXf8AAAACBA153p3ByYH8GZRw4ZMYwpM3wAwAAwA7E3k7j5Ng/zEg4cO0xOKyz3AAgABALQf6M44++D/sYcOD7iMRZHP8AAAAAGOFpkcObPwf7kOHhO3SkGQYbwANgBCDfUyOjun/B+yPjwzPzHJYlf2AOMAAQEjLHd1T+cHxDw4dj+YvjKX/wOBgBwAr/4udN/Zg/4McJxv9xMMLD/GAcACk+o/hOur3Cv/ifD4ZfsMizgO/BHgAEQfC8/bZz8zruHh+KR//FIYA/n2fAAif4ZjrmcnLR/w4jEMH8kQkAAwAJmJEB/j8GSOcFKH/AZjCAz6pCAAAAAHwIho8bjZnNjegf4GxgwD/GUgAGAAB+BIqDh/k3gZKeD/jYRMAB4ZwABwAAIg55/8P3ZwMrM4P/KISAAHimAAOAACIHD//59s8nJDzB/zFMAAAMLwAAi4B7Aen/8P3+7lJpcH9gHAAABzgAACNs+gBs/fx5Pd3ExxgfxngAAAOcCAAMBf4AEB/+P42diY8MD8w4AAAB/wfAOAB4AD4H3w/DcFMOQwP/DAAAAH+B+4AAIAAD8v/X4femHBzl/4AAAAAHwAQAACAAAJ39x/Ct5Dh8Lf/gAAAAAP4AAEh4AADe+/D8HUgxvGf/8AAAAAAOwABf4AAAMT/8fxOQd3i9//8AAAAAAzAAAYAAAD5d/P+5IMxxH//8wAAAAAHYBgCCMAAOPP4fxkHw4Vv/3DAAAAAA5AGAhRwAA/D/D/bD4cMx//wOAAAAADAAf8BAAABwH4f9xzvE/f/4A4AAAAAYAB/gpgAAaf/v+QcPim3//AB4AAAABwAP8AAAABg/8fYeDxmT//wABwAAAAHwD6AADgAHP/h/Dg+1Zf/8=")); + +// *** Global constants from which several other settings are derived + +// Minimum number of pixels to interpret it as drag gesture +const dragThreshold = 10; + +// Maximum number of pixels to interpret a click from a drag event series +const clickThreshold = 3; + +// Number of steps in stone move animation +const animationSteps = 6; + +// Milliseconds to wait between move animation steps +const animationWaitMillis = 30; + +// Total width of the playing field (full screen width) +const fieldw = g.getWidth(); + +// Total height of the playing field (screen height minus widget zones) +const fieldh = g.getHeight() - 48; + + +// *** Global game characteristics + +// Size of the playing field +var stonesPerLine; + +// Size of one field +var stonesize; + +// Actual left start of the playing field (so that it is centered) +var leftstart; + +// Actual top start of the playing field (so that it is centered) +var topstart; + +// Number of stones on the board (needed at several occasions) +var stonesPerBoard; + +// Set the stones per line globally and all derived values, too +function setStonesPreLine(bPL) { + stonesPerLine = bPL; + stonesize = Math.floor(Math.min(fieldw / (stonesPerLine + 1), fieldh / stonesPerLine)) - 2; + leftstart = (fieldw - ((stonesPerLine + 1) * stonesize + 8)) / 2; + topstart = 24 + ((fieldh - (stonesPerLine * stonesize + 6)) / 2); + stonesPerBoard = (stonesPerLine * stonesPerLine); +} + + +// *** Global app settings + +var SETTINGSFILE = "puzzle15.json"; + +// variables defined from settings +var splashMode; +var startWith; + +/* For development purposes +require('Storage').writeJSON(SETTINGSFILE, { + splashMode: "off", + startWith: "5x5", +}); +/* */ + +/* OR (also for development purposes) +require('Storage').erase(SETTINGSFILE); +/* */ + +// Helper method for loading the settings +function def(value, def) { + return (value !== undefined ? value : def); +} + +// Load settings +function loadSettings() { + var settings = require('Storage').readJSON(SETTINGSFILE, true) || {}; + splashMode = def(settings.splashMode, "long"); + startWith = def(settings.startWith, "4x4"); +} + + +// *** Low level helper classes + +// One node of a first-in-first-out storage +class FifoNode { + constructor(payload) { + this.payload = payload; + this.next = null; + } +} + +// Simple first-in-first-out (fifo) storage +// Needed to keep the stone movements in order +class Fifo { + + // Initialize an empty Fifo + constructor() { + this.first = null; + this.last = null; + } + + // Add an element to the end of the internal fifo queue + add(payload) { + if (this.last === null) { // queue is empty + this.first = new FifoNode(payload); + this.last = this.first; + } else { + let newlast = new FifoNode(payload); + this.last.next = newlast; + this.last = newlast; + } + } + + // Returns the first element in the queue, null if it is empty + remove() { + if (this.first === null) + return null; + let oldfirst = this.first; + this.first = this.first.next; + if (this.first === null) + this.last = null; + return oldfirst.payload; + } + + // Returns if the fifo is empty, i.e. it does not hold any elements + isEmpty() { + return (this.first === null); + } + +} + +// Helper class to keep track of tasks +// Executes tasks given by addTask. +// Tasks must call Worker.endTask() when they are finished, for this they get the worker passed as parameter. +// If a task is given with addTask() while another task is still running, +// it is queued and executed once the currently running task and all +// previously scheduled tasks have finished. +// Tasks must be functions with the Worker as first and only parameter. +class Worker { + + // Create an empty worker + constructor() { + this.tasks = new Fifo(); + this.busy = false; + } + + // Add a task to the worker + addTask(task) { + if (this.busy) // other task is running: Queue this task + this.tasks.add(task); + else { // No other task is running: Execute directly + this.busy = true; + task(this); + } + } + + // Called by the task once it finished + endTask() { + if (this.tasks.isEmpty()) // No more tasks queued: Become idle + this.busy = false; + else // Call the next task immediately + this.tasks.remove()(this); + } + +} + +// Evaluate "drag" events from the UI and call handlers for drags or clicks +// The UI sends a drag as a series of events indicating partial movements +// of the finger. +// This class combines such parts to a long drag from start to end +// If the drag is short, it is interpreted as click, +// otherwise as drag. +// The approprate method is called with the data of the drag. +class Dragger { + + constructor(clickHandler, dragHandler, clickThreshold, dragThreshold) { + this.clickHandler = clickHandler; + this.dragHandler = dragHandler; + this.clickThreshold = (clickThreshold === undefined ? 3 : clickThreshold); + this.dragThreshold = (dragThreshold === undefined ? 10 : dragThreshold); + this.dx = 0; + this.dy = 0; + this.enabled = true; + } + + // Enable or disable the Dragger + setEnabled(b) { + this.enabled = b; + } + + // Handle a raw drag event from the UI + handleRawDrag(e) { + if (!this.enabled) + return; + this.dx += e.dx; // Always accumulate + this.dy += e.dy; + if (e.b === 0) { // Drag event ended: Evaluate full drag + if (Math.abs(this.dx) < this.clickThreshold && Math.abs(this.dy) < this.clickThreshold) + this.clickHandler({ + x: e.x - this.dx, + y: e.y - this.dy + }); // take x and y from the drag start + else if (Math.abs(this.dx) > this.dragThreshold || Math.abs(this.dy) > this.dragThreshold) + this.dragHandler({ + x: e.x - this.dx, + y: e.y - this.dy, + dx: this.dx, + dy: this.dy + }); + this.dx = 0; // Clear the drag accumulator + this.dy = 0; + } + } + + // Attach the drag evaluator to the UI + attach() { + Bangle.on("drag", e => this.handleRawDrag(e)); + } +} + +// *** Mid-level game mechanics + +// Representation of a position where a stone is set. +// Stones can be moved from field to field. +// The playing field consists of a fixed set of fields forming a square. +// During an animation, a series of interim field instances is generated +// which represents the locations of a stone during the animation. +class Field { + + // Generate a field with a left and a top coordinate. + // Note that these coordinates are "cooked", i.e. they contain all offsets + // needed place the elements globally correct on the screen + constructor(left, top) { + this.left = left; + this.top = top; + this.centerx = (left + stonesize / 2) + 1; + this.centery = (top + stonesize / 2) + 2; + } + + // Returns whether this field contains the given coordinate + contains(x, y) { + return (this.left < x && this.left + stonesize > x && + this.top < y && this.top + stonesize > y); + } + + // Generate a field for the given playing field index. + // Playing field indexes start at top left with "0" + // and go from left to right line by line from top to bottom. + static forIndex(index) { + return new Field(leftstart + (index % stonesPerLine) * (stonesize + 2), + topstart + (Math.floor(index / stonesPerLine)) * (stonesize + 2)); + + } + // Special field for the result "stone" + static forResult() { + return new Field(leftstart + (stonesPerLine * (stonesize + 2)), + topstart + ((stonesPerLine - 1) * (stonesize + 2))); + } + + // Special field for the menu + static forMenu() { + return new Field(leftstart + (stonesPerLine * (stonesize + 2)), + topstart); + } + +} + +// Representation of a moveable stone of the game. +// Stones are moved from field to field to solve the puzzle +// Stones are numbered from 0 to the maximum number ot stones. +// Stone "0" represents the gap on the playing field. +// The main knowledge of a Stone instance is how to draw itself. +class Stone { + + // Create stone with the given number + // The constructor creates the "draw()" function which is used to draw the stone + constructor(number, targetindex) { + this.number = number; + this.targetindex = targetindex; + // gap: Does not draw anything + if (number === 0) + this.draw = function(field) {}; + else if ((number + (stonesPerLine % 2 == 0 ? (Math.floor((number - 1) / stonesPerLine)) : 0)) % 2 == 0) { + // Black stone + this.draw = function(field) { + g.setFont("Vector", (stonesPerLine === 5 ? 16 : 20)).setFontAlign(0, 0).setColor(0, 0, 0); + g.fillRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + g.setColor(1, 1, 1).drawString(number, field.centerx, field.centery); + }; + } else { + // White stone + this.draw = function(field) { + g.setFont("Vector", (stonesPerLine === 5 ? 16 : 20)).setFontAlign(0, 0).setColor(0, 0, 0); + g.drawRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + g.drawString(number, field.centerx, field.centery); + }; + } + } + + // Returns whether this stone is on its target index + isOnTarget(index) { + return index === this.targetindex; + } +} + +// Helper class which knows how to clear the rectangle opened up by the two given fields +class Clearer { + + // Create a clearer for the area between the two given fields + constructor(startfield, endfield) { + this.minleft = Math.min(startfield.left, endfield.left); + this.mintop = Math.min(startfield.top, endfield.top); + this.maxleft = Math.max(startfield.left, endfield.left); + this.maxtop = Math.max(startfield.top, endfield.top); + } + + // Clear the area defined by this clearer + clearArea() { + g.setColor(1, 1, 1); + g.fillRect(this.minleft, this.mintop, + this.maxleft + stonesize, this.maxtop + stonesize); + } + +} + +// Helper class which moves a stone between two fields +class Mover extends Clearer { + + // Create a mover which moves the given stone from startfield to endfield + // and animate the move in the given number of steps + constructor(stone, startfield, endfield, steps) { + super(startfield, endfield); + this.stone = stone; + this.startfield = startfield; + this.endfield = endfield; + this.steps = steps; + } + + // Create the coordinate between start and end for the given step + // Computation uses sinus for a smooth movement + stepCoo(start, end, step) { + return start + ((end - start) * ((1 + Math.sin((step / this.steps) * Math.PI - (Math.PI / 2))) / 2)); + } + + // Compute the interim field for the stone to place during the animation + stepField(step) { + return new Field( + (this.minleft === this.maxleft ? this.minleft : + this.stepCoo(this.startfield.left, this.endfield.left, step)), + (this.mintop === this.maxtop ? this.mintop : + this.stepCoo(this.startfield.top, this.endfield.top, step))); + } + + // Perform one animation step + animateStep(step, worker) { + this.clearArea(); + this.stone.draw(this.stepField(step)); + if (step < this.steps) // still steps left: Issue next step + setTimeout(function(t) { + t.animateStep(step + 1, worker); + }, animationWaitMillis, this); + else // all steps done: Inform the worker + worker.endTask(); + } + + // Start the animation, this method is called by the worker + animate(worker) { + this.animateStep(1, worker); + } + +} + +// Representation of the playing field +// Knows to draw the field and to move a stone into a gap +class Board { + + // Generates the actual playing field with all fields and stones + constructor() { + this.fields = []; + this.resultField = Field.forResult(); + this.menuField = Field.forMenu(); + for (i = 0; i < stonesPerBoard; i++) + this.fields[i] = Field.forIndex(i); + this.setShuffled(); + //this.setAlmostSolved(); // to test the game end + } + + /* Set the board into the "solved" position. Useful for showcasing and development + setSolved() { + this.stones = []; + for (i = 0; i < stonesPerBoard; i++) + this.stones[i] = new Stone((i + 1) % stonesPerBoard, i); + this.moveCount = 0; + } + /* */ + + /* Initialize an almost solved playing field. Useful for tests and development + setAlmostSolved() { + this.setSolved(); + b = this.stones[this.stones.length - 1]; + this.stones[this.stones.length - 1] = this.stones[this.stones.length - 2]; + this.stones[this.stones.length - 2] = b; + } + /* */ + + // Initialize a shuffled field. The fields are always solvable. + setShuffled() { + let nrs = []; // numbers of the stones + for (i = 0; i < stonesPerBoard; i++) + nrs[i] = i; + this.stones = []; + let count = stonesPerBoard; + for (i = 0; i < stonesPerBoard; i++) { + // Take a random number of the (remaining) numbers + let curridx = Math.floor(Math.random() * count); + let currnr = nrs[curridx]; + // Initialize the next stone with that random number + this.stones[i] = new Stone(currnr, (currnr + (stonesPerBoard - 1)) % stonesPerBoard); + // Remove the number just taken from the list of numbers + for (j = curridx + 1; j < count; j++) + nrs[j - 1] = nrs[j]; + count -= 1; + } + // not solvable: Swap the first and second stone which are not the gap. + // This will always result in a solvable board. + if (!this.isSolvable()) { + let a = (this.stones[0].number === 0 ? 2 : 0); + let b = (this.stones[1].number === 0 ? 2 : 1); + let bx = this.stones[a]; + this.stones[a] = this.stones[b]; + this.stones[b] = bx; + } + this.moveCount = 0; + } + + // Draws the complete playing field + draw() { + new Clearer(this.fields[0], this.fields[this.fields.length - 1]).clearArea(); + for (i = 0; i < this.fields.length; i++) + this.stones[i].draw(this.fields[i]); + this.drawResult(null); + this.drawMenu(); + } + + // returns the index of the field left of the field with the given index, + // -1 if there is none (index indicates already a leftmost field on the board) + leftOf(index) { + return (index % stonesPerLine === 0 ? -1 : index - 1); + } + + // returns the index of the field right of the field with the given index, + // -1 if there is none (index indicates already a rightmost field on the board) + rightOf(index) { + return (index % stonesPerLine === (stonesPerLine - 1) ? -1 : index + 1); + } + + // returns the index of the field top of the field with the given index, + // -1 if there is none (index indicates already a topmost field on the board) + topOf(index) { + return (index >= stonesPerLine ? index - stonesPerLine : -1); + } + + // returns the index of the field bottom of the field with the given index, + // -1 if there is none (index indicates already a bottommost field on the board) + bottomOf(index) { + return (index < (stonesPerLine - 1) * stonesPerLine ? index + stonesPerLine : -1); + } + + // Return the index of the gap in the field, -1 if there is none (should never happel) + indexOf0() { + for (i = 0; i < this.stones.length; i++) + if (this.stones[i].number === 0) + return i; + return -1; + } + + // Returns the row in which the gap is, 0 is upmost + rowOf0() { + let idx = this.indexOf0(); + if (idx < 0) + return -1; + return Math.floor(idx / stonesPerLine); + } + + // Searches the gap on the field and then moves one of the adjacent stones into it. + // The stone is selected by the given startfunc which returns the index + // of the selected adjacent field. + // Startfunc is one of (left|right|top|bottom)Of. + moveTo0(startfunc, worker) { + let endidx = this.indexOf0(); // Target field (the gap) + if (endidx === -1) { + worker.endTask(); + return; + } + let startidx = startfunc(endidx); // Start field (relative to the gap) + if (startidx === -1) { + worker.endTask(); + return; + } + // Replace in the internal representation + let moved = this.stones[startidx]; + this.stones[startidx] = this.stones[endidx]; + this.stones[endidx] = moved; + this.moveCount += 1; + // Move on screen using an animation effect. + new Mover(moved, this.fields[startidx], this.fields[endidx], animationSteps).animate(worker); + } + + // Move the stone right from the gap into the gap + moveRight(worker) { + this.moveTo0(this.leftOf, worker); + } + + // Move the stone left from the gap into the gap + moveLeft(worker) { + this.moveTo0(this.rightOf, worker); + } + + // Move the stone above the gap into the gap + moveUp(worker) { + this.moveTo0(this.bottomOf, worker); + } + + // Move the stone below the gap into the gap + moveDown(worker) { + this.moveTo0(this.topOf, worker); + } + + // Check if the board is solved (all stones at the right position) + isSolved() { + for (i = 0; i < this.stones.length; i++) + if (!this.stones[i].isOnTarget(i)) + return false; + return true; + } + + // counts the inversions on the board + // see https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/ + getInversionCount() { + let inversions = 0; + for (outer = 0; outer < stonesPerBoard - 1; outer++) { + let outernr = this.stones[outer].number; + if (outernr === 0) + continue; + for (inner = outer + 1; inner < stonesPerBoard; inner++) { + let innernr = this.stones[inner].number; + if (innernr > 0 && outernr > innernr) + inversions++; + } + } + return inversions; + } + + // return whether the puzzle is solvable + // see https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/ + isSolvable() { + let invs = this.getInversionCount(); + if (stonesPerLine % 2 !== 0) // odd number of rows/columns + return (invs % 2 === 0); + else { + return ((invs + this.rowOf0()) % 2 !== 0); + } + } + + // draw the result field, pass null as argument if not called from worker + drawResult(worker) { + let field = this.resultField; + let solved = this.isSolved(); + if (solved) + g.setColor(0, 1, 0); + else + g.setColor(1, 0, 0); + g.fillRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + g.setColor(0, 0, 0); + g.drawRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + g.setFont("Vector", 14).setFontAlign(0, 0).drawString(this.moveCount, field.centerx, field.centery); + if (worker !== null) + worker.endTask(); + if (solved) + setTimeout(() => { + gameEnd(this.moveCount); + }, 500); + } + + // draws the menu button + drawMenu() { + let field = this.menuField; + g.setColor(0.5, 0.5, 0.5); + g.fillRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + g.setColor(0, 0, 0); + g.drawRect(field.left, field.top, field.left + stonesize, field.top + stonesize); + let l = field.left + 8; + let r = field.left + stonesize - 8; + let t = field.top + 5; + for (i = 0; i < 3; i++) + g.fillRect(l, t + (i * 6), r, t + (i * 6) + 2); + } + +} + + +// *** Global helper methods + +// draw some text with some surrounding to increase contrast +// text is drawn at given (x,y) position with textcol. +// frame is drawn 2 pixels around (x,y) in each direction in framecol. +function framedText(text, x, y, textcol, framecol) { + g.setColor(framecol); + for (i = -2; i < 3; i++) + for (j = -2; j < 3; j++) { + if (i === 0 && j === 0) + continue; + g.drawString(text, x + i, y + j); + } + g.setColor(textcol).drawString(text, x, y); +} + +// Show the splash screen at program start, call afterSplash afterwards. +// If spash mode is "off", call afterSplash directly. +function showSplash(afterSplash) { + if (splashMode === "off") + afterSplash(); + else { + g.reset(); + g.drawImage(introscreen, 0, 0); + setTimeout(() => { + g.setFont("Vector", 40).setFontAlign(0, 0); + framedText("15", g.getWidth() / 2, g.getHeight() / 2 - g.getFontHeight() * 0.66, "#f00", "#fff"); + setTimeout(() => { + g.setFont("Vector", 40).setFontAlign(0, 0); + framedText("Puzzle", g.getWidth() / 2, g.getHeight() / 2 + g.getFontHeight() * 0.66, "#f00", "#fff"); + setTimeout(afterSplash, (splashMode === "long" ? 2000 : 1000)); + }, (splashMode === "long" ? 1000 : 1)); + }, (splashMode === "long" ? 2000 : 1000)); + } +} + + +// *** Global flow control + +// Initialize the game with an explicit number of stones per line +function initGame(bpl) { + setStonesPreLine(bpl); + newGame(); +} + +// Start a new game with the same number of stones per line as before +function newGame() { + board = new Board(); + continueGame(); +} + +// Continue the currently running game +function continueGame() { + E.showMenu(); + board.draw(); + dragger.setEnabled(true); +} + +// Show message on game end, allows to restart new game +function gameEnd(moveCount) { + dragger.setEnabled(false); + E.showPrompt("You solved the\n" + stonesPerLine + "x" + stonesPerLine + " puzzle in\n" + moveCount + " move" + (moveCount === 1 ? "" : "s") + ".", { + title: "Puzzle solved", + buttons: { + "Again": newGame, + "Menu": () => showMenu(false), + "Exit": exitGame + } + }).then(v => { + E.showPrompt(); + setTimeout(v, 10); + }); +} + +// A tiny about screen +function showAbout(doContinue) { + E.showAlert("Author: Dirk Hillbrecht\nLicense: MIT", "Puzzle15").then(() => { + if (doContinue) + continueGame(); + else + showMenu(false); + }); +} + +// Show the in-game menu allowing to start a new game +function showMenu(withContinue) { + var mainmenu = { + "": { + "title": "15 Puzzle" + } + }; + if (withContinue) + mainmenu.Continue = continueGame; + mainmenu["Start 3x3"] = () => initGame(3); + mainmenu["Start 4x4"] = () => initGame(4); + mainmenu["Start 5x5"] = () => initGame(5); + mainmenu.About = () => showAbout(withContinue); + mainmenu.Exit = exitGame; + dragger.setEnabled(false); + g.clear(true); + E.showMenu(mainmenu); +} + +// Handle a "click" event (only needed for menu button) +function handleclick(e) { + if (board.menuField.contains(e.x, e.y)) + setTimeout(() => showMenu(true), 10); +} + +// Handle a drag event (moving the stones around) +function handledrag(e) { + worker.addTask(Math.abs(e.dx) > Math.abs(e.dy) ? + (e.dx > 0 ? e => board.moveRight(e) : e => board.moveLeft(e)) : + (e.dy > 0 ? e => board.moveDown(e) : e => board.moveUp(e))); + worker.addTask(e => board.drawResult(e)); +} + +// exit the game, clear screen first to prevent ghost images +function exitGame() { + g.clear(true); + setTimeout(load, 300); +} + + +// *** Main program + +g.clear(true); + +// Load global app settings +loadSettings(); + +// We need a worker... +var worker = new Worker(); + +// Board will be initialized after the splash screen has been shown +var board; + +// Dragger is needed for interaction during the game +var dragger = new Dragger(handleclick, handledrag, clickThreshold, dragThreshold); + +// Disable dragger as board is not yet initialized +dragger.setEnabled(false); + +// Nevertheless attach it so that it is ready once the game starts +dragger.attach(); + +// Start the game by handling the splash screen sequence +showSplash(() => { + // Clock mode allows short-press on button to exit + Bangle.setUI("clock"); + // Load widgets + Bangle.loadWidgets(); + Bangle.drawWidgets(); + if (startWith === "3x3") + initGame(3); + else if (startWith === "4x4") + initGame(4); + else if (startWith === "5x5") + initGame(5); + else + showMenu(false); +}); + +// end of file \ No newline at end of file diff --git a/apps/puzzle15/puzzle15.app.png b/apps/puzzle15/puzzle15.app.png new file mode 100644 index 000000000..f95366a46 Binary files /dev/null and b/apps/puzzle15/puzzle15.app.png differ diff --git a/apps/puzzle15/puzzle15.settings.js b/apps/puzzle15/puzzle15.settings.js new file mode 100644 index 000000000..352ec4315 --- /dev/null +++ b/apps/puzzle15/puzzle15.settings.js @@ -0,0 +1,50 @@ +// Settings menu for the Puzzle15 app + +(function(back) { + var FILE = "puzzle15.json"; + // Load settings + var settings = Object.assign({ + splashMode: "long", + startWith: "4x4" + }, require('Storage').readJSON(FILE, true) || {}); + + function writeSettings() { + require('Storage').writeJSON(FILE, settings); + } + + // Helper method which uses int-based menu item for set of string values + function stringItems(startvalue, writer, values) { + return { + value: (startvalue === undefined ? 0 : values.indexOf(startvalue)), + format: v => values[v], + min: 0, + max: values.length - 1, + wrap: true, + step: 1, + onchange: v => { + writer(values[v]); + writeSettings(); + } + }; + } + + // Helper method which breaks string set settings down to local settings object + function stringInSettings(name, values) { + return stringItems(settings[name], v => settings[name] = v, values); + } + + var mainmenu = { + "": { + "title": "15 Puzzle" + }, + "< Back": () => back(), + "Splash": stringInSettings("splashMode", ["long", "short", "off"]), + "Start with": stringInSettings("startWith", ["3x3", "4x4", "5x5", "menu"]) + }; + + // Actually display the menu + E.showMenu(mainmenu); + +}); + +// end of file \ No newline at end of file diff --git a/apps/puzzle15/screenshot.png b/apps/puzzle15/screenshot.png new file mode 100644 index 000000000..3a79a3ae6 Binary files /dev/null and b/apps/puzzle15/screenshot.png differ diff --git a/apps/qmsched/ChangeLog b/apps/qmsched/ChangeLog index f41fe3416..35832a300 100644 --- a/apps/qmsched/ChangeLog +++ b/apps/qmsched/ChangeLog @@ -2,4 +2,5 @@ 0.02: Add widget 0.03: Bangle.js 2 support 0.04: Move Quiet Mode LCD options from global settings to this app -0.05: Avoid immediately redrawing widgets on load \ No newline at end of file +0.05: Avoid immediately redrawing widgets on load +0.06: Fix: don't try to redraw widget when widgets not loaded \ No newline at end of file diff --git a/apps/qmsched/lib.js b/apps/qmsched/lib.js index 9b307769a..e9ed3ec90 100644 --- a/apps/qmsched/lib.js +++ b/apps/qmsched/lib.js @@ -19,5 +19,5 @@ exports.setMode = function(mode) { {quiet:mode} )); exports.applyOptions(mode); - if (WIDGETS && "qmsched" in WIDGETS) WIDGETS["qmsched"].draw(); + if (typeof WIDGETS === "object" && "qmsched" in WIDGETS) WIDGETS["qmsched"].draw(); }; diff --git a/apps/qrcode/ChangeLog b/apps/qrcode/ChangeLog index edcc41cfd..6d9cc0569 100644 --- a/apps/qrcode/ChangeLog +++ b/apps/qrcode/ChangeLog @@ -2,3 +2,4 @@ 0.02: Add posibillity to generate Wifi code. 0.03: Forces integer scaling and adds more configuration (error correction, description, display) 0.04: Allow scanning of QR codes from camera or file +0.05: Change brightness on touch diff --git a/apps/qrcode/custom.html b/apps/qrcode/custom.html index 4920be655..7ae3eb3af 100644 --- a/apps/qrcode/custom.html +++ b/apps/qrcode/custom.html @@ -72,8 +72,10 @@

Additional options:


+ +
-
+

@@ -287,6 +289,14 @@ } var img = imageconverter.canvastoString(document.getElementsByTagName("canvas")[0],{mode:"1bit",output:"string",compression:true}); var app = `var img = ${img}; +${ document.getElementById("preventBrightnessChangeOnTouch").checked ? '' : `var backlight = 0; +Bangle.on('touch', function(button, xy) { + backlight += 0.3; + if (backlight > 1) backlight = 0; + Bangle.setLCDBrightness(backlight); +}); +`} + ${document.getElementById("boostBacklight").checked ? 'Bangle.setLCDBrightness(1);' : ''} ${document.getElementById("stayOn").checked ? 'Bangle.setLCDTimeout(0);' : ''} ${document.getElementById("hideDescription").checked ? '' : `var content = ${JSON.stringify(content)};`} @@ -294,7 +304,7 @@ g.clear(1).setColor(1,1,1).setBgColor(0,0,0); g.fillRect(0,0,g.getWidth()-1,g.getHeight()-1); g.drawImage(img,(g.getWidth()-img[0])/2,(g.getHeight()-img[1])/2); ${ document.getElementById("hideDescription").checked ? '' : `g.setFontAlign(0,0).setFont("6x8").setColor(0,0,0); -g.drawString(content,g.getWidth()/2,g.getHeight()-(g.getHeight()-img[1])/4)); +g.drawString(content,g.getWidth()/2,g.getHeight()-(g.getHeight()-img[1])/4); `} g.setColor(1,1,1); `; diff --git a/apps/rebble/ChangeLog b/apps/rebble/ChangeLog index 16e65d4f9..b9c26b4e3 100644 --- a/apps/rebble/ChangeLog +++ b/apps/rebble/ChangeLog @@ -1,3 +1,4 @@ 0.01: First release 0.02: Fix typo to Purple 0.03: Added dependancy on Pedometer Widget +0.04: Fixed icon and png to 48x48 pixels diff --git a/apps/rebble/README.md b/apps/rebble/README.md index 712fa4e9b..0ecb51d7a 100644 --- a/apps/rebble/README.md +++ b/apps/rebble/README.md @@ -11,6 +11,7 @@ * Uses pedometer widget to get latest step count * Dependant apps are installed when Rebble installs * Uses the whole screen, widgets are made invisible but still run in the background +* The icon is James Dean - 'Rebel Without a Cause' ![](screenshot_rebble.png) ![](screenshot_rebble2.png) diff --git a/apps/rebble/rebble.icon.js b/apps/rebble/rebble.icon.js index 4c898974e..3fc45b820 100644 --- a/apps/rebble/rebble.icon.js +++ b/apps/rebble/rebble.icon.js @@ -1 +1 @@ -require("heatshrink").decompress(atob("oFA4X/AAIHBw3Aiv3HmE/HQQAF/gPEnWqAAOpy2VqoFB3gPIBoIABtQPJ1PVqv1q3qB5OlrNVEIQPK2tlBwOptQPIyvdH4VtrQPI3tbqtdB4OaB5FVH4NV0pgBB5F13//MIIPJ1O2TgWV/o/I1fbB4WpqoPI1NvB4REBJ5APD/wPBD5JOBB4WVqwPH0oPE0oPJ/NX//6AoNVF5HZq3pq2qSYIPI6tX+pNBB5Ol6v6B4IABH5P7//b1oPBN5GlLwPr9IPK1IPC/SvK1QPCOAIPL6te//5B5lW/5ABL5APB/wPB3IPJ1Y/C/yuBF5APC9X+yo/K34LB3QPBtQPJ//23SPB1QPI3eVs2qJwIPJ1flqyeBtQPJtZPBLwIPKzf/1ROCB5OWAQJOBB5QsBAAQGBf5FlB5tVvoPMNQO9B4daB5O+B4aPIqtX35tBB5M1qtbB4i/HB4WvOAjvGB4IpBIQIADB46aBB4t8B49VB54AFB6zrB1Wm1RTBywPI0oPCeQOaB4+ltOlq2V02VqwPOrQPIF5w/PFQIvPB71pH4uqX8g")) +require("heatshrink").decompress(atob("mEw4X/AoOG4EV+/I+dVAAVUCgcFBIYABpIJBgcFoIKEqkQgEH6EH0ILEqAhCgkBqEVBYdAhUBBoU9GAlAlw5CgERgILDIocEgEGoALDlEHwEAlkUg8EBYfAFwVA+BgEqmQjWrBgMQhgvDqmA9Wq1WsNoMALweDBQIAB4E8BYdTpwLD/kA4AXDjwKC1f/IAILDnQLC1//4ALEHQQLCKgILDFwYLB6EATgVABYe///MNgdA3kQEoILGqCNBlfQh//4NAPAVQ+YLBQYM/ocABYfAiEqgE0g6DBF4eAlFrYQZHDoOu1Xo8lgBYtCKIOo9aOBAAJrCBYWv9X/+gXEqSZC/f//4LHz/6DQIjEBYOhgG6BY1a1WggDCB3ojErYTBoEOa4QLF1X9jWrXwILGKYOvBYtfKYX+17iBHYdX1WQgf/34LBUwQLB1cLWIJqCBYdV9W+1+//oLBWQVVqnuD4M/KQoAB/+kBYJGBCwYLCI4P/DQILFnwLCEQ1Vp+q/46CBYtDXgJ1FAAVwfI4ABqAUCBY8A9gLIqEA9ALEKYYLB9YLERwQ=")) diff --git a/apps/rebble/rebble.png b/apps/rebble/rebble.png index 69653015c..acfd37400 100644 Binary files a/apps/rebble/rebble.png and b/apps/rebble/rebble.png differ diff --git a/apps/recorder/ChangeLog b/apps/recorder/ChangeLog index 40240de64..bedc63141 100644 --- a/apps/recorder/ChangeLog +++ b/apps/recorder/ChangeLog @@ -3,3 +3,4 @@ Fix interface.html 0.03: Fix theme and maps/graphing if no GPS 0.04: Multiple bugfixes +0.05: Add recording for coresensor diff --git a/apps/recorder/README.md b/apps/recorder/README.md index ba53a99f2..4a4561f1c 100644 --- a/apps/recorder/README.md +++ b/apps/recorder/README.md @@ -17,6 +17,7 @@ You can record * **GPS** GPS Latitude, Longitude and Altitude * **Steps** Steps counted by the step counter * **HR** Heart rate +* **Core** CoreTemp body temperature **Note:** It is possible for other apps to record information using this app as well. They need to define a `foobar.recorder.js` file - see the `getRecorders` diff --git a/apps/recorder/interface.html b/apps/recorder/interface.html index ad0de4887..0535b2d51 100644 --- a/apps/recorder/interface.html +++ b/apps/recorder/interface.html @@ -18,8 +18,15 @@ ${track[0].Heartrate!==undefined ? ` - Step Count`:``} - + Step Count + `:``} +${track[0].Core!==undefined ? ` + Core Temp + `:``} +${track[0].Skin!==undefined ? ` + Skin Temp + `:``} + Tracks @@ -37,6 +44,12 @@ ${track.map(pt=>` ${0|pt.Heartrate}\n`).join("") ${track[0].Steps!==undefined ? ` ${track.map(pt=>` ${0|pt.Steps}\n`).join("")} `:``} +${track[0].Core!==undefined ? ` +${track.map(pt=>` ${0|pt.Core}\n`).join("")} + `:``} +${track[0].Skin!==undefined ? ` +${track.map(pt=>` ${0|pt.Skin}\n`).join("")} + `:``} @@ -59,8 +72,7 @@ ${track.map(pt=>` ${0|pt.Steps}\n`).join("")} function saveGPX(track, title) { var gpx = ` - - + diff --git a/apps/recorder/widget.js b/apps/recorder/widget.js index 09893bbb7..4d8cdddb1 100644 --- a/apps/recorder/widget.js +++ b/apps/recorder/widget.js @@ -48,7 +48,7 @@ Bangle.removeListener('GPS', onGPS); Bangle.setGPSPower(0,"recorder"); }, - draw : (x,y) => g.setColor(hasFix?"#f00":"#888").drawImage(atob("DAyBAAACADgDuBOAeA4AzAHADgAAAA=="),x,y) + draw : (x,y) => g.setColor(hasFix?"#0ff":"#888").drawImage(atob("DAyBAAACADgDuBOAeA4AzAHADgAAAA=="),x,y) }; }, hrm:function() { @@ -82,6 +82,33 @@ draw : (x,y) => g.setColor(hasBPM?"#f00":"#888").drawImage(atob("DAyBAAAAAD/H/n/n/j/D/B+AYAAAAA=="),x,y) }; }, + + temp:function() { + var core = 0, skin = 0; + var hasCore = false; + function onCore(c) { + core=c.core; + skin=c.skin; + hasCore = true; + } + return { + name : "Core", + fields : ["Core","Skin"], + getValues : () => { + var r = [core,skin]; + return r; + }, + start : () => { + hasCore = false; + Bangle.on('CoreTemp', onCore); + }, + stop : () => { + hasCore = false; + Bangle.removeListener('CoreTemp', onCore); + }, + draw : (x,y) => g.setColor(hasCore?"#0f0":"#888").drawImage(atob("DAyBAAHh0js3EuDMA8A8AWBnDj9A8A=="),x,y) + }; + }, steps:function() { var lastSteps = 0; return { diff --git a/apps/scribble/add_to_apps.json b/apps/scribble/add_to_apps.json deleted file mode 100644 index 054f35d55..000000000 --- a/apps/scribble/add_to_apps.json +++ /dev/null @@ -1,14 +0,0 @@ -{ "id": "scribble", - "name": "Scribble", - "shortName":"Scribble", - "version":"0.01", - "description": "A keyboard on your wrist!", - "icon": "app.png", - "tags": "keyboard, text, scribble", - "supports" : ["BANGLEJS2"], - "readme": "README.md", - "storage": [ - {"name":"scribble.app.js","url":"app.js"}, - {"name":"scribble.img","url":"app-icon.js","evaluate":true} - ] -} diff --git a/apps/sensible/ChangeLog b/apps/sensible/ChangeLog index c50431f51..33e44b70c 100644 --- a/apps/sensible/ChangeLog +++ b/apps/sensible/ChangeLog @@ -2,3 +2,4 @@ 0.02: Corrected variable initialisation 0.03: Advertise app name, added screenshots 0.04: Advertise bar, GPS, HRM and mag services +0.05: Refactored for efficiency, corrected sensor value inaccuracies \ No newline at end of file diff --git a/apps/sensible/sensible.js b/apps/sensible/sensible.js index 3da39998e..73c348556 100644 --- a/apps/sensible/sensible.js +++ b/apps/sensible/sensible.js @@ -124,27 +124,16 @@ function transmitUpdatedSensorData() { isNewMagData = false; } - NRF.setAdvertising(data, { showName: false, interval: 200 }); + let interval = 1000 / data.length; + NRF.setAdvertising(data, { showName: false, interval: interval }); } // Encode the bar service data to fit in a Bluetooth PDU function encodeBarServiceData() { - let tEncoded = Math.round(bar.temperature * 100); - let pEncoded = Math.round(bar.pressure * 100); - let eEncoded = Math.round(bar.altitude * 100); - - if(bar.temperature < 0) { - tEncoded += 0x10000; - } - if(bar.altitude < 0) { - eEncoded += 0x1000000; - } - - let t = [ tEncoded & 0xff, (tEncoded >> 8) & 0xff ]; - let p = [ pEncoded & 0xff, (pEncoded >> 8) & 0xff, (pEncoded >> 16) & 0xff, - (pEncoded >> 24) & 0xff ]; - let e = [ eEncoded & 0xff, (eEncoded >> 8) & 0xff, (eEncoded >> 16) & 0xff ]; + let t = toByteArray(Math.round(bar.temperature * 100), 2, true); + let p = toByteArray(Math.round(bar.pressure * 1000), 4, false); + let e = toByteArray(Math.round(bar.altitude * 100), 3, true); return [ 0x02, 0x01, 0x06, // Flags @@ -157,52 +146,26 @@ function encodeBarServiceData() { // Encode the GPS service data using the Location and Speed characteristic function encodeGpsServiceData() { - let latEncoded = Math.round(gps.lat * 10000000); - let lonEncoded = Math.round(gps.lon * 10000000); - let hEncoded = Math.round(gps.course * 100); - let sEncoded = Math.round(1000 * gps.speed / 36); - - if(gps.lat < 0) { - latEncoded += 0x100000000; - } - if(gps.lon < 0) { - lonEncoded += 0x100000000; - } - - let s = [ sEncoded & 0xff, (sEncoded >> 8) & 0xff ]; - let lat = [ latEncoded & 0xff, (latEncoded >> 8) & 0xff, - (latEncoded >> 16) & 0xff, (latEncoded >> 24) & 0xff ]; - let lon = [ lonEncoded & 0xff, (lonEncoded >> 8) & 0xff, - (lonEncoded >> 16) & 0xff, (lonEncoded >> 24) & 0xff ]; - let h = [ hEncoded & 0xff, (hEncoded >> 8) & 0xff ]; + let s = toByteArray(Math.round(1000 * gps.speed / 36), 2, false); + let lat = toByteArray(Math.round(gps.lat * 10000000), 4, true); + let lon = toByteArray(Math.round(gps.lon * 10000000), 4, true); + let e = toByteArray(Math.round(gps.alt * 100), 3, true); + let h = toByteArray(Math.round(gps.course * 100), 2, false); return [ - 0x02, 0x01, 0x06, // Flags - 0x11, 0x16, 0x67, 0x2a, 0x95, 0x02, s[0], s[1], lat[0], lat[1], lat[2], - lat[3], lon[0], lon[1], lon[2], lon[3], h[0], h[1] // Location and Speed + 0x02, 0x01, 0x06, // Flags + 0x14, 0x16, 0x67, 0x2a, 0x9d, 0x02, s[0], s[1], lat[0], lat[1], lat[2], + lat[3], lon[0], lon[1], lon[2], lon[3], e[0], e[1], e[2], h[0], h[1] + // Location and Speed ]; } // Encode the mag service data using the magnetic flux density 3D characteristic function encodeMagServiceData() { - let xEncoded = mag.x; // TODO: units??? - let yEncoded = mag.y; - let zEncoded = mag.z; - - if(xEncoded < 0) { - xEncoded += 0x10000; - } - if(yEncoded < 0) { - yEncoded += 0x10000; - } - if(yEncoded < 0) { - yEncoded += 0x10000; - } - - let x = [ xEncoded & 0xff, (xEncoded >> 8) & 0xff ]; - let y = [ yEncoded & 0xff, (yEncoded >> 8) & 0xff ]; - let z = [ zEncoded & 0xff, (zEncoded >> 8) & 0xff ]; + let x = toByteArray(mag.x, 2, true); + let y = toByteArray(mag.y, 2, true); + let z = toByteArray(mag.z, 2, true); return [ 0x02, 0x01, 0x06, // Flags @@ -211,6 +174,22 @@ function encodeMagServiceData() { } +// Convert the given value to a little endian byte array +function toByteArray(value, numberOfBytes, isSigned) { + let byteArray = new Array(numberOfBytes); + + if(isSigned && (value < 0)) { + value += 1 << (numberOfBytes * 8); + } + + for(let index = 0; index < numberOfBytes; index++) { + byteArray[index] = (value >> (index * 8)) & 0xff; + } + + return byteArray; +} + + // Update acceleration Bangle.on('accel', function(newAcc) { acc = newAcc; diff --git a/apps/setting/ChangeLog b/apps/setting/ChangeLog index 64844dcbc..4d9881613 100644 --- a/apps/setting/ChangeLog +++ b/apps/setting/ChangeLog @@ -40,3 +40,6 @@ 0.35: Change App/Widget settings to 'App Settings' so it fits on Bangle screen 0.36: Added 'Utils' menu with helpful utilities for restoring Bangle.js 0.37: Going into passkey menu now saves settings with passkey +0.38: Restructed menus as per forum discussion +0.39: Fix misbehaving debug info option +0.40: Moved off into Utils, put System after Apps diff --git a/apps/setting/settings.js b/apps/setting/settings.js index 9cba09d6c..4bdf7f304 100644 --- a/apps/setting/settings.js +++ b/apps/setting/settings.js @@ -61,6 +61,36 @@ if (!settings) resetSettings(); const boolFormat = v => v ? /*LANG*/"On" : /*LANG*/"Off"; function showMainMenu() { + + const mainmenu = { + '': { 'title': 'Settings' }, + '< Back': ()=>load(), + /*LANG*/'Apps': ()=>showAppSettingsMenu(), + /*LANG*/'System': ()=>showSystemMenu(), + /*LANG*/'Bluetooth': ()=>showBLEMenu(), + /*LANG*/'Alerts': ()=>showAlertsMenu(), + /*LANG*/'Utils': ()=>showUtilMenu() + }; + + return E.showMenu(mainmenu); +} + +function showSystemMenu() { + + const mainmenu = { + '': { 'title': 'System' }, + '< Back': ()=>showMainMenu(), + /*LANG*/'Theme': ()=>showThemeMenu(), + /*LANG*/'LCD': ()=>showLCDMenu(), + /*LANG*/'Locale': ()=>showLocaleMenu(), + /*LANG*/'Select Clock': ()=>showClockMenu(), + /*LANG*/'Set Time': ()=>showSetTimeMenu() + }; + + return E.showMenu(mainmenu); +} + +function showAlertsMenu() { var beepMenuItem; if (BANGLEJS2) { beepMenuItem = { @@ -91,12 +121,9 @@ function showMainMenu() { }; } - const mainmenu = { - '': { 'title': 'Settings' }, - '< Back': ()=>load(), - /*LANG*/'App Settings': ()=>showAppSettingsMenu(), - /*LANG*/'BLE': ()=>showBLEMenu(), + '': { 'title': 'Alerts' }, + '< Back': ()=>showMainMenu(), /*LANG*/'Beep': beepMenuItem, /*LANG*/'Vibration': { value: settings.vibrate, @@ -119,23 +146,18 @@ function showMainMenu() { updateOptions(); if ("qmsched" in WIDGETS) WIDGETS["qmsched"].draw(); }, - }, - /*LANG*/'Locale': ()=>showLocaleMenu(), - /*LANG*/'Select Clock': ()=>showClockMenu(), - /*LANG*/'Set Time': ()=>showSetTimeMenu(), - /*LANG*/'LCD': ()=>showLCDMenu(), - /*LANG*/'Theme': ()=>showThemeMenu(), - /*LANG*/'Utils': ()=>showUtilMenu(), - /*LANG*/'Turn Off': ()=>{ if (Bangle.softOff) Bangle.softOff(); else Bangle.off() }, + } }; return E.showMenu(mainmenu); } + function showBLEMenu() { var hidV = [false, "kbmedia", "kb", "joy"]; var hidN = ["Off", "Kbrd & Media", "Kbrd","Joystick"]; E.showMenu({ + '': { 'title': 'Bluetooth' }, '< Back': ()=>showMainMenu(), 'Make Connectable': ()=>makeConnectable(), 'BLE': { @@ -190,7 +212,7 @@ function showThemeMenu() { } var m = E.showMenu({ '':{title:'Theme'}, - '< Back': ()=>showMainMenu(), + '< Back': ()=>showSystemMenu(), 'Dark BW': ()=>{ upd({ fg:cl("#fff"), bg:cl("#000"), @@ -335,7 +357,7 @@ function showWhitelistMenu() { function showLCDMenu() { const lcdMenu = { '': { 'title': 'LCD' }, - '< Back': ()=>showMainMenu(), + '< Back': ()=>showSystemMenu(), 'LCD Brightness': { value: settings.brightness, min: 0.1, @@ -447,7 +469,7 @@ function showLCDMenu() { function showLocaleMenu() { const localemenu = { '': { 'title': 'Locale' }, - '< Back': ()=>showMainMenu(), + '< Back': ()=>showSystemMenu(), 'Time Zone': { value: settings.timezone, min: -11, @@ -476,6 +498,8 @@ function showUtilMenu() { '< Back': ()=>showMainMenu(), 'Debug Info': { value: E.clip(0|settings.log,0,2), + min: 0, + max: 2, format: v => ["Hide","Show","Log"][E.clip(0|v,0,2)], onchange: v => { settings.log = v; @@ -512,7 +536,8 @@ function showUtilMenu() { setTimeout(showMainMenu, 50); } else showUtilMenu(); }); - } + }, + /*LANG*/'Turn Off': ()=>{ if (Bangle.softOff) Bangle.softOff(); else Bangle.off() } }; if (Bangle.factoryReset) { menu['Factory Reset'] = ()=>{ @@ -551,7 +576,7 @@ function showClockMenu() { '': { 'title': 'Select Clock', }, - '< Back': ()=>showMainMenu(), + '< Back': ()=>showSystemMenu(), }; clockApps.forEach((app, index) => { var label = app.name; @@ -578,7 +603,7 @@ function showSetTimeMenu() { '': { 'title': 'Set Time' }, '< Back': function () { setTime(d.getTime() / 1000); - showMainMenu(); + showSystemMenu(); }, 'Hour': { value: d.getHours(), diff --git a/apps/showimg/README.md b/apps/showimg/README.md index 9d7c0067a..0624fd962 100644 --- a/apps/showimg/README.md +++ b/apps/showimg/README.md @@ -1,3 +1,3 @@ Displays an image. I use this app to show my vaccination certificate. -The image is read from the file "showimage.user.img". +The image is read from the file "showimg.user.img". Returns to watch face after 60s/button push. diff --git a/apps/simple_clock/README.md b/apps/simple_clock/README.md new file mode 100644 index 000000000..d44c495c6 --- /dev/null +++ b/apps/simple_clock/README.md @@ -0,0 +1,14 @@ +# Simple Analog Clock # + +This app displays a simple, yet stylish, analog clock. It considers the +currently configured "theme" (and may therefore look different than shown in +the screenshot on your watch depending on which theme you prefer). + +![](app-screenshot.png) + +This clock also acts as an example for the building blocks found in the author's +[GitHub repository](https://github.com/rozek/banglejs-2-activities) + +## License ## + +[MIT License](LICENSE) diff --git a/apps/simple_clock/app-icon.js b/apps/simple_clock/app-icon.js new file mode 100644 index 000000000..9bc0ebfe1 --- /dev/null +++ b/apps/simple_clock/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwwcBIf4AOgPAjgROh/A/+AEZ8DCKH8Gp/4Gp0QCKAARgQRigFACMUICMT7SEcUAkAvK/EAv//BpH8eoYOBAQP//0ECIrvDCIQABj4TB8AREj4RCgIyFn4RJh5HBCJQ1DAA0/UKBuJQZIRgL4wRL4ARhAH4AIg4RQdIwRcnAjiLKIA/ACI=")) \ No newline at end of file diff --git a/apps/simple_clock/app-icon.png b/apps/simple_clock/app-icon.png new file mode 100644 index 000000000..b1dcc461e Binary files /dev/null and b/apps/simple_clock/app-icon.png differ diff --git a/apps/simple_clock/app-screenshot.png b/apps/simple_clock/app-screenshot.png new file mode 100644 index 000000000..ec99c9fc6 Binary files /dev/null and b/apps/simple_clock/app-screenshot.png differ diff --git a/apps/simple_clock/app.js b/apps/simple_clock/app.js new file mode 100644 index 000000000..3c1843cb0 --- /dev/null +++ b/apps/simple_clock/app.js @@ -0,0 +1,230 @@ + let ScreenWidth = g.getWidth(), CenterX = ScreenWidth/2; + let ScreenHeight = g.getHeight(), CenterY = ScreenHeight/2; + + let outerRadius = Math.min(CenterX,CenterY) * 0.9; + + Bangle.loadWidgets(); + +/**** updateClockFaceSize ****/ + + function updateClockFaceSize () { + CenterX = ScreenWidth/2; + CenterY = ScreenHeight/2; + + outerRadius = Math.min(CenterX,CenterY) * 0.9; + + if (global.WIDGETS == null) { return; } + + let WidgetLayouts = { + tl:{ x:0, y:0, Direction:0 }, + tr:{ x:ScreenWidth-1, y:0, Direction:1 }, + bl:{ x:0, y:ScreenHeight-24, Direction:0 }, + br:{ x:ScreenWidth-1, y:ScreenHeight-24, Direction:1 } + }; + + for (let Widget of WIDGETS) { + let WidgetLayout = WidgetLayouts[Widget.area]; // reference, not copy! + if (WidgetLayout == null) { continue; } + + Widget.x = WidgetLayout.x - WidgetLayout.Direction * Widget.width; + Widget.y = WidgetLayout.y; + + WidgetLayout.x += Widget.width * (1-2*WidgetLayout.Direction); + } + + let x,y, dx,dy; + let cx = CenterX, cy = CenterY, r = outerRadius, r2 = r*r; + + x = WidgetLayouts.tl.x; y = WidgetLayouts.tl.y+24; dx = x - cx; dy = y - cy; + if (dx*dx + dy*dy < r2) { + cy = CenterY + 12; dy = y - cy; r2 = dx*dx + dy*dy; r = Math.sqrt(r2); + } + + x = WidgetLayouts.tr.x; y = WidgetLayouts.tr.y+24; dx = x - cx; dy = y - cy; + if (dx*dx + dy*dy < r2) { + cy = CenterY + 12; dy = y - cy; r2 = dx*dx + dy*dy; r = Math.sqrt(r2); + } + + x = WidgetLayouts.bl.x; y = WidgetLayouts.bl.y; dx = x - cx; dy = y - cy; + if (dx*dx + dy*dy < r2) { + cy = CenterY - 12; dy = y - cy; r2 = dx*dx + dy*dy; r = Math.sqrt(r2); + } + + x = WidgetLayouts.br.x; y = WidgetLayouts.br.y; dx = x - cx; dy = y - cy; + if (dx*dx + dy*dy < r2) { + cy = CenterY - 12; dy = y - cy; r2 = dx*dx + dy*dy; r = Math.sqrt(r2); + } + + CenterX = cx; CenterY = cy; outerRadius = r * 0.9; + } + + updateClockFaceSize(); + +/**** custom version of Bangle.drawWidgets (does not clear the widget areas) ****/ + + Bangle.drawWidgets = function () { + var w = g.getWidth(), h = g.getHeight(); + + var pos = { + tl:{x:0, y:0, r:0, c:0}, // if r==1, we're right->left + tr:{x:w-1, y:0, r:1, c:0}, + bl:{x:0, y:h-24, r:0, c:0}, + br:{x:w-1, y:h-24, r:1, c:0} + }; + + if (global.WIDGETS) { + for (var wd of WIDGETS) { + var p = pos[wd.area]; + if (!p) continue; + + wd.x = p.x - p.r*wd.width; + wd.y = p.y; + + p.x += wd.width*(1-2*p.r); + p.c++; + } + + g.reset(); // also loads the current theme + + if (pos.tl.c || pos.tr.c) { + g.setClipRect(0,h-24,w-1,h-1); + g.reset(); // also (re)loads the current theme + } + + if (pos.bl.c || pos.br.c) { + g.setClipRect(0,h-24,w-1,h-1); + g.reset(); // also (re)loads the current theme + } + + try { + for (wd of WIDGETS) { + g.clearRect(wd.x,wd.y, wd.x+wd.width-1,23); + wd.draw(wd); + } + } catch (e) { print(e); } + } + }; + + let HourHandLength = outerRadius * 0.5; + let HourHandWidth = 2*3, halfHourHandWidth = HourHandWidth/2; + + let MinuteHandLength = outerRadius * 0.7; + let MinuteHandWidth = 2*2, halfMinuteHandWidth = MinuteHandWidth/2; + + let SecondHandLength = outerRadius * 0.9; + let SecondHandOffset = 6; + + let twoPi = 2*Math.PI; + let Pi = Math.PI; + let halfPi = Math.PI/2; + + let sin = Math.sin, cos = Math.cos; + + let HourHandPolygon = [ + -halfHourHandWidth,halfHourHandWidth, + -halfHourHandWidth,halfHourHandWidth-HourHandLength, + halfHourHandWidth,halfHourHandWidth-HourHandLength, + halfHourHandWidth,halfHourHandWidth, + ]; + + let MinuteHandPolygon = [ + -halfMinuteHandWidth,halfMinuteHandWidth, + -halfMinuteHandWidth,halfMinuteHandWidth-MinuteHandLength, + halfMinuteHandWidth,halfMinuteHandWidth-MinuteHandLength, + halfMinuteHandWidth,halfMinuteHandWidth, + ]; + +/**** drawClockFace ****/ + + function drawClockFace () { + g.setColor(g.theme.fg); + g.setFont('Vector', 22); + + g.setFontAlign(0,-1); + g.drawString('12', CenterX,CenterY-outerRadius); + + g.setFontAlign(1,0); + g.drawString('3', CenterX+outerRadius,CenterY); + + g.setFontAlign(0,1); + g.drawString('6', CenterX,CenterY+outerRadius); + + g.setFontAlign(-1,0); + g.drawString('9', CenterX-outerRadius,CenterY); + } + +/**** transforme polygon ****/ + + let transformedPolygon = new Array(HourHandPolygon.length); + + function transformPolygon (originalPolygon, OriginX,OriginY, Phi) { + let sPhi = sin(Phi), cPhi = cos(Phi), x,y; + + for (let i = 0, l = originalPolygon.length; i < l; i+=2) { + x = originalPolygon[i]; + y = originalPolygon[i+1]; + + transformedPolygon[i] = OriginX + x*cPhi + y*sPhi; + transformedPolygon[i+1] = OriginY + x*sPhi - y*cPhi; + } + } + +/**** draw clock hands ****/ + + function drawClockHands () { + let now = new Date(); + + let Hours = now.getHours() % 12; + let Minutes = now.getMinutes(); + let Seconds = now.getSeconds(); + + let HoursAngle = (Hours+(Minutes/60))/12 * twoPi - Pi; + let MinutesAngle = (Minutes/60) * twoPi - Pi; + let SecondsAngle = (Seconds/60) * twoPi - Pi; + + g.setColor(g.theme.fg); + + transformPolygon(HourHandPolygon, CenterX,CenterY, HoursAngle); + g.fillPoly(transformedPolygon); + + transformPolygon(MinuteHandPolygon, CenterX,CenterY, MinutesAngle); + g.fillPoly(transformedPolygon); + + let sPhi = Math.sin(SecondsAngle), cPhi = Math.cos(SecondsAngle); + + g.setColor(g.theme.fg2); + g.drawLine( + CenterX + SecondHandOffset*sPhi, + CenterY - SecondHandOffset*cPhi, + CenterX - SecondHandLength*sPhi, + CenterY + SecondHandLength*cPhi + ); + } + +/**** refreshDisplay ****/ + + let Timer; + function refreshDisplay () { + g.clear(true); // also loads current theme + + Bangle.drawWidgets(); + + drawClockFace(); + drawClockHands(); + + let Pause = 1000 - (Date.now() % 1000); + Timer = setTimeout(refreshDisplay,Pause); + } + + setTimeout(refreshDisplay, 500); // enqueue first draw request + + Bangle.on('lcdPower', (on) => { + if (on) { + if (Timer != null) { clearTimeout(Timer); Timer = undefined; } + refreshDisplay(); + } + }); + + Bangle.loadWidgets(); + + Bangle.setUI('clock'); diff --git a/apps/slash/ChangeLog b/apps/slash/ChangeLog new file mode 100644 index 000000000..f3fae1785 --- /dev/null +++ b/apps/slash/ChangeLog @@ -0,0 +1 @@ +0.01: First version for upload diff --git a/apps/slash/README.md b/apps/slash/README.md new file mode 100644 index 000000000..9bef104cc --- /dev/null +++ b/apps/slash/README.md @@ -0,0 +1,11 @@ +# Slash Watch + +![](screenshot.png) + +Slash Watch, a recreation of the Slash watch face for Pebble watches by Nikki. +Simple watchface with a slash through the hours and minutes. Date shown at the bottom. Theme will change (light/dark) based on watch theme. + +This watch face was made using Espruino documentation, Espruino forum threads, the 93 Dub watch face, the barclock watch face, and the waveclk app. + +Contributors: +* Ray Holder (93 Dub watchface helped create this one) diff --git a/apps/slash/app-icon.js b/apps/slash/app-icon.js new file mode 100644 index 000000000..a0737974a --- /dev/null +++ b/apps/slash/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwwgEBgUiACUgC4IWTAAIuVGAQWVAH4A/AH4AmmQWVl//C6s//4wPkfzAof/F4U/DRgpFC4Uj/4hEFw4RBC4QTDBIouJEoYrEBQouLRwXyBZAuKAwQXCGBQiHPgowJEI6mDGBYXXHIy6GPBQhFRwJ9GVBAiFUwjYNEYiOFa5YkFC4guMFYqOEPgwwIBoSmFn4uLJYopMABKOEACUjCyoA/AH4A/AE0CCysggAXVgEAGCguB")) diff --git a/apps/slash/app.js b/apps/slash/app.js new file mode 100644 index 000000000..f548bcaf7 --- /dev/null +++ b/apps/slash/app.js @@ -0,0 +1,109 @@ +// Get 12 hour status, from barclock +const is12Hour = (require("Storage").readJSON("setting.json", 1) || {})["12hour"]; + +// Used from waveclk to schedule updates every minute +var drawTimeout; + +// Schedule a draw for the next minute +function queueDraw() { + if (drawTimeout) clearTimeout(drawTimeout); + drawTimeout = setTimeout(function() { + drawTimeout = undefined; + draw(); + }, 60000 - (Date.now() % 60000)); +} + +// From forum conversation 348275 +function fillLine(x1, y1, x2, y2, lineWidth) { + var dx, dy, d; + if (!lineWidth) { + g.drawLine(x1, y1, x2, y2); + } else { + lineWidth = (lineWidth - 1) / 2; + dx = x2 - x1; + dy = y2 - y1; + d = Math.sqrt(dx * dx + dy * dy); + dx = Math.round(dx * lineWidth / d, 0); + dy = Math.round(dy * lineWidth / d, 0); + g.fillPoly([x1 + dx, y1 - dy, x1 - dx, y1 + dy, x2 - dx, y2 + dy, x2 + dx, y2 - dy], true); + } +} + +// Mainly to convert day number to day of the week +function convertDate(date) { + var dayNum = date.getDay(); + var month = date.getMonth(); + var dayOfMonth = date.getDate(); + var dayChar; + + month += 1; + + switch (dayNum) { + case 0 : dayChar = "Sun"; break; + case 1 : dayChar = "Mon"; break; + case 2 : dayChar = "Tue"; break; + case 3 : dayChar = "Wed"; break; + case 4 : dayChar = "Thur"; break; + case 5 : dayChar = "Fri"; break; + case 6 : dayChar = "Sat"; break; + } + + return dayChar + " " + month + "/" + dayOfMonth; +} + +function draw() { + var d = new Date(); + var h = d.getHours(), m = d.getMinutes(); + var minutes = ("0"+m).substr(-2); + g.reset(); + + // Convert to 12hr time mode + if (is12Hour && h > 12) { + h = h - 12; + if (h < 10) { + h = "0" + h; + } + } else if (h < 12) { + h = "0" + h; + } else if (h == 0) { + h = 12; + } + + var hour = (" "+h).substr(-2); + + // Draw the time, vector font + g.setFont("Vector", 50); + g.setFontAlign(1,1); // Align right bottom + g.drawString(hour, 85, 80, true); + g.drawString(minutes, 155, 140, true); + + // Draw slash, width 6 + fillLine(57, 120, 112, 40, 6); + + // Convert date then draw + g.setFont("Vector", 20); + g.setFontAlign(0,1); // Align center bottom + var convertedDate = convertDate(d); + g.drawString(convertedDate, g.getWidth()/2, 170, true); + + Bangle.drawWidgets(); + queueDraw(); +} + +// Clear screen and draw +g.clear(); +draw(); + +// From waveclk +Bangle.on('lcdPower',on=>{ + if (on) { + draw(); // Draw immediately, queue redraw + } else { // Stop draw timer + if (drawTimeout) clearTimeout(drawTimeout); + drawTimeout = undefined; + } +}); + +Bangle.setUI("clock"); +Bangle.loadWidgets(); +Bangle.drawWidgets(); diff --git a/apps/slash/screenshot.png b/apps/slash/screenshot.png new file mode 100644 index 000000000..41008d76c Binary files /dev/null and b/apps/slash/screenshot.png differ diff --git a/apps/slash/slash.png b/apps/slash/slash.png new file mode 100644 index 000000000..cbfc8693d Binary files /dev/null and b/apps/slash/slash.png differ diff --git a/apps/slimehunt/ChangeLog b/apps/slimehunt/ChangeLog new file mode 100644 index 000000000..eb0cc5918 --- /dev/null +++ b/apps/slimehunt/ChangeLog @@ -0,0 +1,2 @@ +0.01: Public version is a go! +0.02: Fixed bug where Critial Up wasn't letting player attack. diff --git a/apps/slimehunt/README.md b/apps/slimehunt/README.md new file mode 100644 index 000000000..84d8f2b16 --- /dev/null +++ b/apps/slimehunt/README.md @@ -0,0 +1,77 @@ +<><><><>-SLIME HUNT-<><><><> + +Slime Hunt is a RPG turn-based style combat game +where you fight slimes until your HP runs out. + +The main goal is to beat your personal highscore! + +============================ + +During each fight the player has 3 options, + +BTN1) FIGHT +- Attacks the slime, dealing 1 hp worth of damage. + +BTN2) DEFEND +- Defends against the slime, blocking 3 damage from the next slime attack. + +BTN3) RUN +- Find a new slime to fight against. (This could change in the future!) + +============================ + +There are currently 5 types of slime each with unique behavior. + +<><>-BEHAVIORS-<><> + +1. NEUTRAL +- Slime deals 0-1 damage on it's next attack. + +2. ANGRY +- Slime deals 3-5 damage on it's next attack. + +3. ERACTIC +- Slime deals 0-5 damage on it's next attack. + +<><>-ITEMS-<><> + +1. Attack Up +- +1 damage next battle. + +2. Defence Up +- +1 defence next battle, stacks with block. +Setting defence to 4 when using DEFEND, and 1 otherwise. + +3. HP Up +- +3 HP. + +4. Block Up +- +2 block on DEFEND next battle, +setting Defence to 5 when using DEFEND command. + +5. Critical Up +- 20% chance to crit next battle on each attack, +instantly defeating the Slime. + +*****Using the RUN command causes you to lose your item!***** + +<><>-SLIMES-<><> + +1. GREEN SLIME +- Is always neutral. | 0% chance of item. + +2. RED SLIME +- Can be either neutral or angry. | 10% chance of item. + +3. GRAY SLIME +- Can be neutral, angry or eratic. | 20% chance of item. + +4. YELLOW SLIME +- Is always eratic. | 50% chance of item. + +5. PURPLE SLIME +- Is always angry. | 100% chance of item. + +============================ + +Created by Colton LaChance! diff --git a/apps/slimehunt/app-icon.js b/apps/slimehunt/app-icon.js new file mode 100644 index 000000000..36486cb8a --- /dev/null +++ b/apps/slimehunt/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwxH+If4A/AH4A/AH4A/AH4A/AH4A/AH4A/AH9bxgAM1gtsGTwtTGDVhFSPX64wZLqgwFF6iMVGAhgUF6owBMCzsWAAthL1AAGF/4vxrdhADVbeCQA/AH4A/AH4A/AH4A/AH4A/AH4A/AH4A/AH4AFA")) diff --git a/apps/slimehunt/app.js b/apps/slimehunt/app.js new file mode 100644 index 000000000..547ea7356 --- /dev/null +++ b/apps/slimehunt/app.js @@ -0,0 +1,477 @@ +//Create constants------------------------------------------------------------------ + +//Slimes +const GREEN_SLIME = 1; //Normal slime, is always neutral. | 0% Item chance +const PINK_SLIME = 2; //Can get angry. | 10% Item chance +const GRAY_SLIME = 3; //Can be neutral, angry or erratic. | 20% Item chance +const YELLOW_SLIME = 4; //Is always erratic. | 50% Item chance +const PURPLE_SLIME = 5; //Is always angry. | 100% Item chance + +//Items +const ITEM_ATK_UP = 1; //Raises damage dealt by +1 for next battle +const ITEM_DEF_UP = 2; //Reduces all damage by +1 for next battle +const ITEM_HP_UP = 3; //Increases HP by 3 +const ITEM_BLOCK_UP = 4; //Raises defence when defending by from 3 to 5 for next battle +const ITEM_CRIT_UP = 5; //Gives attack a 20% chance to instantly KO slime for next battle + +//Base stats +const BASE_ATK = 1; +const BASE_DEF = 0; +const BASE_BLOCK = 3; +const BASE_CRIT = 0; + +//Initialize variables------------------------------------------------------------------ +var playerHP = 20; +var slimeHP = 3; +var slimeType = GREEN_SLIME; +var turn = 0; +var screenWidth = g.getWidth(); +var screenHeight = g.getHeight(); +var slimeState = 0; +var showBattleResult = false; +var dmgDealt = 0; +var playerDefence = 0; +var playerItem = 0; +var critChance = 0; + +//Stats (Modifiers) +var statAtk = 1; +var statDef = 0; +var statBlock = 3; +var statCrit = 0; + +//Item vars +var itemName = ""; +var itemDesc = ""; +var itemChance = 0; + +var refreshInterval; +var waitTime = 0; + +var highscore = 0; +var score = 0; + +var themeNote = 0; + +//Load files------------------------------------------------------------------ +var file = require("Storage").open("highscore.txt", "r"); +highscore = file.readLine(); +if (highscore == undefined) highscore = 0; + +var greenSlime = require("Storage").read("slime.img"); +var pinkSlime = require("Storage").read("slimered.img"); +var graySlime = require("Storage").read("slimegray.img"); +var yellowSlime = require("Storage").read("slimeyellow.img"); +var purpleSlime = require("Storage").read("slimepurple.img"); + +//UI Stuff------------------------------------------------------------------ +function drawOpeningUI() { + g.clear(); + g.setFont("Vector", screenWidth / 15); + g.setFontAlign(0, 0); // center font + g.drawString("SLIME HUNT", screenWidth / 2, screenHeight * 0.1); + g.drawString("-SCORE TO BEAT-", screenWidth / 2, screenHeight * 0.3); + g.drawString("<><><> " + highscore + " <><><>", screenWidth / 2, screenHeight * 0.45); + g.setFont("Vector", screenWidth / 20); + g.drawString("A Slime approches...", screenWidth / 2, screenHeight * 0.6); + wait(8, waitForBattle); +} + +function drawSlime() { + switch (slimeType) { + case GREEN_SLIME: + g.drawImage(greenSlime, screenWidth / 2, screenHeight / 2, { + scale: 4, + rotate: 0 + }); + break; + case PINK_SLIME: + g.drawImage(pinkSlime, screenWidth / 2, screenHeight / 2, { + scale: 4, + rotate: 0 + }); + break; + case GRAY_SLIME: + g.drawImage(graySlime, screenWidth / 2, screenHeight / 2, { + scale: 4, + rotate: 0 + }); + break; + case YELLOW_SLIME: + g.drawImage(yellowSlime, screenWidth / 2, screenHeight / 2, { + scale: 4, + rotate: 0 + }); + break; + case PURPLE_SLIME: + g.drawImage(purpleSlime, screenWidth / 2, screenHeight / 2, { + scale: 4, + rotate: 0 + }); + break; + } +} + +function drawBattleUI() { + g.clear(); + g.setFont("Vector", screenWidth / 8); + g.setFontAlign(0, 0); // center font + g.drawString("SLIME HP: " + slimeHP, screenWidth / 2, screenHeight * 0.1); + g.setFont("Vector", screenWidth / 20); + if (!showBattleResult) { + switch (slimeState) { + case 0: + g.drawString("The slime seems neutral...", screenWidth / 2, screenHeight * 0.25); + break; + case 1: + g.drawString("The slime seems angry...", screenWidth / 2, screenHeight * 0.25); + break; + case 2: + g.drawString("The slime seems eratic...", screenWidth / 2, screenHeight * 0.25); + break; + } + } else { + var brString = (turn == 0 ? "The Slime loses " : "You lose "); + g.drawString(brString + dmgDealt + "HP!", screenWidth / 2, screenHeight * 0.25); + } + drawSlime(); + g.drawLine(0, screenHeight * 0.72, screenWidth, screenHeight * 0.72); + if (turn == 0) { + g.setFont("Vector", screenWidth / 15); + g.drawString("Your HP is " + playerHP + ".", screenWidth / 2, screenHeight * 0.8); + g.setFont("Vector", screenWidth / 20); + g.drawString("(B1) FIGHT\t|\t(B2) DEFEND\t|\t(B3) RUN", screenWidth / 2, screenHeight * 0.9); + } +} + +//Win / lose functions------------------------------------------------------------------ +function win() { + wait(5, winTheme); + calcScore(slimeType); + showBattleResult = false; + g.clear(); + g.setFont("Vector", screenWidth / 8); + g.setFontAlign(0, 0); // center font + g.drawString("YOU WON!", screenWidth / 2, screenHeight * 0.1); + g.drawLine(0, screenHeight * 0.2, screenWidth, screenHeight * 0.2); + g.setFont("Vector", screenWidth / 12); + g.drawString((playerItem == 0 ? "No Item." : "GOT ITEM!"), screenWidth / 2, screenHeight * 0.27); + g.setFont("Vector", screenWidth / 15); + g.drawString((playerItem == 0 ? "" : "<><> " + itemName + " <><>"), screenWidth / 2, screenHeight * 0.40); + g.setFont("Vector", screenWidth / 20); + g.drawString((playerItem == 0 ? "" : itemDesc), screenWidth / 2, screenHeight * 0.52); + g.drawLine(0, screenHeight * 0.6, screenWidth, screenHeight * 0.6); + g.drawString("Your score is << " + score + " >>", screenWidth / 2, screenHeight * 0.75); + g.drawString("Press (B3) to find another slime!", screenWidth / 2, screenHeight * 0.9); + turn = 0; + setWatch(run, BTN3); +} + +function lose() { + wait(5, loseTheme); + playerHP = 20; + showBattleResult = false; + g.clear(); + g.setFont("Vector", screenWidth / 8); + g.setFontAlign(0, 0); // center font + g.drawString("You lose...", screenWidth / 2, screenHeight * 0.1); + g.drawLine(0, screenHeight * 0.2, screenWidth, screenHeight * 0.2); + g.setFont("Vector", screenWidth / 12); + g.drawString((score > highscore ? "-NEW HIGHSCORE-" : "-SCORE TO BEAT-"), screenWidth / 2, screenHeight * 0.27); + g.setFont("Vector", screenWidth / 15); + g.drawString((score > highscore ? "<><> " + score + " <><>" : "<><> " + highscore + " <><>"), screenWidth / 2, screenHeight * 0.43); + g.drawLine(0, screenHeight * 0.6, screenWidth, screenHeight * 0.6); + g.setFont("Vector", screenWidth / 20); + g.drawString("Your score is << " + score + " >>", screenWidth / 2, screenHeight * 0.75); + g.drawString("Press (B3) to try again...", screenWidth / 2, screenHeight * 0.9); + score = 0; + turn = 0; + setWatch(run, BTN3); +} + +//Battle Stuff------------------------------------------------------------------ +function nextTurn() { + turn = (turn == 0 ? 1 : 0); +} + +function slimeFight() { + Bangle.beep(100, 500); + switch (slimeState) { + case 0: + dmgDealt = Math.floor(Math.random() * 2); + break; + case 1: + dmgDealt = Math.floor(Math.random() * 3) + 3; + break; + case 2: + dmgDealt = Math.floor(Math.random() * 6); + break; + } + dmgDealt = Math.max(0, dmgDealt - playerDefence); + playerHP -= dmgDealt; + slimeAI(); +} + +function fight() { + if (turn == 0 && waitTime <= 0) { + Bangle.beep(100, 1000); + dmgDealt = statAtk; + playerDefence = statDef; + if (statCrit == 0) { + slimeHP -= dmgDealt; + }else{ + critChance = Math.floor(Math.random() * 100); + if (critChance >= 100-statCrit) { + slimeHP = 0; + dmgDealt = 99; + }else{ + slimeHP -= dmgDealt; + } + critChance = 0; + } + showBattleResult = true; + drawBattleUI(); + wait(5, waitForTurn); + } +} + +function defend() { + if (turn == 0 && waitTime <= 0) { + dmgDealt = 0; + playerDefence = statBlock + statDef; + showBattleResult = true; + drawBattleUI(); + wait(5, waitForTurn); + } +} + +function run() { + if (turn == 0 && waitTime <= 0) { + showBattleResult = false; + Bangle.beep(200, 4000); + wait(3, waitForBattle); + } +} + + +function newBattle() { + showBattleResult = false; + slimeType = Math.floor(Math.random() * 5) + 1; + useItem(); //Use item at start of new battle + switch (slimeType) { + case GREEN_SLIME: + slimeHP = 3; + break; + case PINK_SLIME: + slimeHP = 3; + break; + case GRAY_SLIME: + slimeHP = 5; + break; + case YELLOW_SLIME: + slimeHP = 5; + break; + case PURPLE_SLIME: + slimeHP = 5; + break; + } + turn = 0; + battle(); + slimeAI(); + drawBattleUI(); +} + +function battle() { + setWatch(fight, BTN1); + setWatch(defend, BTN2); + setWatch(run, BTN3); +} + +function slimeAI() { + switch (slimeType) { + case GREEN_SLIME: + slimeState = 0; + break; + case PINK_SLIME: + slimeState = Math.floor(Math.random() * 2); + break; + case GRAY_SLIME: + slimeState = Math.floor(Math.random() * 3); + break; + case YELLOW_SLIME: + slimeState = 2; + break; + case PURPLE_SLIME: + slimeState = 1; + break; + } +} +//Items------------------------------------------------------------------ +function getItem() { + playerItem = Math.floor(Math.random() * 5) + 1; + switch (playerItem) { + case ITEM_ATK_UP: + itemName = "Attack Up"; + itemDesc = "+1 damage next battle."; + break; + case ITEM_DEF_UP: + itemName = "Defence Up"; + itemDesc = "+1 defence next battle."; + break; + case ITEM_HP_UP: + itemName = "HP Up"; + itemDesc = "+3 HP."; + break; + case ITEM_BLOCK_UP: + itemName = "Block Up"; + itemDesc = "+2 block on DEFEND next battle."; + break; + case ITEM_CRIT_UP: + itemName = "Critical Up"; + itemDesc = "20% chance to crit next battle."; + break; + } +} + +function useItem() { + statAtk = BASE_ATK; + statDef = BASE_DEF; + statBlock = BASE_BLOCK; + statCrit = BASE_CRIT; + switch (playerItem) { + case ITEM_ATK_UP: + statAtk = 2; + break; + case ITEM_DEF_UP: + statDef = 1; + break; + case ITEM_HP_UP: + playerHP += 3; + break; + case ITEM_BLOCK_UP: + statBlock = 5; + break; + case ITEM_CRIT_UP: + statCrit = 20; + break; + } + playerItem = 0; +} + +//Timed transitions------------------------------------------------------------------ +function wait(duration, waitFunc) { + waitTime = duration; + if (!refreshInterval) + refreshInterval = setInterval(waitFunc, 500); +} + +function waitForTurn() { + waitTime--; + if (waitTime <= 0) { + clearInterval(refreshInterval); + refreshInterval = undefined; + nextTurn(); + if (playerHP > 0 && slimeHP > 0) { + if (turn == 1) { + slimeFight(); + wait(5, waitForTurn); + } else { + showBattleResult = false; + battle(); + } + drawBattleUI(); + } else { + if (playerHP <= 0) { + lose(); + } + if (slimeHP <= 0) { + win(); + } + } + } + Bangle.setLCDPower(1); +} + +function waitForBattle() { + waitTime--; + Bangle.beep(100, 1000); + if (waitTime <= 0) { + clearInterval(refreshInterval); + refreshInterval = undefined; + showBattleResult = false; + newBattle(); + } + Bangle.setLCDPower(1); +} + +function winTheme() { + waitTime--; + Bangle.beep(200, 100 * themeNote); + themeNote++; + if (waitTime <= 0) { + themeNote = 0; + clearInterval(refreshInterval); + refreshInterval = undefined; + setWatch(run, BTN3); + } + Bangle.setLCDPower(1); +} + +function loseTheme() { + waitTime--; + Bangle.beep(200, 600 - (100 * themeNote)); + themeNote++; + if (waitTime <= 0) { + themeNote = 0; + clearInterval(refreshInterval); + refreshInterval = undefined; + setWatch(run, BTN3); + } + Bangle.setLCDPower(1); +} + +//Calculations------------------------------------------------------------------ +function calcScore(slimeType) { + switch (slimeType) { + case GREEN_SLIME: + score += 1; + //No items + break; + case PINK_SLIME: + score += 2; + itemChance = Math.floor(Math.random() * 100); + if (itemChance >= 100 - 10) { //100 - ITEM CHANCE % + getItem(); + } + break; + case GRAY_SLIME: + score += 3; + itemChance = Math.floor(Math.random() * 100); + if (itemChance >= 100 - 25) { //100 - ITEM CHANCE % + getItem(); + } + break; + case YELLOW_SLIME: + score += 5; + itemChance = Math.floor(Math.random() * 100); + if (itemChance >= 100 - 50) { //100 - ITEM CHANCE % + getItem(); + } + break; + case PURPLE_SLIME: + score += 10; + getItem(); + break; + } + if (score > highscore) { + file.erase(); + file = require("Storage").open("highscore.txt", "w"); + file.write(score); + } +} + + +//------------------------------------GAME STARTS HERE ----------------------------------------------- + +//Load opening UI +drawOpeningUI(); diff --git a/apps/slimehunt/app.png b/apps/slimehunt/app.png new file mode 100644 index 000000000..208e68f46 Binary files /dev/null and b/apps/slimehunt/app.png differ diff --git a/apps/sonicclk/Changelog b/apps/sonicclk/Changelog new file mode 100644 index 000000000..7c83f6988 --- /dev/null +++ b/apps/sonicclk/Changelog @@ -0,0 +1,2 @@ +1.00 Added sonic clock app +1.01 Fixed text alignment issue; Increased acceleration required to activate twist; \ No newline at end of file diff --git a/apps/sonicclk/README.md b/apps/sonicclk/README.md new file mode 100644 index 000000000..a381e0a07 --- /dev/null +++ b/apps/sonicclk/README.md @@ -0,0 +1,13 @@ +# Sonic Clock + +A classic sonic clock featuring run, stop and wait animations. + +![Sonic Clock screenshot](screenshot.png) + +## Usage + +- Sonic will run when the screen is unlocked +- Sonic will stop when the screen is locked +- Sonic will wait when looking at your watch face (when `Bangle.on("twist", fn)` is fired). + +### Made with love by [Joseph](https://github.com/Johoseph) 🤗 diff --git a/apps/sonicclk/app-icon.js b/apps/sonicclk/app-icon.js new file mode 100644 index 000000000..33e22971b --- /dev/null +++ b/apps/sonicclk/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwwkBiIA/AE0ZzIACBIgFFC7oTCylEzOIDYeZogX6LwWd7oYCAAOJC82UpoXFAAKnMC6x2CpIVFC/gSCxOYAYP///4C4X/DBIXWIIwWBDAWPAYIXedQJwG/8AgEP//wgAX2CwIADRoQXmSIoXtJAeEoi+C+lEoAcBogX7zOUondolEpvdAAQXgYIgXCAAwXlAAIYC6ENLx4XtAYMZDAvd6gWJC7IKJABgX/C74A/ADY")) diff --git a/apps/sonicclk/app.js b/apps/sonicclk/app.js new file mode 100644 index 000000000..296677281 --- /dev/null +++ b/apps/sonicclk/app.js @@ -0,0 +1,284 @@ +const vw = g.getWidth(); +const bgWidth = 384; + +const sonic = { + bpp: 4, + transparent: 1, +}; + +const defaultSonic = { + width: 36, + height: 62, + buffer: require("heatshrink").decompress(atob("iIADzIACA4gNECKYOComZxAVDogRXBQfdCQQABCLITCogRFCQIRYLAgAFCQwRQBoQCC///AYYRWGAoMBAAgRYCYf/gEAB4ICBCKrDDCL4UECMA3DolEB4IDBAAQRb7oMB7vdHIIRWCAYRCAAoRWCoozDCBQRRBQI3FERIRPPIbGBPIQiICKAQCdQRZDAYIRXCQIJB/4RDEhQRQGYP//7FEGpARQCAYREgEzERQRNAAIRCLIKkBCLg4CYoIABB5IRWAQQRcBoIODCRYRQB4INECLkRgH/ZAMACRgRSmbGBCIIFBmYWCCLAAC7oCBdgNEAgIRWBQY2B7oTBAwMzCYoRUBIIQBCQQGBHIYRUABwRRA=")), +}; + +const startingBuffers = [ + { + width: 49, + height: 63, + buffer: require("heatshrink").decompress(atob("iIAFzIAEyMRjICBABkZDAogCCxgRBxAACzOUpIzDFxmYC4WJzNEGYgyQzOd6lIDoJiNGQYwB7tEDoQxQI4NN7BPDGJ54BondQAgvPGCjDDGCQVCCAVESAOIx/4GJYuCSIQwBFwX/GJbyEAAmDn///AwJjLyDAAsz/4xBGBAvJGAfwhIwHF5QwDgAwHXwYADGB6+DAAY2EGBYzHGA8P+EAgLyKGBIBBgD3ObwVPGAMEoAwIe4+ZolEGAVEGBRfDAYOUpvd6gaBpvQF5IuBFoOJDANE7vdC4IEBF5h8DGAQABGQNBF5YuCGAgyDYZwxE6lDmcxR5gAFGINEmczF6IxCob1B+YxIF5AxCeoQxJzLNBAAQFBhOUoEDGAIxJjOQC4cJAoIvBgAwCGJIwWiEAgcwglEpOZGwgvCGBANBmcAaIJ2BC4cPC4QwIga3BmEIeoIwBDoJhDF4j5DBgIABgGIGAROBMIYvEilBGAgvDAARIBGQL0FA4IwFF4YABJQIyBoczF4lEGA0JCwWUEoPd7qBCzIwDgAwGF4YXBpvd6iyBzORGAVAgLEEF4YwCF4IwEMYMzGAjECC4YwBF4IwEycxic0GAsN7vRiMZDIQvDBwItBS4IqBGAgQBAgIXCzovCLwItBS4MwgAwCF4XTn/xGIiODF4QwCF40z/4xERwYvCGAQvF7vf+CUEEobvCAAJgEF4Xd/6UEXgTvDAANAMAwwFCwgwESBAwFC4owCF43f/vUoaSCABAvCMAv/aQKSDAA8UF4JgG7/0oIWJGAhgG/9EC5YwCSA5eKFQiQIC5sQF4QwD6hfMGpAvBL5g1IhovVGAQvUGAMEF6owBF6owB")), + }, + { + width: 42, + height: 62, + buffer: require("heatshrink").decompress(atob("iIADzIAEA4QNEAAwUSBwOIAAWZogXECjgWFzPdogECCj5pDondIggUeSAYUjCISRDCQX/CpIUTXQgAEmf/CoIUaCZIUDgAUZRoYADCkIXHCg4BBgAUZX4y+BogUCogUccwgTB7vdCwIEBFA4UTHQYACCgQACogoJCiYAFCoYTHCigTHCoQnICioaJCRwUUHYbhBHpwUTXoQTCmczCpgUTcwYUB/8zAIIUfgDeBCoQUC/4UeRYQPBCoITCHxQUXCYMAgAVBmboKCjCUCAAQPFToIUaMgOIAAIUGBoIUYCoS9DNYIVECYwUWmYVBcIYVBokRBQIUbBoLhB7pjFOYQTGCixpCAwidCCY4UVCoYGFCYIUeBwLaGCZYUVDQ4TRChA")), + }, + { + width: 34, + height: 60, + buffer: require("heatshrink").decompress(atob("iIADzIADBAgOECCALBxAABAYIUDxAQVCQQNBogVFCDAAB7oRFCCwPCogQcNoQQCBoP/CI4QPS4gACmf/CIQQTBwwQEgGIfoQQPfIg1ECC6XFCA4ACCCYRFolECAVECCq5CbobeBAAPdCCgPECAYADoggHCCIRFB4YQQXYwSDOgwQPAAoQDBwMzmYRICB5SCGIYQZB4h0CEBoQKmf/oj/CCQQgHCB4PBAAJ1CxAWBEBAQRmYPBAgJCKCCIyCfoYQXCIKQBB4ndGoIQWiL4BgDaBS4IPBGw4QPBwQSCAgMzCoScECCg4FAAQQVB4IREABAQSAAQtGCCoRDOQYiMCBpxGCCoA==")), + }, + { + width: 44, + height: 62, + buffer: require("heatshrink").decompress(atob("iIAEzIADBAgPFCrIQBxAABAYIZDxAVfC4QSBogaFCsQAB7oWFCsAUCogVmSAQVCCQP/CxgVUYggACmf/CwQVdCYwVEgGIgAVbSoQADCsgYGCowACCroWFolECoVECr7wCAALyB7oXBAYJCJCqgUECoYADokzmYWFCrYWFNoIVceQwXDS4QUBCrYACRwQVDAoIXBCrznCMwRAFAAYpFCqf/mf/CgKZFohQGCrIACS4hFCCQ3dIgIVXIQIUDxAVIBAIVXCYJAFxGITIIVfCwMziOZAIIXEAAIVeAAQFBgBFEDITADCrUAAAoeDCwP/IAX/CrAPBog/CJQoWBHwJsFCrAWBCYpqCCgQNECqwUBCpJrCBooVUIBgABEQwVWokzChRPDCrA/NKIgxJCp4FEAB4VVA")), + }, + { + width: 38, + height: 62, + buffer: require("heatshrink").decompress(atob("iIADzIADBAgOECSgNBxAABAYIWDxASZCgQPBogXFCTgAB7oTFCTQRCogSgPYQSCB4P/CZISRVIgACmf/CYQSXCAwSEgGIgASVdgbvDCToVGCQwACCS4TFolECQVECTLPCe4b4BAAPdCTARECQYADogkJCSYTFCIoSSaIwUDEYwSTAATKCCQa4GCSwRC/8zog3CehASYaIkAmYTGCSYTBCIISEBIITGCSStEZ4YSceo7PBQpASSBAQVFaBISRgChBAIIRCxAkKCSAPBeQI5CK4ITG7oJBCSgRCPoYSFCIISVTwaiEzIREEAISTABH/AAIDBG4YSce4IAB/43MCSQRD7q1CEhwSQRwS1CCTqzDWwgSTA==")), + }, + { + width: 40, + height: 60, + buffer: require("heatshrink").decompress(atob("iIADzIAEA4QNEAAoTRBoOIAAWZogWECbQVFzPdogECCbpkDondIIgTcRIYThCASKDCIX/ChATSWIgAEmf/CgITYCRITDgATXQwYADCb4WHCY4BBgATXWwy1BogTCogTabYgSB7vdCoIDBEwwTSG4YACB4QACogmICaQAFCgYSGCaYSHCgQlHCagZIWIISNCaQ5DmYTB/8zCbq0DogThbYgTDExwTQWIszmazKCagWFbQNEgATcHwpoBomZgAULCaYUFgA8SCZlE7q5DHIITdBQPda4ITDRpQTXMQoUJCbLhCCgUzCgwTWCgIJFMxATVCgQABBYoACCa4IEBQwAICZwA=")), + }, + { + width: 36, + height: 60, + buffer: require("heatshrink").decompress(atob("iIANzIPOCI+ZABWICKwTDxGZogDBAAIRaHAfdCQoRXKQdECLhWCBIQRBAgP/CQwRQB4YAFmf/CQQRUK4YRIgGIgARUdIoReCQgRGAAQRVCQtEogRCogRXBoLqEdYIAB7oRWCAczmYRCAAdEEQ4RNOIR4CCQoQECKJxBogQCCIJcCPYPdCKo1CCIwIBG4QRUSYZ8BGgszUoQRSFIQSBdQbGDQQIVBCKIQCGILJCCAYRBRIKuCCKf/xARIiIRYK4ZYExBYDCKjDBxGICQdEAYQQCCKjcBBQKjFGgayDCKYAGT4gRSCQYRICAgRVCRYRYcIIRdCQSZCG44YFCKArCEiARQAAYTCChwRKA==")), + }, + { + width: 34, + height: 60, + buffer: require("heatshrink").decompress(atob("iIADzIADBAgOECCALBxAABAYIUDxAQVCQQNBogVFCDAAB7oRFCCwPCogQcNoQQCBoP/CI4QPS4gACmf/CIQQTBwwQEgGIfoQQPfIg1ECC6XFCA4ACCCYRFolECAVECCq5C7oADCQLABCCgPBBwkACgogECBwJFCAoPDCCAPFJgJ5BKYJjECCBqBBwf/mYQBAoMzmYRCCCIpCBAIPCA4gQSB4RrBboY6CoggGCCC+DB4YQBOogQRXwYQGU4YQUSYRTEdQgQTWYQzDB4gQVKooABBwYQSRAIQECYgQCHoQQWHQIQDXYLdDCB4RELYQPDCCyOGXYIPKCCAPGCAIgOCBpBLCCKyDBxYQMA==")), + }, + { + width: 36, + height: 60, + buffer: require("heatshrink").decompress(atob("iIANzIPOCI+ZABWICKwTDxGZogDBAAIRaHAfdCQoRXKQdECLhWCBIQRBAgP/CQwRQB4YAFmf/CQQRUK4YRIgGIgARUdIoReCQgRGAAQRVCQtEogRCogRXBoLqEdYIAB7oRWCAczmYRCAAdEEQ4RNOIR4CCQoQECKJxBogQCCIJcCPYwRRGoQRGBAITCCKoACPgI0FUYQSGCJpNDdQbGDQQQRTJooQECIIMBCMMRCKhwDPIMALAoZBCLQADxAABCAQRXogOBUYgUBCLTIDAAQSB/4RYB4oAB/4QDWQYROYowADgDHCCLASGCIYJDCKI2MDQwRQCQgcGQwwRRBAIAGB44RPA==")), + }, + { + width: 34, + height: 60, + buffer: require("heatshrink").decompress(atob("iIADzIADBAgOECCALBxAABAYIUDxAQVCQQNBogVFCDAAB7oRFCCwPCogQcNoQQCBoP/CI4QPS4gACmf/CIQQTBwwQEgGIfoQQPfIg1ECC6XFCA4ACCCYRFolECAVECCq5CbobeBAAPdCCgPDmczCAQADoggGCBkAA4RPBCIoPDCCAPDCAZXCOgoQQJYgQEBwJbBCIQQUBAIxFCCgPDboi7DEA4QPXwYPDCAJ1GCDQJCA4YQPB4hTEdQYQXgCXDB4YQVawQDBxAFBBwYQVAAYQBGAoABCCCqBBAcAAAIQGXYQQPCIcAYApACCCgPFAAX/XoQ5FCCwPBGQIPFCCIREmYOCB44QRTAabHCCAA==")), + }, +]; + +const stoppingBuffers = [ + { + width: 44, + height: 60, + buffer: require("heatshrink").decompress(atob("iIAEzIACA4gOFAAwVTCQVEzOIDIdECsAWC7oWCAAIVkogVFCwIVgNggAECsARCAQX//4VC/4WJCqg8FCgIWCAQIVdM43/gEACYICBCriVBAAQVmIg4VmIQdETAVEogZBogVhzNE7oTB7oACCoYbBCrCbECQgVFIoIVeCwcACg4VbN4xrGCrgCBBwMAC4QNBBwYVeM4IABIYYABBgIUGCqv/iK1CCQOINwdEAwIVDC4QVVmf/G4QNBCooFCCoRRBCqv//4WBCpJsECrb0DC4QVDYYgHBCq8zCohEDNAIGBCrgTBCob4DZAQGCCgYZBCqoICAAqUBdwQUCKYLaCCsACBCwP/IAP/IBQVVCgQECCgRrBmYVfAAhACe4QUOCqzwCCoKCLCrYWDCiIVWeQYVY")), + }, + { + width: 48, + height: 60, + buffer: require("heatshrink").decompress(atob("iIAEzIAFBIYQFAAwXXDAVEzOIxAaCogXlDAPdDAYZBC8wPBC4oYBC8h2FC84VBB4QCB///C4X/DBQXWIIwWBDAQCBC8AWGCQMAgAVBAQIXgOwR4DC9JLGC83/JIuIoimColEDYNEC7wYCHYIACondCoPdAAQXDDoIXYCoT7CC4gAFC4RLBC7IWHDAkACw4XZToY9CJI51EC7ZICAoIJBCAMADIQJCC8IADCAQXDbIJHBDgIWJC7AABCgOIPAdEAwIXDDJIXWCwQXFAoQXCcIIXnOwgXjDIQXDaogHBC8JKDOQIGBC8zaGAwQWDDYIXeDYkADAIPBUoX/IxAXeAQIYB/5GB/5GMC64WCAgQWCOoMzC8YAEIwVEapIXhDANEC4KONC7oYDCyYXYDAIABC7QA==")), + }, +]; + +const waitingBuffers = [ + { + width: 36, + height: 62, + offset: -1, + buffer: require("heatshrink").decompress(atob("iIADzIACA4gNECKYOComZxAVDogRXBQfdCQQABCLITCogRFCQIRYLAgAFCQwRQBoR7C/5aECKwwF/4ABBAQDBCK4TD/8AgH/HQYRUYYYRGzICCCKgUECIoDBCLA3DolEB4IDBAAQRb7oMB7vdHIIRWCAYRCAAoRWCoozDCBQRRBQI3FERIRPPIbGBPIQiICKAQCdQRZDAYIRXCQIJB/4RDEhQRQGYP//7FEGpARQCAYREgEzERQRNAAIRCLIKkBCLg4CYoIABB5IRWAQQRcBoIODCRYRQB4INECLkRgH/ZAMACRgRSmbGBCIIFBmYWCCLAAC7oCBdgNEAgIRWBQY2B7oTBAwMzCYoRUBIIQBCQQGBHIYRUABwRRA")), + }, + { + width: 38, + height: 62, + offset: 1, + buffer: require("heatshrink").decompress(atob("iIADzIACA4gNECSoPComZxAWDogSZBYfdCYQABCTYUCogSFCYISaLogAFCY4SRBwSCC/5fECTAzF/4ABBAQDBCTIUD/8AgH/HoYSWZwYSGzICCCSwVECQoDBCTQ6DolECAIDBAAQSd7oNB7vdHgISYCIYSCAAoSYCwo2DCJYSSBYI6FEhQSQQAbRBQAQkJCSIRCe4ReDAYISZCYIKB/4SDExYSRGwP//7QEHBISRCIYSEgEzEhYSOAAISCLwKtBCTw7CaAIABCBQSXAQQSeBwIPDCZgSRCAIOECT0RgH/aYMACYUzAgQSambRBBoIFBmdEgAAECSwAC7oCBfINECgIABCSwLDHIPdCgIRDEYgSWBYIRBCYSFBQwwSTABKpICR4A=")), + }, +]; + +const bg = { + width: 384, + height: 153, + bpp: 8, + transparent: 254, + buffer: require("heatshrink").decompress(atob("i4ASj0evF4pFIDKYA/AEp//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5/bx+PB5vX64RFC54v3P/4v/P/4v/P/4v/P/4v/P/4v7CY5/VHIKxZACYvvP/4v/P/4v/P4/GAAR/BAAJP/P/5P/P/5P/F8sjkYnBO4oAHP64vHGKJfdF7p//P/5//P/4dTP4dIpB//P/5//P/5//F+p/TIIpDXMIohLF95//P/5//P/4APj0eP/5//P/5//P/4vxB4Z/XAH4AfP/4A/P/4A/P/4A/P/4A/P/4A/AB5/JTIaXJWZobFDpovvP/5//P/5//P/5//P/5//P/5//AAIPFCpp/JEpoABIIZHBL7IvvR45//P/5//P/5//P/5//P/5//P/IbTP6IAbJIpLXF+Z//F/5//F/5//F/5//F/5//F/5/tAH5//AH5//AH5//AH5//AH5//AH5//AH5//AH5//AH4AP4wACP4IABI/5//I/5//I/5//I/5//I/5//I/6B7PoNIpBF/P/5F/P/5F/P/5F/P/5F/P/5F/AHMejx//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//P/5//AHfGAAR/BAAJH/P/5H/P/5H/P/5H/P/5H/P/5H/QPZ9BpFIIv5//Iv4Aj6XSP/4A/P/4A/P/4A96XSP/4A/ACcejx//P/5//AEplB6XSAYJ//AH5//AH5//AHJlB6XSAYJ//AH5//AH5//AGPSAARhBA4oABA4ILBA4p//AH5//AH5//AE/SAARhBA4oABA4ILBA4p//AH5//AH5//AE5dB6QACAofX64HFAoZ//AH5//AH5//AFJdB6QACAofX64HFAoZ//AH5//AH5//AFJdB6XS6/XAYIFLCYJ//AH5//AH5//AFJdB6XS6/XAYIFLCYJ//AH5//AH5//AFZfB6XS6/XhgAEA4ILBB4J//AH5//AH5//AFpfB6XS6/XhgAEA4ILBB4J//AH5//AH5//AE5ZBAAvS6UMhhnBiQACA4ILBCo5//AH5//AH5//AEJZBAAvS6UMhhnBiQACA4ILBCo5//AH4AD4wACRZIA/P/4A/AB/SAA0MhkejwDBAA4VHP/4A/P/4A/P/4Ah6QAGhkMj0eAYIAHCo5//AH4AFP4dIpBF/P/5F/ACpZB6QAC6/XhkMiUSAYIAHB4IABCoIbBP74jBP/7//AH5//AH5ZB6QAC6/XhkMiUSAYIAHB4IABCoIbBP74jBP/4Ajj0ef/5//P/4AF64ACCqJbBAAPS6UMABgPBCoZ/fG4YlJAH7//AH5//AEPXAAQVRLYIAB6XShgAMB4IVDP743DEpIA/f/4A/P/4Af6/X5YACAoIbTL4PS6UMABALBB4J/bD4IhFA4YABHooHDAH7//AH5//ADvX6/LAAQFBDaZfB6XShgAIBYIPBP7YfBEIoHDAAI9FA4YA/f/4A/P/4AV5YACH4PX64HDAAYJBBoIHDEZYRB6XSC4MMAAgHBBYJ/dFoYABGYoHFAobl/f/4A/P/4AX5YACH4PX64HDAAYJBBoIHDEZYRB6XSC4MMAAgHBBYJ/dFoYABGYoHFAobl/f/4A/P/4AX5fL43GH4IFBABINBCIIFBEJIPB6XS6/XAYIABhkMAoYLDP7YvJApITBcv7//AH5//AC/L5fG4w/BAoIAJBoIRBAoIhJB4PS6XX64DBAAMMhgFDBYZ/bF5IFJCYLl/f/4A/P/4AXHYIAD5YAKCIohL6QAEA4MMhgLHP7olD6/XFoIADA4I5Dcf7//AH5//ADI7BAAfLABQRFEJfSAAgHBhkMBY5/dEofX64tBAAYHBHIbj/f/4A/P/4AZ6/X5fLH4IABAoIAFBYoVBEJPSAAQVDNIcMhgJDCIZ/VDoYhFFIIXBiQACA4I9FIIoA/f/4A/P/4AR6/X5fLH4IABAoIAFBYoVBEJPSAAQVDNIcMhgJDCIZ/VDoYhFFIIXBiQACA4I9FIIoA/ACPGAARb/P/5/56/X5YAEIIfSAAQHDCIoZBEY5dJj0ehkMCJp/PIYYADE4IrDAA4VHdf7//AH5//ACPX6/LAAhBD6QACA4YRFDIIjHLpMej0MhgRNP55DDAAYnBFYYAHCo7r/ACp/DpFIIv5//HOfX6/LABHS6QNBAAIFBCJINBF58ej0Mhh/dBIJBBJIYnBiUSAYIAHLIobBdP7//AH5//AB/X6/LABHS6QNBAAIFBCJINBF58ej0Mhh/dBIJBBJIYnBiUSAYIAHLIobBdP4AVSoL/3AH5//6/X5YAI6XSBoIABAoIRJBoJpRhkMP74LBAAJFBE4IALB4IVDc/7//AH5//ACPX6/LABHS6QNBAAIFBCJINBNKMMhh/fBYIABIoInBABYPBCobn/f/4A/P/4AR6/X5YAIIYPSAAQFBCJIdBMJIABiUSA4cMhgHBBoZ/dJYYpBAA5VDcf7//AH5//ACvX6/LABBDB6QACAoIRJDoJhJAAMSiQHDhkMA4INDP7pLDFIIAHKobj/f/4A/P/4AX6/X5YAEIIIHFBJIZBLo4JBAAYHBiUSAYoPHP7IPB6XSEIMMAAgHBBYLh/f/4A/P/4AZ6/X5YAEIIIHFBJIZBLo4JBAAYHBiUSAYoPHP7IPB6XSEIMMAAgHBBYLh/f/4A/P/4Ab6/X5fLH4IDBABINDCoIdFhkMLoIABiUSA4IADBIIHFB4IVDA4J/VBoPS6Q/BAYIABEIIFDBYbj/f/4A/P/4AZ6/X5fLH4IDBABINDCoIdFhkMLoIABiUSA4IADBIIHFB4IVDA4J/VBoPS6Q/BAYIABEIIFDBYbj/f/4A/P/4AZHYIAD6/X5YAGBIIRFD48MAARhBAAMSiUAgAFBAYIHBBoYVDP64NB6QAEA4IjBBY7j/f/4A/P/4AZHYIAD6/X5YAGBIIRFD48MAARhBAAMSiUAgAFBAYIHBBoYVDP64NB6QAEA4IjBBY7j/f/4A/P/4AZ5fL43GH4IAB6/XBIIABAoILDCIIJBEZcMAAUAgBpDA4YNDP7fSAARFDF4oJDCIbl/f/4A/P/4AX5fL43GH4IAB6/XBIIABAoILDCIIJBEZcMAAUAgBpDA4YNDP7fSAARFDF4oJDCIbl/AC6rBX4pH/P/4/35YACHoYDB64ACBIoTDFacej0Mhh/hBpIvHT/b//AH5//AD/LAAQ9DAYPXAAQJFCYYrTj0ehkMP8INJF46f7AEJ/DpFIIv4AhZoJ//MMMMhgfxP7JPfAH7//AFrNBP/5hhhkMD+J/ZJ74A/Mo7//AEvS6R//ZMMMhgfxP7JPfAH7//AFvS6R//ZMMMhgfxP7JPfAH7//MtvS6USiR//La4ABLYYFBhkMA4INDD9Z/RJ74A/f/5l16XSaYZ//IKoABLYYFBhkMA4INDD9Z/RJ74A/f/4Az6QACaYZ//HqPXAAgHBLoIDFB44flP54vhAH7//AGvSAATNBP/49T64AEA4JdBAYoPHD8p/PF8IA/f/5j16QACZoIABP/4ANhkMHoIABKoIHBAAYJBA4oPBCoYHBD8J/PF8YA/f/5j16QACY4IABP/4ANhkMHoIABKoIHBAAYJBA4oPBCoYHBD8J/PF8YA/f/4Ar6XSXYJjFAAILDBo4HFP/4ADhgACLoZRBgEAAoIDBA4INDCoYflP54vhAH4APf/oAd6XSX4JjFAAILDBo4HFP/4ADhgACLoZRBgEAAoIDBA4INDCoYflP54vhAH4APf/oAd6XSX4IABMYYABBZIJDP/4ALhgACgEAJIYHDBoYfrP6JPfAH4ANf/4Ab6XSiQACMYYABBZIJDP/4ALhgACgEAJIYHDBoYfrP6JPfAH4AL4wACP4IABI/4AVYIPS6USiTRDBIrJDCY5//NqZfDD9p/bJ74A/f/4AhYIPS6USiQHBY4IJFZ4YTHP/5tTL4YftP7ZPfAH6BHPoNIpBF/eK/S6USAATHBBIoHHAAJ//NqpfBD+J/ZJ74A/f/4AhYIPS6USAATHBBIoHHAAJ//NqpfBD+J/ZJ74A/Mo7//LrvS6USiTHBA5p//Na5fBD+J/ZJ74A/f/5dl6XSiUSY4IHNP/5rXL4IfxP7JPfAH7//LsvS6USiTHBA44FDAAJ//MZ4ABKYYFBL4IHBBoYfrP6JPfAH6dPf/5dd6XSYYLHBA44FDbYZ//IJoABKYYFBL4IHBBoYfrP6JPfAH6dPf/5ff6XSYoLJBZobXDbIZ//HpfXAAhZDAYoPHD8p/PF8IA/YKL/7L8fS6THBhkMA4IDDBIIABP/49N64AELIYDFB44flP54vhAH7BRf/ZbfYIMMhgFHBJPS6R//AApLDKYoADMIYADB4IVDA4IfhP54vjAH4APf/ZbhZYYFHBJPS6R//AApLDKYoADMIYADB4IVDA4IfhP54vjAH4APf/YAd6QACZooFDYoYLDCoYNDP/4AFJ4JdDLIcAgAFBAYJlDAAIVDD8p/PF8IA/AB7/9ADfSAATJDaIYFBZIYLDCoYNDP/4AFJ4JdDLIcAgAFBAYJlDAAIVDD8p/PF8IA/AB7/9Lb/S6TLDaYYFBA4YPBA4YABP/4ALKoIABgEAJIYHDBoYfrP6JPfAH4ANf/5bd6XSAYMSiTBBAoYHDB4IHDAAJ//ABZVBAAMAgBJDA4YNDD9Z/RJ74A/ABfGAAR/BAAJH/ADbHBiQAEA4IJDP/5nbhkMD95/bJ74A/f/4AnY4MSAAgHBBIZ//M7cMhgfvP7ZPfAGPSAARVBAoYH/A/4H/A/4H/A/4H/A/4H/A/4H/A+4FBiUSA/4H/A/4H/A/4H/A/4H/A/4H/A/4H7AoNIpALBA/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H3AAIFBAAYH/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A/4H/A+8SiQH/A/4H/A/4H/A/4H/A/4H/A/4H/A/oAFvF4A4vG4wHNC44f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D7IZDAoYHFC4IZDAoYHFD/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4fjABYZFABIf/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D/4f/D8IA=")), +}; + +const topSpeed = 15; +const timeout = 200; +let currentSpeed = 0; +let currentSonic = -1; + +let drawTimeout, drawInterval, waitTimeout; +let bgScroll = [0, null]; + +const start = () => { + if (drawTimeout) clearTimeout(drawTimeout); + if (waitTimeout) clearTimeout(waitTimeout); + if (drawInterval) clearInterval(drawInterval); + + drawInterval = setInterval(() => { + draw("start"); + bgScroll[0] += currentSpeed; + if (bgScroll[1]) bgScroll[1] += currentSpeed; + if (currentSpeed < topSpeed) currentSpeed++; + }, timeout); +}; + +const stop = () => { + if (drawTimeout) clearTimeout(drawTimeout); + if (drawInterval) clearInterval(drawInterval); + + drawInterval = setInterval(() => { + if (currentSpeed <= 0) { + clearInterval(drawInterval); + draw("reset"); + } else { + draw("stop"); + bgScroll[0] += currentSpeed; + if (bgScroll[1]) bgScroll[1] += currentSpeed; + currentSpeed--; + } + }, timeout); +}; + +const wait = () => { + currentSonic = -1; + currentSpeed = 0; + if (drawTimeout) clearTimeout(drawTimeout); + if (drawInterval) clearInterval(drawInterval); + Bangle.setLCDPower(1); + + drawInterval = setInterval(() => draw("wait"), timeout); + + waitTimeout = setTimeout(() => { + clearInterval(drawInterval); + currentSonic = -1; + draw("reset"); + }, 7500); +}; + +const queueDraw = () => { + if (drawTimeout) clearTimeout(drawTimeout); + drawTimeout = setTimeout(function () { + drawTimeout = undefined; + draw("reset"); + }, 60000 - (Date.now() % 60000)); +}; + +const drawSonic = (action) => { + let target; + + if (action === "reset" || currentSonic === -1) { + target = defaultSonic; + } else if (action === "start") { + target = startingBuffers[currentSonic]; + } else if (action === "stop") { + if (currentSonic > 1) currentSonic = 0; + target = stoppingBuffers[currentSonic]; + } else { + target = waitingBuffers[currentSonic]; + } + + sonic.width = target.width; + sonic.height = target.height; + sonic.buffer = target.buffer; + sonic.offset = target.offset; + + g.drawImage( + sonic, + vw / 2 - 30 + (50 - sonic.width) + (sonic.offset || 0), + 86 + (65 - sonic.height) + ); + + if (action === "start") { + if (currentSonic === startingBuffers.length - 1) { + currentSonic = 6; + } else { + currentSonic++; + } + } else if (action === "stop") { + if (currentSpeed <= 2) { + currentSonic = -1; + } else if (currentSpeed <= 14) { + currentSonic = 1; + } else { + currentSonic = 0; + } + } else { + if (currentSonic === waitingBuffers.length - 1) { + currentSonic = 0; + } else { + currentSonic++; + } + } +}; + +const drawTime = () => { + const x = vw / 2; + const y = 24 + 25; + + const date = new Date(); + const timeStr = require("locale").time(date, 1).trim(); + const dateStr = require("locale").date(date).toUpperCase(); + + g.setColor("#000"); + g.setFontAlign(0, 0).setFont("6x8", 5); + g.drawString(timeStr, x + 3, y + 2); + + g.setFont("6x8", 1.5); + g.drawString(dateStr, x + 1, y + 29); + + g.setColor("#fff"); + g.setFontAlign(0, 0).setFont("6x8", 5); + g.drawString(timeStr, x, y); + + g.setFont("6x8", 1.5); + g.drawString(dateStr, x, y + 28); +}; + +const draw = (action) => { + if (bgWidth - bgScroll[0] < 0) { + bgScroll[0] = bgScroll[1]; + bgScroll[1] = null; + } + + g.drawImage(bg, -bgScroll[0], 24); + + if (bgWidth - bgScroll[0] < vw) { + bgScroll[1] = bgScroll[0] - bgWidth; + g.drawImage(bg, -bgScroll[1], 24); + } + + drawSonic(action); + drawTime(); + if (action === "reset") queueDraw(); +}; + +g.setTheme({ bg: "#0099ff", fg: "#fff", dark: true }).clear(); + +Bangle.on("lock", (locked) => { + if (locked) { + stop(); + } else { + start(); + } +}); + +Bangle.on("twist", () => wait()); + +Bangle.setOptions({ + lockTimeout: 10000, + backlightTimeout: 12000, + twistThreshold: 1600, +}); + +Bangle.setUI("clock"); + +Bangle.loadWidgets(); +Bangle.drawWidgets(); + +draw("reset"); + +if (Bangle.isLocked()) { + stop(); +} else { + start(); +} diff --git a/apps/sonicclk/app.png b/apps/sonicclk/app.png new file mode 100644 index 000000000..db359d1e5 Binary files /dev/null and b/apps/sonicclk/app.png differ diff --git a/apps/sonicclk/screenshot.png b/apps/sonicclk/screenshot.png new file mode 100644 index 000000000..63173989a Binary files /dev/null and b/apps/sonicclk/screenshot.png differ diff --git a/apps/speedalt2/ChangeLog b/apps/speedalt2/ChangeLog index bd338f8b2..fa2e32f5b 100644 --- a/apps/speedalt2/ChangeLog +++ b/apps/speedalt2/ChangeLog @@ -1,3 +1,4 @@ 0.01: Initial import. 0.07: Add swipe to change screens. 1.06: Misc memory and screen optimisations. +1.10: ... diff --git a/apps/supf/ChangeLog b/apps/supf/ChangeLog new file mode 100644 index 000000000..55ebb3e4b --- /dev/null +++ b/apps/supf/ChangeLog @@ -0,0 +1 @@ +0.01: New App diff --git a/apps/supf/README.md b/apps/supf/README.md new file mode 100644 index 000000000..258a69d4b --- /dev/null +++ b/apps/supf/README.md @@ -0,0 +1,4 @@ +# Simple Clock with Date +Simple Clock with seconds and date in custom language. Install 'Languages' to get localized names. + +![](screenshot_supf.png) diff --git a/apps/supf/app.js b/apps/supf/app.js new file mode 100644 index 000000000..d7a30aed9 --- /dev/null +++ b/apps/supf/app.js @@ -0,0 +1,56 @@ +require("Font7x11Numeric7Seg").add(Graphics); + +function draw() { + var d = new Date(); + var size = Math.floor(g.getWidth()/(7*6)); + var x = (g.getWidth()/2) - size*6, + y = (g.getHeight()/2) - size*7 - 0; + // y variable for ':' + var y_dop = 70 - 0; + g.reset().clearRect(0,y,g.getWidth(),y+size*28); + // draw hours in 24h format + g.setFont("7x11Numeric7Seg",size).setFontAlign(1,-1); + if (d.getHours().toString.length < 2) { + g.drawString('0'+d.getHours(), 58, y); + } + else { + g.drawString(d.getHours(), 58, y); + } + g.setFont("7x11Numeric7Seg",size/2).setFontAlign(1,-1); + g.drawString(":",64,y_dop); + g.setFont("7x11Numeric7Seg",size).setFontAlign(1,-1); + // draw minutes + g.drawString(("0"+d.getMinutes()).substr(-2),118,y); + g.setFont("7x11Numeric7Seg",size/2).setFontAlign(1,-1); + g.drawString(":",124,y_dop); + // draw seconds + g.setFont("7x11Numeric7Seg",size).setFontAlign(1,-1); + g.drawString(("0"+d.getSeconds()).substr(-2),178,y); + // date + g.setFont("6x8",size/2).setFontAlign(0,-1); + // draw name of day + g.drawString(require('locale').dow(new Date()),g.getWidth()/2, y + size*16); + // draw date and name of month + g.drawString(d.getDate()+' '+require('locale').month(new Date()),g.getWidth()/2, y + size*20); + // draw year + g.drawString((d.getFullYear()),g.getWidth()/2, y + size*24); + +} +// Only update when display turns on +if (process.env.BOARD!="SMAQ3") // hack for Q3 which is always-on +Bangle.on('lcdPower', function(on) { + if (secondInterval) + clearInterval(secondInterval); + secondInterval = undefined; + if (on) + secondInterval = setInterval(draw, 1000); + draw(); +}); + +g.clear(); +var secondInterval = setInterval(draw, 1000); +draw(); +// Show launcher when button pressed +Bangle.setUI("clock"); +Bangle.loadWidgets(); +Bangle.drawWidgets(); diff --git a/apps/supf/icon.js b/apps/supf/icon.js new file mode 100644 index 000000000..9b880b5e9 --- /dev/null +++ b/apps/supf/icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEw4UBAoP/AAXnnNVAH4ACoEABZJXBgoLUGaIAIgILLbf4AUnWqweq1gEB4QEBBZ0OwEA9k7h3C2ALGlk4BZAeBBZAvCBZOv/gLJ2EABZOggE7hQLFL5U+1XDBYYEB3jB/AClABRMBqoAXEhAiCBZdQBY8FHTAAj")) diff --git a/apps/supf/icon.png b/apps/supf/icon.png new file mode 100644 index 000000000..2ca4d6140 Binary files /dev/null and b/apps/supf/icon.png differ diff --git a/apps/supf/screenshot_supf.png b/apps/supf/screenshot_supf.png new file mode 100644 index 000000000..18e391f28 Binary files /dev/null and b/apps/supf/screenshot_supf.png differ diff --git a/apps/swp2clk/ChangeLog b/apps/swp2clk/ChangeLog new file mode 100644 index 000000000..ea6473980 --- /dev/null +++ b/apps/swp2clk/ChangeLog @@ -0,0 +1 @@ +0.01: Initial creation of "Swipe back to the Clock" App. Let's you swipe from left to right on any app to return back to the clock face. diff --git a/apps/swp2clk/README.md b/apps/swp2clk/README.md new file mode 100644 index 000000000..877a13ecc --- /dev/null +++ b/apps/swp2clk/README.md @@ -0,0 +1,22 @@ +# Swipe back to the Clock + +Let's you swipe from left to right on any app to return back to the clock face. + +## Configurable Modes: + +The swipe modes can be configured in the settings app, under "Swipe to Clock". + +- Always Off: Deactivated for all apps (Default) +- White List: Only activate for chosen apps, otherwise deactivated for all apps. +- Black List: Only disabled for chosen apps, otherwise activated for all apps. +- Always On: Active for all apps (Not actually recommended! E.g. Games need to be able to deal with swipe gestures) + +## Motivation: + +The goal is to further support touch-only usage of the BangleJS 2 watch. You can use the [Swiper Clock Launch](https://banglejs.com/apps/#swiper%20clock%20launch) or the [Pattern Launcher](https://banglejs.com/apps/#pattern%20launcher) to further enable touch-only support of the watch. + +## Credits: + +Initial creation: [crazysaem](https://github.com/crazysaem) + +Inspired by: [Swiper Clock Launch](https://banglejs.com/apps/#swiper%20clock%20launch) \ No newline at end of file diff --git a/apps/swp2clk/app.png b/apps/swp2clk/app.png new file mode 100644 index 000000000..b964520e6 Binary files /dev/null and b/apps/swp2clk/app.png differ diff --git a/apps/swp2clk/boot.js b/apps/swp2clk/boot.js new file mode 100644 index 000000000..bb8e792c4 --- /dev/null +++ b/apps/swp2clk/boot.js @@ -0,0 +1,109 @@ +/** + * How does this work? + * + * Every *boot.js file is executed everytime any app is loaded, including this one. + * We just need to figure out which app is currently loaded, in case we are in the white list / black list mode, + * to figure out if the swipe handler should be attached or not. + * It does not seem to be the case that this can be done easily, but we can work around it. + * It seems that every app is loaded via the global "load" function, which takes a fileName as it's first parameter to load any app + * or the default clock when the fileName is undefined. + * To be able to use this for us, we wrap the global "load" function, and determine before loading the next app, + * whether the swipe handler should be added or not, since we now know which app will be loaded. + * Note: We cannot add the swipe handler inside the wrapped "load" function, because once the "load" function is complete + * everything is cleaned up. That's why we merely save a flag, whether the swipe handler should be attached or not, + * which is evaluated once this file is executed again, which will be right after the load function completes + * (since every *boot.js file is executed everytime any app is loaded). + */ + +(function () { + var DEBUG = false; + var FILE = "swp2clk.data.json"; + + var main = () => { + var settings = readSettings(); + + if (settings.addSwipeHandler) { + var swipeHandler = (dir) => { + log("swipe"); + log(dir); + if (dir === 1) { + load(); + } + }; + Bangle.on("swipe", swipeHandler); + } + + var global_load = global.load; + global.load = (fileName) => { + log("loading filename!"); + log(fileName); + var settings = readSettings(); + + if (fileName) { + // "Off" + if (settings.mode === 0) { + settings.addSwipeHandler = false; + } + + // "White List" + if (settings.mode === 1) { + if (settings.whiteList.indexOf(fileName) >= 0) { + settings.addSwipeHandler = true; + } else { + settings.addSwipeHandler = false; + } + } + + // "Black List" + if (settings.mode === 2) { + if (settings.blackList.indexOf(fileName) >= 0) { + settings.addSwipeHandler = false; + } else { + settings.addSwipeHandler = true; + } + } + + // "Always" + if (settings.mode === 3) { + settings.addSwipeHandler = true; + } + } else { + // Clock will load + settings.addSwipeHandler = false; + } + + writeSettings(settings); + global_load(fileName); + }; + }; + + // lib functions + + var log = (message) => { + if (DEBUG) { + console.log(JSON.stringify(message)); + } + }; + + var readSettings = () => { + log("reading settings"); + var settings = require("Storage").readJSON(FILE, 1) || { + mode: 0, + whiteList: [], + blackList: [], + addSwipeHandler: false, + }; + log(settings); + return settings; + }; + + var writeSettings = (settings) => { + log("writing settings"); + log(settings); + require("Storage").writeJSON(FILE, settings); + }; + + // start main function + + main(); +})(); diff --git a/apps/swp2clk/settings.js b/apps/swp2clk/settings.js new file mode 100644 index 000000000..a97b51fab --- /dev/null +++ b/apps/swp2clk/settings.js @@ -0,0 +1,181 @@ +(function (back) { + var DEBUG = false; + var FILE = "swp2clk.data.json"; + + var settings = {}; + + var showMainMenu = () => { + log("Loading main menu"); + + E.showMenu({ + "": { title: "Swipe to Clock" }, + "< Back": () => back(), + Mode: { + value: settings.mode, + min: 0, + max: 3, + format: (value) => ["Off", "White List", "Black List", "Always"][value], + onchange: (value) => { + settings.mode = value; + writeSettings(settings); + }, + }, + "White List": () => showWhiteListMenu(), + "Black List": () => showBlackListMenu(), + }); + }; + + var showWhiteListMenu = () => { + var appList = getAppList(); + + var whiteListMenu = { + "": { title: "White List" }, + "< Back": () => showMainMenu(), + "_Add App_": () => { + var addAppMenu = { + "": { title: "Add app to WL" }, + "< Back": () => showWhiteListMenu(), + }; + + appList.forEach((app) => { + if (settings.whiteList.indexOf(app.src) < 0) { + addAppMenu[app.name] = () => { + settings.whiteList.push(app.src); + writeSettings(settings); + showWhiteListMenu(); + }; + } + }); + + E.showMenu(addAppMenu); + }, + }; + + appList.forEach((app) => { + if (settings.whiteList.indexOf(app.src) >= 0) { + whiteListMenu[app.name] = () => { + E.showPrompt("Delete from WL?", { + title: "Delete from WL?", + buttons: { Yes: true, No: false }, + }).then(function (flag) { + if (flag) { + settings.whiteList.splice(index, 1); + writeSettings(settings); + } + + showWhiteListMenu(); + }); + }; + } + }); + + log("Loading white list menu"); + E.showMenu(whiteListMenu); + }; + + var showBlackListMenu = () => { + var appList = getAppList(); + + var blackListMenu = { + "": { title: "Black List" }, + "< Back": () => showMainMenu(), + "_Add App_": () => { + var addAppMenu = { + "": { title: "Add app to BL" }, + "< Back": () => showBlackListMenu(), + }; + + appList.forEach((app) => { + if (settings.blackList.indexOf(app.src) < 0) { + addAppMenu[app.name] = () => { + settings.blackList.push(app.src); + writeSettings(settings); + showBlackListMenu(); + }; + } + }); + + E.showMenu(addAppMenu); + }, + }; + + appList.forEach((app) => { + if (settings.blackList.indexOf(app.src) >= 0) { + blackListMenu[app.name] = () => { + E.showPrompt("Delete from BL?", { + title: "Delete from BL?", + buttons: { Yes: true, No: false }, + }).then(function (flag) { + if (flag) { + settings.blackList.splice(index, 1); + writeSettings(settings); + } + + showBlackListMenu(); + }); + }; + } + }); + + log("Loading black list menu"); + E.showMenu(blackListMenu); + }; + + // lib functions + + var log = (message) => { + if (DEBUG) { + console.log(JSON.stringify(message)); + } + }; + + var readSettings = () => { + log("reading settings"); + var settings = require("Storage").readJSON(FILE, 1) || { + mode: 0, + whiteList: [], + blackList: [], + addSwipeHandler: false, + }; + log(settings); + return settings; + }; + + var writeSettings = (settings) => { + log("writing settings"); + log(settings); + require("Storage").writeJSON(FILE, settings); + }; + + var getAppList = () => { + var appList = storage + .list(/\.info$/) + .map((appInfoFileName) => { + var appInfo = storage.readJSON(appInfoFileName, 1); + return ( + appInfo && { + name: appInfo.name, + // type: appInfo.type, + // icon: appInfo.icon, + sortorder: appInfo.sortorder, + src: appInfo.src, + } + ); + }) + .filter((app) => app && !!app.src); + appList.sort((a, b) => { + var n = (0 | a.sortorder) - (0 | b.sortorder); + if (n) return n; // do sortorder first + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + return 0; + }); + + return appList; + }; + + // start main function + + settings = readSettings(); + showMainMenu(); +}); diff --git a/apps/tapelauncher/icon.js b/apps/tapelauncher/icon.js index bf323e5bf..25ca0a4c6 100644 --- a/apps/tapelauncher/icon.js +++ b/apps/tapelauncher/icon.js @@ -1 +1 @@ -require("heatshrink").decompress(atob("AH4A/ACXd7vQC6vUpoBBDaQXEDaQXIDZwXMAIQZHC4R6BAAIZJDAwXIDY4XHAAodJ7oXMDpQXSAAiRHhoWN7zFLDY/e9ve9zeMhvQCIIBFC5ARIC5oVNC5EOCpwABC4vuCZYXPCIwXOCJAAFC5gAJ8AXFCpwuHgDjCFqQXC6lN6gbFf5gXEAInd6AXVDYndhoXKBoIbMC5QZLC44AFDpIXNDpQXdhoYMAAbwIC6oZQbxhOKC5gbKC6BUGC6oA/AHgA==")) +require("heatshrink").decompress(atob("mEw4UA///sH8ov+8GyJf4AIgt8BZV9voNIBYQNIBYgNGBYwMEBYNVqoMEoALGBoYLDBQILCAQVQBYoOEBZIABBYUAgILGsBiEBodWy2gN4soywACBYcI1QJDBYoJFBYkCBQ2qBYUKBIoLHBAQLHBAYACBYwAEwALBgwKG1S/DC4wWCa4Y3Efa19mALKvrLDfY7XGBwjvVBYjuHfYgLLBg4LEAAMVBZQNEBZBPCBZQA+A")) diff --git a/apps/teatimer/README.md b/apps/teatimer/README.md new file mode 100644 index 000000000..71bec3ea8 --- /dev/null +++ b/apps/teatimer/README.md @@ -0,0 +1,45 @@ +# Tea Timer app + +A simple timer. You can easyly set up the time. The initial time is 2:30 + +On the first screen, you can +- tap to get help +- swipe up/down to change the timer by +/- one minute +- swipe left/right to change the time by +/- 15 seconds +- press Btn1 to start + +Press Btn1 again to stop the timer +- when time is up, your Bangle will buzz for 15 seconds +- and it will count up to 60 seconds and stop after that + +## Images +_1. Startscreen_ + +![](TeatimerStart.jpg) +Current time is displayed below the Title. Initial time is 2:30. + +_2. Help Screen_ + +![](TeatimerHelp.jpg) + +_3. Tea Timer running_ + +![](TeatimerRun.jpg) +Remainig time is shown in big font size. Above the initial time is shown. + +_4. When time is up_ + +![](TeatimerUp.jpg) +When time is up, the watch will buzz for 15 seconds. It will count up to 60 seconds. + +## Requests + +Please mail any issues to thomas.fehling@mailbox.org + +## Creator + +Thomas Fehling + +## Attributions + +Icons used in this app are from https://icons8.com diff --git a/apps/teatimer/TeatimerHelp.jpg b/apps/teatimer/TeatimerHelp.jpg new file mode 100644 index 000000000..e22960c66 Binary files /dev/null and b/apps/teatimer/TeatimerHelp.jpg differ diff --git a/apps/teatimer/TeatimerRun.jpg b/apps/teatimer/TeatimerRun.jpg new file mode 100644 index 000000000..a442d12a5 Binary files /dev/null and b/apps/teatimer/TeatimerRun.jpg differ diff --git a/apps/teatimer/TeatimerStart.jpg b/apps/teatimer/TeatimerStart.jpg new file mode 100644 index 000000000..4fa8f2fc4 Binary files /dev/null and b/apps/teatimer/TeatimerStart.jpg differ diff --git a/apps/teatimer/TeatimerUp.jpg b/apps/teatimer/TeatimerUp.jpg new file mode 100644 index 000000000..80b8c3c8a Binary files /dev/null and b/apps/teatimer/TeatimerUp.jpg differ diff --git a/apps/teatimer/app-icon.js b/apps/teatimer/app-icon.js new file mode 100644 index 000000000..ae91f88d7 --- /dev/null +++ b/apps/teatimer/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwxH+AAONjQAoxoutGAYusGAQutABs4qwAUnAwYik4vQAQnEUMTcxqoAOm6Sdm9PAB0TF7sTF90awIAOFz0bxIAOjYv/F/2s1eq5wAI1Wr1gvg4/GABXH1Yvg5wvL5xffjWIMBfH1lkFzwwC1YvJ1eIF0CRC5CNJF0KRK5CNiGBS8BRsQwJ468jAA2JGAJdpF4et1ms1uJF9YADF1GIxIAD1qQoFwgwpLwoADF1jABxJgjLpGt2YwBjYugjaMIF4IwBsgvgsgvMxIwfLxIwC66RhF/ezF9q/B6/XF9xfrLwYvhjWBABGsAAOmwWBFz0Tp4AOiYvdm4vumNVAB0xFrcUnF6ACE4iguYnFWACk4ebwAcxouu/wwsFwIABGFQuCA==")) diff --git a/apps/teatimer/app.js b/apps/teatimer/app.js new file mode 100644 index 000000000..dd7afdadb --- /dev/null +++ b/apps/teatimer/app.js @@ -0,0 +1,233 @@ +// Tea Timer +// Button press stops timer, next press restarts timer +let drag; +var counter = 0; +var counterStart = 150; // 150 seconds +var counterInterval; +const states = { + init: 1, // unused + help: 2, // show help text + start: 4, // show/change initial counter + count: 8, // count down + countUp: 16, // count up after timer finished + stop: 32 // timer stopped +}; +var state = states.start; +E.setTimeZone(1); + +// Title showing current time +function appTitle() { + return "Tea Timer " + currentTime(); +} + +function currentTime() { + min = Date().getMinutes(); + if (min < 10) min = "0" + min; + return Date().getHours() + ":" + min; +} + +function timeFormated(sec) { + var min = Math.floor(sec / 60); + sec = sec % 60; + if (sec < 10) sec = "0" + sec; + return min + ":" + sec; +} + +// initialize timer and show timer value => state: start +function initTimer() { + counter = counterStart; + setState(states.start); + showCounter(true); +} + +// timer value (counter) can be changed in state start +function changeCounter(diff) { + if (state == states.start) { + if (counter + diff > 0) { + counter = counter + diff; + showCounter(true); + } + } +} + +// start or restart timer => state: count +function startTimer() { + counterStart = counter; + setState(states.count); + countDown(); + if (!counterInterval) + counterInterval = setInterval(countDown, 1000); +} + +/* show current counter value at start and while count down + Show + - Title with current time + - initial timer value + - remaining time + - hint for help in state start +*/ +function showCounter(withHint) { + //g.clear(); + E.showMessage("", appTitle()); + g.setFontAlign(0,0); // center font + // draw the current counter value + g.setBgColor(-1).setColor(0,0,1); // blue + g.setFont("Vector",20); // vector font, 20px + g.drawString("Timer: " + timeFormated(counterStart),80,55); + g.setFont("Vector",60); // vector font, 60px + g.drawString(timeFormated(counter),83,100); + if (withHint) { + g.setFont("Vector",20); // vector font, 80px + g.drawString("Tap for help",80,150); + } +} + +// count down and update every second +// when time is up, start counting up +function countDown() { + counter--; + // Out of time + if (counter<=0) { + outOfTime(); + countUp(); + counterInterval = setInterval(countUp, 1000); + return; + } + showCounter(false); +} + +// +function outOfTime() { + E.showMessage("Time is up!",appTitle()); + setState(states.countUp); + resetTimer(); + Bangle.buzz(); + Bangle.buzz(); +} + +/* this counts up (one minute), after time is up + Show + - Title with current time + - initial timer value + - "Time is up!" + - time since timer finished +*/ +function countUp() { + // buzz for 15 seconds + counter++; + if (counter <=15) { + Bangle.buzz(); + } + // stop counting up after 60 seconds + if (counter > 60) { + outOfTime(); + return; + } + g.clear(); + E.showMessage("", appTitle()); + g.setFontAlign(0,0); // center font + g.setBgColor(-1).setColor(0,0,1); // blue + g.setFont("Vector",20); // vector font, 20px + g.drawString("Timer: " + timeFormated(counterStart),80,55); + g.setFont("Vector",30); // vector font, 80px + g.setBgColor(-1).setColor(1,0,0); // red + g.drawString("Time is up!",85,85); + g.setFont("Vector",40); // vector font, 80px + // draw the current counter value + g.drawString(timeFormated(counter),80,130); +} + +// reset when interupted by user oder 60 seconds after timer finished +function resetTimer() { + clearInterval(); + counterInterval = undefined; +} + +// timer is stopped by user => state: stop +function stopTimer() { + resetTimer(); + E.showMessage("Timer stopped!", appTitle()); + setState(states.stop); +} + +// timer is stopped by user while counting up => state: start +function stopTimer2() { + resetTimer(); + initTimer(); +} + + +function setState(st) { + state = st; +} + +function buttonPressed() { + switch(state) { + case states.init: + initTimer(); + break; + case states.help: + initTimer(); + break; + case states.start: + startTimer(); + break; + case states.count: + stopTimer(); + break; + case states.countUp: + stopTimer2(); + break; + case states.stop: + initTimer(); + break; + default: + initTimer(); + break; + } +} + +/* Change initial counter value by swiping + swipe up: +1 minute + swipe down: -1 minute + swipe right: +15 seconds + swipe left: -15 seconds */ +function initDragEvents() { + Bangle.on("drag", e => { + if (state == states.start) { + if (!drag) { // start dragging + drag = {x: e.x, y: e.y}; + } else if (!e.b) { // released + const dx = e.x-drag.x, dy = e.y-drag.y; + drag = null; + if (Math.abs(dx)>Math.abs(dy)+10) { + // horizontal + changeCounter(dx>0 ? 15 : -15); + } else if (Math.abs(dy)>Math.abs(dx)+10) { + // vertical + changeCounter(dy>0 ? -60 : 60); + } + } + } +}); +} + +// show help text while in start state (see initDragEvents()) +function showHelp() { + if (state == states.start) { + state = states.help; + E.showMessage("Swipe up/down\n+/- one minute\n\nSwipe left/right\n+/- 15 seconds\n\nPress Btn1 to start","Tea timer help"); + } + // return to start + else if (state == states.help) { + initTimer(); + } +} + +// drag events in start state (to change counter value) +initDragEvents(); +// Show help test in start state +Bangle.on('touch', function(button, xy) { showHelp(); }); +// event handling for button1 +setWatch(buttonPressed, BTN1, {repeat: true}); +initTimer(); diff --git a/apps/teatimer/teatimer.png b/apps/teatimer/teatimer.png new file mode 100644 index 000000000..29ca58f0e Binary files /dev/null and b/apps/teatimer/teatimer.png differ diff --git a/apps/themesetter/README.md b/apps/themesetter/README.md new file mode 100644 index 000000000..518d05c01 --- /dev/null +++ b/apps/themesetter/README.md @@ -0,0 +1,22 @@ +# Theme Setter # + +This little tool allows you to configure the global theme of all Bangle.js apps +(provided that they do not override global settings) in a more comfortable way +than through the settings menu. + +![](ThemeSetter-MainScreen.png) +![](ThemeSetter-DetailSelectionScreen.png) +![](ThemeSetter-ColorSelectionScreen.png) +![](ThemeSetter-ThemePreviewScreen.png) + +This app also acts as an example for a non-trivial Bangle.js application +using the "layout" library, custom controls and generic event dispatching. +See [GitHub](https://github.com/rozek/banglejs-2-activities) for details. + +## License ## + +[MIT License](LICENSE) + +## Credits ## + +The icon for this app was taken from [icons8.com](https://icons8.com/). \ No newline at end of file diff --git a/apps/themesetter/ThemeSetter-ColorSelectionScreen.png b/apps/themesetter/ThemeSetter-ColorSelectionScreen.png new file mode 100644 index 000000000..3ed4d857e Binary files /dev/null and b/apps/themesetter/ThemeSetter-ColorSelectionScreen.png differ diff --git a/apps/themesetter/ThemeSetter-DetailSelectionScreen.png b/apps/themesetter/ThemeSetter-DetailSelectionScreen.png new file mode 100644 index 000000000..79a983652 Binary files /dev/null and b/apps/themesetter/ThemeSetter-DetailSelectionScreen.png differ diff --git a/apps/themesetter/ThemeSetter-MainScreen.png b/apps/themesetter/ThemeSetter-MainScreen.png new file mode 100644 index 000000000..3a0fc215c Binary files /dev/null and b/apps/themesetter/ThemeSetter-MainScreen.png differ diff --git a/apps/themesetter/ThemeSetter-ThemePreviewScreen.png b/apps/themesetter/ThemeSetter-ThemePreviewScreen.png new file mode 100644 index 000000000..1d21935b2 Binary files /dev/null and b/apps/themesetter/ThemeSetter-ThemePreviewScreen.png differ diff --git a/apps/themesetter/app-icon.js b/apps/themesetter/app-icon.js new file mode 100644 index 000000000..31fc30449 --- /dev/null +++ b/apps/themesetter/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwgP/ACHgDAQWBApfjCoXxAqHwg4FP+PHApY7EApheEAq3+g4FD/EPAofAj4QDgAQECwgQQ8E/Cwg+EAvYAhA==")) \ No newline at end of file diff --git a/apps/themesetter/app-icon.png b/apps/themesetter/app-icon.png new file mode 100644 index 000000000..078920a27 Binary files /dev/null and b/apps/themesetter/app-icon.png differ diff --git a/apps/themesetter/app-screenshot.png b/apps/themesetter/app-screenshot.png new file mode 100644 index 000000000..e7bf5a6a2 Binary files /dev/null and b/apps/themesetter/app-screenshot.png differ diff --git a/apps/themesetter/app.js b/apps/themesetter/app.js new file mode 100644 index 000000000..aa3c608cf --- /dev/null +++ b/apps/themesetter/app.js @@ -0,0 +1,498 @@ + let Layout = require('Layout'); + + let ScreenWidth = g.getWidth(), halfWidth = ScreenWidth/2; + let ScreenHeight = g.getHeight(); + + let normalizedColorSet = { + black:g.toColor(0,0,0), white: g.toColor(1,1,1), + red: g.toColor(1,0,0), yellow: g.toColor(1,1,0), + green:g.toColor(0,1,0), magenta:g.toColor(1,0,1), + blue: g.toColor(0,0,1), cyan: g.toColor(0,1,1) + }; + + let activeTheme = g.theme; // currently active theme + let pendingTheme = Object.assign({},activeTheme); + let chosenDetail = null; // one of 'fg','bg','fg2','bg2','fgH','bgH' + +/**** Label ****/ + + function Label (Text, Options) { + function renderLabel (Details) { + let halfWidth = Details.w/2, xAlignment = Details.halign || 0; + let halfHeight = Details.h/2, yAlignment = Details.valign || 0; + let Padding = Details.pad || 0; + + g.setColor(Details.col || g.theme.fg || '#000000'); + + if (Details.font != null) { g.setFont(Details.font); } + g.setFontAlign(xAlignment,yAlignment); + + let x = Details.x + halfWidth + xAlignment*(halfWidth+Padding); + let y = Details.y + halfHeight + yAlignment*(halfHeight+Padding); + + g.drawString(Details.label, x,y); + if (Details.bold) { + g.drawString(Details.label, x+1,y); + g.drawString(Details.label, x,y+1); + g.drawString(Details.label, x+1,y+1); + } + } + + let Result = Object.assign(( + Options == null ? {} : Object.assign({}, Options.common || {}, Options) + ), { + type:'custom', render:renderLabel, label:Text || '' + }); + let TextMetrics; + if (! Result.width || ! Result.height) { + if (Result.font != null) { g.setFont(Result.font); } + TextMetrics = g.stringMetrics(Result.label); + } + + Result.width = Result.width || TextMetrics.width + 2*(Result.pad || 0); + Result.height = Result.height || TextMetrics.height + 2*(Result.pad || 0); + return Result; + } + + if (g.drawRoundedRect == null) { + g.drawRoundedRect = function drawRoundedRect (x1,y1, x2,y2, r) { + let x,y; + if (x1 > x2) { x = x1; x1 = x2; x2 = x; } + if (y1 > y2) { y = y1; y1 = y2; y2 = y; } + + r = Math.min(r || 0, (x2-x1)/2, (y2-y1)/2); + + let cx1 = x1+r, cx2 = x2-r; + let cy1 = y1+r, cy2 = y2-r; + + this.drawLine(cx1,y1, cx2,y1); + this.drawLine(cx1,y2, cx2,y2); + this.drawLine(x1,cy1, x1,cy2); + this.drawLine(x2,cy1, x2,cy2); + + x = r; y = 0; + + let dx,dy, Error = 0; + while (y <= x) { + dy = 1 + 2*y; y++; Error -= dy; + if (Error < 0) { + dx = 1 - 2*x; x--; Error -= dx; + } + + this.setPixel(cx1 - x, cy1 - y); this.setPixel(cx1 - y, cy1 - x); + this.setPixel(cx2 + x, cy1 - y); this.setPixel(cx2 + y, cy1 - x); + this.setPixel(cx2 + x, cy2 + y); this.setPixel(cx2 + y, cy2 + x); + this.setPixel(cx1 - x, cy2 + y); this.setPixel(cx1 - y, cy2 + x); + } + }; + } + + +/**** Button ****/ + + function Button (Text, Options) { + function renderButton (Details) { + let x = Details.x, Width = Details.w, halfWidth = Width/2; + let y = Details.y, Height = Details.h, halfHeight = Height/2; + let Padding = Details.pad || 0; + + g.setColor(Details.col || g.theme.fg || '#000000'); + + if (Details.font != null) { g.setFont(Details.font); } + g.setFontAlign(0,0); + + g.drawRoundedRect(x+Padding,y+Padding, x+Width-Padding-1,y+Height-Padding-1,8); + g.drawString(Details.label, x+halfWidth,y+halfHeight); + g.drawString(Details.label, x+halfWidth+1,y+halfHeight); + g.drawString(Details.label, x+halfWidth,y+halfHeight+1); + g.drawString(Details.label, x+halfWidth+1,y+halfHeight+1); + } + + let Result = Object.assign(( + Options == null ? {} : Object.assign({}, Options.common || {}, Options) + ), { + type:'custom', render:renderButton, label:Text || 'Tap' + }); + let TextMetrics; + if (! Result.width || ! Result.height) { + if (Options.font != null) { g.setFont(Options.font); } + TextMetrics = g.stringMetrics(Result.label); + } + + Result.width = Result.width || TextMetrics.width + 2*10 + 2*(Result.pad || 0); + Result.height = Result.height || TextMetrics.height + 2*5 + 2*(Result.pad || 0); + return Result; + } + +/**** ColorDemo ****/ + + function ColorDemo (Text, Options) { + function renderDemo (Details) { + let x = Details.x, Width = Details.w, halfWidth = Width/2; + let y = Details.y, Height = Details.h, halfHeight = Height/2; + let Padding = Details.pad || 0; + + if (Details.font != null) { g.setFont(Details.font); } + g.setFontAlign(0,0); + + g.setColor(Details.bg); // do not use "bgCol"! + g.fillRect(x+Padding, y+Padding, x+Width-Padding, y+Height-Padding); + + g.setColor(Details.fg); + g.drawString(Details.label, x+halfWidth,y+halfHeight); + } + + let Result = Object.assign(( + Options == null ? {} : Object.assign({}, Options.common || {}, Options) + ), { + type:'custom', render:renderDemo, label:Text || 'Test' + }); + let TextMetrics; + if (! Result.width || ! Result.height) { + if (Result.font != null) { g.setFont(Result.font); } + TextMetrics = g.stringMetrics(Result.label); + } + + Result.width = Result.width || TextMetrics.width + 2*2 + 2*(Result.pad || 0); + Result.height = Result.height || TextMetrics.height + 2*2 + 2*(Result.pad || 0); + return Result; + } + + +/**** ColorView ****/ + + function ColorView (Color, Options) { + function renderColorView (Details) { + let x = Details.x, Width = Details.w; + let y = Details.y, Height = Details.h; + let Padding = Details.pad || 0; + + g.setColor('#000000'); + g.drawRect(x+Padding,y+Padding, x+Width-Padding-1,y+Height-Padding-1); + + g.setColor(Details.col); + g.fillRect(x+Padding+2, y+Padding+2, x+Width-Padding-3, y+Height-Padding-3); + } + + let Result = Object.assign(( + Options == null ? {} : Object.assign({}, Options.common || {}, Options) + ), { + type:'custom', render:renderColorView, col:Color + }); + Result.width = Math.max(10, Result.width || 10) + 2*(Result.pad || 0); + Result.height = Math.max(10, Result.height || 10) + 2*(Result.pad || 0); + return Result; + } + + +/**** ColorSelectionView ****/ + + function ColorSelectionView (Color, Options) { + function renderColorView (Details) { + let x = Details.x, Width = Details.w; + let y = Details.y, Height = Details.h; + let Padding = Details.pad || 0; + + if (Details.selected) { + g.setColor(Details.selected ? '#FF0000' : '#000000'); + g.fillRect(x+Padding,y+Padding, x+Width-Padding-1,y+Height-Padding-1); + + g.setColor('#FFFFFF'); + g.drawRect(x+Padding+4,y+Padding+4, x+Width-Padding-5,y+Height-Padding-5); + } else { + g.setColor('#000000'); + g.drawRect(x+Padding+3,y+Padding+3, x+Width-Padding-4,y+Height-Padding-4); + } + + g.setColor(Details.col); + g.fillRect(x+Padding+5, y+Padding+5, x+Width-Padding-6, y+Height-Padding-6); + } + + let Result = Object.assign(( + Options == null ? {} : Object.assign({}, Options.common || {}, Options) + ), { + type:'custom', render:renderColorView, col:Color + }); + Result.width = Math.max(10, Result.width || 10) + 2*(Result.pad || 0); + Result.height = Math.max(10, Result.height || 10) + 2*(Result.pad || 0); + return Result; + } + + +/**** EventConsumerAtPoint ****/ + + function EventConsumerAtPoint (HandlerName, x,y) { + let Layout = (activeLayout || {}).l; + if (Layout == null) { return; } + + function ConsumerIn (Control) { + if ( + (x < Control.x) || (x >= Control.x + Control.w) || + (y < Control.y) || (y >= Control.y + Control.h) + ) { return undefined; } + + if (typeof Control[HandlerName] === 'function') { return Control; } + + if (Control.c != null) { + let ControlList = Control.c; + for (let i = 0, l = ControlList.length; i < l; i++) { + let Consumer = ConsumerIn(ControlList[i]); + if (Consumer != null) { return Consumer; } + } + } + + return undefined; + } + + return ConsumerIn(Layout); + } + +/**** dispatchTouchEvent ****/ + + function dispatchTouchEvent () { + function handleTouchEvent (Button, xy) { + let Control = EventConsumerAtPoint('onTouch', xy.x,xy.y); + if (Control != null) { + Control.onTouch(Control, Button, xy); + } + } + Bangle.on('touch',handleTouchEvent); + } + dispatchTouchEvent(); + +/**** dispatchStrokeEvent ****/ + + function dispatchStrokeEvent () { + function handleStrokeEvent (Coordinates) { + let Control = EventConsumerAtPoint('onStroke', Coordinates.xy[0],Coordinates.xy[1]); + if (Control != null) { + Control.onStroke(Control, Coordinates); + } + } + Bangle.on('stroke',handleStrokeEvent); + } + dispatchStrokeEvent(); + + let ScreenSet = {}; + + g.setFont12x20(); // does not seem to be respected in layout! + let leftColumnWidth = Math.max( + g.stringWidth('Normal '), g.stringWidth('Accented '), g.stringWidth('Hilighted ') + ); + + let StdFont = { font:'12x20' }; + let legible = Object.assign({ col:'#000000', bgCol:'#FFFFFF' }, StdFont); + let leftAligned = Object.assign({ halign:-1, valign:0 }, legible); + let MainLabel = Object.assign({ pad:4, width:leftColumnWidth }, leftAligned); + let halfWidthButton = Object.assign({ pad:4, width:halfWidth }, legible); + + ScreenSet['MainScreen'] = new Layout({ + type:'v', c:[ + Label('Current Theme', { common:legible, pad:8, bold:true, filly:1 }), + { type:'h', c:[ + Label('Normal', { common:MainLabel }), + ColorDemo(' Demo ',{ common:StdFont, pad:2, id:'NormalDemo' }), + ] }, + { type:'h', c:[ + Label('Accented', { common:MainLabel }), + ColorDemo(' Demo ',{ common:StdFont, pad:2, id:'AccentedDemo' }), + ] }, + { type:'h', c:[ + Label('Hilighted', { common:MainLabel }), + ColorDemo(' Demo ',{ common:StdFont, pad:2, id:'HilitedDemo' }), + ] }, + { height:4 }, + { type:'h', c:[ + Button('Exit', { common:halfWidthButton, onTouch:() => load() }), + Button('Config', { common:halfWidthButton, onTouch:() => gotoScreen('DetailSelectionScreen') }) + ], filly:1 } + ] + }); + + let LabelWidth = Math.max( + g.stringWidth('Fg '), g.stringWidth('Fg2 '), g.stringWidth('FgH '), + g.stringWidth('Bg '), g.stringWidth('Bg2 '), g.stringWidth('BgH ') + ); + let LabelHeight = g.stringMetrics('FgH').height; + + let DetailLabel = Object.assign({ pad:4, width:LabelWidth }, leftAligned); + let DetailView = { width:30, height:LabelHeight, pad:2 }; + + ScreenSet['DetailSelectionScreen'] = new Layout({ + type:'v', c:[ + Label('Configure Detail', { font:'12x20', pad:8, col:'#000000', bgCol:'#FFFFFF', bold:true, filly:1 }), + { type:'h', c:[ + Label('fg', { common:DetailLabel, onTouch:() => configureDetail('fg') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('fg'), id:'fgView' }), + { width:20 }, + Label('bg', { common:DetailLabel, onTouch:() => configureDetail('bg') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('bg'), id:'bgView' }), + ] }, + { type:'h', c:[ + Label('fg2', { common:DetailLabel, onTouch:() => configureDetail('fg2') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('fg2'), id:'fg2View' }), + { width:20 }, + Label('bg2', { common:DetailLabel, onTouch:() => configureDetail('bg2') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('bg2'), id:'bg2View' }), + ] }, + { type:'h', c:[ + Label('fgH', { common:DetailLabel, onTouch:() => configureDetail('fgH') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('fgH'), id:'fgHView' }), + { width:20 }, + Label('bgH', { common:DetailLabel, onTouch:() => configureDetail('bgH') }), + ColorView(0, { common:DetailView, onTouch:() => configureDetail('bgH'), id:'bgHView' }), + ] }, + { type:'h', c:[ + Button('Save', { common:halfWidthButton, onTouch:() => { applyChanges(); gotoScreen('MainScreen'); } }), + Button('Cancel', { common:halfWidthButton, onTouch:() => gotoScreen('MainScreen') }) + ], filly:1 }, + ] + }); + + let StdSelectionView = { width:40, height:40, pad:2 }; + + ScreenSet['ColorSelectionScreen'] = new Layout({ + type:'v', c:[ + Label('Choose Color', { font:'12x20', pad:8, col:'#000000', bgCol:'#FFFFFF', bold:true, filly:1 }), + { type:'h', c:[ + ColorSelectionView('#000000',{ common:StdSelectionView, id:'black', + onTouch:() => selectColor(0,0,0) }), + ColorSelectionView('#FF0000',{ common:StdSelectionView, id:'red', + onTouch:() => selectColor(1,0,0) }), + ColorSelectionView('#00FF00',{ common:StdSelectionView, id:'green', + onTouch:() => selectColor(0,1,0) }), + ColorSelectionView('#0000FF',{ common:StdSelectionView, id:'blue', + onTouch:() => selectColor(0,0,1) }), + ] }, + { type:'h', c:[ + ColorSelectionView('#FFFFFF',{ common:StdSelectionView, id:'white', + onTouch:() => selectColor(1,1,1) }), + ColorSelectionView('#FFFF00',{ common:StdSelectionView, id:'yellow', + onTouch:() => selectColor(1,1,0) }), + ColorSelectionView('#FF00FF',{ common:StdSelectionView, id:'magenta', + onTouch:() => selectColor(1,0,1) }), + ColorSelectionView('#00FFFF',{ common:StdSelectionView, id:'cyan', + onTouch:() => selectColor(0,1,1) }), + ] }, + { height:4 }, + { type:'h', c:[ + Button('Back', { common:halfWidthButton, onTouch:() => gotoScreen('DetailSelectionScreen') }), + Button('Preview', { common:halfWidthButton, onTouch:() => gotoScreen('ThemePreviewScreen') }) + ], filly:1 }, + ] + }); + + ScreenSet['ThemePreviewScreen'] = new Layout({ + type:'v', c:[ + Label('Theme Preview', { common:legible, bold:true, filly:1 }), + { type:'h', c:[ + Label('Normal', { common:MainLabel }), + ColorDemo(' Test ',{ common:StdFont, pad:2, id:'NormalTest' }), + ] }, + { type:'h', c:[ + Label('Accented', { common:MainLabel }), + ColorDemo(' Test ',{ common:StdFont, pad:2, id:'AccentedTest' }), + ] }, + { type:'h', c:[ + Label('Hilighted', { common:MainLabel }), + ColorDemo(' Test ',{ common:StdFont, pad:2, id:'HilitedTest' }), + ] }, + { height:4 }, + { type:'h', c:[ + Button('Back', { common:legible, pad:4, onTouch:() => gotoScreen('ColorSelectionScreen') }) + ], filly:1 } + ] + }); + + +/**** applyChanges ****/ + + function applyChanges () { + let pendingBg = pendingTheme.bg; + let R = ((pendingBg >> 11) & 0b11111) / 0b11111; + let G = ((pendingBg >> 5) & 0b111111) / 0b111111; + let B = (pendingBg & 0b11111) / 0b11111; + pendingTheme.dark = (0.2126*R + 0.7152*G + 0.0722*B < 0.5); + + activeTheme = Object.assign(activeTheme,pendingTheme); + + let globalSettings = Object.assign( + require('Storage').readJSON('setting.json', true) || {}, + { theme:activeTheme } + ); + require('Storage').writeJSON('setting.json', globalSettings); + } + +/**** configureDetail ****/ + + function configureDetail (Detail) { + chosenDetail = Detail; + gotoScreen('ColorSelectionScreen'); + } + +/**** updateColorSelection ****/ + + function updateColorSelection () { + let selectedColor = pendingTheme[chosenDetail]; + + for (let Key in normalizedColorSet) { + if (normalizedColorSet.hasOwnProperty(Key)) { + activeLayout[Key].selected = (selectedColor === normalizedColorSet[Key]); + } + } + } + +/**** selectColor ****/ + + function selectColor (R,G,B) { + let selectedColor = g.toColor(R,G,B); + pendingTheme[chosenDetail] = selectedColor; + + updateColorSelection(); + g.clear(); + activeLayout.render(); + } + +/**** gotoScreen ****/ + + let activeLayout; + + function gotoScreen (ScreenName) { + activeLayout = ScreenSet[ScreenName]; + + switch (ScreenName) { + case 'MainScreen': + activeLayout['NormalDemo'].fg = activeTheme.fg; + activeLayout['NormalDemo'].bg = activeTheme.bg; + activeLayout['AccentedDemo'].fg = activeTheme.fg2; + activeLayout['AccentedDemo'].bg = activeTheme.bg2; + activeLayout['HilitedDemo'].fg = activeTheme.fgH; + activeLayout['HilitedDemo'].bg = activeTheme.bgH; + break; + case 'DetailSelectionScreen': + activeLayout['fgView'].col = pendingTheme.fg; + activeLayout['bgView'].col = pendingTheme.bg; + activeLayout['fg2View'].col = pendingTheme.fg2; + activeLayout['bg2View'].col = pendingTheme.bg2; + activeLayout['fgHView'].col = pendingTheme.fgH; + activeLayout['bgHView'].col = pendingTheme.bgH; + break; + case 'ColorSelectionScreen': + updateColorSelection(); + break; + case 'ThemePreviewScreen': + activeLayout['NormalTest'].fg = pendingTheme.fg; + activeLayout['NormalTest'].bg = pendingTheme.bg; + activeLayout['AccentedTest'].fg = pendingTheme.fg2; + activeLayout['AccentedTest'].bg = pendingTheme.bg2; + activeLayout['HilitedTest'].fg = pendingTheme.fgH; + activeLayout['HilitedTest'].bg = pendingTheme.bgH; + } + + g.setColor('#000000'); g.setBgColor('#FFFFFF'); // assert legibility + g.clear(); + + activeLayout.render(); + } + gotoScreen('MainScreen'); + diff --git a/apps/thermom/ChangeLog b/apps/thermom/ChangeLog index 6183ac17b..6d3a966e3 100644 --- a/apps/thermom/ChangeLog +++ b/apps/thermom/ChangeLog @@ -1,3 +1,6 @@ 0.02: New App! 0.03: Improved messages and added Celsius sign 0.04: Make temperature value readable on smaller screens +0.05: Use temperature from current locale + Update every 10s, average last 5 readings + Changes based on #1092 diff --git a/apps/thermom/app.js b/apps/thermom/app.js index 145854765..0e45ed3e7 100644 --- a/apps/thermom/app.js +++ b/apps/thermom/app.js @@ -1,13 +1,27 @@ +// history of temperature readings +var history = []; + + +// When we get temperature... function onTemperature(p) { - g.reset(1).clearRect(0,24,g.getWidth(),g.getHeight()); + var rect = Bangle.appRect; + g.reset(1).clearRect(rect.x, rect.y, rect.x2, rect.y2); g.setFont("6x8",2).setFontAlign(0,0); - var x = g.getWidth()/2; - var y = g.getHeight()/2 + 10; + var x = (rect.x+rect.x2)/2; + var y = (rect.y+rect.y2)/2 + 10; g.drawString("Temperature:", x, y - 45); - g.setFontVector(g.getWidth() > 200 ? 70 : 40).setFontAlign(0,0); - g.drawString(p.temperature.toFixed(1) + " °C", x, y); + g.setFontVector(g.getWidth() > 200 ? 70 : 50).setFontAlign(0,0); + + // Average the last 5 temperature readings + while (history.length>4) history.shift(); + history.push(p.temperature); + var avrTemp = E.sum(history) / history.length; + // Draw the temperature + var t = require('locale').temp(avrTemp).replace("'","°"); + g.drawString(t, x, y); } +// Gets the temperature in the most accurate way (pressure sensor or inbuilt thermistor) function drawTemperature() { if (Bangle.getPressure) { Bangle.getPressure().then(onTemperature); @@ -18,11 +32,10 @@ function drawTemperature() { } } - setInterval(function() { drawTemperature(); -}, 20000); -drawTemperature(); +}, 10000); E.showMessage("Reading temperature..."); +drawTemperature(); Bangle.loadWidgets(); Bangle.drawWidgets(); diff --git a/apps/thermom/screenshot.png b/apps/thermom/screenshot.png new file mode 100644 index 000000000..a12bbef1c Binary files /dev/null and b/apps/thermom/screenshot.png differ diff --git a/apps/tinydraw/ChangeLog b/apps/tinydraw/ChangeLog new file mode 100644 index 000000000..af7f83942 --- /dev/null +++ b/apps/tinydraw/ChangeLog @@ -0,0 +1 @@ +0.01: Initial release diff --git a/apps/tinydraw/README.md b/apps/tinydraw/README.md new file mode 100644 index 000000000..a4acd9a72 --- /dev/null +++ b/apps/tinydraw/README.md @@ -0,0 +1,14 @@ +TinyDraw +======== + +This is a simple drawing application to make sketches +using different brushes and colors for your BangleJS2 watch! + +* Brush types: dot, brush, circle, square + +It is my first BangleJS application, I plan +to continue improving this app over time, but +if you want to contribute or provide feedback +don't hesitate to contact me! + +--pancake diff --git a/apps/tinydraw/app-icon.js b/apps/tinydraw/app-icon.js new file mode 100644 index 000000000..1f0eaae27 --- /dev/null +++ b/apps/tinydraw/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwwhC/ACEF7vd6oXTroXB7tQC6QWC7vQC6Xf//9C6n4xGPC4VM5nMoAXNxH/xH96EECwPM4gXNx///AXBhgXC5gXRqAXOt3u91gC4S/BC5sGCwPu8wXCuAXOhwXC9wXcR5oXJX5oXHxGIuF3DYQXRDIWHC5SPH/7yBAIN3u6/QC4JME+AXIg5WCC44CBJRN4KwQXHAgOAC5BWCC6gOCC6xUBC6cIUIQbCAAwXJvAMBQ4QXRg6fEC6SQBLQQXRJAYAJC5UIFpIXMMAQXUVIYXVGBQXLh4XKw4XKgCpCAA34F5apK/FwC5ZIJxAWLSJP4LxhhJxBGMMIeIJQX4xH3Cxz0CxAACu4WQAH4A/AAwA==")) diff --git a/apps/tinydraw/app.js b/apps/tinydraw/app.js new file mode 100644 index 000000000..e4c612219 --- /dev/null +++ b/apps/tinydraw/app.js @@ -0,0 +1,159 @@ +(function () { + var pen = 'circle'; + var discard = null; + var kule = [255, 255, 255]; + var oldLock = false; + + setInterval(() => { + if (Bangle.isLocked()) { + if (oldLock) { + return; + } + g.setColor('#fff'); + g.fillRect(0, 0, g.getWidth(), 20); + g.setFont('6x8', 2); + g.setColor('#000'); + g.drawString('PLEASE UNLOCK', 10, 2); + oldLock = true; + } else { + oldLock = false; + drawUtil(); + } + }, 1000); + + function nextColor () { + kule[0] = Math.random(); + kule[1] = Math.random(); + kule[2] = Math.random(); + } + + function nextPen () { + switch (pen) { + case 'circle': pen = 'pixel'; break; + case 'pixel': pen = 'crayon'; break; + case 'crayon': pen = 'square'; break; + case 'square': pen = 'circle'; break; + default: pen = 'pixel'; break; + } + console.log('set time'); + drawUtil(); + + discard = setTimeout(function () { console.log('timeout'); discard = null; }, 500); + } + + function drawUtil () { + if (Bangle.isLocked()) { + // do something to tell the user to unlock the screen + } + // titlebar + g.setColor(kule[0], kule[1], kule[2]); + g.fillRect(0, 0, g.getWidth(), 20); + // clear button + g.setColor('#000'); // black + g.fillCircle(10, 10, 8, 8); + g.setColor('#fff'); + g.drawLine(8, 8, 13, 13); + g.drawLine(13, 8, 8, 13); + // tool button + g.setColor('#fff'); + g.fillCircle(g.getWidth() - 10, 10, 8); + g.setColor('#000'); + + var w = g.getWidth(); + switch (pen) { + case 'circle': + g.fillCircle(w - 10, 10, 5); + break; + case 'square': + g.fillRect(w - 5, 5, w - 15, 15); + break; + case 'pixel': + g.setPixel(10, 10); + g.fillCircle(w - 10, 10, 2); + break; + case 'crayon': + var tap = { x: 10, y: 15, dy: -5, dx: 5 }; + g.drawLine(w - tap.x, tap.y, w - tap.x + tap.dx, tap.y + tap.dy); + g.drawLine(w - tap.x + 1, tap.y + 2, w - tap.x + tap.dx, tap.y + tap.dy - 2); + g.drawLine(w - tap.x + 2, tap.y + 2, w - tap.x + tap.dx, tap.y + tap.dy + 2); + break; + } + } + var tapTimer = null; + Bangle.on('drag', function (tap) { + if (tap.b === 0) { + if (tapTimer !== null) { + clearTimeout(tapTimer); + tapTimer = null; + } + } + // tap and hold the clear button + if (tap.x < 32 && tap.y < 32) { + if (tap.b === 1) { + if (tapTimer === null) { + tapTimer = setTimeout(function () { + g.clear(); + drawUtil(); + tapTimer = null; + }, 800); + } + if (discard) { + clearTimeout(discard); discard = null; + return; + } + } + return; + } + if (tap.x > g.getWidth() - 32 && tap.y < 32) { + if (tap.b === 1) { + if (tapTimer === null) { + tapTimer = setTimeout(function () { + g.clear(); + drawUtil(); + tapTimer = null; + }, 800); + } + if (discard) { + clearTimeout(discard); + discard = null; + return; + } + nextPen(); + } + drawUtil(); + return; + } else if (tap.y < 32) { + nextColor(); + drawUtil(); + return; + } + + g.setColor(kule[0], kule[1], kule[2]); + + switch (pen) { + case 'pixel': + g.setPixel(tap.x, tap.y); + g.drawLine(tap.x, tap.y, tap.x + tap.dx, tap.y + tap.dy); + break; + case 'crayon': + g.drawLine(tap.x, tap.y, tap.x + tap.dx, tap.y + tap.dy); + g.drawLine(tap.x + 1, tap.y + 2, tap.x + tap.dx, tap.y + tap.dy - 2); + g.drawLine(tap.x + 2, tap.y + 2, tap.x + tap.dx, tap.y + tap.dy + 2); + break; + case 'circle': + var XS = tap.dx / 10; + var YS = tap.dy / 10; + for (i = 0; i < 10; i++) { + g.fillCircle(tap.x + (i * XS), tap.y + (i * YS), 4, 4); + } + break; + case 'square': + g.fillRect(tap.x - 10, tap.y - 10, tap.x + 10, tap.y + 10); + break; + } + drawUtil(); + }); + + g.clear(); + drawUtil(); +})(); diff --git a/apps/tinydraw/app.png b/apps/tinydraw/app.png new file mode 100644 index 000000000..01eda0a60 Binary files /dev/null and b/apps/tinydraw/app.png differ diff --git a/apps/tinydraw/screenshot.png b/apps/tinydraw/screenshot.png new file mode 100644 index 000000000..27d5cc56c Binary files /dev/null and b/apps/tinydraw/screenshot.png differ diff --git a/apps/toucher/app.js b/apps/toucher/app.js index 8ac198f52..aab50fbda 100644 --- a/apps/toucher/app.js +++ b/apps/toucher/app.js @@ -293,9 +293,9 @@ Bangle.on('swipe', dir => { else next(); }); -// close launcher when lcd is off -Bangle.on('lcdPower', on => { - if(!on) return load(); +// close launcher when screen is locked +Bangle.on('lock', on => { + if(on) return load(); }); if (process.env.HWVERSION == 1) { diff --git a/apps/touchmenu/ChangeLog b/apps/touchmenu/ChangeLog new file mode 100644 index 000000000..c5277e465 --- /dev/null +++ b/apps/touchmenu/ChangeLog @@ -0,0 +1 @@ +0.01: App launched diff --git a/apps/touchmenu/README.md b/apps/touchmenu/README.md new file mode 100644 index 000000000..0e81f3755 --- /dev/null +++ b/apps/touchmenu/README.md @@ -0,0 +1,40 @@ +# TouchMenu + +A redesign of the built-in `E.showMenu()` to take advantage of the full touch screen on the Bangle.js 2. + +![screenshot](touchmenu.gif) + +## Features + +- All of the features of the built-in `E.showMenu()` +- Icon support for menu items: + ```javascript + menu.items[0].icon = Graphics.createImage(...); + ``` +- Custom accent colors: + ```javascript + E.showMenu({ + "": { + cAB: g.theme.bg2, // Accent background + cAF: g.theme.fg2 // Accent foreground + } + }) + ``` +- Automatic back button detection - name a button `< Back` and it will be given a special position and icon + +## Controls + +- Scroll through the options +- Tap on an option to select it +- Tap on a button again to use it +- Tap on a selected Boolean to toggle it +- Tap on a selected number to change - tap the right side of the screen to decrease, left side to increase +- If detected, tap on the back button in the upper left to go back + +## Requests + +Contact information is on my website: [kyleplo](https://kyleplo.com) + +## Creator + +[kyleplo](https://kyleplo.com) diff --git a/apps/touchmenu/touchmenu.boot.js b/apps/touchmenu/touchmenu.boot.js new file mode 100644 index 000000000..93a0ba1c8 --- /dev/null +++ b/apps/touchmenu/touchmenu.boot.js @@ -0,0 +1,197 @@ +E.showMenu = function(items) { + const gw = g.getWidth(); + const gh = g.getHeight(); + Bangle.removeAllListeners("drag"); + if(!items){ + delete m; + g.clearRect(0, 30, gw, gh - 30); + return false; + } + var loc = require("locale"); + var m = { + info: { + title: "Menu", + cB: g.theme.bg, + cF: g.theme.fg, + cHB: g.theme.bgH, + cHF: g.theme.fgH, + cAB: g.theme.bg2, + cAF: g.theme.fg2, + predraw : () => {}, + preflip : () => {} + }, + scroll: 0, + items: [], + selected: -1, + draw: () => { + g.reset().setFont('12x20'); + m.info.predraw(g); + g.setColor(m.info.cB).fillRect(0, 50, gw, gh - 30).setColor(m.info.cF); + m.items.forEach((e, i) => { + const s = (i * 48) - m.scroll + 50; + if(s < 30 || s > gh - 74){ + return false; + } + if(i == m.selected){ + g.setColor(m.info.cHB).fillRect(0, s, gw, Math.min(s + 48, gh - 30)).setColor(m.info.cHF); + }else{ + g.setColor(m.info.cF); + } + g.drawString(e.title, (e.icon ? 30 : 10), s + 5); + if(e.icon){ + g.drawImage(e.icon, 5, s + 5); + } + if(e.type && s < gh - 72){ + if(e.format){ + g.setFontAlign(1, -1, 0).drawString(e.format(e.value), gw - 10, s + 25).setFontAlign(-1, -1, 0); + }else{ + g.setFontAlign(1, -1, 0).drawString(e.value, gw - 10, s + 25).setFontAlign(-1, -1, 0); + } + } + }); + g.setColor(m.info.cAB).fillRect(0, 30, gw, 50); + g.setColor(m.info.cAF).drawString(m.info.title, (m.back ? 30 : 10), 32); + if(m.back){ + g.drawLine(5, 40, 20, 40); + g.drawLine(5, 40, 15, 33); + g.drawLine(5, 40, 15, 47); + } + m.info.preflip(g, m.scroll > 0, m.scroll < (m.items.length - 1) * 48); + }, + select: (x, y) => { + if(m.selected == -1 || m.selected !== Math.max(Math.min(Math.floor((y + m.scroll - 50) / 48), m.items.length - 1), 0)){ + if(y){ + if(y < 50 || y > gh - 30){ + return false; + }else{ + m.selected = Math.max(Math.min(Math.floor((y + m.scroll - 50) / 48), m.items.length - 1), 0); + } + }else{ + m.selected = Math.floor(m.scroll / 48); + } + m.draw(); + }else{ + if(m.items[m.selected].type && m.items[m.selected].type === "boolean"){ + m.items[m.selected].value = !m.items[m.selected].value; + m.items[m.selected].onchange(m.items[m.selected].value); + m.draw(); + }else if(m.items[m.selected].type && m.items[m.selected].type === "number"){ + if(x && x < (gw / 2)){ + m.items[m.selected].value = m.items[m.selected].value - (m.items[m.selected].step ? m.items[m.selected].step : 1); + }else{ + m.items[m.selected].value = m.items[m.selected].value + (m.items[m.selected].step ? m.items[m.selected].step : 1); + } + if(m.items[m.selected].value > (m.items[m.selected].max ? m.items[m.selected].max : Infinity)){ + m.items[m.selected].value = m.items[m.selected].min ? m.items[m.selected].min : 0; + } + if(m.items[m.selected].value < (m.items[m.selected].min ? m.items[m.selected].min : 0)){ + m.items[m.selected].value = m.items[m.selected].max ? m.items[m.selected].max : 10; + } + m.items[m.selected].onchange(m.items[m.selected].value); + m.draw(); + }else{ + if(m.items[m.selected]){ + m.items[m.selected](); + } + } + } + }, + move: d => { + m.scroll += (d * 48); + m.scroll = Math.min(Math.max(m.scroll, 0), (m.items.length - 1) * 48); + m.selected = Math.max(Math.min(Math.floor((m.scroll - 50) / 48), m.items.length - 1), 0); + m.draw(); + }, + }; + Object.keys(items).forEach(i => { + if(i == ""){ + m.info = Object.assign(m.info, items[i]); + }else if(i === "< Back" && items[i]){ + m.back = items[i]; + }else if(items[i]){ + m.items.push(items[i]); + m.items[m.items.length - 1].title = loc.translate(i); + if(items[i].hasOwnProperty("value")){ + if(typeof items[i].value === "boolean"){ + m.items[m.items.length - 1].type = "boolean"; + }else{ + m.items[m.items.length - 1].type = "number"; + } + } + } + }); + m.info.title = loc.translate(m.info.title); + m.draw(); + Bangle.on("drag", d => { + if(!d.b){ + return false; + } + if(d.dx == 0 && d.dy == 0){ + if(d.x < 30 && d.y < 50){ + m.back(); + return false; + } + m.select(d.x, d.y); + }else{ + m.selected = -1; + m.scroll -= d.dy; + m.scroll = Math.min(Math.max(m.scroll, 0), (m.items.length - 1) * 48); + m.draw(); + } + }); + return m; +}; + +E.showAlert = function (e, t){ + if(!e){ + E.showMenu(); + return false; + } + return new Promise(r => { + const menu = { + "": { + "title": (t ? t : "Alert") + }, + Ok: () => { + E.showMenu(); + r(); + } + }; + menu[e] = () => {}; + E.showMenu(menu); + }); +}; +E.showMessage = E.showAlert; + +E.showPrompt = function (e, t){ + if(!e){ + E.showMenu(); + return false; + } + return new Promise(r => { + const menu = { + "": { + "title": (t && t.title ? t.title : "Choose") + } + }; + menu[e] = () => {}; + if(t && t.buttons){ + Object.keys(t.buttons).forEach(b => { + menu[b] = () => { + E.showMenu(); + r(t.buttons[b]); + }; + }); + }else{ + menu.Yes = () => { + E.showMenu(); + r(true); + }; + menu.No = () => { + E.showMenu(); + r(false); + }; + } + E.showMenu(menu); + }); +}; diff --git a/apps/touchmenu/touchmenu.gif b/apps/touchmenu/touchmenu.gif new file mode 100644 index 000000000..3df4b3462 Binary files /dev/null and b/apps/touchmenu/touchmenu.gif differ diff --git a/apps/touchmenu/touchmenu.png b/apps/touchmenu/touchmenu.png new file mode 100644 index 000000000..58733cbc7 Binary files /dev/null and b/apps/touchmenu/touchmenu.png differ diff --git a/apps/touchtimer/0_dark_timer_edit.png b/apps/touchtimer/0_dark_timer_edit.png new file mode 100644 index 000000000..2160ef38d Binary files /dev/null and b/apps/touchtimer/0_dark_timer_edit.png differ diff --git a/apps/touchtimer/0_light_timer_edit.png b/apps/touchtimer/0_light_timer_edit.png new file mode 100644 index 000000000..361223af9 Binary files /dev/null and b/apps/touchtimer/0_light_timer_edit.png differ diff --git a/apps/touchtimer/1_dark_timer_ready.png b/apps/touchtimer/1_dark_timer_ready.png new file mode 100644 index 000000000..236aef7f9 Binary files /dev/null and b/apps/touchtimer/1_dark_timer_ready.png differ diff --git a/apps/touchtimer/1_light_timer_ready.png b/apps/touchtimer/1_light_timer_ready.png new file mode 100644 index 000000000..5e2ca3c9d Binary files /dev/null and b/apps/touchtimer/1_light_timer_ready.png differ diff --git a/apps/touchtimer/2_dark_timer_running.png b/apps/touchtimer/2_dark_timer_running.png new file mode 100644 index 000000000..4de00cc61 Binary files /dev/null and b/apps/touchtimer/2_dark_timer_running.png differ diff --git a/apps/touchtimer/2_light_timer_running.png b/apps/touchtimer/2_light_timer_running.png new file mode 100644 index 000000000..2a0d314f4 Binary files /dev/null and b/apps/touchtimer/2_light_timer_running.png differ diff --git a/apps/touchtimer/3_dark_timer_finished.png b/apps/touchtimer/3_dark_timer_finished.png new file mode 100644 index 000000000..c6dd77b82 Binary files /dev/null and b/apps/touchtimer/3_dark_timer_finished.png differ diff --git a/apps/touchtimer/3_light_timer_finished.png b/apps/touchtimer/3_light_timer_finished.png new file mode 100644 index 000000000..18ee015e3 Binary files /dev/null and b/apps/touchtimer/3_light_timer_finished.png differ diff --git a/apps/touchtimer/ChangeLog b/apps/touchtimer/ChangeLog new file mode 100644 index 000000000..01904c6ea --- /dev/null +++ b/apps/touchtimer/ChangeLog @@ -0,0 +1,2 @@ +0.01: Initial creation of the touch timer app +0.02: Add settings menu \ No newline at end of file diff --git a/apps/touchtimer/README.md b/apps/touchtimer/README.md new file mode 100644 index 000000000..39afba8e5 --- /dev/null +++ b/apps/touchtimer/README.md @@ -0,0 +1,29 @@ +# Touch Timer + +Quickly and easily create a timer with touch-only input. The time can be easily set with a number pad. + +## How to + +- First input the timer time via the input buttons +- If you need to correct the time, press "<-". +- If the timer time is correct, press "OK". +- If you have accidentially pressed "OK", press "STOP" to go cancel. +- Press "START" to start the timer, if the time is correct. +- The timer will run the time until 0. Once it hits zero the watch will buzz for 1 second every 1 seconds for a total of 3 times, or until you press "STOP" +- -> The number of buzzes, the buzz duration, and the pause between buzzes is configurable in the settings app + +## Screenshots + +### Light Theme + +![](0_light_timer_edit.png) +![](1_light_timer_ready.png) +![](2_light_timer_running.png) +![](3_light_timer_finished.png) + +### Dark Theme + +![](0_dark_timer_edit.png) +![](1_dark_timer_ready.png) +![](2_dark_timer_running.png) +![](3_dark_timer_finished.png) \ No newline at end of file diff --git a/apps/touchtimer/app-icon.js b/apps/touchtimer/app-icon.js new file mode 100644 index 000000000..d58446bcc --- /dev/null +++ b/apps/touchtimer/app-icon.js @@ -0,0 +1 @@ +require("heatshrink").decompress(atob("mEwwkE/4A3mUQIAMRkYWQkBaFiQWQgMjn8zGYUDCxkxFA3zD4MfCxXygECMAURiReCDAM/IpUBFIJ2CAAIeB+ZJKBYI8BCwMBiABBDARSBC5EwFwMwEwUwh5FCEIJhJiEfGIIXC+IQBSwQeBNYR1Gn4xB+MDDYITBiEzFoIOCC4vwEAIxBAwQzBAoQtCBgaNEh4iEAwMwRQXxHgRnBLwsvFQJdCFoIGBl55DH4QAEEIK/BC4KjBC4RECiED+RnBXooxCn4uBKwPwgIiB+fxgQQCRwgeBLwRbBkAXBh5yCBwoACEAoVBC4fwJ4I+DC5EjJQQXDBYP/kJWDC4qmBBYYXFfIQXKiQvUL6AXGR5LzBR4YXIBAS/BC4UCeAQOFC4rvDN4LvCFYMgd4IXJmEABgMxC4bWBiADDC45EBZIRHBMYINCBQQXIIgIkB//wgIFDmBKBC5QNB+UDboU/kEzgCRBC5QTBNwUxLoZRDC5J5EmAqBkEAiYMCC5XzFIMRkECAgILDC5YYDAAUBIoQXNDAMhiMRkYJEC5oAKC7qKBACDfCK4IWRPwjqBkczAB0yGAcQGgYAOmByCfAYAP+MBC4QWR//yC4ciACMhC4YATC4T9BACUSLiQAdA=")) \ No newline at end of file diff --git a/apps/touchtimer/app.js b/apps/touchtimer/app.js new file mode 100644 index 000000000..ffa1af80a --- /dev/null +++ b/apps/touchtimer/app.js @@ -0,0 +1,456 @@ +var DEBUG = false; +var FILE = "touchtimer.data.json"; + +var main = () => { + var settings = readSettings(); + + var button1 = new Button({ x1: 1, y1: 35, x2: 58, y2: 70 }, 1); + var button2 = new Button({ x1: 60, y1: 35, x2: 116, y2: 70 }, 2); + var button3 = new Button({ x1: 118, y1: 35, x2: 174, y2: 70 }, 3); + + var button4 = new Button({ x1: 1, y1: 72, x2: 58, y2: 105 }, 4); + var button5 = new Button({ x1: 60, y1: 72, x2: 116, y2: 105 }, 5); + var button6 = new Button({ x1: 118, y1: 72, x2: 174, y2: 105 }, 6); + + var button7 = new Button({ x1: 1, y1: 107, x2: 58, y2: 140 }, 7); + var button8 = new Button({ x1: 60, y1: 107, x2: 116, y2: 140 }, 8); + var button9 = new Button({ x1: 118, y1: 107, x2: 174, y2: 140 }, 9); + + var buttonOK = new Button({ x1: 1, y1: 142, x2: 58, y2: 174 }, "OK"); + var button0 = new Button({ x1: 60, y1: 142, x2: 116, y2: 174 }, 0); + var buttonDelete = new Button({ x1: 118, y1: 142, x2: 174, y2: 174 }, "<-"); + + var timerNumberButtons = [ + button1, + button2, + button3, + button4, + button5, + button6, + button7, + button8, + button9, + button0, + ]; + + var timerInputButtons = [ + button1, + button2, + button3, + button4, + button5, + button6, + button7, + button8, + button9, + buttonOK, + button0, + buttonDelete, + ]; + + var buttonStartPause = new Button( + { x1: 1, y1: 35, x2: 174, y2: 105 }, + "START" + ); + var buttonStop = new Button({ x1: 1, y1: 107, x2: 174, y2: 174 }, "STOP"); + + var timerRunningButtons = [buttonStartPause, buttonStop]; + + var timerEdit = new TimerEdit(); + timerNumberButtons.forEach((numberButton) => { + numberButton.setOnClick((number) => { + log("number button clicked"); + log(number); + timerEdit.appendNumber(number); + timerEdit.draw(); + }); + }); + + buttonDelete.setOnClick(() => { + log("delete button clicked"); + timerEdit.removeNumber(); + timerEdit.draw(); + }); + + buttonOK.setOnClick(() => { + if (timerEdit.timeStr.length === 0) { + return; + } + + g.clear(); + timerEdit.draw(); + + timerInputButtons.forEach((button) => button.disable()); + + timerRunningButtons.forEach((button) => { + button.enable(); + button.draw(); + }); + }); + + var timerIntervalId = undefined; + var buzzIntervalId = undefined; + var timerCountDown = undefined; + buttonStartPause.setOnClick(() => { + if (buttonStartPause.value === "PAUSE") { + if (timerCountDown) { + timerCountDown.pause(); + } + + buttonStartPause.value = "START"; + buttonStartPause.draw(); + + if (timerIntervalId) { + clearInterval(timerIntervalId); + timerIntervalId = undefined; + } + + if (buzzIntervalId) { + clearInterval(buzzIntervalId); + buzzIntervalId = undefined; + } + + return; + } + + if (buttonStartPause.value === "START") { + if (!timerCountDown) { + timerCountDown = new TimerCountDown(timerEdit.timeStr); + } else { + timerCountDown.unpause(); + } + + buttonStartPause.value = "PAUSE"; + buttonStartPause.draw(); + + timerIntervalId = setInterval(() => { + timerCountDown.draw(); + + if (timerCountDown.isFinished()) { + buttonStartPause.value = "FINISHED!"; + buttonStartPause.draw(); + + if (timerIntervalId) { + clearInterval(timerIntervalId); + timerIntervalId = undefined; + } + + var buzzCount = 1; + Bangle.buzz(settings.buzzDuration * 1000, 1); + buzzIntervalId = setInterval(() => { + if (buzzCount >= settings.buzzCount) { + clearInterval(buzzIntervalId); + buzzIntervalId = undefined; + return; + } else { + Bangle.buzz(settings.buzzDuration * 1000, 1); + buzzCount++; + } + }, settings.buzzDuration * 1000 + settings.pauseBetween * 1000); + } + }, 1000); + + return; + } + }); + + buttonStop.setOnClick(() => { + if (timerCountDown) { + timerCountDown = undefined; + } + + if (timerIntervalId) { + clearInterval(timerIntervalId); + timerIntervalId = undefined; + } + + if (buzzIntervalId) { + clearInterval(buzzIntervalId); + buzzIntervalId = undefined; + } + + buttonStartPause.value = "START"; + buttonStartPause.draw(); + + g.clear(); + timerEdit.reset(); + timerEdit.draw(); + + timerRunningButtons.forEach((button) => button.disable()); + + timerInputButtons.forEach((button) => { + button.enable(); + button.draw(); + }); + }); + + // initalize + g.clear(); + timerEdit.draw(); + timerInputButtons.forEach((button) => { + button.enable(); + button.draw(); + }); +}; + +// lib functions + +var log = (message) => { + if (DEBUG) { + console.log(JSON.stringify(message)); + } +}; + +var touchHandlers = []; + +Bangle.on("touch", (_button, xy) => { + log("touch"); + log(xy); + + var x = Math.min(Math.max(xy.x, 1), 174); + var y = Math.min(Math.max(xy.y, 1), 174); + + touchHandlers.forEach((touchHandler) => { + touchHandler(x, y); + }); +}); + +var BUTTON_BORDER_WITH = 2; + +class Button { + constructor(position, value) { + this.position = position; + this.value = value; + + this.touchHandler = undefined; + this.highlightTimeoutId = undefined; + } + + draw(highlight) { + g.setColor(g.theme.fg); + g.fillRect( + this.position.x1, + this.position.y1, + this.position.x2, + this.position.y2 + ); + + if (highlight) { + g.setColor(g.theme.bgH); + } else { + g.setColor(g.theme.bg); + } + g.fillRect( + this.position.x1 + BUTTON_BORDER_WITH, + this.position.y1 + BUTTON_BORDER_WITH, + this.position.x2 - BUTTON_BORDER_WITH, + this.position.y2 - BUTTON_BORDER_WITH + ); + + g.setColor(g.theme.fg); + g.setFontAlign(0, 0); + g.setFont("Vector", 35); + g.drawString( + this.value, + this.position.x1 + (this.position.x2 - this.position.x1) / 2 + 2, + this.position.y1 + (this.position.y2 - this.position.y1) / 2 + 2 + ); + } + + setOnClick(callback) { + this.touchHandler = (x, y) => { + if ( + x >= this.position.x1 && + x <= this.position.x2 && + y >= this.position.y1 && + y <= this.position.y2 + ) { + this.draw(true); + this.highlightTimeoutId = setTimeout(() => { + this.draw(); + this.highlightTimeoutId = undefined; + }, 100); + setTimeout(() => callback(this.value), 25); + } + }; + } + + disable() { + log("disable button"); + log(this.value); + var touchHandlerIndex = touchHandlers.indexOf(this.touchHandler); + if (touchHandlerIndex > -1) { + log("clearing touch handler"); + touchHandlers.splice(touchHandlerIndex, 1); + } + + if (this.highlightTimeoutId) { + log("clearing higlight timeout"); + clearTimeout(this.highlightTimeoutId); + this.highlightTimeoutId = undefined; + } + } + + enable() { + if (this.touchHandler) { + touchHandlers.push(this.touchHandler); + } + } +} + +class TimerEdit { + constructor() { + this.timeStr = ""; + } + + appendNumber(number) { + if (number === 0 && this.timeStr.length === 0) { + return; + } + + if (this.timeStr.length <= 6) { + this.timeStr = this.timeStr + number; + } + } + + removeNumber() { + if (this.timeStr.length > 0) { + this.timeStr = this.timeStr.slice(0, -1); + } + } + + reset() { + this.timeStr = ""; + } + + draw() { + log("drawing timer edit"); + var timeStrPadded = this.timeStr.padStart(6, "0"); + var timeStrDisplay = + "" + + timeStrPadded.slice(0, 2) + + "h " + + timeStrPadded.slice(2, 4) + + "m " + + timeStrPadded.slice(4, 6) + + "s"; + log(timeStrPadded); + log(timeStrDisplay); + + g.clearRect(0, 0, 176, 34); + g.setColor(g.theme.fg); + g.setFontAlign(-1, -1); + g.setFont("Vector:26x40"); + g.drawString(timeStrDisplay, 2, 0); + } +} + +class TimerCountDown { + constructor(timeStr) { + log("creating timer"); + this.timeStr = timeStr; + log(this.timeStr); + this.start = Math.floor(Date.now() / 1000); + log(this.start); + this.pausedTime = undefined; + } + + getAdjustedTime() { + var elapsedTime = Math.floor(Date.now() / 1000) - this.start; + + var timeStrPadded = this.timeStr.padStart(6, "0"); + var timeStrHours = parseInt(timeStrPadded.slice(0, 2), 10); + var timeStrMinutes = parseInt(timeStrPadded.slice(2, 4), 10); + var timeStrSeconds = parseInt(timeStrPadded.slice(4, 6), 10); + + var hours = timeStrHours; + var minutes = timeStrMinutes; + var seconds = timeStrSeconds - elapsedTime; + + if (seconds < 0) { + var neededMinutes = Math.ceil(Math.abs(seconds) / 60); + + seconds = seconds + neededMinutes * 60; + minutes = minutes - neededMinutes; + + if (minutes < 0) { + var neededHours = Math.ceil(Math.abs(minutes) / 60); + + minutes = minutes + neededHours * 60; + hours = hours - neededHours; + } + } + + if (hours < 0 || minutes < 0 || seconds < 0) { + hours = 0; + minutes = 0; + seconds = 0; + } + + return { hours: hours, minutes: minutes, seconds: seconds }; + } + + pause() { + this.pausedTime = Math.floor(Date.now() / 1000); + } + + unpause() { + if (this.pausedTime) { + this.start += Math.floor(Date.now() / 1000) - this.pausedTime; + } + + this.pausedTime = undefined; + } + + draw() { + log("drawing timer count down"); + var adjustedTime = this.getAdjustedTime(); + var hours = adjustedTime.hours; + var minutes = adjustedTime.minutes; + var seconds = adjustedTime.seconds; + + var timeStrDisplay = + "" + + hours.toString().padStart(2, "0") + + "h " + + minutes.toString().padStart(2, "0") + + "m " + + seconds.toString().padStart(2, "0") + + "s"; + log(timeStrDisplay); + + g.clearRect(0, 0, 176, 34); + g.setColor(g.theme.fg); + g.setFontAlign(-1, -1); + g.setFont("Vector:26x40"); + g.drawString(timeStrDisplay, 2, 0); + } + + isFinished() { + var adjustedTime = this.getAdjustedTime(); + var hours = adjustedTime.hours; + var minutes = adjustedTime.minutes; + var seconds = adjustedTime.seconds; + + if (hours <= 0 && minutes <= 0 && seconds <= 0) { + return true; + } else { + return false; + } + } +} + +var readSettings = () => { + log("reading settings"); + var settings = require("Storage").readJSON(FILE, 1) || { + buzzCount: 3, + buzzDuration: 1, + pauseBetween: 1, + }; + log(settings); + return settings; +}; + +// start main function + +main(); diff --git a/apps/touchtimer/app.png b/apps/touchtimer/app.png new file mode 100644 index 000000000..8ccdb17f0 Binary files /dev/null and b/apps/touchtimer/app.png differ diff --git a/apps/touchtimer/settings.js b/apps/touchtimer/settings.js new file mode 100644 index 000000000..885670f57 --- /dev/null +++ b/apps/touchtimer/settings.js @@ -0,0 +1,77 @@ +(function (back) { + var DEBUG = false; + var FILE = "touchtimer.data.json"; + + var settings = {}; + + var showMainMenu = () => { + log("Loading main menu"); + + E.showMenu({ + "": { title: "Touch Timer" }, + "< Back": () => back(), + "Buzz Count": { + value: settings.buzzCount, + min: 1, + max: 3, + step: 1, + onchange: (value) => { + settings.buzzCount = value; + writeSettings(settings); + }, + }, + "Buzz Duration": { + value: settings.buzzDuration, + min: 1, + max: 10, + step: 0.5, + format: (value) => value + "s", + onchange: (value) => { + settings.buzzDuration = value; + writeSettings(settings); + }, + }, + "Pause Between": { + value: settings.pauseBetween, + min: 1, + max: 5, + step: 1, + format: (value) => value + "s", + onchange: (value) => { + settings.pauseBetween = value; + writeSettings(settings); + }, + }, + }); + }; + + // lib functions + + var log = (message) => { + if (DEBUG) { + console.log(JSON.stringify(message)); + } + }; + + var readSettings = () => { + log("reading settings"); + var settings = require("Storage").readJSON(FILE, 1) || { + buzzCount: 3, + buzzDuration: 1, + pauseBetween: 1, + }; + log(settings); + return settings; + }; + + var writeSettings = (settings) => { + log("writing settings"); + log(settings); + require("Storage").writeJSON(FILE, settings); + }; + + // start main function + + settings = readSettings(); + showMainMenu(); +}); diff --git a/apps/vectorclock/ChangeLog b/apps/vectorclock/ChangeLog new file mode 100644 index 000000000..8addc7170 --- /dev/null +++ b/apps/vectorclock/ChangeLog @@ -0,0 +1,3 @@ +0.01: New watch face +0.02: Use Bangle.setUI for button/launcher handling +0.03: Bangle.js 2 support diff --git a/apps/vectorclock/Changelog b/apps/vectorclock/Changelog deleted file mode 100644 index c2a6fbcf4..000000000 --- a/apps/vectorclock/Changelog +++ /dev/null @@ -1,3 +0,0 @@ -0.1: New watch face -0.2: Use Bangle.setUI for button/launcher handling -0.3: Bangle.js 2 support \ No newline at end of file diff --git a/apps/weather/ChangeLog b/apps/weather/ChangeLog index fb6b28bf6..101da48e1 100644 --- a/apps/weather/ChangeLog +++ b/apps/weather/ChangeLog @@ -10,3 +10,5 @@ 0.11: Bangle.js 2 support 0.12: Allow hiding the widget 0.13: Tweak Bangle.js 2 light theme colors +0.14: Use weather condition code for icon selection +0.15: Fix widget icon diff --git a/apps/weather/app.js b/apps/weather/app.js index 8c8526fbd..efd9b0209 100644 --- a/apps/weather/app.js +++ b/apps/weather/app.js @@ -9,7 +9,7 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [ {filly: 1}, {type: "h", filly: 0, c: [ {type: "custom", width: g.getWidth()/2, height: g.getWidth()/2, valign: -1, txt: "unknown", id: "icon", - render: l => weather.drawIcon(l.txt, l.x+l.w/2, l.y+l.h/2, l.w/2-5)}, + render: l => weather.drawIcon(l, l.x+l.w/2, l.y+l.h/2, l.w/2-5)}, {type: "v", fillx: 1, c: [ {type: "h", pad: 2, c: [ {type: "txt", font: "18%", id: "temp", label: "000"}, @@ -47,6 +47,7 @@ function formatDuration(millis) { function draw() { layout.icon.txt = current.txt; + layout.icon.code = current.code; const temp = locale.temp(current.temp-273.15).match(/^(\D*\d*)(.*)$/); layout.temp.label = temp[1]; layout.tempUnit.label = temp[2]; diff --git a/apps/weather/lib.js b/apps/weather/lib.js index 7cb9a9f9b..1d48116e1 100644 --- a/apps/weather/lib.js +++ b/apps/weather/lib.js @@ -16,7 +16,7 @@ function scheduleExpiry(json) { function update(weatherEvent) { let json = storage.readJSON('weather.json')||{}; - + if (weatherEvent) { let weather = weatherEvent.clone(); delete weather.t; @@ -53,9 +53,19 @@ exports.get = function() { scheduleExpiry(storage.readJSON('weather.json')||{}); +/** + * + * @param cond Weather condition, as one of: + * {number} code: (Preferred form) https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 + * {string} weather description (in English: breaks for other languages!) + * {object} use cond.code if present, or fall back to cond.txt + * @param x Left + * @param y Top + * @param r Icon Size + */ exports.drawIcon = function(cond, x, y, r) { var palette; - + if (B2) { if (g.theme.dark) { palette = { @@ -101,7 +111,7 @@ exports.drawIcon = function(cond, x, y, r) { }; } } - + function drawSun(x, y, r) { g.setColor(palette.sun); g.fillCircle(x, y, r); @@ -249,36 +259,82 @@ exports.drawIcon = function(cond, x, y, r) { g.setColor(g.theme.fg).setFontAlign(0, 0).setFont('Vector', r*2).drawString("?", x+r/10, y+r/6); } - function chooseIcon(condition) { - if (!condition) return () => {}; - condition = condition.toLowerCase(); - if (condition.includes("thunderstorm")) return drawThunderstorm; - if (condition.includes("freezing")||condition.includes("snow")|| - condition.includes("sleet")) { + /* + * Choose weather icon to display based on weather description + */ + function chooseIconByTxt(txt) { + if (!txt) return () => {}; + txt = txt.toLowerCase(); + if (txt.includes("thunderstorm")) return drawThunderstorm; + if (txt.includes("freezing")||txt.includes("snow")|| + txt.includes("sleet")) { return drawSnow; } - if (condition.includes("drizzle")|| - condition.includes("shower")) { + if (txt.includes("drizzle")|| + txt.includes("shower")) { return drawRain; } - if (condition.includes("rain")) return drawShowerRain; - if (condition.includes("clear")) return drawSun; - if (condition.includes("few clouds")) return drawFewClouds; - if (condition.includes("scattered clouds")) return drawCloud; - if (condition.includes("clouds")) return drawBrokenClouds; - if (condition.includes("mist") || - condition.includes("smoke") || - condition.includes("haze") || - condition.includes("sand") || - condition.includes("dust") || - condition.includes("fog") || - condition.includes("ash") || - condition.includes("squalls") || - condition.includes("tornado")) { + if (txt.includes("rain")) return drawShowerRain; + if (txt.includes("clear")) return drawSun; + if (txt.includes("few clouds")) return drawFewClouds; + if (txt.includes("scattered clouds")) return drawCloud; + if (txt.includes("clouds")) return drawBrokenClouds; + if (txt.includes("mist") || + txt.includes("smoke") || + txt.includes("haze") || + txt.includes("sand") || + txt.includes("dust") || + txt.includes("fog") || + txt.includes("ash") || + txt.includes("squalls") || + txt.includes("tornado")) { return drawMist; } return drawUnknown; } + /* + * Choose weather icon to display based on weather conditition code + * https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 + */ + function chooseIconByCode(code) { + const codeGroup = Math.round(code / 100); + switch (codeGroup) { + case 2: return drawThunderstorm; + case 3: return drawRain; + case 5: + switch (code) { + case 511: return drawSnow; + case 520: return drawShowerRain; + case 521: return drawShowerRain; + case 522: return drawShowerRain; + case 531: return drawShowerRain; + default: return drawRain; + } + case 6: return drawSnow; + case 7: return drawMist; + case 8: + switch (code) { + case 800: return drawSun; + case 801: return drawFewClouds; + case 802: return drawCloud; + default: return drawBrokenClouds; + } + default: return drawUnknown; + } + } + + function chooseIcon(cond) { + if (typeof (cond)==="object") { + if ("code" in cond) return chooseIconByCode(cond.code); + if ("txt" in cond) return chooseIconByTxt(cond.txt); + } else if (typeof (cond)==="number") { + return chooseIconByCode(cond.code); + } else if (typeof (cond)==="string") { + return chooseIconByTxt(cond.txt); + } + return drawUnknown; + } chooseIcon(cond)(x, y, r); + }; diff --git a/apps/weather/widget.js b/apps/weather/widget.js index f2ddf0b5b..2905d776b 100644 --- a/apps/weather/widget.js +++ b/apps/weather/widget.js @@ -52,8 +52,8 @@ if (!w) return; g.reset(); g.clearRect(this.x, this.y, this.x+this.width-1, this.y+23); - if (w.txt) { - weather.drawIcon(w.txt, this.x+10, this.y+8, 7.5); + if (w.code||w.txt) { + weather.drawIcon(w, this.x+10, this.y+8, 7.5); } if (w.temp) { let t = require('locale').temp(w.temp-273.15); // applies conversion diff --git a/apps/weatherClock/ChangeLog b/apps/weatherClock/ChangeLog index 72b53ebbf..a6a12c297 100644 --- a/apps/weatherClock/ChangeLog +++ b/apps/weatherClock/ChangeLog @@ -2,3 +2,4 @@ 0.02: Minor layout format tweak so it uses less memory and draws ok on Bangle.js 1 (#1012) 0.03: Minor layout extra spaces. 0.04: Layout now compatible with Bangle.js 2 +0.05: Use weather condition code for icon selection diff --git a/apps/weatherClock/app.js b/apps/weatherClock/app.js index 799f9abc6..1a7f53f05 100644 --- a/apps/weatherClock/app.js +++ b/apps/weatherClock/app.js @@ -53,6 +53,29 @@ function chooseIcon(condition) { return cloudIcon; } +/* +* Choose weather icon to display based on weather conditition code +* https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 +*/ +function chooseIconByCode(code) { + const codeGroup = Math.round(code / 100); + switch (codeGroup) { + case 2: return stormIcon; + case 3: return rainIcon; + case 5: return rainIcon; + case 6: return snowIcon; + case 7: return cloudIcon; + case 8: + switch (code) { + case 800: return sunIcon; + case 801: return partSunIcon; + default: return cloudIcon; + } + break; + default: return cloudIcon; + } +} + /** Get weather stored in json file by weather app. */ @@ -105,7 +128,12 @@ function draw() { var currentWeather = weatherJson.weather; const temp = locale.temp(currentWeather.temp-273.15).match(/^(\D*\d*)(.*)$/); clockLayout.temp.label = temp[1] + " " + temp[2]; - clockLayout.weatherIcon.src = chooseIcon(currentWeather.txt); + const code = currentWeather.code || -1; + if (code > 0) { + clockLayout.weatherIcon.src = chooseIconByCode(code); + } else { + clockLayout.weatherIcon.src = chooseIcon(currentWeather.txt); + } const wind = locale.speed(currentWeather.wind).match(/^(\D*\d*)(.*)$/); clockLayout.wind.label = wind[1] + " " + wind[2] + " " + (currentWeather.wrose||'').toUpperCase(); } diff --git a/apps/wid_a_battery_widget/ChangeLog b/apps/wid_a_battery_widget/ChangeLog index b04824ae8..8a1538479 100644 --- a/apps/wid_a_battery_widget/ChangeLog +++ b/apps/wid_a_battery_widget/ChangeLog @@ -1,3 +1,4 @@ 1.00: Release for Bangle 2 (2021/11/18) 1.01: Internal id update to wid_* as per Gordon's request (2021/11/21) -1.02: Support dark themes \ No newline at end of file +1.02: Support dark themes +1.03: Increase screen update rate when charging diff --git a/apps/wid_a_battery_widget/widget.js b/apps/wid_a_battery_widget/widget.js index 8ab644ab3..74c76784d 100644 --- a/apps/wid_a_battery_widget/widget.js +++ b/apps/wid_a_battery_widget/widget.js @@ -1,4 +1,7 @@ (function(){ + const intervalLow = 60000; // update time when not charging + const intervalHigh = 2000; // update time when charging + let COLORS = { 'white': g.theme.dark ? "#000" : "#fff", 'black': g.theme.dark ? "#fff" : "#000", @@ -36,10 +39,14 @@ g.setFontAlign(0,0); g.setFont('6x8'); g.drawString(l, x + 14, y + 10); + + if (Bangle.isCharging()) changeInterval(id, intervalHigh); + else changeInterval(id, intervalLow); } + Bangle.on('charging',function(charging) { draw(); }); - setInterval(()=>WIDGETS["wid_a_battery_widget"].draw(), 60000); + var id = setInterval(()=>WIDGETS["wid_a_battery_widget"].draw(), intervalLow); WIDGETS["wid_a_battery_widget"]={area:"tr",width:30,draw:draw}; })(); diff --git a/apps/widbatpc/ChangeLog b/apps/widbatpc/ChangeLog index 99822b5a9..e70093659 100644 --- a/apps/widbatpc/ChangeLog +++ b/apps/widbatpc/ChangeLog @@ -11,3 +11,5 @@ 0.12: Fixed for Bangle 2 0.13: Fillbar setting added, see README 0.14: Fix drawing the bar when charging +0.15: Added option to always display the icon when charging (useful if 'hide if charge greater than' is enabled) +0.16: Increase screen update rate when charging diff --git a/apps/widbatpc/settings.js b/apps/widbatpc/settings.js index b7a5db9e6..b45fc6749 100644 --- a/apps/widbatpc/settings.js +++ b/apps/widbatpc/settings.js @@ -13,6 +13,7 @@ 'fillbar': false, 'charger': true, 'hideifmorethan': 100, + 'alwaysoncharge': false, } // ...and overwrite them with any saved values // This way saved values are preserved if a new version adds more settings @@ -68,6 +69,11 @@ format: x => x+"%", onchange: save('hideifmorethan'), }, + 'Show on charge': { // Not sure if this is readable enough in the 'big' menu + value: s.alwaysoncharge, + format: onOffFormat, + onchange: save('alwaysoncharge'), + }, } E.showMenu(menu) }) diff --git a/apps/widbatpc/widget.js b/apps/widbatpc/widget.js index 3e5ff47b4..529923386 100644 --- a/apps/widbatpc/widget.js +++ b/apps/widbatpc/widget.js @@ -1,6 +1,9 @@ (function(){ + const intervalLow = 60000; // update time when not charging + const intervalHigh = 2000; // update time when charging + let COLORS = {}; - + if (process.env.HWVERSION == 1) { COLORS = { 'white': -1, // White @@ -17,31 +20,32 @@ 'high': "#0f0", // Green 'ok': "#ff0", // Orange 'low': "#f00", // Red - }; + }; } - const SETTINGS_FILE = 'widbatpc.json' + const SETTINGS_FILE = 'widbatpc.json'; - let settings + let settings; function loadSettings() { - settings = require('Storage').readJSON(SETTINGS_FILE, 1) || {} + settings = require('Storage').readJSON(SETTINGS_FILE, 1) || {}; const DEFAULTS = { 'color': 'By Level', 'percentage': true, 'charger': true, 'hideifmorethan': 100, + 'alwaysoncharge': false, }; Object.keys(DEFAULTS).forEach(k=>{ - if (settings[k]===undefined) settings[k]=DEFAULTS[k] + if (settings[k]===undefined) settings[k]=DEFAULTS[k]; }); } function setting(key) { - if (!settings) { loadSettings() } + if (!settings) { loadSettings(); } return settings[key]; } const levelColor = (l) => { // "charging" is very bright -> percentage is hard to read, "high" is ok(ish) - const green = setting('percentage') ? COLORS.high : COLORS.charging + const green = setting('percentage') ? COLORS.high : COLORS.charging; switch (setting('color')) { case 'Monochrome': return COLORS.white; // no chance of reading the percentage here :-( case 'Green': return green; @@ -58,21 +62,26 @@ if (l >= 15) return COLORS.ok; return COLORS.low; } - } + }; const chargerColor = () => { - return (setting('color') === 'Monochrome') ? COLORS.white : COLORS.charging - } + return (setting('color') === 'Monochrome') ? COLORS.white : COLORS.charging; + }; + // sets width, returns true if it changed function setWidth() { var w = 40; if (Bangle.isCharging() && setting('charger')) w += 16; - if (E.getBattery() > setting('hideifmorethan')) + if (E.getBattery() > setting('hideifmorethan')) { w = 0; + if( Bangle.isCharging() && setting('alwaysoncharge') === true) + w = 56; + } var changed = WIDGETS["batpc"].width != w; WIDGETS["batpc"].width = w; return changed; } + function draw() { // if hidden, don't draw if (!WIDGETS["batpc"].width) return; @@ -102,11 +111,11 @@ if (!setting('percentage')) { return; } - let gfx = g + let gfx = g; if (setting('color') === 'Monochrome') { // draw text inverted on battery level gfx = Graphics.createCallback(g.getWidth(),g.getHeight(), 1, - (x,y) => {g.setPixel(x,y,x<=xl?0:-1)}) + (x,y) => {g.setPixel(x,y,x<=xl?0:-1);}); } gfx.setFontAlign(-1,-1); if (l >= 100) { @@ -118,19 +127,24 @@ gfx.drawString(l, x + 6, y + 4); } } + // reload widget, e.g. when settings have changed function reload() { - loadSettings() + loadSettings(); // need to redraw all widgets, because changing the "charger" setting // can affect the width and mess with the whole widget layout - setWidth() + setWidth(); g.clear(); Bangle.drawWidgets(); } + // update widget - redraw just widget, or all widgets if size changed function update() { if (setWidth()) Bangle.drawWidgets(); else WIDGETS["batpc"].draw(); + + if (Bangle.isCharging()) changeInterval(id, intervalHigh); + else changeInterval(id, intervalLow); } Bangle.on('charging',function(charging) { @@ -138,20 +152,13 @@ update(); g.flip(); }); - var batteryInterval; + Bangle.on('lcdPower', function(on) { - if (on) { - update(); - // refresh once a minute if LCD on - if (!batteryInterval) - batteryInterval = setInterval(update, 60000); - } else { - if (batteryInterval) { - clearInterval(batteryInterval); - batteryInterval = undefined; - } - } + if (on) update(); }); + + var id = setInterval(()=>WIDGETS["batpc"].draw(), intervalLow); + WIDGETS["batpc"]={area:"tr",width:40,draw:draw,reload:reload}; setWidth(); -})() +})(); diff --git a/apps/widbt/ChangeLog b/apps/widbt/ChangeLog index 7aa96ce5c..4c2132122 100644 --- a/apps/widbt/ChangeLog +++ b/apps/widbt/ChangeLog @@ -4,3 +4,4 @@ 0.05: Make Bluetooth widget thinner, and when on a bright theme use light grey for disabled color 0.06: Tweaking colors for dark/light themes and low bpp screens 0.07: Memory usage improvements +0.08: Disable LCD on, on bluetooth status change diff --git a/apps/widbt/widget.js b/apps/widbt/widget.js index 88be3d5c9..c7ef8c0ad 100644 --- a/apps/widbt/widget.js +++ b/apps/widbt/widget.js @@ -7,7 +7,6 @@ WIDGETS["bluetooth"]={area:"tr",width:15,draw:function() { g.drawImage(atob("CxQBBgDgFgJgR4jZMawfAcA4D4NYybEYIwTAsBwDAA=="),2+this.x,2+this.y); },changed:function() { WIDGETS["bluetooth"].draw(); - Bangle.setLCDPower(1); // turn screen on }}; NRF.on('connect',WIDGETS["bluetooth"].changed); NRF.on('disconnect',WIDGETS["bluetooth"].changed); diff --git a/apps/widclkbttm/Changelog b/apps/widclkbttm/ChangeLog similarity index 100% rename from apps/widclkbttm/Changelog rename to apps/widclkbttm/ChangeLog diff --git a/apps/widpedom/ChangeLog b/apps/widpedom/ChangeLog index c033ea505..3483c3390 100644 --- a/apps/widpedom/ChangeLog +++ b/apps/widpedom/ChangeLog @@ -20,3 +20,4 @@ Fix issue with widget overwrite in large font mode Memory usage enhancements 0.20: Fix issue where step count would randomly reset +0.21: Memory usage improvements, fix widget initial width (fix #1170) diff --git a/apps/widpedom/widget.js b/apps/widpedom/widget.js index 0ec0780c9..3a079c066 100644 --- a/apps/widpedom/widget.js +++ b/apps/widpedom/widget.js @@ -1,5 +1,4 @@ (() => { - const PEDOMFILE = "wpedom.json" // Last time Bangle.on('step' was called let lastUpdate = new Date(); // Last step count when Bangle.on('step' was called @@ -8,19 +7,14 @@ let settings; function loadSettings() { - const d = require('Storage').readJSON(PEDOMFILE, 1) || {}; - settings = d.settings || {}; - } - - function setting(key) { - if (!settings) { loadSettings() } - const DEFAULTS = { + const d = require('Storage').readJSON("wpedom.json", 1) || {}; + settings = Object.assign({ 'goal': 10000, 'progress': false, 'large': false, 'hide': false - } - return (key in settings) ? settings[key] : DEFAULTS[key]; + }, d.settings || {}); + return d; } Bangle.on('step', stepCount => { @@ -31,10 +25,10 @@ if (lastUpdate.getDate() == date.getDate()){ stp_today += steps; } else { - // TODO: could save this to PEDOMFILE for lastUpdate's day? + // TODO: could save this to "wpedom.json" for lastUpdate's day? stp_today = steps; } - if (stp_today === setting('goal') + if (stp_today === settings.goal && !(require('Storage').readJSON('setting.json',1)||{}).quiet) { let b = 3, buzz = () => { if (b--) Bangle.buzz().then(() => setTimeout(buzz, 100)) @@ -51,29 +45,31 @@ }); // When unloading, save state E.on('kill', () => { - if (!settings) { loadSettings() } - let d = { + require("Storage").writeJSON("wpedom.json",{ lastUpdate : lastUpdate.valueOf(), stepsToday : stp_today, settings : settings, - }; - require("Storage").write(PEDOMFILE,d); + }); }); // add your widget - WIDGETS["wpedom"]={area:"tl",width:26, - redraw:function() { // work out the width, and queue a full redraw if needed - let stps = stp_today.toString(); + WIDGETS["wpedom"]={area:"tl",width:0, + getWidth:function() { let newWidth = 24; - if (setting('hide')) + if (settings.hide) newWidth = 0; else { - if (setting('large')) { + if (settings.large) { newWidth = 12 * stps.length + 3; - if (setting('progress')) + if (settings.progress) newWidth += 24; } } + return newWidth; + }, + redraw:function() { // work out the width, and queue a full redraw if needed + let stps = stp_today.toString(); + let newWidth = this.getWidth(); if (newWidth!=this.width) { // width has changed, re-layout all widgets this.width = newWidth; @@ -84,14 +80,14 @@ } }, draw:function() { - if (setting('hide')) return; + if (settings.hide) return; if (stp_today > 99999) stp_today = stp_today % 100000; // cap to five digits + comma = 6 characters let stps = stp_today.toString(); g.reset().clearRect(this.x, this.y, this.x + this.width, this.y + 23); // erase background - if (setting('progress')) { + if (settings.progress) { const width = 23, half = 11; - const goal = setting('goal'), left = Math.max(goal-stps,0); + const goal = settings.goal, left = Math.max(goal-stps,0); // blue or dark green g.setColor(left ? "#08f" : "#080").fillCircle(this.x + half, this.y + half, half); if (left) { @@ -113,10 +109,10 @@ } g.reset(); } - if (setting('large')) { + if (settings.large) { g.setFont("6x8",2); g.setFontAlign(-1, 0); - g.drawString(stps, this.x + (setting('progress')?28:4), this.y + 12); + g.drawString(stps, this.x + (settings.progress?28:4), this.y + 12); } else { let w = 24; if (stps.length > 3){ @@ -137,11 +133,12 @@ getSteps:()=>stp_today }; // Load data at startup - let pedomData = require("Storage").readJSON(PEDOMFILE,1); + let pedomData = loadSettings(); if (pedomData) { if (pedomData.lastUpdate) lastUpdate = new Date(pedomData.lastUpdate); stp_today = pedomData.stepsToday|0; delete pedomData; } + WIDGETS["wpedom"].width = WIDGETS["wpedom"].getWidth(); })() diff --git a/apps/widviztime/README.md b/apps/widviztime/README.md new file mode 100644 index 000000000..73e24b658 --- /dev/null +++ b/apps/widviztime/README.md @@ -0,0 +1,8 @@ +# Widget Autohide Widget +This widget is forked from the "Widget Visibility Widget" +It should make widgets completely hidden (except for 4 seconds after the watch is unlocked) + +Additional features that I want to implement: +- Only show widgets when in app launcher +- Make timeout adjustable +- Disable widgets completely diff --git a/apps/widviztime/changelog b/apps/widviztime/changelog new file mode 100644 index 000000000..287061d0c --- /dev/null +++ b/apps/widviztime/changelog @@ -0,0 +1 @@ +0.01: New Widget, forked from widviz diff --git a/apps/widviztime/eye.png b/apps/widviztime/eye.png new file mode 100644 index 000000000..9aec8ce89 Binary files /dev/null and b/apps/widviztime/eye.png differ diff --git a/apps/widviztime/widget.js b/apps/widviztime/widget.js new file mode 100644 index 000000000..5e81af611 --- /dev/null +++ b/apps/widviztime/widget.js @@ -0,0 +1,53 @@ +(() => { + + var saved = null; + + + function hide() { + if (!Bangle.isLCDOn() || saved) return; + saved = []; + for (var wd of WIDGETS) { + saved.push({ + d: wd.draw, + a: wd.area + }); + wd.draw = () => {}; + wd.area = ""; + } + g.setColor(0, 0, 0); + g.fillRect(0, 0, g.getWidth(), 23); + } + + function reveal() { + if (!Bangle.isLCDOn() || !saved) return; + for (var wd of WIDGETS) { + var o = saved.shift(); + wd.draw = o.d; + wd.area = o.a; + } + Bangle.drawWidgets(); + saved = null; + } + + function draw() { + g.setColor(0x07ff); + g.drawImage(atob("GBgBAAAAAAAAAAAAAAAAAH4AAf+AB4HgDgBwHDw4OH4cMOcMYMMGYMMGMOcMOH4cHDw4DgBwB4HgAf+AAH4AAAAAAAAAAAAAAAAA"), this.x, this.y); + } + + WIDGETS.viz = { + area: "tl", + width: 24, + draw: draw + }; + + + + Bangle.on('lock', (locked) => { + if (!locked) { + reveal(); + setTimeout(function() { + hide(); + }, 4000); + } + }); +})(); diff --git a/bin/sanitycheck.js b/bin/sanitycheck.js index 572364224..e50256fb6 100755 --- a/bin/sanitycheck.js +++ b/bin/sanitycheck.js @@ -3,6 +3,7 @@ */ var fs = require("fs"); +var heatshrink = require("../core/lib/heatshrink"); var acorn; try { acorn = require("acorn"); @@ -59,6 +60,7 @@ const STORAGE_KEYS = ['name', 'url', 'content', 'evaluate', 'noOverwite', 'suppo const DATA_KEYS = ['name', 'wildcard', 'storageFile', 'url', 'content', 'evaluate']; const FORBIDDEN_FILE_NAME_CHARS = /[,;]/; // used as separators in appid.info const VALID_DUPLICATES = [ '.tfmodel', '.tfnames' ]; +const GRANDFATHERED_ICONS = ["s7clk", "snek", "astral", "alpinenav", "slomoclock", "arrow", "pebble", "rebble"]; function globToRegex(pattern) { const ESCAPE = '.*+-?^${}()|[]\\'; @@ -74,8 +76,11 @@ function globToRegex(pattern) { const isGlob = f => /[?*]/.test(f) // All storage+data files in all apps: {app:,[file: | data:]} let allFiles = []; +let existingApps = []; apps.forEach((app,appIdx) => { if (!app.id) ERROR(`App ${appIdx} has no id`); + if (existingApps.includes(app.id)) ERROR(`Duplicate app '${app.id}'`); + existingApps.push(app.id); //console.log(`Checking ${app.id}...`); var appDir = APPSDIR+app.id+"/"; if (!fs.existsSync(APPSDIR+app.id)) ERROR(`App ${app.id} has no directory`); @@ -175,6 +180,23 @@ apps.forEach((app,appIdx) => { for (const key in file) { if (!STORAGE_KEYS.includes(key)) ERROR(`App ${app.id} file ${file.name} has unknown key ${key}`); } + // warn if JS icon is the wrong size + if (file.name == app.id+".img") { + let icon; + let match = fileContents.match(/E\.toArrayBuffer\(atob\(\"([^"]*)\"\)\)/); + if (match) icon = Buffer.from(match[1], 'base64'); + else { + match = fileContents.match(/require\(\"heatshrink\"\)\.decompress\(\s*atob\(\s*\"([^"]*)\"\s*\)\s*\)/); + if (match) icon = heatshrink.decompress(Buffer.from(match[1], 'base64')); + else ERROR(`JS icon ${file.name} does not match the pattern 'require("heatshrink").decompress(atob("..."))'`); + } + if (match) { + if (icon[0] > 48 || icon[0] < 24 || icon[1] > 48 || icon[1] < 24) { + if (GRANDFATHERED_ICONS.includes(app.id)) WARN(`JS icon ${file.name} should be 48x48px (or slightly under) but is instead ${icon[0]}x${icon[1]}px`); + else ERROR(`JS icon ${file.name} should be 48x48px (or slightly under) but is instead ${icon[0]}x${icon[1]}px`); + } + } + } }); let dataNames = []; (app.data||[]).forEach((data)=>{ diff --git a/core b/core index b033af017..b05af96b2 160000 --- a/core +++ b/core @@ -1 +1 @@ -Subproject commit b033af017f6789a6a7777e6ef1428d94995a9b8b +Subproject commit b05af96b2522a7a7225a56d804faf9383f8a8f97 diff --git a/loader.js b/loader.js index 768f5f38f..a0c280634 100644 --- a/loader.js +++ b/loader.js @@ -40,7 +40,7 @@ function onFoundDeviceInfo(deviceId, deviceVersion) { if (deviceId != "BANGLEJS" && deviceId != "BANGLEJS2") { showToast(`You're using ${deviceId}, not a Bangle.js. Did you want espruino.com/apps instead?` ,"warning", 20000); } else if (versionLess(deviceVersion, RECOMMENDED_VERSION)) { - showToast(`You're using an old Bangle.js firmware (${deviceVersion}). You can update with the instructions here` ,"warning", 20000); + showToast(`You're using an old Bangle.js firmware (${deviceVersion}) and ${RECOMMENDED_VERSION} is available (see changes). You can update with the instructions here` ,"warning", 20000); } diff --git a/modules/Layout.js b/modules/Layout.js index 6dc4b6368..65e9a8dc8 100644 --- a/modules/Layout.js +++ b/modules/Layout.js @@ -42,8 +42,8 @@ layoutObject has: and `fillx`/`filly` to be set. Not compatible with text rotation. * A `col` field, eg `#f00` for red * A `bgCol` field for background color (will automatically fill on render) -* A `halign` field to set horizontal alignment. `-1`=left, `1`=right, `0`=center -* A `valign` field to set vertical alignment. `-1`=top, `1`=bottom, `0`=center +* A `halign` field to set horizontal alignment WITHIN a `v` container. `-1`=left, `1`=right, `0`=center +* A `valign` field to set vertical alignment WITHIN a `h` container. `-1`=top, `1`=bottom, `0`=center * A `pad` integer field to set pixels padding * A `fillx` int to choose if the object should fill available space in x. 0=no, 1=yes, 2=2x more space * A `filly` int to choose if the object should fill available space in y. 0=no, 1=yes, 2=2x more space